text
stringlengths
3
1.05M
/** * controller 的集合,所有 controller 都在这里进行统一管理 */ const MAPPING = {}; const { Mark } = Coralian.constants; const ERROR_NAME = "/error"; function putContoller(ctrlerName, ctrler) { let instance = ctrler; let route = ctrlerName.split(Mark.SLASH); let outRoute = []; for (let i = 0, len = route.length; i < len; i++) { if (!String.isEmpty(route[i])) { outRoute.push(route[i]); } } let ctrlerWrapper = { instance: instance, inspectors: ctrler.inspectors || [], name: { path: ctrlerName, route: outRoute, // 文件系统的物理路径 type: Function.getName(instance) } }; MAPPING[ctrlerName] = ctrlerWrapper; return ctrlerWrapper; } function getContoller(ctrlerName) { let ctrler = MAPPING[ctrlerName]; if (ctrlerName === ERROR_NAME && !ctrler) { ctrler = putContoller(ctrlerName, require("../error/controller")) } return ctrler; } exports = module.exports = { put: putContoller, get: getContoller, error: () => { return getContoller(ERROR_NAME); }, "delete": (name) => { let ctrler = MAPPING[name]; delete MAPPING[name]; return ctrler; } }
/* Based on Cendors copy command for QuestMUD */ /* Evil hax0r bulut */ #define PATH this_player()->query_path() #define WIZARD_DIR "/wizards/" status copy_file(string in, string out) { int f_size, current_byte,path; int max_byte; string txt,tmp; tmp = extract(out,0,0); if(tmp != "/") { out = "/"+PATH+"/"+out; } tmp = ""; tmp = extract(in,0,0); if(tmp != "/") { in = "/"+PATH+"/"+in; } if(file_size(in) < 1) { write("No such file '" + tmp + "'\n"); return 1; } if(file_size(out) > 0) { write("File Already Exists: "+out+"\n"); return 0; } if(valid_read(out,this_player()) == 0) { write("Access denied.\n"); return 1; } write("Renaming "+in+" to "+out+"\n"); f_size = file_size(in); while(current_byte < f_size) { if(current_byte + 8192 > f_size) max_byte = f_size - current_byte; else max_byte = 8192; txt = read_bytes(in, current_byte, max_byte); write_file(out, txt); current_byte += max_byte; current_byte += sizeof(explode(txt, "\n")) - 1; } return 1; } cmd_rn(string str) { string tmp, tmp2; if(!str) { write("## Usage : rn [FROM_PATH] [TO_PATH]\n"); write(" Example : rn /wizards/cendor/sword.c /wizards/cendor/eq/sword.c\n"); write(" Example2: rn sword.c eq/sword.c\n"); return 1; } if(sscanf(str, "%s %s" , tmp, tmp2) != 2) return 0; if(!file_size(tmp2)) { write("No such file '" + tmp + "'\n"); return 1; } copy_file(tmp,tmp2) ; rm(tmp); return 1; }
const { RESTDataSource } = require("apollo-datasource-rest"); class LaunchAPI extends RESTDataSource { constructor() { super(); this.baseURL = "https://api.spacexdata.com/v2/"; } async getAllLaunches() { const resp = await this.get("launches"); return Array.isArray(resp) ? resp.map((launch) => this.launchReducer(launch)) : []; } async getLaunchById({ laundId }) { const resp = await this.get("launches", { flight_number: laundId }); return this.launchReducer(resp[0]); } getLaunchesByIds({ launchIds }) { return Promise.all( launchIds.map((launchId) => this.getLaunchById({ launchId })) ); } launchReducer(launch) { return { id: launch.flight_number || 0, cursor: `${launch.launch_date_unix}`, site: launch.launch_site && launch.launch_site.site_name, mission: { name: launch.mission_name, missionPatchSmall: launch.links.mission_patch_small, missionPatchLarge: launch.links.mission_patch, }, rocket: { id: launch.rocket.rocket_id, name: launch.rocket.rocket_name, type: launch.rocket.rocket_type, }, }; } } module.exports = LaunchAPI;
import { Vue } from 'ui.vue'; import { Loc } from 'main.core'; import 'bootstrap'; import './style.css'; Vue.component('vue-cart-detail-total-buttons', { data() { return { customSubmitButtonHTML: null, } }, props: ['basketError'], computed: { localize() { return Vue.getFilteredPhrases("VUE_CART_"); }, cartNumber: (state) => { return state.$store.getters['basket/basketNumber'] }, cartCount: (state) => { return state.$store.getters['basket/getItemsCount'] }, cartQuantity: (state) => { return state.$store.getters['basket/getItemsQuantity'] }, cartPrice: (state) => { return state.cartBasePrice }, cartPriceCurrency: (state) => { return BX?.Currency?.currencyFormat(state.cartPrice, state.$store.getters['basket/getCurrency'], true); }, cartWeight: (state) => { return state.$store.getters['basket/getBasketWeight'] }, cartPriceAvailable: (state) => { return state.$store.getters['basket/getBasketPriceAvailable'] }, cartPriceAvailableCurrency: (state) => { return state.$store.getters['basket/getBasketPriceAvailableCurrency'] }, cartBasePrice: (state) => { return state.$store.getters['basket/getBasketBasePrice']; }, cartBasePriceCurrency: (state) => { return state.$store.getters['basket/getBasketBasePriceCurrency']; }, cartPriceDiscount: (state) => { return state.$store.getters['basket/getBasketPriceDiscount']; }, cartPriceDiscountCurrency: (state) => { return state.$store.getters['basket/getBasketPriceDiscountCurrency']; }, cartPriceDiscountError: (state) => { return state.$store.getters['basket/getBasketPriceDiscountError']; }, basketOwner: (state) => { return state.$store.getters['basket/getOwner']; }, basketOwnerTitle: (state) => { let title = ""; let currentUser = state.$store.getters['getUser']; if (state.basketOwner?.ID == currentUser?.ID) { title = state.localize.VUE_CART_OWNER_YOU; } else { title = state.localize.VUE_CART_OWNER_LOGIN.replace("#LOGIN#", state.basketOwner.LOGIN); } return title; }, submitButtonErrorTitle: (state) => { return state.localize?.VUE_CART_BUTTON_ERROR_TITLE }, submitButtonName: (state) => { return Loc.getMessage('SBB_ORDER') }, clearButtonName: (state) => { return Loc.getMessage('SBB_ORDER_CLEAR') }, basketErrorCount: (state) => { return Object.keys(state.$props.basketError)?.length; }, }, created() { this.$root.$on("set:custom-submit-button", BX.proxy(function (value) { this.customSubmitButtonHTML = value; }, this)); BX.addCustomEvent("OnSwitchBasket", BX.proxy(function (event) { this.customSubmitButtonHTML = ""; })); }, methods: { basketSubmit: function (event) { if (this.cartQuantity > 0 && !this.basketErrorCount) { // TODO перенести на вызовы Vue this.$root.$emit('cartCheckout'); } }, basketClear: function () { if (this.cartQuantity > 0) { // TODO перенести на вызовы Vue this.$root.$emit('cartClear'); } }, showButtonTooltip: function (event) { if (this.basketErrorCount && event.target) { debugger; if (false && BX.UI?.Hint) { BX.UI.Hint.initNode(event.target, this.submitButtonErrorTitle); } else { alert(this.submitButtonErrorTitle); } } } }, template: `<div data-entity="basket-checkout-button"> <div class="cart-total-buttons" @click="showButtonTooltip" :data-hint="basketErrorCount ? submitButtonErrorTitle : submitButtonName" :title="basketErrorCount ? submitButtonErrorTitle : submitButtonName" :class="{disabled: basketErrorCount}"> <div v-if="customSubmitButtonHTML" v-html="customSubmitButtonHTML"></div> <div v-else> <button :title="basketErrorCount ? submitButtonErrorTitle : submitButtonName" class="btn btn-lg btn-primary cart-btn-checkout" @click="basketSubmit"> <i class="far fa-paper-plane h5 my-0"></i> {{submitButtonName}} </button> <button v-if="false" :title="clearButtonName" class="btn btn-sm small cart-btn-clear" @click="basketClear"> <i class="fas fa-trash-alt"></i> <span class="h5 my-1">{{clearButtonName}}</span> </button> <div class="small" v-if="basketErrorCount">{{submitButtonErrorTitle}}</div> </div> </div> </div> ` });
import logging __all__ = ( "logger", "set_verbosity_level" ) logging.basicConfig( stream=None, level=logging.CRITICAL, format="%(asctime)s - %(name)s (%(levelname)s): %(message)s" ) logger = logging.getLogger("siliqua") def set_verbosity_level(verbosity_level=0): """ Set the logging verbosity level :param verbosity_level: Verbosity level as defined in `logging` module """ if verbosity_level == 0: logger.setLevel(logging.ERROR) elif verbosity_level == 1: logger.setLevel(logging.WARNING) elif verbosity_level == 2: logger.setLevel(logging.INFO) elif verbosity_level >= 3: logger.setLevel(logging.DEBUG)
/** * A class which provides a reliable callback using either * a Web Worker, or if that isn't supported, falls back to setTimeout. */ var Ticker = /** @class */ (function () { function Ticker(callback, type, updateInterval) { this._callback = callback; this._type = type; this._updateInterval = updateInterval; // create the clock source for the first time this._createClock(); } /** * Generate a web worker */ Ticker.prototype._createWorker = function () { var blob = new Blob([ /* javascript */ "\n\t\t\t// the initial timeout time\n\t\t\tlet timeoutTime = " + (this._updateInterval * 1000).toFixed(1) + ";\n\t\t\t// onmessage callback\n\t\t\tself.onmessage = function(msg){\n\t\t\t\ttimeoutTime = parseInt(msg.data);\n\t\t\t};\n\t\t\t// the tick function which posts a message\n\t\t\t// and schedules a new tick\n\t\t\tfunction tick(){\n\t\t\t\tsetTimeout(tick, timeoutTime);\n\t\t\t\tself.postMessage('tick');\n\t\t\t}\n\t\t\t// call tick initially\n\t\t\ttick();\n\t\t\t" ], { type: "text/javascript" }); var blobUrl = URL.createObjectURL(blob); var worker = new Worker(blobUrl); worker.onmessage = this._callback.bind(this); this._worker = worker; }; /** * Create a timeout loop */ Ticker.prototype._createTimeout = function () { var _this = this; this._timeout = setTimeout(function () { _this._createTimeout(); _this._callback(); }, this._updateInterval * 1000); }; /** * Create the clock source. */ Ticker.prototype._createClock = function () { if (this._type === "worker") { try { this._createWorker(); } catch (e) { // workers not supported, fallback to timeout this._type = "timeout"; this._createClock(); } } else if (this._type === "timeout") { this._createTimeout(); } }; /** * Clean up the current clock source */ Ticker.prototype._disposeClock = function () { if (this._timeout) { clearTimeout(this._timeout); this._timeout = 0; } if (this._worker) { this._worker.terminate(); this._worker.onmessage = null; } }; Object.defineProperty(Ticker.prototype, "updateInterval", { /** * The rate in seconds the ticker will update */ get: function () { return this._updateInterval; }, set: function (interval) { this._updateInterval = Math.max(interval, 128 / 44100); if (this._type === "worker") { this._worker.postMessage(Math.max(interval * 1000, 1)); } }, enumerable: true, configurable: true }); Object.defineProperty(Ticker.prototype, "type", { /** * The type of the ticker, either a worker or a timeout */ get: function () { return this._type; }, set: function (type) { this._disposeClock(); this._type = type; this._createClock(); }, enumerable: true, configurable: true }); /** * Clean up */ Ticker.prototype.dispose = function () { this._disposeClock(); }; return Ticker; }()); export { Ticker }; //# sourceMappingURL=Ticker.js.map
import { useMutation, useFlash } from '@redwoodjs/web'; import { navigate, routes } from '@redwoodjs/router'; import SocialHandleForm from 'src/components/SocialHandleForm'; import { QUERY } from 'src/components/SocialHandlesCell'; const CREATE_SOCIAL_HANDLE_MUTATION = gql` mutation CreateSocialHandleMutation($input: CreateSocialHandleInput!) { createSocialHandle(input: $input) { id } } `; const NewSocialHandle = () => { const { addMessage } = useFlash(); const [createSocialHandle, { loading, error }] = useMutation(CREATE_SOCIAL_HANDLE_MUTATION, { onCompleted: () => { navigate(routes.socialHandles()); addMessage('SocialHandle created.', { classes: 'rw-flash-success' }); }, // This refetches the query on the list page. Read more about other ways to // update the cache over here: // https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates refetchQueries: [{ query: QUERY }], awaitRefetchQueries: true, }); const onSave = (input) => { createSocialHandle({ variables: { input } }); }; return ( <div className='rw-segment'> <header className='rw-segment-header'> <h2 className='rw-heading rw-heading-secondary'>New SocialHandle</h2> </header> <div className='rw-segment-main'> <SocialHandleForm onSave={onSave} loading={loading} error={error} /> </div> </div> ); }; export default NewSocialHandle;
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """ This module contains the Filters for use with the MessageHandler class """ from telegram import Chat try: str_type = base_string except NameError: str_type = str class BaseFilter(object): """Base class for all Message Filters Subclassing from this class filters to be combined using bitwise operators: And: >>> (Filters.text & Filters.entity(MENTION)) Or: >>> (Filters.audio | Filters.video) Not: >>> ~ Filters.command Also works with more than two filters: >>> (Filters.text & (Filters.entity(URL) | Filters.entity(TEXT_LINK))) >>> Filters.text & (~ Filters.forwarded) If you want to create your own filters create a class inheriting from this class and implement a `filter` method that returns a boolean: `True` if the message should be handled, `False` otherwise. Note that the filters work only as class instances, not actual class objects (so remember to initialize your filter classes). """ def __call__(self, message): return self.filter(message) def __and__(self, other): return MergedFilter(self, and_filter=other) def __or__(self, other): return MergedFilter(self, or_filter=other) def __invert__(self): return InvertedFilter(self) def filter(self, message): raise NotImplementedError class InvertedFilter(BaseFilter): """Represents a filter that has been inverted. Args: f: The filter to invert """ def __init__(self, f): self.f = f def filter(self, message): return not self.f(message) def __str__(self): return "<telegram.ext.filters.InvertedFilter inverting {}>".format(self.f) __repr__ = __str__ class MergedFilter(BaseFilter): """Represents a filter consisting of two other filters. Args: base_filter: Filter 1 of the merged filter and_filter: Optional filter to "and" with base_filter. Mutually exclusive with or_filter. or_filter: Optional filter to "or" with base_filter. Mutually exclusive with and_filter. """ def __init__(self, base_filter, and_filter=None, or_filter=None): self.base_filter = base_filter self.and_filter = and_filter self.or_filter = or_filter def filter(self, message): if self.and_filter: return self.base_filter(message) and self.and_filter(message) elif self.or_filter: return self.base_filter(message) or self.or_filter(message) def __str__(self): return ("<telegram.ext.filters.MergedFilter consisting of" " {} {} {}>").format(self.base_filter, "and" if self.and_filter else "or", self.and_filter or self.or_filter) __repr__ = __str__ class Filters(object): """ Predefined filters for use with the `filter` argument of :class:`telegram.ext.MessageHandler`. """ class _All(BaseFilter): def filter(self, message): return True all = _All() class _Text(BaseFilter): def filter(self, message): return bool(message.text and not message.text.startswith('/')) text = _Text() class _Command(BaseFilter): def filter(self, message): return bool(message.text and message.text.startswith('/')) class _Reply(BaseFilter): def filter(self, message): return bool(message.reply_to_message) reply = _Reply() command = _Command() class _Audio(BaseFilter): def filter(self, message): return bool(message.audio) audio = _Audio() class _Document(BaseFilter): def filter(self, message): return bool(message.document) document = _Document() class _Photo(BaseFilter): def filter(self, message): return bool(message.photo) photo = _Photo() class _Sticker(BaseFilter): def filter(self, message): return bool(message.sticker) sticker = _Sticker() class _Video(BaseFilter): def filter(self, message): return bool(message.video) video = _Video() class _Voice(BaseFilter): def filter(self, message): return bool(message.voice) voice = _Voice() class _Contact(BaseFilter): def filter(self, message): return bool(message.contact) contact = _Contact() class _Location(BaseFilter): def filter(self, message): return bool(message.location) location = _Location() class _Venue(BaseFilter): def filter(self, message): return bool(message.venue) venue = _Venue() class _StatusUpdate(BaseFilter): class _NewChatMembers(BaseFilter): def filter(self, message): return bool(message.new_chat_members) new_chat_members = _NewChatMembers() class _LeftChatMember(BaseFilter): def filter(self, message): return bool(message.left_chat_member) left_chat_member = _LeftChatMember() class _NewChatTitle(BaseFilter): def filter(self, message): return bool(message.new_chat_title) new_chat_title = _NewChatTitle() class _NewChatPhoto(BaseFilter): def filter(self, message): return bool(message.new_chat_photo) new_chat_photo = _NewChatPhoto() class _DeleteChatPhoto(BaseFilter): def filter(self, message): return bool(message.delete_chat_photo) delete_chat_photo = _DeleteChatPhoto() class _ChatCreated(BaseFilter): def filter(self, message): return bool(message.group_chat_created or message.supergroup_chat_created or message.channel_chat_created) chat_created = _ChatCreated() class _Migrate(BaseFilter): def filter(self, message): return bool(message.migrate_from_chat_id or message.migrate_to_chat_id) migrate = _Migrate() class _PinnedMessage(BaseFilter): def filter(self, message): return bool(message.pinned_message) pinned_message = _PinnedMessage() def filter(self, message): return bool(self.new_chat_members(message) or self.left_chat_member(message) or self.new_chat_title(message) or self.new_chat_photo(message) or self.delete_chat_photo(message) or self.chat_created(message) or self.migrate(message) or self.pinned_message(message)) status_update = _StatusUpdate() class _Forwarded(BaseFilter): def filter(self, message): return bool(message.forward_date) forwarded = _Forwarded() class _Game(BaseFilter): def filter(self, message): return bool(message.game) game = _Game() class entity(BaseFilter): """Filters messages to only allow those which have a :class:`telegram.MessageEntity` where their `type` matches `entity_type`. Args: entity_type: Entity type to check for. All types can be found as constants in :class:`telegram.MessageEntity`. Returns: function to use as filter """ def __init__(self, entity_type): self.entity_type = entity_type def filter(self, message): return any([entity.type == self.entity_type for entity in message.entities]) class _Private(BaseFilter): def filter(self, message): return message.chat.type == Chat.PRIVATE private = _Private() class _Group(BaseFilter): def filter(self, message): return message.chat.type in [Chat.GROUP, Chat.SUPERGROUP] group = _Group() class _Invoice(BaseFilter): def filter(self, message): return bool(message.invoice) invoice = _Invoice() class _SuccessfulPayment(BaseFilter): def filter(self, message): return bool(message.successful_payment) successful_payment = _SuccessfulPayment() class language(BaseFilter): """ Filters messages to only allow those which are from users with a certain language code. Note that according to telegrams documentation, every single user does not have the language_code attribute. Args: lang (str|list): Which language code(s) to allow through. This will be matched using .startswith meaning that 'en' will match both 'en_US' and 'en_GB' """ def __init__(self, lang): if isinstance(lang, str_type): self.lang = [lang] else: self.lang = lang def filter(self, message): return message.from_user.language_code and any( [message.from_user.language_code.startswith(x) for x in self.lang])
from django.contrib import admin from django.urls import reverse from django.utils.html import format_html from typeidea.custom_site import custon_site from .models import Category, Tag, Post from .adminforms import PostAdminForms from typeidea.base_admin import BaseUseradmin # Register your models here. class CategoryUserFilter(admin.SimpleListFilter): title = '分类过滤器' parameter_name = 'user_category' #先到LOOK里找 不是None 就调 queryset def lookups(self, request, model_admin): return Category.objects.filter(user=request.user).values_list('id', 'name') # value 是查询字符串 def queryset(self, request, queryset): print(queryset) category_id = self.value() if category_id: return queryset.filter(category_id=self.value()) return queryset # 内置改变 # class PostInline(admin.StackedInline): # fields = ('title', 'desc') # extra = 1 # model = Post @admin.register(Category, site=custon_site) class CategoryAdmin(BaseUseradmin): # inlines = [PostInline,] 内置 list_display = ['name', 'status', 'is_nav', 'create_time','post_number'] fields = ('name', 'status', 'is_nav') def save_model(self, request, obj, form, change): obj.user = request.user return super().save_model(request, obj, form, change) def post_number(self,obj): return '共{}篇文章'.format(obj.post_set.count()) post_number.short_description = '文章总数' @admin.register(Tag, site=custon_site) class TagAdmin(BaseUseradmin): list_display = ['name', 'status', 'create_time'] fields = ('name', 'status') def save_model(self, request, obj, form, change): obj.user = request.user return super().save_model(request, obj, form, change) @admin.register(Post, site=custon_site) class PostAdmin(BaseUseradmin): form = PostAdminForms list_display = [ 'title', 'category','user', 'status', 'create_time', 'operator' ] list_display_links = [] list_filter = [CategoryUserFilter] #右侧过滤器 search_fields = ['title', 'category__name'] # 搜索框 actions_on_top = True # 动作 ——————【执行】 actions_on_bottom = True save_on_top = True #保存选项 #自定义字段的展示 exclude = ('user',) # fields = ( # ('category', 'title'), # 'desc', # 'status', # 'content', # 'tag', # ) # 自定义显示格式 fieldsets = ( ('基础配置',{ 'description':'基础配置描述', 'fields':( ('title', 'category'), 'status', ), }), ('内容', { 'fields':( 'desc', 'content', ), }), ('额外信息',{ 'classes':('collapse',), 'fields':('tag',), }) ) # 水平显示的字段 filter_horizontal = ('tag',) def operator(self, obj): return format_html( '<a href="{}">编辑</a>', reverse('cus_admin:blog_post_change',args=(obj.id,)) ) operator.short_description = '操作' def save_model(self, request, obj, form, change): obj.user = request.user return super().save_model(request, obj, form, change) # 显示内容的处理 def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user = request.user) # class Media: # css = { # 'all': ("https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css",), # } # js = ('https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.js',)
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from base_reporter import BaseReporter import json from pathlib import Path class JSONReporter(BaseReporter): def __init__(self, metric_provider, log_filename): super(JSONReporter, self).__init__(metric_provider) log_filename = Path(log_filename) self.log_handle = open(log_filename, 'w') substrates_filename = log_filename.parent / (log_filename.stem + '-substrates.jsonl') self.substrates_log_handle = open(substrates_filename, 'w') def report(self, generation): metric_values = self.get_metric_values() self.log_handle.write(json.dumps(metric_values)) self.log_handle.write('\n') self.log_handle.flush() self.substrates_log_handle.write(json.dumps( {str(k): v for k,v in self.metric_provider.get_substrate_count().items()})) self.substrates_log_handle.write('\n') self.substrates_log_handle.flush()
# -*- coding: utf-8 -*- from yookassa.domain.common.response_object import ResponseObject from yookassa.domain.response.refund_response import RefundResponse class RefundListResponse(ResponseObject): __type = None __next_cursor = None __items = None @property def type(self): return self.__type @type.setter def type(self, value): self.__type = value @property def next_cursor(self): return self.__next_cursor @next_cursor.setter def next_cursor(self, value): self.__next_cursor = value @property def items(self): return self.__items @items.setter def items(self, value): if isinstance(value, list): self.__items = [RefundResponse(refund) for refund in value] else: self.__items = value
"""Binary sensor platform for Pandora Car Alarm System.""" __all__ = ["ENTITY_TYPES", "async_setup_entry"] import logging from asyncio import run_coroutine_threadsafe from functools import partial from typing import Any from homeassistant.components.switch import SwitchEntity, DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT from homeassistant.const import ATTR_NAME, ATTR_ICON, ATTR_COMMAND from . import ( ATTR_FLAG, ATTR_ATTRIBUTE, ATTR_STATE_SENSITIVE, ATTR_FEATURE, ATTR_DEFAULT, PandoraCASBooleanEntity, async_platform_setup_entry, ) from .api import BitStatus, CommandID, Features _LOGGER = logging.getLogger(__name__) ENTITY_TYPES = { 'active_security': { ATTR_NAME: "Active Security", ATTR_ICON: ("mdi:shield-off", "mdi:shield-car"), ATTR_ATTRIBUTE: "status", ATTR_FLAG: BitStatus.ACTIVE_SECURITY, ATTR_STATE_SENSITIVE: True, ATTR_COMMAND: (CommandID.DISABLE_ACTIVE_SECURITY, CommandID.ENABLE_ACTIVE_SECURITY), ATTR_FEATURE: Features.ACTIVE_SECURITY, ATTR_DEFAULT: True, }, 'tracking': { ATTR_NAME: "Tracking", ATTR_ICON: ("mdi:map-marker-off", "mdi:map-marker-distance"), ATTR_ATTRIBUTE: "status", ATTR_FLAG: BitStatus.TRACKING_ENABLED, ATTR_STATE_SENSITIVE: True, ATTR_COMMAND: (CommandID.DISABLE_TRACKING, CommandID.ENABLE_TRACKING), ATTR_FEATURE: Features.TRACKING, }, 'coolant_heater': { ATTR_NAME: "Coolant Heater", ATTR_ICON: ("mdi:radiator-disabled", "mdi:radiator"), ATTR_ATTRIBUTE: "status", ATTR_FLAG: BitStatus.BLOCK_HEATER_ACTIVE, ATTR_STATE_SENSITIVE: True, ATTR_COMMAND: (CommandID.TURN_OFF_COOLANT_HEATER, CommandID.TURN_ON_COOLANT_HEATER), ATTR_FEATURE: Features.COOLANT_HEATER, ATTR_DEFAULT: True, }, # 'ext_channel': { # ATTR_NAME: "Extra Channel", # ATTR_ATTRIBUTE: "status", ATTR_FLAG: BitStatus.COOLANT_HEATER, # ATTR_STATE_SENSITIVE: True, # ATTR_COMMAND: (CommandID.TURN_OFF_EXT_CHANNEL, CommandID.TURN_ON_COOLANT_HEATER), # ATTR_FEATURE: Features.EXT_CHANNEL, # }, 'engine': { ATTR_NAME: "Engine", ATTR_ICON: ("mdi:fan-off", "mdi:fan"), ATTR_ATTRIBUTE: "status", ATTR_FLAG: BitStatus.ENGINE_RUNNING, ATTR_STATE_SENSITIVE: True, ATTR_COMMAND: (CommandID.STOP_ENGINE, CommandID.START_ENGINE), ATTR_DEFAULT: True, }, 'service_mode': { ATTR_NAME: "Service Mode", ATTR_ICON: "mdi:wrench", ATTR_COMMAND: (CommandID.DISABLE_SERVICE_MODE, CommandID.ENABLE_SERVICE_MODE), }, 'ext_channel': { ATTR_NAME: "Extra Channel", ATTR_ICON: "mdi:export", ATTR_FEATURE: Features.EXT_CHANNEL, ATTR_COMMAND: (CommandID.TURN_OFF_EXT_CHANNEL, CommandID.TURN_ON_EXT_CHANNEL), } } class PandoraCASSwitch(PandoraCASBooleanEntity, SwitchEntity): ENTITY_TYPES = ENTITY_TYPES ENTITY_ID_FORMAT = ENTITY_ID_FORMAT @property def is_on(self) -> bool: """Return current state of switch.""" return bool(self._state) @property def assumed_state(self) -> bool: """Missing attribute implies unable to access exact state.""" return ATTR_ATTRIBUTE not in self._entity_config async def async_turn_on(self, **kwargs) -> None: """Proxy method to run enable boolean command.""" await self._run_boolean_command(True) async def async_turn_off(self, **kwargs) -> None: """Proxy method to run disable boolean command.""" await self._run_boolean_command(False) def turn_on(self, **kwargs: Any) -> None: """Compatibility for synchronous turn on calls.""" run_coroutine_threadsafe( self.async_turn_on(), self.hass.loop ).result() def turn_off(self, **kwargs: Any) -> None: """Compatibility for synchronous turn off calls.""" run_coroutine_threadsafe( self.async_turn_off(), self.hass.loop ).result() async_setup_entry = partial(async_platform_setup_entry, PLATFORM_DOMAIN, PandoraCASSwitch, logger=_LOGGER)
var Twig = Twig || requireUncached("../twig"), twig = twig || Twig.twig; describe("Twig.js Filters ->", function() { // Encodings describe("url_encode ->", function() { it("should encode URLs", function() { var test_template = twig({data: '{{ "http://google.com/?q=twig.js"|url_encode() }}' }); test_template.render().should.equal("http%3A%2F%2Fgoogle.com%2F%3Fq%3Dtwig.js" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|url_encode() }}' }); test_template.render().should.equal("" ); }); it("should handle special characters", function() { var data = { "foo": "<foo> \\&\"'.,-_?/Ķä€台北[]{}\t\r\n\b\x80" }; var test_template = twig({data: '{{ foo|url_encode() }}' }); test_template.render(data).should.equal("%3Cfoo%3E%20%5C%26%22%27.%2C-_%3F%2F%C4%B6%C3%A4%E2%82%AC%E5%8F%B0%E5%8C%97%5B%5D%7B%7D%09%0D%0A%08%C2%80" ); }); }); describe("json_encode ->", function() { it("should encode strings to json", function() { var test_template = twig({data: '{{ test|json_encode }}' }); test_template.render({test:'value'}).should.equal('"value"' ); }); it("should encode numbers to json", function() { var test_template = twig({data: '{{ test|json_encode }}' }); test_template.render({test:21}).should.equal('21' ); }); it("should encode arrays to json", function() { var test_template = twig({data: '{{ [1,"b",3]|json_encode }}' }); test_template.render().should.equal('[1,"b",3]' ); }); it("should encode objects to json", function() { var test_template = twig({data: '{{ {"a":[1,"b",3]}|json_encode }}' }); test_template.render().should.equal('{"a":[1,"b",3]}' ); }); it("should retain key order in an object", function() { twig({data: '{{ { "foo": 1, "bar": 2, "baz": 3 }|json_encode }}'}).render().should.equal( '{"foo":1,"bar":2,"baz":3}' ); }); it("should not add additional information to objects", function() { twig({data: '{{ { "foo": 1, "bar": [1, 2, 3], "baz": { "a": "a", "b": "b" } }|json_encode }}'}).render().should.equal( '{"foo":1,"bar":[1,2,3],"baz":{"a":"a","b":"b"}}' ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|json_encode }}' }); test_template.render().should.equal("null" ); }); it("should encode dates correctly", function() { var test_template = twig({data: '{{ test|json_encode }}' }); var data = {a: new Date("2011-10-10")}; test_template.render({test: data}).should.equal('{"a":"2011-10-10T00:00:00.000Z"}'); }); }); // String manipulation describe("upper ->", function() { it("should convert text to uppercase", function() { var test_template = twig({data: '{{ "hello"|upper }}' }); test_template.render().should.equal("HELLO" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|upper }}' }); test_template.render().should.equal("" ); }); }); describe("lower ->", function() { it("should convert text to lowercase", function() { var test_template = twig({data: '{{ "HELLO"|lower }}' }); test_template.render().should.equal("hello" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|lower }}' }); test_template.render().should.equal("" ); }); }); describe("capitalize ->", function() { it("should capitalize the first word in a string", function() { var test_template = twig({data: '{{ "hello world"|capitalize }}' }); test_template.render().should.equal("Hello world" ); var test_template2 = twig({data: '{{ "HELLO WORLD"|capitalize }}' }); test_template2.render().should.equal("Hello world" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|capitalize }}' }); test_template.render().should.equal("" ); }); }); describe("title ->", function() { it("should capitalize all the words in a string", function() { var test_template = twig({data: '{{ "hello world"|title }}' }); test_template.render().should.equal("Hello World" ); var test_template2 = twig({data: '{{ "HELLO WORLD"|title }}' }); test_template2.render().should.equal("Hello World" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|title }}' }); test_template.render().should.equal("" ); }); }); // String/Object/Array check describe("length ->", function() { it("should determine the length of a string", function() { var test_template = twig({data: '{{ "test"|length }}' }); test_template.render().should.equal("4"); }); it("should determine the length of an array", function() { var test_template = twig({data: '{{ [1,2,4,76,"tesrt"]|length }}' }); test_template.render().should.equal("5"); }); it("should determine the length of an object", function() { var test_template = twig({data: '{{ {"a": "b", "c": "1", "test": "test"}|length }}' }); test_template.render().should.equal("3"); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|length }}' }); test_template.render().should.equal("0" ); }); }); // Array/object manipulation describe("sort ->", function() { it("should sort an array", function() { var test_template = twig({data: '{{ [1,5,2,7]|sort }}' }); test_template.render().should.equal("1,2,5,7" ); test_template = twig({data: '{{ ["test","abc",2,7]|sort }}' }); test_template.render().should.equal("2,7,abc,test" ); }); it("should sort an object", function() { var test_template = twig({data: "{% set obj = {'c': 1,'d': 5,'t': 2,'e':7}|sort %}{% for key,value in obj|sort %}{{key}}:{{value}} {%endfor %}" }); test_template.render().should.equal("c:1 t:2 d:5 e:7 " ); test_template = twig({data: "{% set obj = {'m':'test','z':'abc','a':2,'y':7} %}{% for key,value in obj|sort %}{{key}}:{{value}} {%endfor %}" }); test_template.render().should.equal("a:2 y:7 z:abc m:test " ); test_template = twig({data: "{% set obj = {'z':'abc','a':2,'y':7,'m':'test'} %}{% for key,value in obj|sort %}{{key}}:{{value}} {%endfor %}" }); test_template.render().should.equal("a:2 y:7 z:abc m:test " ); }); it("should handle undefined", function() { var test_template = twig({data: '{% set obj = undef|sort %}{% for key, value in obj|sort %}{{key}}:{{value}}{%endfor%}' }); test_template.render().should.equal("" ); }); }); describe("reverse ->", function() { it("should reverse an array", function() { var test_template = twig({data: '{{ ["a", "b", "c"]|reverse }}' }); test_template.render().should.equal("c,b,a" ); }); it("should reverse an object", function() { }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|reverse }}' }); test_template.render().should.equal("" ); }); }); describe("keys ->", function() { it("should return the keys of an array", function() { var test_template = twig({data: '{{ ["a", "b", "c"]|keys }}' }); test_template.render().should.equal("0,1,2" ); }); it("should return the keys of an object", function() { var test_template = twig({data: '{{ {"a": 1, "b": 4, "c": 5}|keys }}' }); test_template.render().should.equal("a,b,c" ); test_template = twig({data: '{{ {"0":"a", "1":"b", "2":"c"}|keys }}' }); test_template.render().should.equal("0,1,2" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|keys }}' }); test_template.render().should.equal("" ); }); }); describe("merge ->", function() { it("should merge two objects into an object", function() { // Object merging var test_template = twig({data: '{% set obj= {"a":"test", "b":"1"}|merge({"b":2,"c":3}) %}{% for key in obj|keys|sort %}{{key}}:{{obj[key]}} {%endfor %}' }); test_template.render().should.equal('a:test b:2 c:3 ' ); }); it("should merge two arrays into and array", function() { // Array merging var test_template = twig({data: '{% set obj= ["a", "b"]|merge(["c", "d"]) %}{% for key in obj|keys|sort %}{{key}}:{{obj[key]}} {%endfor %}' }); test_template.render().should.equal('0:a 1:b 2:c 3:d ' ); }); it("should merge an object and an array into an object", function() { // Mixed merging var test_template = twig({data: '{% set obj= ["a", "b"]|merge({"a": "c", "3":4}, ["c", "d"]) %}{% for key in obj|keys|sort %}{{key}}:{{obj[key]}} {%endfor %}' }); test_template.render().should.equal('0:a 1:b 3:4 4:c 5:d a:c ' ); // Mixed merging(2) test_template = twig({data: '{% set obj= {"1":"a", "a":"b"}|merge(["c", "d"]) %}{% for key in obj|keys %}{{key}}:{{obj[key]}} {%endfor %}' }); test_template.render().should.equal('1:a a:b 2:c 3:d ' ); }); }); describe("join ->", function() { it("should join all values in an object", function() { var test_template = twig({data: '{{ {"a":"1", "b": "b", "c":test}|join("-") }}' }); test_template.render({"test": "t"}).should.equal("1-b-t" ); }); it("should joing all values in an array", function() { var test_template = twig({data: '{{ [1,2,4,76]|join }}' }); test_template.render().should.equal("12476" ); test_template = twig({data: '{{ [1+ 5,2,4,76]|join("-" ~ ".") }}' }); test_template.render().should.equal("6-.2-.4-.76" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|join }}' }); test_template.render().should.equal("" ); }); }); // Other describe("default ->", function() { it("should not provide the default value if a key is defined and not empty", function() { var test_template = twig({data: '{{ var|default("Not Defined") }}' }); test_template.render({"var":"value"}).should.equal("value" ); }); it("should provide a default value if a key is not defined", function() { var test_template = twig({data: '{{ var|default("Not Defined") }}' }); test_template.render().should.equal("Not Defined" ); }); it("should provide a default value if a value is empty", function() { var test_template = twig({data: '{{ ""|default("Empty String") }}' }); test_template.render().should.equal("Empty String" ); test_template = twig({data: '{{ var.key|default("Empty Key") }}' }); test_template.render({'var':{}}).should.equal("Empty Key" ); }); it("should provide a default value of '' if no parameters are passed and a default key is not defined", function () { var test_template = twig({data: '{{ var|default }}' }); test_template.render().should.equal(""); }); it("should provide a default value of '' if no parameters are passed and a value is empty", function () { var test_template = twig({data: '{{ ""|default }}' }); test_template.render().should.equal(""); test_template = twig({data: '{{ var.key|default }}' }); test_template.render({'var':{}}).should.equal(""); }); }); describe("date ->", function() { function pad(num) {return num<10?'0'+num:num;} function stringDate(date){ return pad(date.getDate()) + "/" + pad(date.getMonth()+1) + "/" + date.getFullYear() + " @ " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()); } // NOTE: these tests are currently timezone dependent it("should recognize timestamps", function() { var template = twig({data: '{{ 27571323556|date("d/m/Y @ H:i:s") }}'}) , date = new Date(27571323556000); // 13/09/2843 @ 08:59:16 EST template.render().should.equal( stringDate(date) ); }); it("should recognize timestamps, when they are passed as string", function() { var template = twig({data: '{{ "27571323556"|date("d/m/Y @ H:i:s") }}'}) , date = new Date(27571323556000); // 13/09/2843 @ 08:59:16 EST template.render().should.equal( stringDate(date) ); }); it("should recognize string date formats", function() { var template = twig({data: '{{ "Tue Aug 14 08:52:15 +0000 2007"|date("d/m/Y @ H:i:s") }}'}) , date = new Date(1187081535000); // 14/08/2007 @ 04:52:15 EST template.render().should.equal( stringDate(date) ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|date("d/m/Y @ H:i:s") }}' }); var date = new Date(); test_template.render().should.equal(stringDate(date)); }); it("should handle empty strings", function() { var test_template = twig({data: '{{ ""|date("d/m/Y @ H:i:s") }}' }); var date = new Date(); test_template.render().should.equal(stringDate(date)); }); it("should work with no parameters", function() { var test_template = twig({data: '{{ 27571323556|date }}' }); test_template.render().should.equal(twig({data: '{{ 27571323556|date("F j, Y H:i") }}'}).render()); }); }); describe("replace ->", function() { it("should replace strings provided in a map", function() { var template = twig({data: '{{ "I like %this% and %that%. Seriously, I like %this% and %that%."|replace({"%this%": foo, "%that%": "bar"}) }}'}); template.render({foo: "foo"}).should.equal("I like foo and bar. Seriously, I like foo and bar." ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|replace }}' }); test_template.render().should.equal("" ); }); }); describe("format ->", function() { it("should replace formatting tags with parameters", function() { var template = twig({data: '{{ "I like %s and %s."|format(foo, "bar") }}'}); template.render({foo: "foo"}).should.equal("I like foo and bar." ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|format }}' }); test_template.render().should.equal("" ); }); it("should handle positive leading sign without padding", function() { var template = twig({data: '{{ "I like positive numbers like %+d."|format(123) }}'}); template.render({foo: "foo"}).should.equal("I like positive numbers like +123." ); }); it("should handle negative leading sign without padding", function() { var template = twig({data: '{{ "I like negative numbers like %+d."|format(-123) }}'}); template.render({foo: "foo"}).should.equal("I like negative numbers like -123." ); }); it("should handle positive leading sign with padding zero", function() { var template = twig({data: '{{ "I like positive numbers like %+05d."|format(123) }}'}); template.render({foo: "foo"}).should.equal("I like positive numbers like +0123." ); }); it("should handle negative leading sign with padding zero", function() { var template = twig({data: '{{ "I like negative numbers like %+05d."|format(-123) }}'}); template.render({foo: "foo"}).should.equal("I like negative numbers like -0123." ); }); it("should handle positive leading sign with padding space", function() { var template = twig({data: '{{ "I like positive numbers like %+5d."|format(123) }}'}); template.render({foo: "foo"}).should.equal("I like positive numbers like +123." ); }); it("should handle negative leading sign with padding space", function() { var template = twig({data: '{{ "I like negative numbers like %+5d."|format(-123) }}'}); template.render({foo: "foo"}).should.equal("I like negative numbers like -123." ); }); }); describe("striptags ->", function() { it("should remove tags from a value", function() { var template = twig({data: '{{ "<p>Test paragraph.</p><!-- Comment --> <a href=\\"#fragment\\">Other text</a>"|striptags }}'}); template.render().should.equal("Test paragraph. Other text" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|striptags }}' }); test_template.render().should.equal("" ); }); }); describe("escape ->", function() { it("should convert unsafe characters to HTML entities", function() { var template = twig({data: '{{ "<p>Test paragraph.</p><!-- Comment --> <a href=\'#fragment\'>Other text</a>"|escape }}'}); template.render().should.equal("&lt;p&gt;Test paragraph.&lt;/p&gt;&lt;!-- Comment --&gt; &lt;a href=&#039;#fragment\&#039;&gt;Other text&lt;/a&gt;" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|escape }}' }); test_template.render().should.equal("" ); }); it("should not escape twice if autoescape is on", function() { twig({ autoescape: true, data: '{{ value|escape }}' }).render({ value: "<test>&</test>" }).should.equal('&lt;test&gt;&amp;&lt;/test&gt;'); }); it("should handle the strategy parameter", function() { var data = { "foo": "<foo> \\&\"'.,-_?/Ķä€台北[]{}\t\r\n\b\x80" }; var test_template = twig({data: 'Default: {{ foo|escape }}' }); test_template.render(data).should.equal("Default: &lt;foo&gt; \\&amp;&quot;&#039;.,-_?/Ķä€台北[]{}\t\r\n\b\x80" ); var test_template = twig({data: 'html: {{ foo|escape("html") }}' }); test_template.render(data).should.equal("html: &lt;foo&gt; \\&amp;&quot;&#039;.,-_?/Ķä€台北[]{}\t\r\n\b\x80" ); var test_template = twig({data: 'js: {{ foo|escape("js") }}' }); test_template.render(data).should.equal("js: \\x3Cfoo\\x3E\\x20\\x5C\\x26\\x22\\x27.,\\x2D_\\x3F\\x2F\\u0136\\u00E4\\u20AC\\u53F0\\u5317\\x5B\\x5D\\x7B\\x7D\\x9\\xD\\xA\\x8\\u0080" ); var test_template = twig({data: 'css: {{ foo|escape("css") }}' }); test_template.render(data).should.equal("css: \\3C foo\\3E \\20 \\5C \\26 \\22 \\27 \\2E \\2C \\2D \\5F \\3F \\2F \\136 \\E4 \\20AC \\53F0 \\5317 \\5B \\5D \\7B \\7D \\9 \\D \\A \\8 \\80 " ); var test_template = twig({data: 'url: {{ foo|escape("url") }}' }); test_template.render(data).should.equal("url: %3Cfoo%3E%20%5C%26%22%27.%2C-_%3F%2F%C4%B6%C3%A4%E2%82%AC%E5%8F%B0%E5%8C%97%5B%5D%7B%7D%09%0D%0A%08%C2%80" ); var test_template = twig({data: 'html_attr: {{ foo|escape("html_attr") }}' }); test_template.render(data).should.equal("html_attr: &lt;foo&gt;&#x20;&#x5C;&amp;&quot;&#x27;.,-_&#x3F;&#x2F;&#x0136;&#x00E4;&#x20AC;&#x53F0;&#x5317;&#x5B;&#x5D;&#x7B;&#x7D;&#x09;&#x0D;&#x0A;&#xFFFD;&#x0080;" ); }); it("should escape strategy != 'html' if autoescape is on", function() { twig({ autoescape: true, data: '{{ value|escape("js") }}' }).render({ value: "<test>&</test>" }).should.equal('\\x3Ctest\\x3E\\x26\\x3C\\x2Ftest\\x3E'); }); it("should not escape twice if autoescape is not html", function() { twig({ autoescape: 'js', data: '{{ value|escape("js") }}' }).render({ value: "<test>&</test>" }).should.equal('\\x3Ctest\\x3E\\x26\\x3C\\x2Ftest\\x3E'); }); it("should escape twice if escape strategy is different from autoescape option", function() { twig({ autoescape: 'css', data: '{{ value|escape("js") }}\n{{ value|escape }}' }).render({ value: "<test>&</test>" }).should.equal('\\5C x3Ctest\\5C x3E\\5C x26\\5C x3C\\5C x2Ftest\\5C x3E\n\\26 lt\\3B test\\26 gt\\3B \\26 amp\\3B \\26 lt\\3B \\2F test\\26 gt\\3B '); }); }); describe("e ->", function() { it("should alias escape function with e", function() { var template = twig({data: '{{ "<p>Test paragraph.</p><!-- Comment --> <a href=\'#fragment\'>Other text</a>"|e }}'}); template.render().should.equal("&lt;p&gt;Test paragraph.&lt;/p&gt;&lt;!-- Comment --&gt; &lt;a href=&#039;#fragment\&#039;&gt;Other text&lt;/a&gt;" ); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|e }}' }); test_template.render().should.equal("" ); }); it("should not escape twice if autoescape is on", function() { var template = twig({ autoescape: true, data: '{{ value|e }}' }); template.render({ value: "<test>&</test>" }).should.equal('&lt;test&gt;&amp;&lt;/test&gt;'); }); }); describe("nl2br ->", function() { it("should convert newlines into html breaks", function() { var template = twig({data: '{{ test|nl2br }}'}); template.render({ test: 'Line 1\r\nLine 2\nLine 3\rLine 4\n\n' }) .should.equal("Line 1<br />\nLine 2<br />\nLine 3<br />\nLine 4<br />\n<br />\n"); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|nl2br }}' }); test_template.render().should.equal("" ); }); it("should not escape br tags if autoescape is on", function() { twig({ autoescape: true, data: '{{ test|nl2br }}' }).render({ test: '<test>Line 1\nLine2</test>' }).should.equal("&lt;test&gt;Line 1<br />\nLine2&lt;/test&gt;"); }); }); describe("truncate ->", function() { it("should truncate string to default size(20) and add default separator", function() { var template = twig({data: '{{ test|truncate }}'}); template.render({test: '01234567890123456789012345678901234567890123456789'}).should.equal("012345678901234567890123456789..."); }); it("should truncate string to custom size(10) and add default separator", function() { var template = twig({data: '{{ test|truncate(10) }}'}); template.render({test: '01234567890123456789012345678901234567890123456789'}).should.equal("0123456789..."); }); it("should truncate string to custom size(15) with preserve and add default separator", function() { var template = twig({data: '{{ test|truncate(15, true) }}'}); template.render({test: '0123456789 0123456789 0123456789 0123456789 0123456789'}).should.equal("0123456789 0123456789..."); }); it("should truncate string to custom size(15) with preserve and add custom(*) separator", function() { var template = twig({data: '{{ test|truncate(15, true, "*") }}'}); template.render({test: '0123456789 0123456789 0123456789 0123456789 0123456789'}).should.equal("0123456789 0123456789*"); }); }); describe("trim ->", function() { it("should trim whitespace from strings", function() { var template = twig({data: '{{ test|trim }}'}); template.render({ test: '\r\n Test\n ' }).should.equal("Test"); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|trim }}' }); test_template.render().should.equal("" ); }); it("should not autoescape", function() { var template = twig({data: '{{ test|trim }}'}); template.render({ test: '\r\n <a href="">Test</a>\n ' }).should.equal("<a href=\"\">Test</a>"); }); }); describe("number_format ->", function() { it("should round to nearest integer if no parameters", function() { var template = twig({data: '{{ 1234.56|number_format }}'}); template.render().should.equal("1,235"); }); it("should have customizable precision", function() { var template = twig({data: '{{ 1234.567890123|number_format(4) }}'}); template.render().should.equal("1,234.5679"); }); it("should have a customizable decimal seperator", function() { var template = twig({data: '{{ 1234.567890123|number_format(2,",") }}'}); template.render().should.equal("1,234,57"); }); it("should have a customizable thousands seperator", function() { var template = twig({data: '{{ 1234.5678|number_format(2,","," ") }}'}); template.render().should.equal("1 234,57"); }); it("should handle blank seperators", function() { var template = twig({data: '{{ 1234.5678|number_format(2,"","") }}'}); template.render().should.equal("123457"); }); it("should handle undefined", function() { var test_template = twig({data: '{{ undef|number_format }}' }); test_template.render().should.equal("0"); }); }); describe("slice ->", function() { it("should slice a string", function() { var test_template = twig({data: "{{ '12345'|slice(1, 2) }}" }); test_template.render().should.equal("23"); }); it("should slice a string to the end", function() { var test_template = twig({data: "{{ '12345'|slice(2) }}" }); test_template.render().should.equal("345"); }); it("should slice a string from the start", function() { var test_template = twig({data: "{{ '12345'|slice(null, 2) }}" }); test_template.render().should.equal("12"); }); it("should slice a string from a negative offset", function() { var test_template = twig({data: "{{ '12345'|slice(-2, 1) }}" }); test_template.render().should.equal("4"); }); it("should slice a string from a negative offset to end of string", function() { var test_template = twig({data: "{{ '12345'|slice(-2) }}" }); test_template.render().should.equal("45"); }); it("should slice an array", function() { var test_template = twig({data: "{{ [1, 2, 3, 4, 5]|slice(1, 2)|join(',') }}" }); test_template.render().should.equal("2,3"); }); it("should slice an array to the end", function() { var test_template = twig({data: "{{ [1, 2, 3, 4, 5]|slice(2)|join(',') }}" }); test_template.render().should.equal("3,4,5"); }); it("should slice an array from the start", function() { var test_template = twig({data: "{{ [1, 2, 3, 4, 5]|slice(null, 2)|join(',') }}" }); test_template.render().should.equal("1,2"); }); it("should slice an array from a negative offset", function() { var test_template = twig({data: "{{ [1, 2, 3, 4, 5]|slice(-2, 1)|join(',') }}" }); test_template.render().should.equal("4"); }); it("should slice an array from a negative offset to the end of the array", function() { var test_template = twig({data: "{{ [1, 2, 3, 4, 5]|slice(-4)|join(',') }}" }); test_template.render().should.equal("2,3,4,5"); }); }); describe('abs ->', function () { it('should convert negative numbers to its absolute value', function () { var test_template = twig({data: "{{ '-7.365'|abs }}"}); test_template.render().should.equal("7.365"); }); it('should not alter absolute numbers', function () { var test_template = twig({data: "{{ 95|abs }}"}); test_template.render().should.equal("95"); }); }); describe('first ->', function () {'' it('should return first item in array', function () { var test_template = twig({data: "{{ ['a', 'b', 'c', 'd']|first }}"}); test_template.render().should.equal("a"); }); it('should return first member of object', function () { var test_template = twig({data: "{{ { item1: 'a', item2: 'b', item3: 'c', item4: 'd'}|first }}"}); test_template.render().should.equal("a"); }); it('should not fail when passed empty obj, arr or str', function () { var test_template = twig({data: "{{ {}|first }}"}); test_template.render().should.equal(""); var test_template = twig({data: "{{ []|first }}"}); test_template.render().should.equal(""); var test_template = twig({data: "{{ myemptystr|first }}"}); test_template.render({myemptystr: ""}).should.equal(""); }); it('should return first character in string', function () { var test_template = twig({data: "{{ 'abcde'|first }}"}); test_template.render().should.equal("a"); }); }); describe('split ->', function () { it('should split string with a separator', function () { var test_template = twig({data: "{{ 'one-two-three'|split('-') }}"}); test_template.render().should.equal("one,two,three"); }); it('should split string with a separator and positive limit', function () { var test_template = twig({data: "{{ 'one-two-three-four-five'|split('-', 3) }}"}); test_template.render().should.equal("one,two,three-four-five"); }); it('should split string with a separator and negative limit', function () { var test_template = twig({data: "{{ 'one-two-three-four-five'|split('-', -2) }}"}); test_template.render().should.equal("one,two,three"); }); it('should split with empty separator', function () { var test_template = twig({data: "{{ '123'|split('') }}"}); test_template.render().should.equal("1,2,3"); }); it('should split with empty separator and limit', function () { var test_template = twig({data: "{{ 'aabbcc'|split('', 2) }}"}); test_template.render().should.equal("aa,bb,cc"); }); }); describe('batch ->', function () { it('should work with arrays that require filling (with fill specified)', function () { var test_template = twig({data: "{{ ['a', 'b', 'c', 'd', 'e', 'f', 'g']|batch(3, 'x') }}"}); test_template.render().should.equal("a,b,c,d,e,f,g,x,x"); }); it('should work with arrays that require filling (without fill specified)', function () { var test_template = twig({data: "{{ ['a', 'b', 'c', 'd', 'e', 'f', 'g']|batch(3) }}"}); test_template.render().should.equal("a,b,c,d,e,f,g"); }); it('should work with arrays that do not require filling (with fill specified)', function () { var test_template = twig({data: "{{ ['a', 'b', 'c', 'd', 'e', 'f']|batch(3, 'x') }}"}); test_template.render().should.equal("a,b,c,d,e,f"); }); it('should work with arrays that do not require filling (without fill specified)', function () { var test_template = twig({data: "{{ ['a', 'b', 'c', 'd', 'e', 'f']|batch(3) }}"}); test_template.render().should.equal("a,b,c,d,e,f"); }); it('should return an empty result for an empty array', function () { var test_template = twig({data: "{{ []|batch(3, 'x') }}"}); test_template.render().should.equal(""); }); }); describe('last ->', function () { it('should return last character in string', function () { var test_template = twig({data: "{{ 'abcd'|last }}"}); test_template.render().should.equal("d"); }); it('should return last item in array', function () { var test_template = twig({data: "{{ ['a', 'b', 'c', 'd']|last }}"}); test_template.render().should.equal("d"); }); it('should return last item in a sorted object', function () { var test_template = twig({data: "{{ {'m':1, 'z':5, 'a':3}|sort|last }}" }); test_template.render().should.equal("5"); }); }); describe('raw ->', function () { it('should output the raw value if autoescape is on', function () { var template = twig({ autoescape: true, data: '{{ value|raw }}' }); template.render({ value: "<test>&</test>" }).should.equal('<test>&</test>'); }); it('should output the raw value if autoescape is off', function () { var template = twig({ autoescape: false, data: '{{ value|raw }}' }); template.render({ value: "<test>&</test>" }).should.equal('<test>&</test>'); }); }); describe('round ->', function () { it('should round up (common)', function () { var test_template = twig({data: "{{ 2.7|round }}"}); test_template.render().should.equal("3"); }); it('should round down (common)', function () { var test_template = twig({data: "{{ 2.1|round }}"}); test_template.render().should.equal("2"); }); it('should truncate input when input decimal places exceeds precision (floor)', function () { var test_template = twig({data: "{{ 2.1234|round(3, 'floor') }}" }); test_template.render().should.equal("2.123"); }); it('should round up (ceil)', function () { var test_template = twig({data: "{{ 2.1|round(0, 'ceil') }}" }); test_template.render().should.equal("3"); }); it('should truncate precision when a negative precision is passed (common)', function () { var test_template = twig({data: "{{ 21.3|round(-1)}}" }); test_template.render().should.equal("20"); }); it('should round up and truncate precision when a negative precision is passed (ceil)', function () { var test_template = twig({data: "{{ 21.3|round(-1, 'ceil')}}" }); test_template.render().should.equal("30"); }); it('should round down and truncate precision when a negative precision is passed (floor)', function () { var test_template = twig({data: "{{ 21.3|round(-1, 'ceil')}}" }); test_template.render().should.equal("30"); }); }); it("should chain", function() { var test_template = twig({data: '{{ ["a", "b", "c"]|keys|reverse }}' }); test_template.render().should.equal("2,1,0"); }); });
""" Módulo que representa um entidade no Movidesk (Tickets, Persons ou Services). Exemplo de uso. >>> from pyvidesk.tickets import Tickets >>> tickets = Tickets(token="my_token") >>> ticket = ticket.get_by_id(3) >>> print(ticket) ... <Model for Ticket(id=3)> >>> print(ticket.id) ... 3 >>> print(ticket.subject) ... 'Assunto' """ from .api import Api from .config import QUERY_PARAMS from .exceptions import ( PyvideskPropertyNotValidError, PyvideskPropertyWithWrongType, PyvideskWrongKwargError, ) from .model import EmptyModel from .properties import ComplexProperty from .query import Query from .utils import get_property_name class Entity: """Classe que representa uma entidade do Movidesk (Tickets, Persons...)""" def __init__(self, token): """ Args: token (str): O token que permitirá o acesso aos dados do Movidesk. """ base_url = self.BASE_URL + f"?token={token}" self.api = Api(base_url=base_url) @property def query(self): return Query(entity=self) def get_properties(self, **kwargs): # pylint: disable=unused-argument """ Metodo que obtem as propriedades da entidade. Args: kwargs (): Utilizado apenas para adequacao do metodo de mesmo nome da classe ComplexProperty. Returns: properties (dict): Dicionário com as propriedades da entidade. """ properties = dict() for property_name, property_infos in self.VALID_PARAMS.items(): property_class = property_infos["property"] properties[property_name] = property_class( name_=property_name, description_=property_infos["description"], read_only=property_infos["readOnly"], ) return properties def describe(self): """Metodo que descreve a entidade e suas principais propriedades""" def _describe(properties, escape_code=""): """ Funcao que introduz uma recursão na hora de buscarmos todas as propriedades da entity. Args: properties (dict): Dicionário com nome e objeto das propriedades. escape_code (str): Utilizado quando queremos tabular uma propriedade e facilitar a visualização de propriedades complexas. """ for property_name, property_obj in properties.items(): print(escape_code + f"Propriedade: {property_name}") print(escape_code + f"Tipo: {property_obj.alias}") print( escape_code + f"Descrição: {property_obj.get_description()}", ) if isinstance(property_obj, ComplexProperty): _describe( properties=property_obj.get_properties(), escape_code=escape_code + "\t", ) print("\n") print( "\n\n\t\t------------------------------------" f"Descrição da entidade {self.__class__.__name__}" "------------------------------------------------------\n\n" ) _describe(properties=self.get_properties()) print( "\n\n----------------------------------------------------------------------" "--------------------------------------------------------------------------\n\n" ) def get_empty_model(self): return EmptyModel(entity=self) def __getattr__(self, attr): """ Utilizado para requisições mais simples. Não deve ser usado para consulta de propriedades complexas. Exemplo: >>> from pyvidesk.persons import Persons >>> persons = Persons(token="my_token") >>> person = persons.get_by_id("1", select="businessName") >>> print(person) ... <Model for Person(businessName=Murilo Scarpa Sitonio)> Returns: (pyvidesk.model.Model): Se o parametro de filtro for o id, como no exemplo acima. OU (pyvidesk.query.Query): Caso o filtro possa retornar múltiplos valores. Raises: PyvideskPropertyNotValidError: Se a propriedade nao pertencer a entidade. """ try: param = attr.split("get_by_")[1] except IndexError as attr_error: raise AttributeError( f"'{self.__class__.__name__}' object has no attribute '{attr}'" ) from attr_error if param not in self.VALID_PARAMS: raise PyvideskPropertyNotValidError(param=param, class_=self) def wrapper(*args, **kwargs): self._pre_validate_request(param, *args, **kwargs) properties = self.get_properties() param_value = kwargs.pop(param, None) or args[0] query = Query( entity=self, options=_organize_options(options=kwargs), ).filter(properties[param] == param_value) if param in ("id", "codeReferenceAdditional"): return query.first() return query return wrapper def _pre_validate_request(self, property_name, *args, **kwargs): """ Pre validacao da requisicao analisando o tipo dos valores. Args: property_name (str): O nome da propriedade. Raises: PyvideskPropertyWithWrongType: A propriedade tem um tipo de valor diferente do definido na documentacao do Movidesk; PyvideskWrongKwargError: O kwarg usado nao é uma das opcoes da query (select, top, skip...); """ properties = self.get_properties() for arg in args: if not isinstance(arg, properties[property_name].alias): raise PyvideskPropertyWithWrongType( param=property_name, value=arg, correct_type=properties[property_name].alias, ) for key, value in kwargs.items(): try: valid_params = {**properties, **QUERY_PARAMS} try: data_type = valid_params[key].alias except AttributeError: data_type = valid_params[key] except KeyError as wrong_wkarg_error: raise PyvideskWrongKwargError( param=property_name, kwarg=key ) from wrong_wkarg_error if not isinstance(value, data_type): raise PyvideskPropertyWithWrongType( param=key, value=value, correct_type=data_type ) def _organize_options(options): """Funcao que organiza as opcoes da query de __getattr__""" def organize_option_that_can_have_multiple_values(option): if isinstance(option, (tuple, list)): return [get_property_name(prop) for prop in option] return [get_property_name(option)] _options = dict() for option, option_value in options.items(): if option in ("top", "skip"): _options["$" + option] = option_value else: _options["$" + option] = organize_option_that_can_have_multiple_values( option_value ) return _options
export default { getAmountInBaseCurrency: (state, getters, rootState) => ({ amount, currency }) => { const fixed = rootState.currencies.base === 'RUB' ? 0 : 2 const baseValue = (amount / rootState.currencies.rates[currency]).toFixed(fixed) return Number(baseValue) } }
/* */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif float x; int y; int main (int argc, char * argv[]) { #ifdef _OPENMP omp_set_num_threads(4); #endif x=1.0; y=1; #pragma omp parallel private(x) { printf("x=%f, y=%d\n",x,y); } return 0; }
/* File: universal_memory_output_stream_test.h; Copyright and License: see below */ #ifndef UNIVERSAL_MEMORY_OUTPUT_STREAM_TEST_H #define UNIVERSAL_MEMORY_OUTPUT_STREAM_TEST_H /*! * \file * \brief UNITTEST for universal_memory_output_stream */ #include "test_suite.h" test_suite_t universal_memory_output_stream_test_get_list(void); #endif /* UNIVERSAL_MEMORY_OUTPUT_STREAM_TEST_H */ /* * Copyright 2020-2021 Andreas Warnke * * 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 file is derived from the MicroPython project, http://micropython.org/ * * Copyright (c) 2018, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence * v1.0 document supplied with this file, or available at: * https://www.pycom.io/opensource/licensing * * This file contains code under the following copyright and licensing notices. * The code has been changed but otherwise retained. */ /* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech Description: Generic GPIO driver implementation Comment: Relies on the specific board GPIO implementation as well as on IO expander driver implementation if one is available on the target board. License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: Miguel Luis and Gregory Cristian */ #ifndef __LORA_GPIO_H__ #define __LORA_GPIO_H__ #include "py/obj.h" #include "esp_heap_caps.h" #include "sdkconfig.h" #include "esp_system.h" #include "esp_spi_flash.h" #include "nvs_flash.h" #include "esp_event.h" #include "driver/gpio.h" #include "machpin.h" #include "pinName-board.h" /*! * Board GPIO pin names */ typedef enum { MCU_PINS, // Not connected NC = (int)0xFFFFFFFF }PinNames; /*! * Operation Mode for the GPIO */ typedef enum { PIN_INPUT = GPIO_MODE_INPUT, PIN_OUTPUT = GPIO_MODE_OUTPUT }PinModes; /*! * Add a pull-up, a pull-down or nothing on the GPIO line */ typedef enum { PIN_NO_PULL = MACHPIN_PULL_NONE, PIN_PULL_UP = MACHPIN_PULL_UP, PIN_PULL_DOWN = MACHPIN_PULL_DOWN }PinTypes; /*! * Define the GPIO as Push-pull type or Open Drain */ typedef enum { PIN_PUSH_PULL = 0, PIN_OPEN_DRAIN }PinConfigs; /*! * Define the GPIO IRQ on a rising, falling or both edges */ typedef enum { NO_IRQ = 0xFF, IRQ_RISING_EDGE = GPIO_INTR_POSEDGE, IRQ_FALLING_EDGE = GPIO_INTR_NEGEDGE, IRQ_RISING_FALLING_EDGE = GPIO_INTR_ANYEDGE }IrqModes; /*! * Define the IRQ priority on the GPIO */ typedef enum { IRQ_VERY_LOW_PRIORITY = 0, IRQ_LOW_PRIORITY, IRQ_MEDIUM_PRIORITY, IRQ_HIGH_PRIORITY, IRQ_VERY_HIGH_PRIORITY }IrqPriorities; /*! * Structure for the GPIO */ typedef struct { pin_obj_t *pin_obj; } Gpio_t; /*! * GPIO IRQ handler function prototype */ typedef void( GpioIrqHandler )( void ); /*! * \brief Initializes the given GPIO object * * \param [IN] obj Pointer to the GPIO object * \param [IN] pin Pin name ( please look in pinName-board.h file ) * \param [IN] mode Pin mode [PIN_INPUT, PIN_OUTPUT, * PIN_ALTERNATE_FCT, PIN_ANALOGIC] * \param [IN] config Pin config [PIN_PUSH_PULL, PIN_OPEN_DRAIN] * \param [IN] type Pin type [PIN_NO_PULL, PIN_PULL_UP, PIN_PULL_DOWN] * \param [IN] value Default output value at initialisation */ void GpioInit( Gpio_t *obj, PinNames pin, PinModes mode, PinConfigs config, PinTypes type, uint32_t value ); /*! * \brief GPIO IRQ Initialization * * \param [IN] obj Pointer to the GPIO object * \param [IN] irqMode IRQ mode [NO_IRQ, IRQ_RISING_EDGE, * IRQ_FALLING_EDGE, IRQ_RISING_FALLING_EDGE] * \param [IN] irqPriority IRQ priority [IRQ_VERY_LOW_PRIORITY, IRQ_LOW_PRIORITY * IRQ_MEDIUM_PRIORITY, IRQ_HIGH_PRIORITY * IRQ_VERY_HIGH_PRIORITY] * \param [IN] irqHandler Callback function pointer */ void GpioSetInterrupt( Gpio_t *obj, IrqModes irqMode, IrqPriorities irqPriority, GpioIrqHandler *irqHandler ); /*! * \brief Removes the interrupt from the object * * \param [IN] obj Pointer to the GPIO object */ void GpioRemoveInterrupt( Gpio_t *obj ); /*! * \brief Writes the given value to the GPIO output * * \param [IN] obj Pointer to the GPIO object * \param [IN] value New GPIO output value */ void GpioWrite( Gpio_t *obj, uint32_t value ); #endif // __LORA_GPIO_H__
# -*- coding: utf-8 -*- """The Arakawa-C Grid""" import numpy as np class Arakawa1D(object): def __init__(self, nx, Lx): super(Arakawa1D, self).__init__() self.nx = nx self.Lx = Lx # Arakawa-C grid # +-------+ * (nx) phi points at grid centres # u phi u * (nx+1) u points on vertical edges (u[0] and u[nx] are boundary values) # +-------+ self._u = np.zeros((nx+3), dtype=np.float) self._phi = np.zeros((nx+2), dtype=np.float) self.dx = dx = float(Lx) / nx # positions of the nodes self.ux = (-Lx/2 + np.arange(nx+1)*dx) self.phix = (-Lx/2 + dx/2.0 + np.arange(nx)*dx) self.shape = self.phi.shape self._shape = self._phi.shape self.true_slice = [slice(1,-1)]*len(self.shape) # slice of state arrays w/out BCs # define u, v and h properties to return state without the boundaries @property def u(self): return self._u[1:-1] @property def phi(self): return self._phi[1:-1] @property def state(self): return np.array([self.u, self.phi]) @state.setter def state(self, value): u, phi = value self.u[:] = u self.phi[:] = phi # Define finite-difference methods on the grid def diffx(self, psi): """Calculate ∂/∂x[psi] over a single grid square. i.e. d/dx(psi)[i,j] = (psi[i+1/2, j] - psi[i-1/2, j]) / dx The derivative is returned at x points at the midpoint between x points of the input array.""" return (psi[1:] - psi[:-1]) / self.dx def diff2x(self, psi): """Calculate ∂2/∂x2[psi] over a single grid square. i.e. d2/dx2(psi)[i,j] = (psi[i+1, j] - psi[i, j] + psi[i-1, j]) / dx^2 The derivative is returned at the same x points as the x points of the input array, with dimension (nx-2).""" return (psi[:-2] - 2*psi[1:-1] + psi[2:]) / self.dx**2 del2 = diff2x def x_average(self, psi): """Average adjacent values in the x dimension. If psi has shape (nx), returns an array of shape (nx-1).""" return 0.5*(psi[:-1] + psi[1:]) def advect(self, field): """Calculates the conservation of the advected tracer by the fluid flow. ∂[q]/∂t + ∇ . (uq) = 0 Returns the divergence term i.e. ∇.(uq) """ q_at_u = self.x_average(field) # (nx+1) return self.diffx(q_at_u * self.u) # (nx) def _apply_boundary_conditions(self): # left and right-hand boundary values the same for u # u[0] = u[nx] # copy u[dx] to u[nx+dx] # and u[nx-dx] to u[-dx] # to simulate periodic continuity self._u[0] = self._u[-3] self._u[1] = self._u[-2] self._u[-1] = self._u[2] # phi points are not on boundary # so just simulate periodic continuity self._phi[0] = self._phi[-2] self._phi[-1] = self._phi[1] def apply_boundary_conditions_to(self, field): # periodic boundary in the x-direction field[0] = field[-2] field[-1] = field[1] class ArakawaCGrid(object): def __init__(self, nx, ny, Lx, Ly): super(ArakawaCGrid, self).__init__() self.nx = nx self.ny = ny self.Lx = Lx self.Ly = Ly self.true_slice = [slice(1,-1)]*2 # slice of state arrays w/out BCs # Arakawa-C grid # +-- v --+ # | | * (nx, ny) phi points at grid centres # u phi u * (nx+1, ny) u points on vertical edges (u[0] and u[nx] are boundary values) # | | * (nx, ny+1) v points on horizontal edges # +-- v --+ self._u = np.zeros((nx+3, ny+2), dtype=np.float) self._v = np.zeros((nx+2, ny+3), dtype=np.float) self._phi = np.zeros((nx+2, ny+2), dtype=np.float) self.dx = dx = float(Lx) / nx self.dy = dy = float(Ly) / ny # positions of the nodes self.ux = (-Lx/2 + np.arange(nx+1)*dx)[:, np.newaxis] self.vx = (-Lx/2 + dx/2.0 + np.arange(nx)*dx)[:, np.newaxis] self.vy = (-Ly/2 + np.arange(ny+1)*dy)[np.newaxis, :] self.uy = (-Ly/2 + dy/2.0 + np.arange(ny)*dy)[np.newaxis, :] self.phix = self.vx self.phiy = self.uy self.shape = self.phi.shape self._shape = self._phi.shape # define u, v and h properties to return state without the boundaries @property def u(self): return self._u[1:-1, 1:-1] @property def v(self): return self._v[1:-1, 1:-1] @property def phi(self): return self._phi[1:-1, 1:-1] @property def state(self): return np.array([self.u, self.v, self.phi]) @state.setter def state(self, value): u, v, phi = value self.u[:] = u self.v[:] = v self.phi[:] = phi # Define finite-difference methods on the grid def diffx(self, psi): """Calculate ∂/∂x[psi] over a single grid square. i.e. d/dx(psi)[i,j] = (psi[i+1/2, j] - psi[i-1/2, j]) / dx The derivative is returned at x points at the midpoint between x points of the input array.""" return (psi[1:,:] - psi[:-1,:]) / self.dx def diffy(self, psi): """Calculate ∂/∂y[psi] over a single grid square. i.e. d/dy(psi)[i,j] = (psi[i, j+1/2] - psi[i, j-1/2]) / dy The derivative is returned at y points at the midpoint between y points of the input array.""" return (psi[:, 1:] - psi[:,:-1]) / self.dy def del2(self, psi): """Returns the Laplacian of psi.""" return self.diff2x(psi)[:, 1:-1] + self.diff2y(psi)[1:-1, :] def diff2x(self, psi): """Calculate ∂2/∂x2[psi] over a single grid square. i.e. d2/dx2(psi)[i,j] = (psi[i+1, j] - psi[i, j] + psi[i-1, j]) / dx^2 The derivative is returned at the same x points as the x points of the input array, with dimension (nx-2, ny).""" return (psi[:-2, :] - 2*psi[1:-1, :] + psi[2:, :]) / self.dx**2 def diff2y(self, psi): """Calculate ∂2/∂y2[psi] over a single grid square. i.e. d2/dy2(psi)[i,j] = (psi[i, j+1] - psi[i, j] + psi[i, j-1]) / dy^2 The derivative is returned at the same y points as the y points of the input array, with dimension (nx, ny-2).""" return (psi[:, :-2] - 2*psi[:, 1:-1] + psi[:, 2:]) / self.dy**2 def centre_average(self, psi): """Returns the four-point average at the centres between grid points. If psi has shape (nx, ny), returns an array of shape (nx-1, ny-1).""" return 0.25*(psi[:-1,:-1] + psi[:-1,1:] + psi[1:, :-1] + psi[1:,1:]) def y_average(self, psi): """Average adjacent values in the y dimension. If psi has shape (nx, ny), returns an array of shape (nx, ny-1).""" return 0.5*(psi[:,:-1] + psi[:,1:]) def x_average(self, psi): """Average adjacent values in the x dimension. If psi has shape (nx, ny), returns an array of shape (nx-1, ny).""" return 0.5*(psi[:-1,:] + psi[1:,:]) def divergence(self): """Returns the horizontal divergence at h points.""" return self.diffx(self.u) + self.diffy(self.v) def vorticity(self): """Returns the vorticity at grid corners.""" return self.diffy(self.u)[1:-1, :] - self.diffx(self.v)[:, 1:-1] def uvath(self): """Calculate the value of u at h points (cell centres).""" ubar = self.x_average(self.u) # (nx, ny) vbar = self.y_average(self.v) # (nx, ny) return ubar, vbar def uvatuv(self): """Calculate the value of u at v and v at u.""" ubar = self.centre_average(self._u)[1:-1, :] # (nx, ny+1) vbar = self.centre_average(self._v)[:, 1:-1] # (nx+1, ny) return ubar, vbar def _fix_boundary_corners(self, field): # fix corners to be average of neighbours field[0, 0] = 0.5*(field[1, 0] + field[0, 1]) field[-1, 0] = 0.5*(field[-2, 0] + field[-1, 1]) field[0, -1] = 0.5*(field[1, -1] + field[0, -2]) field[-1, -1] = 0.5*(field[-1, -2] + field[-2, -1]) def advect(self, field): """Calculates the conservation of the advected tracer by the fluid flow. ∂[q]/∂t + ∇ . (uq) = 0 Returns the divergence term i.e. ∇.(uq) """ q_at_u = self.x_average(field)[:, 1:-1] # (nx+1, ny) q_at_v = self.y_average(field)[1:-1, :] # (nx, ny+1) return self.diffx(q_at_u * self.u) + self.diffy(q_at_v * self.v) # (nx, ny) # def apply_boundary_conditions(self): # """Set the boundary values of the u v and phi fields. # This should be implemented by a subclass.""" # raise NotImplemented # def apply_boundary_conditions_to(self, field): # """Set the boundary values of a given field. # This should be implemented by a subclass.""" # raise NotImplemented class PeriodicBoundaries: """Peridoic domain in the x-direction. This is a mixin class for the ArakawaCGrid to produce a grid with periodic boundaries in the x-direction. """ def apply_boundary_conditions(self): # left and right-hand boundary values the same for u # u[0] = u[nx] # copy u[dx] to u[nx+dx] # and u[nx-dx] to u[-dx] # to simulate periodic continuity self._u[0, :] = self._u[-3, :] self._u[1, :] = self._u[-2, :] self._u[-1, :] = self._u[2, :] # other fields are not on boundary # so just simulate periodic continuity self._v[0, :] = self._v[-2, :] self._v[-1, :] = self._v[1, :] self._phi[0, :] = self._phi[-2, :] self._phi[-1, :] = self._phi[1, :] # top and bottom boundaries: zero derivative fields = self._u, self._v, self._phi for field in fields: field[:, 0] = field[:, 1] field[:, -1] = field[:, -2] self._fix_boundary_corners(field) def apply_boundary_conditions_to(self, field): # periodic boundary in the x-direction field[0, :] = field[-2, :] field[-1, :] = field[1, :] # top and bottom boundaries: zero derivative field[:, 0] = field[:, 1] field[:, -1] = field[:, -2] self._fix_boundary_corners(field) class WallBoundaries: """Add walls to the domain at x=0 and x=Lx. This is a mixin class for the ArakawaCGrid to produce a grid with walled boundaries in the x-direction. """ def apply_boundary_conditions(self): # No flow through the boundary at x=0 self._u[0, :] = 0 self._u[1, :] = 0 self._u[-1, :] = 0 self._u[-2, :] = 0 # free-slip of other variables: zero-derivative self._v[0, :] = self._v[1, :] self._v[-1, :] = self._v[-2, :] self._phi[0, :] = self._phi[1, :] self._phi[-1, :] = self._phi[-2, :] fields = self._u, self._v, self._phi # top and bottom boundaries: zero deriv for field in fields: field[:, 0] = field[:, 1] field[:, -1] = field[:, -2] self._fix_boundary_corners(field) def apply_boundary_conditions_to(self, field): # free slip on left and right boundares: zero derivative field[0, :] = field[1, :] field[-1, :] = field[-2, :] # top and bottom boundaries: zero deriv and damping field[:, 0] = field[:, 1] field[:, -1] = field[:, -2] self._fix_boundary_corners(field)
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import 'ngreact'; import { InfluencersCell } from './influencers_cell'; import { uiModules } from 'ui/modules'; const module = uiModules.get('apps/ml', ['react']); module.directive('mlInfluencersCell', function (reactDirective) { return reactDirective(InfluencersCell, undefined, { restrict: 'E' }); });
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from torch.autograd import Variable from fairseq import data, dictionary, utils from fairseq.models import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqModel, ) def dummy_dictionary(vocab_size, prefix='token_'): d = dictionary.Dictionary() for i in range(vocab_size): token = prefix + str(i) d.add_symbol(token) d.finalize() return d def dummy_dataloader( samples, padding_idx=1, eos_idx=2, batch_size=None, ): if batch_size is None: batch_size = len(samples) # add any missing data to samples for i, sample in enumerate(samples): if 'id' not in sample: sample['id'] = i # create dataloader dataset = TestDataset(samples) dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, collate_fn=( lambda samples: data.LanguagePairDataset.collate( samples, padding_idx, eos_idx, ) ), ) return iter(dataloader) class TestDataset(torch.utils.data.Dataset): def __init__(self, data): super().__init__() self.data = data def __getitem__(self, index): return self.data[index] def __len__(self): return len(self.data) class TestModel(FairseqModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @classmethod def build_model(cls, args, src_dict, dst_dict): encoder = TestEncoder(args, src_dict) decoder = TestIncrementalDecoder(args, dst_dict) return cls(encoder, decoder) class TestEncoder(FairseqEncoder): def __init__(self, args, dictionary): super().__init__(dictionary) self.args = args def forward(self, src_tokens, src_lengths): return src_tokens class TestIncrementalDecoder(FairseqIncrementalDecoder): def __init__(self, args, dictionary): super().__init__(dictionary) assert hasattr(args, 'beam_probs') or hasattr(args, 'probs') args.max_decoder_positions = getattr(args, 'max_decoder_positions', 100) self.args = args def forward(self, prev_output_tokens, encoder_out, incremental_state=None): if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] bbsz = prev_output_tokens.size(0) vocab = len(self.dictionary) src_len = encoder_out.size(1) tgt_len = prev_output_tokens.size(1) # determine number of steps if incremental_state is not None: # cache step number step = utils.get_incremental_state(self, incremental_state, 'step') if step is None: step = 0 utils.set_incremental_state(self, incremental_state, 'step', step + 1) steps = [step] else: steps = list(range(tgt_len)) # define output in terms of raw probs if hasattr(self.args, 'probs'): assert self.args.probs.dim() == 3, \ 'expected probs to have size bsz*steps*vocab' probs = self.args.probs.index_select(1, torch.LongTensor(steps)) else: probs = torch.FloatTensor(bbsz, len(steps), vocab).zero_() for i, step in enumerate(steps): # args.beam_probs gives the probability for every vocab element, # starting with eos, then unknown, and then the rest of the vocab if step < len(self.args.beam_probs): probs[:, i, self.dictionary.eos():] = self.args.beam_probs[step] else: probs[:, i, self.dictionary.eos()] = 1.0 # random attention attn = torch.rand(bbsz, src_len, tgt_len) return Variable(probs), Variable(attn) def get_normalized_probs(self, net_output, log_probs): # the decoder returns probabilities directly probs = net_output[0] if log_probs: return probs.log() else: return probs def max_positions(self): return self.args.max_decoder_positions
# Run this with: # python setup.py install --install-lib=. from distutils.core import setup, Extension from rdkit import RDConfig # force the use of g++ please from distutils import sysconfig save_init_posix = sysconfig._init_posix def my_init_posix(): print('my_init_posix: changing gcc to g++') save_init_posix() g = sysconfig.get_config_vars() g['CC'] = 'g++' g['LDSHARED'] = 'g++ -shared' g['PY_CFLAGS'] = g['PY_CFLAGS'].replace('-O3', '') sysconfig._init_posix = my_init_posix destDir = RDConfig.RDCodeDir extDir = RDConfig.RDBaseDir + "/External" # this is how things are done with BPLv2 boostInc = '-isystem%s' % (extDir + "/boost_1_29_0") incDirs = [] # FIX: there's gotta be a better way of doing this pyLibDir = '/usr/lib/python2.2/config' boostLibDir = extDir + "/boost_1_29_0/libs/python/build/bin/libboost_python.so/gcc/debug/runtime-link-dynamic/shared-linkable-true/" boostLib = "boost_python" libDirs = [boostLibDir, pyLibDir] libraries = [boostLib, "python2.2"] # have to include g++ here or we get link errors with boost compileArgs = ['-ftemplate-depth-150', '-DBOOST_PYTHON_DYNAMIC_LIB', boostInc, ] setup(name="python_objs", version="1.0", ext_modules=[Extension( "python_objs", ["python_objs.cpp"], include_dirs=incDirs, library_dirs=libDirs, libraries=libraries, extra_compile_args=compileArgs)])
def pageview( path=None, host_name=None, location=None, title=None, language=None, referrer=None, **extra_data): payload = {'t': 'pageview'} if location: payload['dl'] = location if host_name: payload['dh'] = host_name if path: payload['dp'] = path if title: payload['dt'] = title if referrer: payload['dr'] = referrer if language: payload['ul'] = language payload.update(extra_data) yield payload
import numpy as np import cv2 as cv feature_params = dict( maxCorners = 10, qualityLevel = 0.98, minDistance = 100, blockSize = 8 ) lk_params = dict( winSize = (10,10), maxLevel = 5, criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03), flags = cv.OPTFLOW_LK_GET_MIN_EIGENVALS ) class point: def __init__(self): self.data = [] def add(self, value): self.data.append(value) if len(self.data) >= 6: self.data.pop(0) def getSum(self): sumX = 0; sumY = 0 for i in self.data: sumX += i[0] sumY += i[1] return [sumX, sumY] class SLAM: def __init__(self, lk, fp): self.lk_params = lk; self.feature_params = fp self.cap = cv.VideoCapture(0) self.cap.set(cv.CAP_PROP_EXPOSURE, -3) self.h = int(self.cap.get(cv.CAP_PROP_FRAME_HEIGHT)) self.w = int(self.cap.get(cv.CAP_PROP_FRAME_WIDTH)) self.mask = np.zeros((self.h,self.w,1), np.uint8); self.mask[:] = 255 self.clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) self.diff_frame = np.zeros((self.h,self.w,3), np.uint8) self.frame = None self.getFrame() self.p0 = cv.goodFeaturesToTrack(self.frame, mask = self.mask, **self.feature_params) self.st = np.array([[0] for i in range(len(self.p0))]) self.trackMemory = np.array([point() for i in range(len(self.p0))]) def getFrame(self): ret, frame = self.cap.read() self.frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) self.frame = cv.bilateralFilter(self.frame, 9, 75, 75) #self.frame = self.clahe.apply(self.frame) def getFeatures(self): new = cv.goodFeaturesToTrack(self.frame, mask = self.mask, **self.feature_params) if np.any(new != None): self.p0 = np.concatenate((self.p0, new), axis=0) self.st = np.concatenate((self.st, [[0] for i in range(len(new))]), axis=0) self.trackMemory = np.concatenate((self.trackMemory, [point() for i in range(len(new))]), axis=0) return len(new) return 0 def setMask(self): self.mask[:] = 255 for x in self.p0: a,b = x.ravel() self.mask = cv.circle(self.mask,(a,b), self.feature_params["minDistance"], (0,0,0), -1) def track(self, st, new): old = self.p0[st != 0] diff = np.subtract(old, new)#.reshape(-1,1,2) for i in range(len(diff)): self.trackMemory[i].add([diff[i][0], diff[i][1]]) delta = [] for i in range(len(self.st)): if self.st[i][0] >= 5: sx, sy = self.trackMemory[i].getSum() delta.append([new[i][0], new[i][1], sx, sy]) return delta def iterate(self): old_frame = self.frame.copy() self.getFrame() if np.any(old_frame == None): return p1, st, err = cv.calcOpticalFlowPyrLK(old_frame, self.frame, self.p0, None, **self.lk_params) self.st = np.add(self.st, st) self.st = self.st[st != 0].reshape(-1,1) self.trackMemory = self.trackMemory[st.reshape(-1) != 0] good_new = p1[st != 0] diff = self.track(st, good_new) self.p0 = good_new.reshape(-1,1,2) self.setMask() features_number = self.getFeatures() vframe = cv.cvtColor(self.frame, cv.COLOR_GRAY2BGR) for a,b in good_new: vframe = cv.circle(vframe,(a,b),5,(255,0,0),-1) cv.imshow('frame',vframe) self.diff_frame[:] = (0,0,0) for x,y,dx,dy in diff: delta = np.sqrt( dx**2 + dy**2 ) d_color = int(delta/4 * 255/2) self.diff_frame = cv.circle(self.diff_frame,(x,y),3,(d_color,0,0),-1) cv.imshow('color',self.diff_frame) S = SLAM(lk_params, feature_params) while True: S.iterate() k = cv.waitKey(30) & 0xff if k == 27: break
import cv2 import gym import numpy as np from brawl_stars_gym.try_brawler import TryBrawler class RandomAgent(object): """The world's simplest agent!""" def __init__(self, action_space): self.action_space = action_space def act(self, observation, reward, done): return self.action_space.sample() env = gym.make( "BrawlStarsTryBrawler-v0", ldplayer_executable_filepath=r"D:\\LDPlayer\\LDPlayer4.0\\dnplayer.exe", # fps=10, ) agent = RandomAgent(env.action_space) episode_count = 100 reward = 0 done = False for i in range(episode_count): ob = env.reset() while True: action = agent.act(ob, reward, done) ob, reward, done, _ = env.step(action) if done: break # Note there's no env.render() here. But the environment still can open window and # render if asked by env.monitor: it calls env.render('rgb_array') to record video. # Video is not recorded every episode, see capped_cubic_video_schedule for details. # env.render() # Close the env and write monitor result info to disk env.close()
const $ = (str) => { return document.querySelector(str); }; const setRotate = (dom, rotate) => { dom.style.webkitTransform = "rotate(" + rotate + "deg)"; }; let roateBox = $("#rotateBox"); // 旋转按钮代码 // 获取方形中心坐标点即坐标轴原点 let centerPointX = roateBox.getBoundingClientRect().left + roateBox.getBoundingClientRect().width / 2; let centerPointY = roateBox.getBoundingClientRect().top + roateBox.getBoundingClientRect().height / 2; // 鼠标移动事件 const moveEvent = (e) => { let X = e.clientX; let Y = e.clientY; e.stopPropagation(); let oY = Math.abs(Y - centerPointY); let oX = Math.abs(X - centerPointX); // 避免水平和垂直位置的就相当于和坐标轴相交的时候设置除数为0或者不知道为360度还是180度 oY === 0 && (oY = 0.01); oX === 0 && (oX = 0.01); let degEnd = (Math.atan(oX / oY) / (2 * Math.PI)) * 360; // 第一象限 if (X > centerPointX && Y < centerPointY) { console.log("第一象限"); setRotate(roateBox, degEnd); } // 第二象限 if (X > centerPointX && Y > centerPointY) { console.log("第二象限"); setRotate(roateBox, 180 - degEnd); } // 第三象限 if (X < centerPointX && Y > centerPointY) { console.log("第三象限"); setRotate(roateBox, degEnd + 180); } // 第四象限 if (X < centerPointX && Y < centerPointY) { console.log("第四象限"); setRotate(roateBox, 360 - degEnd); } }; $("#rotateBox .point").addEventListener( "mousedown", function (e) { e.stopPropagation(); document.addEventListener("mousemove", moveEvent, false); }, false ); document.addEventListener( "mouseup", function () { document.removeEventListener("mousemove", moveEvent); }, false ); // 释放文档按下事件 document.onmouseup = function () { document.onmousemove = null; }; // 右下角拉伸点 let startX, startY, owidth, oheight, oleft, otop; const MAXWIDTH = 50; // 限制最大宽度 const MAXHEIGHT = 50; // 限制最大高度 $("#rotateBox .rb-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveX = e.clientX; let moveY = e.clientY; let mWidth = moveX - startX; let mHeight = moveY - startY; console.log(mWidth, mHeight); that.parentNode.style.left = oleft + "px"; that.parentNode.style.width = (owidth + mWidth > MAXWIDTH ? owidth + mWidth : MAXWIDTH) + "px"; that.parentNode.style.height = (oheight + mHeight > MAXHEIGHT ? oheight + mHeight : MAXHEIGHT) + "px"; }; }, false ); // 左下角拉伸点 $("#rotateBox .lb-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveX = e.clientX; let moveY = e.clientY; let mWidth = startX - moveX; let mHeight = moveY - startY; console.log(mWidth, mHeight); that.parentNode.style.left = moveX + "px"; that.parentNode.style.width = (owidth + mWidth > MAXWIDTH ? owidth + mWidth : MAXWIDTH) + "px"; that.parentNode.style.height = (oheight + mHeight > MAXHEIGHT ? oheight + mHeight : MAXHEIGHT) + "px"; }; }, false ); // 左上角拉伸点 $("#rotateBox .lt-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; otop = this.parentNode.getBoundingClientRect().top; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveX = e.clientX; let moveY = e.clientY; let mWidth = startX - moveX; let mHeight = startY - moveY; console.log(mWidth, mHeight); that.parentNode.style.left = moveX + "px"; that.parentNode.style.top = moveY + "px"; that.parentNode.style.width = (owidth + mWidth > MAXWIDTH ? owidth + mWidth : MAXWIDTH) + "px"; that.parentNode.style.height = (oheight + mHeight > MAXHEIGHT ? oheight + mHeight : MAXHEIGHT) + "px"; }; }, false ); // 右上角拉伸点 $("#rotateBox .rt-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; otop = this.parentNode.getBoundingClientRect().top; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveX = e.clientX; let moveY = e.clientY; let mWidth = moveX - startX; let mHeight = startY - moveY; console.log(mWidth, mHeight); that.parentNode.style.left = oleft + "px"; that.parentNode.style.top = moveY + "px"; that.parentNode.style.width = (owidth + mWidth > MAXWIDTH ? owidth + mWidth : MAXWIDTH) + "px"; that.parentNode.style.height = (oheight + mHeight > MAXHEIGHT ? oheight + mHeight : MAXHEIGHT) + "px"; }; }, false ); // 中上拉伸点 $("#rotateBox .ct-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; otop = this.parentNode.getBoundingClientRect().top; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveY = e.clientY; let mHeight = startY - moveY; that.parentNode.style.top = moveY + "px"; that.parentNode.style.height = (oheight + mHeight > MAXHEIGHT ? oheight + mHeight : MAXHEIGHT) + "px"; }; }, false ); // 中下拉伸点 $("#rotateBox .cb-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; otop = this.parentNode.getBoundingClientRect().top; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveY = e.clientY; let mHeight = moveY - startY; that.parentNode.style.height = (oheight + mHeight > MAXHEIGHT ? oheight + mHeight : MAXHEIGHT) + "px"; }; }, false ); // 左中拉伸点 $("#rotateBox .cl-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; otop = this.parentNode.getBoundingClientRect().top; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveY = e.clientY; let moveX = e.clientX; let mWidth = startX - moveX; that.parentNode.style.left = moveX + "px"; that.parentNode.style.width = (owidth + mWidth > MAXWIDTH ? owidth + mWidth : MAXWIDTH) + "px"; }; }, false ); // 右中拉伸点 $("#rotateBox .cr-point").addEventListener( "mousedown", function (e) { let that = this; startX = e.clientX; startY = e.clientY; oleft = this.parentNode.getBoundingClientRect().left; otop = this.parentNode.getBoundingClientRect().top; owidth = this.parentNode.getBoundingClientRect().width; oheight = this.parentNode.getBoundingClientRect().height; e.stopPropagation(); document.onmousemove = function (e) { let moveY = e.clientY; let moveX = e.clientX; let mWidth = moveX - startX; that.parentNode.style.width = (owidth + mWidth > MAXWIDTH ? owidth + mWidth : MAXWIDTH) + "px"; }; }, false ); const $Dragble = { dom: "", isMove: false, left: "", top: "", mouseStartX: "", mouseStartY: "", positionType: "", mousemove: function (maxleft, maxtop) { $Dragble.dom.style.top = $Dragble.top + (window.event.pageY - $Dragble.mouseStartY) + "px"; $Dragble.dom.style.left = $Dragble.left + (window.event.pageX - $Dragble.mouseStartX) + "px"; // 这两行必须要有,为了移动的时候重置中心点的坐标 centerPointX = $Dragble.dom.getBoundingClientRect().left + $Dragble.dom.getBoundingClientRect().width / 2; centerPointY = $Dragble.dom.getBoundingClientRect().top + $Dragble.dom.getBoundingClientRect().height / 2; }, mouseup: function () { document.removeEventListener("mousemove", this.mousemove); }, // 初始化数据 intData: function (dom, type, maxLeft, maxTop) { this.dom = dom; this.isMove = true; this.positionType = type; this.dom.style.position = type; this.mouseStartX = window.event.pageX; this.mouseStartY = window.event.pageY; this.left = Number.parseFloat(this.dom.style.left); this.top = Number.parseFloat(this.dom.style.top); this.dom.style.left ? this.dom.style.left : (this.dom.style.left = 0); this.dom.style.top ? this.dom.style.top : (this.dom.style.top = 0); }, mousedown: function (dom, type, maxLeft, maxTop) { this.intData(dom, type, maxLeft, maxTop); document.addEventListener("mousemove", this.mousemove, false); document.removeEventListener("mouseup", this.mousemove); }, };
//>>built define( "dojox/editor/plugins/nls/ja/TextColor", //begin v1.x content ({ "setButtonText": "設定", "cancelButtonText": "キャンセル" }) //end v1.x content );
var express = require('express'), http = require('http'), path = require('path'), twilio = require('twilio'), tyrion = require('./lib'), pkg = require('./package.json'), config = require('./config'), mongoose = require('mongoose'); //Initialize the MongoDB connection mongoose.connect(config.mongoUrl); //initialize Tyrion from config tyrion.init(); //Express app configuration var app = express(); app.configure(function () { app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); }); app.configure('development', function () { app.use(express.errorHandler()); }); //Print server status app.get('/', function(request, response) { response.type('text/html') response.send('<html><body><h1>Tyrion SMS Chat Server (v.'+pkg.version+')</h1> <p>Text <b>'+config.number+'</b> to subscribe.</p></body></html>'); }); //Handle incoming SMS app.post('/sms', function(request, response) { //Only handle incoming requests from Twilio if (twilio.validateExpressRequest(request, config.authToken)) { //Create TwiML response var resp = new twilio.TwimlResponse(); //Parse and handle the incoming message with tyrion tyrion.parseBody(request.body.Body, request.body.From, function(message) { if (message) resp.sms(message); response.type('text/xml'); response.send(resp.toString()); }); } else { response.status(403); response.send('Forbidden'); } }); //Start express server http.createServer(app).listen(app.get('port'), function () { console.log("Tyrion express.js server listening on port " + app.get('port')); });
import {Box2} from 'three/src/math/Box2'; import {BufferGeometry} from 'three/src/core/BufferGeometry'; import {FileLoader} from 'three/src/loaders/FileLoader'; import {Float32BufferAttribute} from 'three/src/core/BufferAttribute'; import {Loader} from 'three/src/loaders/Loader'; import {Matrix3} from 'three/src/math/Matrix3'; import {Path} from 'three/src/extras/core/Path'; import {Shape} from 'three/src/extras/core/Shape'; import {ShapePath} from 'three/src/extras/core/ShapePath'; import {ShapeUtils} from 'three/src/extras/ShapeUtils'; import {Vector2} from 'three/src/math/Vector2'; import {Vector3} from 'three/src/math/Vector3'; var SVGLoader = function ( manager ) { Loader.call( this, manager ); // Default dots per inch this.defaultDPI = 90; // Accepted units: 'mm', 'cm', 'in', 'pt', 'pc', 'px' this.defaultUnit = 'px'; }; SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: SVGLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.setRequestHeader( scope.requestHeader ); loader.setWithCredentials( scope.withCredentials ); loader.load( url, function ( text ) { try { onLoad( scope.parse( text ) ); } catch ( e ) { if ( onError ) { onError( e ); } else { console.error( e ); } scope.manager.itemError( url ); } }, onProgress, onError ); }, parse: function ( text ) { var scope = this; function parseNode( node, style ) { if ( node.nodeType !== 1 ) return; var transform = getNodeTransform( node ); var traverseChildNodes = true; var path = null; switch ( node.nodeName ) { case 'svg': break; case 'style': parseCSSStylesheet( node ); break; case 'g': style = parseStyle( node, style ); break; case 'path': style = parseStyle( node, style ); if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node ); break; case 'rect': style = parseStyle( node, style ); path = parseRectNode( node ); break; case 'polygon': style = parseStyle( node, style ); path = parsePolygonNode( node ); break; case 'polyline': style = parseStyle( node, style ); path = parsePolylineNode( node ); break; case 'circle': style = parseStyle( node, style ); path = parseCircleNode( node ); break; case 'ellipse': style = parseStyle( node, style ); path = parseEllipseNode( node ); break; case 'line': style = parseStyle( node, style ); path = parseLineNode( node ); break; case 'defs': traverseChildNodes = false; break; case 'use': style = parseStyle( node, style ); var usedNodeId = node.href.baseVal.substring( 1 ); var usedNode = node.viewportElement.getElementById( usedNodeId ); if ( usedNode ) { parseNode( usedNode, style ); } else { console.warn( 'SVGLoader: \'use node\' references non-existent node id: ' + usedNodeId ); } break; default: // console.log( node ); } if ( path ) { if ( style.fill !== undefined && style.fill !== 'none' ) { path.color.setStyle( style.fill ); } transformPath( path, currentTransform ); paths.push( path ); path.userData = { node: node, style: style }; } if ( traverseChildNodes ) { var nodes = node.childNodes; for ( var i = 0; i < nodes.length; i ++ ) { parseNode( nodes[ i ], style ); } } if ( transform ) { transformStack.pop(); if ( transformStack.length > 0 ) { currentTransform.copy( transformStack[ transformStack.length - 1 ] ); } else { currentTransform.identity(); } } } function parsePathNode( node ) { var path = new ShapePath(); var point = new Vector2(); var control = new Vector2(); var firstPoint = new Vector2(); var isFirstPoint = true; var doSetFirstPoint = false; var d = node.getAttribute( 'd' ); // console.log( d ); var commands = d.match( /[a-df-z][^a-df-z]*/ig ); for ( var i = 0, l = commands.length; i < l; i ++ ) { var command = commands[ i ]; var type = command.charAt( 0 ); var data = command.substr( 1 ).trim(); if ( isFirstPoint === true ) { doSetFirstPoint = true; isFirstPoint = false; } switch ( type ) { case 'M': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x = numbers[ j + 0 ]; point.y = numbers[ j + 1 ]; control.x = point.x; control.y = point.y; if ( j === 0 ) { path.moveTo( point.x, point.y ); } else { path.lineTo( point.x, point.y ); } if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'H': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.x = numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'V': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.y = numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'L': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x = numbers[ j + 0 ]; point.y = numbers[ j + 1 ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'C': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) { path.bezierCurveTo( numbers[ j + 0 ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], numbers[ j + 5 ] ); control.x = numbers[ j + 2 ]; control.y = numbers[ j + 3 ]; point.x = numbers[ j + 4 ]; point.y = numbers[ j + 5 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'S': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.bezierCurveTo( getReflection( point.x, control.x ), getReflection( point.y, control.y ), numbers[ j + 0 ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ] ); control.x = numbers[ j + 0 ]; control.y = numbers[ j + 1 ]; point.x = numbers[ j + 2 ]; point.y = numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'Q': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.quadraticCurveTo( numbers[ j + 0 ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ] ); control.x = numbers[ j + 0 ]; control.y = numbers[ j + 1 ]; point.x = numbers[ j + 2 ]; point.y = numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'T': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { var rx = getReflection( point.x, control.x ); var ry = getReflection( point.y, control.y ); path.quadraticCurveTo( rx, ry, numbers[ j + 0 ], numbers[ j + 1 ] ); control.x = rx; control.y = ry; point.x = numbers[ j + 0 ]; point.y = numbers[ j + 1 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'A': var numbers = parseFloats( data, [ 3, 4 ], 7 ); for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) { // skip command if start point == end point if ( numbers[ j + 5 ] == point.x && numbers[ j + 6 ] == point.y ) continue; var start = point.clone(); point.x = numbers[ j + 5 ]; point.y = numbers[ j + 6 ]; control.x = point.x; control.y = point.y; parseArcCommand( path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'm': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x += numbers[ j + 0 ]; point.y += numbers[ j + 1 ]; control.x = point.x; control.y = point.y; if ( j === 0 ) { path.moveTo( point.x, point.y ); } else { path.lineTo( point.x, point.y ); } if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'h': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.x += numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'v': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.y += numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'l': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x += numbers[ j + 0 ]; point.y += numbers[ j + 1 ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'c': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) { path.bezierCurveTo( point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ], point.x + numbers[ j + 2 ], point.y + numbers[ j + 3 ], point.x + numbers[ j + 4 ], point.y + numbers[ j + 5 ] ); control.x = point.x + numbers[ j + 2 ]; control.y = point.y + numbers[ j + 3 ]; point.x += numbers[ j + 4 ]; point.y += numbers[ j + 5 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 's': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.bezierCurveTo( getReflection( point.x, control.x ), getReflection( point.y, control.y ), point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ], point.x + numbers[ j + 2 ], point.y + numbers[ j + 3 ] ); control.x = point.x + numbers[ j + 0 ]; control.y = point.y + numbers[ j + 1 ]; point.x += numbers[ j + 2 ]; point.y += numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'q': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.quadraticCurveTo( point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ], point.x + numbers[ j + 2 ], point.y + numbers[ j + 3 ] ); control.x = point.x + numbers[ j + 0 ]; control.y = point.y + numbers[ j + 1 ]; point.x += numbers[ j + 2 ]; point.y += numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 't': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { var rx = getReflection( point.x, control.x ); var ry = getReflection( point.y, control.y ); path.quadraticCurveTo( rx, ry, point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ] ); control.x = rx; control.y = ry; point.x = point.x + numbers[ j + 0 ]; point.y = point.y + numbers[ j + 1 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'a': var numbers = parseFloats( data, [ 3, 4 ], 7 ); for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) { // skip command if no displacement if ( numbers[ j + 5 ] == 0 && numbers[ j + 6 ] == 0 ) continue; var start = point.clone(); point.x += numbers[ j + 5 ]; point.y += numbers[ j + 6 ]; control.x = point.x; control.y = point.y; parseArcCommand( path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'Z': case 'z': path.currentPath.autoClose = true; if ( path.currentPath.curves.length > 0 ) { // Reset point to beginning of Path point.copy( firstPoint ); path.currentPath.currentPoint.copy( point ); isFirstPoint = true; } break; default: console.warn( command ); } // console.log( type, parseFloats( data ), parseFloats( data ).length ) doSetFirstPoint = false; } return path; } function parseCSSStylesheet( node ) { if ( ! node.sheet || ! node.sheet.cssRules || ! node.sheet.cssRules.length ) return; for ( var i = 0; i < node.sheet.cssRules.length; i ++ ) { var stylesheet = node.sheet.cssRules[ i ]; if ( stylesheet.type !== 1 ) continue; var selectorList = stylesheet.selectorText .split( /,/gm ) .filter( Boolean ) .map( i => i.trim() ); for ( var j = 0; j < selectorList.length; j ++ ) { stylesheets[ selectorList[ j ] ] = Object.assign( stylesheets[ selectorList[ j ] ] || {}, stylesheet.style ); } } } /** * https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes * https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion * From * rx ry x-axis-rotation large-arc-flag sweep-flag x y * To * aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation */ function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) { if ( rx == 0 || ry == 0 ) { // draw a line if either of the radii == 0 path.lineTo( end.x, end.y ); return; } x_axis_rotation = x_axis_rotation * Math.PI / 180; // Ensure radii are positive rx = Math.abs( rx ); ry = Math.abs( ry ); // Compute (x1', y1') var dx2 = ( start.x - end.x ) / 2.0; var dy2 = ( start.y - end.y ) / 2.0; var x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2; var y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2; // Compute (cx', cy') var rxs = rx * rx; var rys = ry * ry; var x1ps = x1p * x1p; var y1ps = y1p * y1p; // Ensure radii are large enough var cr = x1ps / rxs + y1ps / rys; if ( cr > 1 ) { // scale up rx,ry equally so cr == 1 var s = Math.sqrt( cr ); rx = s * rx; ry = s * ry; rxs = rx * rx; rys = ry * ry; } var dq = ( rxs * y1ps + rys * x1ps ); var pq = ( rxs * rys - dq ) / dq; var q = Math.sqrt( Math.max( 0, pq ) ); if ( large_arc_flag === sweep_flag ) q = - q; var cxp = q * rx * y1p / ry; var cyp = - q * ry * x1p / rx; // Step 3: Compute (cx, cy) from (cx', cy') var cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2; var cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2; // Step 4: Compute θ1 and Δθ var theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry ); var delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 ); path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation ); } function svgAngle( ux, uy, vx, vy ) { var dot = ux * vx + uy * vy; var len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy ); var ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang; return ang; } /* * According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute * rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough */ function parseRectNode( node ) { var x = parseFloatWithUnits( node.getAttribute( 'x' ) || 0 ); var y = parseFloatWithUnits( node.getAttribute( 'y' ) || 0 ); var rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 ); var ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 ); var w = parseFloatWithUnits( node.getAttribute( 'width' ) ); var h = parseFloatWithUnits( node.getAttribute( 'height' ) ); var path = new ShapePath(); path.moveTo( x + 2 * rx, y ); path.lineTo( x + w - 2 * rx, y ); if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y, x + w, y, x + w, y + 2 * ry ); path.lineTo( x + w, y + h - 2 * ry ); if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y + h, x + w, y + h, x + w - 2 * rx, y + h ); path.lineTo( x + 2 * rx, y + h ); if ( rx !== 0 || ry !== 0 ) { path.bezierCurveTo( x, y + h, x, y + h, x, y + h - 2 * ry ); } path.lineTo( x, y + 2 * ry ); if ( rx !== 0 || ry !== 0 ) { path.bezierCurveTo( x, y, x, y, x + 2 * rx, y ); } return path; } function parsePolygonNode( node ) { function iterator( match, a, b ) { var x = parseFloatWithUnits( a ); var y = parseFloatWithUnits( b ); if ( index === 0 ) { path.moveTo( x, y ); } else { path.lineTo( x, y ); } index ++; } var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g; var path = new ShapePath(); var index = 0; node.getAttribute( 'points' ).replace( regex, iterator ); path.currentPath.autoClose = true; return path; } function parsePolylineNode( node ) { function iterator( match, a, b ) { var x = parseFloatWithUnits( a ); var y = parseFloatWithUnits( b ); if ( index === 0 ) { path.moveTo( x, y ); } else { path.lineTo( x, y ); } index ++; } var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g; var path = new ShapePath(); var index = 0; node.getAttribute( 'points' ).replace( regex, iterator ); path.currentPath.autoClose = false; return path; } function parseCircleNode( node ) { var x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 ); var y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 ); var r = parseFloatWithUnits( node.getAttribute( 'r' ) || 0 ); var subpath = new Path(); subpath.absarc( x, y, r, 0, Math.PI * 2 ); var path = new ShapePath(); path.subPaths.push( subpath ); return path; } function parseEllipseNode( node ) { var x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 ); var y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 ); var rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 ); var ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 ); var subpath = new Path(); subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2 ); var path = new ShapePath(); path.subPaths.push( subpath ); return path; } function parseLineNode( node ) { var x1 = parseFloatWithUnits( node.getAttribute( 'x1' ) || 0 ); var y1 = parseFloatWithUnits( node.getAttribute( 'y1' ) || 0 ); var x2 = parseFloatWithUnits( node.getAttribute( 'x2' ) || 0 ); var y2 = parseFloatWithUnits( node.getAttribute( 'y2' ) || 0 ); var path = new ShapePath(); path.moveTo( x1, y1 ); path.lineTo( x2, y2 ); path.currentPath.autoClose = false; return path; } // function parseStyle( node, style ) { style = Object.assign( {}, style ); // clone style var stylesheetStyles = {}; if ( node.hasAttribute( 'class' ) ) { var classSelectors = node.getAttribute( 'class' ) .split( /\s/ ) .filter( Boolean ) .map( i => i.trim() ); for ( var i = 0; i < classSelectors.length; i ++ ) { stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '.' + classSelectors[ i ] ] ); } } if ( node.hasAttribute( 'id' ) ) { stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '#' + node.getAttribute( 'id' ) ] ); } function addStyle( svgName, jsName, adjustFunction ) { if ( adjustFunction === undefined ) adjustFunction = function copy( v ) { if ( v.startsWith( 'url' ) ) console.warn( 'SVGLoader: url access in attributes is not implemented.' ); return v; }; if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) ); if ( stylesheetStyles[ svgName ] ) style[ jsName ] = adjustFunction( stylesheetStyles[ svgName ] ); if ( node.style && node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] ); } function clamp( v ) { return Math.max( 0, Math.min( 1, parseFloatWithUnits( v ) ) ); } function positive( v ) { return Math.max( 0, parseFloatWithUnits( v ) ); } addStyle( 'fill', 'fill' ); addStyle( 'fill-opacity', 'fillOpacity', clamp ); addStyle( 'opacity', 'opacity', clamp ); addStyle( 'stroke', 'stroke' ); addStyle( 'stroke-opacity', 'strokeOpacity', clamp ); addStyle( 'stroke-width', 'strokeWidth', positive ); addStyle( 'stroke-linejoin', 'strokeLineJoin' ); addStyle( 'stroke-linecap', 'strokeLineCap' ); addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive ); addStyle( 'visibility', 'visibility' ); return style; } // http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes function getReflection( a, b ) { return a - ( b - a ); } // from https://github.com/ppvg/svg-numbers (MIT License) function parseFloats( input, flags, stride ) { if ( typeof input !== 'string' ) { throw new TypeError( 'Invalid input: ' + typeof input ); } // Character groups var RE = { SEPARATOR: /[ \t\r\n\,.\-+]/, WHITESPACE: /[ \t\r\n]/, DIGIT: /[\d]/, SIGN: /[-+]/, POINT: /\./, COMMA: /,/, EXP: /e/i, FLAGS: /[01]/ }; // States var SEP = 0; var INT = 1; var FLOAT = 2; var EXP = 3; var state = SEP; var seenComma = true; var result = [], number = '', exponent = ''; function throwSyntaxError( current, i, partial ) { var error = new SyntaxError( 'Unexpected character "' + current + '" at index ' + i + '.' ); error.partial = partial; throw error; } function newNumber() { if ( number !== '' ) { if ( exponent === '' ) result.push( Number( number ) ); else result.push( Number( number ) * Math.pow( 10, Number( exponent ) ) ); } number = ''; exponent = ''; } var current, i = 0, length = input.length; for ( i = 0; i < length; i ++ ) { current = input[ i ]; // check for flags if ( Array.isArray( flags ) && flags.includes( result.length % stride ) && RE.FLAGS.test( current ) ) { state = INT; number = current; newNumber(); continue; } // parse until next number if ( state === SEP ) { // eat whitespace if ( RE.WHITESPACE.test( current ) ) { continue; } // start new number if ( RE.DIGIT.test( current ) || RE.SIGN.test( current ) ) { state = INT; number = current; continue; } if ( RE.POINT.test( current ) ) { state = FLOAT; number = current; continue; } // throw on double commas (e.g. "1, , 2") if ( RE.COMMA.test( current ) ) { if ( seenComma ) { throwSyntaxError( current, i, result ); } seenComma = true; } } // parse integer part if ( state === INT ) { if ( RE.DIGIT.test( current ) ) { number += current; continue; } if ( RE.POINT.test( current ) ) { number += current; state = FLOAT; continue; } if ( RE.EXP.test( current ) ) { state = EXP; continue; } // throw on double signs ("-+1"), but not on sign as separator ("-1-2") if ( RE.SIGN.test( current ) && number.length === 1 && RE.SIGN.test( number[ 0 ] ) ) { throwSyntaxError( current, i, result ); } } // parse decimal part if ( state === FLOAT ) { if ( RE.DIGIT.test( current ) ) { number += current; continue; } if ( RE.EXP.test( current ) ) { state = EXP; continue; } // throw on double decimal points (e.g. "1..2") if ( RE.POINT.test( current ) && number[ number.length - 1 ] === '.' ) { throwSyntaxError( current, i, result ); } } // parse exponent part if ( state === EXP ) { if ( RE.DIGIT.test( current ) ) { exponent += current; continue; } if ( RE.SIGN.test( current ) ) { if ( exponent === '' ) { exponent += current; continue; } if ( exponent.length === 1 && RE.SIGN.test( exponent ) ) { throwSyntaxError( current, i, result ); } } } // end of number if ( RE.WHITESPACE.test( current ) ) { newNumber(); state = SEP; seenComma = false; } else if ( RE.COMMA.test( current ) ) { newNumber(); state = SEP; seenComma = true; } else if ( RE.SIGN.test( current ) ) { newNumber(); state = INT; number = current; } else if ( RE.POINT.test( current ) ) { newNumber(); state = FLOAT; number = current; } else { throwSyntaxError( current, i, result ); } } // add the last number found (if any) newNumber(); return result; } // Units var units = [ 'mm', 'cm', 'in', 'pt', 'pc', 'px' ]; // Conversion: [ fromUnit ][ toUnit ] (-1 means dpi dependent) var unitConversion = { 'mm': { 'mm': 1, 'cm': 0.1, 'in': 1 / 25.4, 'pt': 72 / 25.4, 'pc': 6 / 25.4, 'px': - 1 }, 'cm': { 'mm': 10, 'cm': 1, 'in': 1 / 2.54, 'pt': 72 / 2.54, 'pc': 6 / 2.54, 'px': - 1 }, 'in': { 'mm': 25.4, 'cm': 2.54, 'in': 1, 'pt': 72, 'pc': 6, 'px': - 1 }, 'pt': { 'mm': 25.4 / 72, 'cm': 2.54 / 72, 'in': 1 / 72, 'pt': 1, 'pc': 6 / 72, 'px': - 1 }, 'pc': { 'mm': 25.4 / 6, 'cm': 2.54 / 6, 'in': 1 / 6, 'pt': 72 / 6, 'pc': 1, 'px': - 1 }, 'px': { 'px': 1 } }; function parseFloatWithUnits( string ) { var theUnit = 'px'; if ( typeof string === 'string' || string instanceof String ) { for ( var i = 0, n = units.length; i < n; i ++ ) { var u = units[ i ]; if ( string.endsWith( u ) ) { theUnit = u; string = string.substring( 0, string.length - u.length ); break; } } } var scale = undefined; if ( theUnit === 'px' && scope.defaultUnit !== 'px' ) { // Conversion scale from pixels to inches, then to default units scale = unitConversion[ 'in' ][ scope.defaultUnit ] / scope.defaultDPI; } else { scale = unitConversion[ theUnit ][ scope.defaultUnit ]; if ( scale < 0 ) { // Conversion scale to pixels scale = unitConversion[ theUnit ][ 'in' ] * scope.defaultDPI; } } return scale * parseFloat( string ); } // Transforms function getNodeTransform( node ) { if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) { return null; } var transform = parseNodeTransform( node ); if ( transformStack.length > 0 ) { transform.premultiply( transformStack[ transformStack.length - 1 ] ); } currentTransform.copy( transform ); transformStack.push( transform ); return transform; } function parseNodeTransform( node ) { var transform = new Matrix3(); var currentTransform = tempTransform0; if ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) { var tx = parseFloatWithUnits( node.getAttribute( 'x' ) ); var ty = parseFloatWithUnits( node.getAttribute( 'y' ) ); transform.translate( tx, ty ); } if ( node.hasAttribute( 'transform' ) ) { var transformsTexts = node.getAttribute( 'transform' ).split( ')' ); for ( var tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) { var transformText = transformsTexts[ tIndex ].trim(); if ( transformText === '' ) continue; var openParPos = transformText.indexOf( '(' ); var closeParPos = transformText.length; if ( openParPos > 0 && openParPos < closeParPos ) { var transformType = transformText.substr( 0, openParPos ); var array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) ); currentTransform.identity(); switch ( transformType ) { case 'translate': if ( array.length >= 1 ) { var tx = array[ 0 ]; var ty = tx; if ( array.length >= 2 ) { ty = array[ 1 ]; } currentTransform.translate( tx, ty ); } break; case 'rotate': if ( array.length >= 1 ) { var angle = 0; var cx = 0; var cy = 0; // Angle angle = - array[ 0 ] * Math.PI / 180; if ( array.length >= 3 ) { // Center x, y cx = array[ 1 ]; cy = array[ 2 ]; } // Rotate around center (cx, cy) tempTransform1.identity().translate( - cx, - cy ); tempTransform2.identity().rotate( angle ); tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 ); tempTransform1.identity().translate( cx, cy ); currentTransform.multiplyMatrices( tempTransform1, tempTransform3 ); } break; case 'scale': if ( array.length >= 1 ) { var scaleX = array[ 0 ]; var scaleY = scaleX; if ( array.length >= 2 ) { scaleY = array[ 1 ]; } currentTransform.scale( scaleX, scaleY ); } break; case 'skewX': if ( array.length === 1 ) { currentTransform.set( 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0, 0, 1, 0, 0, 0, 1 ); } break; case 'skewY': if ( array.length === 1 ) { currentTransform.set( 1, 0, 0, Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0, 0, 0, 1 ); } break; case 'matrix': if ( array.length === 6 ) { currentTransform.set( array[ 0 ], array[ 2 ], array[ 4 ], array[ 1 ], array[ 3 ], array[ 5 ], 0, 0, 1 ); } break; } } transform.premultiply( currentTransform ); } } return transform; } function transformPath( path, m ) { function transfVec2( v2 ) { tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m ); v2.set( tempV3.x, tempV3.y ); } var isRotated = isTransformRotated( m ); var subPaths = path.subPaths; for ( var i = 0, n = subPaths.length; i < n; i ++ ) { var subPath = subPaths[ i ]; var curves = subPath.curves; for ( var j = 0; j < curves.length; j ++ ) { var curve = curves[ j ]; if ( curve.isLineCurve ) { transfVec2( curve.v1 ); transfVec2( curve.v2 ); } else if ( curve.isCubicBezierCurve ) { transfVec2( curve.v0 ); transfVec2( curve.v1 ); transfVec2( curve.v2 ); transfVec2( curve.v3 ); } else if ( curve.isQuadraticBezierCurve ) { transfVec2( curve.v0 ); transfVec2( curve.v1 ); transfVec2( curve.v2 ); } else if ( curve.isEllipseCurve ) { if ( isRotated ) { console.warn( 'SVGLoader: Elliptic arc or ellipse rotation or skewing is not implemented.' ); } tempV2.set( curve.aX, curve.aY ); transfVec2( tempV2 ); curve.aX = tempV2.x; curve.aY = tempV2.y; curve.xRadius *= getTransformScaleX( m ); curve.yRadius *= getTransformScaleY( m ); } } } } function isTransformRotated( m ) { return m.elements[ 1 ] !== 0 || m.elements[ 3 ] !== 0; } function getTransformScaleX( m ) { var te = m.elements; return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] ); } function getTransformScaleY( m ) { var te = m.elements; return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] ); } // var paths = []; var stylesheets = {}; var transformStack = []; var tempTransform0 = new Matrix3(); var tempTransform1 = new Matrix3(); var tempTransform2 = new Matrix3(); var tempTransform3 = new Matrix3(); var tempV2 = new Vector2(); var tempV3 = new Vector3(); var currentTransform = new Matrix3(); var xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml parseNode( xml.documentElement, { fill: '#000', fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, strokeLineJoin: 'miter', strokeLineCap: 'butt', strokeMiterLimit: 4 } ); var data = { paths: paths, xml: xml.documentElement }; // console.log( paths ); return data; } } ); SVGLoader.createShapes = function ( shapePath ) { // Param shapePath: a shapepath as returned by the parse function of this class // Returns Shape object const BIGNUMBER = 999999999; const IntersectionLocationType = { ORIGIN: 0, DESTINATION: 1, BETWEEN: 2, LEFT: 3, RIGHT: 4, BEHIND: 5, BEYOND: 6 }; const classifyResult = { loc: IntersectionLocationType.ORIGIN, t: 0 }; function findEdgeIntersection( a0, a1, b0, b1 ) { var x1 = a0.x; var x2 = a1.x; var x3 = b0.x; var x4 = b1.x; var y1 = a0.y; var y2 = a1.y; var y3 = b0.y; var y4 = b1.y; var nom1 = ( x4 - x3 ) * ( y1 - y3 ) - ( y4 - y3 ) * ( x1 - x3 ); var nom2 = ( x2 - x1 ) * ( y1 - y3 ) - ( y2 - y1 ) * ( x1 - x3 ); var denom = ( y4 - y3 ) * ( x2 - x1 ) - ( x4 - x3 ) * ( y2 - y1 ); var t1 = nom1 / denom; var t2 = nom2 / denom; if ( ( ( denom === 0 ) && ( nom1 !== 0 ) ) || ( t1 <= 0 ) || ( t1 >= 1 ) || ( t2 < 0 ) || ( t2 > 1 ) ) { //1. lines are parallel or edges don't intersect return null; } else if ( ( nom1 === 0 ) && ( denom === 0 ) ) { //2. lines are colinear //check if endpoints of edge2 (b0-b1) lies on edge1 (a0-a1) for ( var i = 0; i < 2; i ++ ) { classifyPoint( i === 0 ? b0 : b1, a0, a1 ); //find position of this endpoints relatively to edge1 if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) { var point = ( i === 0 ? b0 : b1 ); return { x: point.x, y: point.y, t: classifyResult.t }; } else if ( classifyResult.loc == IntersectionLocationType.BETWEEN ) { var x = + ( ( x1 + classifyResult.t * ( x2 - x1 ) ).toPrecision( 10 ) ); var y = + ( ( y1 + classifyResult.t * ( y2 - y1 ) ).toPrecision( 10 ) ); return { x: x, y: y, t: classifyResult.t, }; } } return null; } else { //3. edges intersect for ( var i = 0; i < 2; i ++ ) { classifyPoint( i === 0 ? b0 : b1, a0, a1 ); if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) { var point = ( i === 0 ? b0 : b1 ); return { x: point.x, y: point.y, t: classifyResult.t }; } } var x = + ( ( x1 + t1 * ( x2 - x1 ) ).toPrecision( 10 ) ); var y = + ( ( y1 + t1 * ( y2 - y1 ) ).toPrecision( 10 ) ); return { x: x, y: y, t: t1 }; } } function classifyPoint( p, edgeStart, edgeEnd ) { var ax = edgeEnd.x - edgeStart.x; var ay = edgeEnd.y - edgeStart.y; var bx = p.x - edgeStart.x; var by = p.y - edgeStart.y; var sa = ax * by - bx * ay; if ( ( p.x === edgeStart.x ) && ( p.y === edgeStart.y ) ) { classifyResult.loc = IntersectionLocationType.ORIGIN; classifyResult.t = 0; return; } if ( ( p.x === edgeEnd.x ) && ( p.y === edgeEnd.y ) ) { classifyResult.loc = IntersectionLocationType.DESTINATION; classifyResult.t = 1; return; } if ( sa < - Number.EPSILON ) { classifyResult.loc = IntersectionLocationType.LEFT; return; } if ( sa > Number.EPSILON ) { classifyResult.loc = IntersectionLocationType.RIGHT; return; } if ( ( ( ax * bx ) < 0 ) || ( ( ay * by ) < 0 ) ) { classifyResult.loc = IntersectionLocationType.BEHIND; return; } if ( ( Math.sqrt( ax * ax + ay * ay ) ) < ( Math.sqrt( bx * bx + by * by ) ) ) { classifyResult.loc = IntersectionLocationType.BEYOND; return; } var t; if ( ax !== 0 ) { t = bx / ax; } else { t = by / ay; } classifyResult.loc = IntersectionLocationType.BETWEEN; classifyResult.t = t; } function getIntersections( path1, path2 ) { const intersectionsRaw = []; const intersections = []; for ( let index = 1; index < path1.length; index ++ ) { const path1EdgeStart = path1[ index - 1 ]; const path1EdgeEnd = path1[ index ]; for ( let index2 = 1; index2 < path2.length; index2 ++ ) { const path2EdgeStart = path2[ index2 - 1 ]; const path2EdgeEnd = path2[ index2 ]; const intersection = findEdgeIntersection( path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd ); if ( intersection !== null && intersectionsRaw.find( i => i.t <= intersection.t + Number.EPSILON && i.t >= intersection.t - Number.EPSILON ) === undefined ) { intersectionsRaw.push( intersection ); intersections.push( new Vector2( intersection.x, intersection.y ) ); } } } return intersections; } function getScanlineIntersections( scanline, boundingBox, paths ) { const center = new Vector2(); boundingBox.getCenter( center ); const allIntersections = []; paths.forEach( path => { // check if the center of the bounding box is in the bounding box of the paths. // this is a pruning method to limit the search of intersections in paths that can't envelop of the current path. // if a path envelops another path. The center of that oter path, has to be inside the bounding box of the enveloping path. if ( path.boundingBox.containsPoint( center ) ) { const intersections = getIntersections( scanline, path.points ); intersections.forEach( p => { allIntersections.push( { identifier: path.identifier, isCW: path.isCW, point: p } ); } ); } } ); allIntersections.sort( ( i1, i2 ) => { return i1.point.x - i2.point.x; } ); return allIntersections; } function isHoleTo( simplePath, allPaths, scanlineMinX, scanlineMaxX, _fillRule ) { if ( _fillRule === null || _fillRule === undefined || _fillRule === '' ) { _fillRule = 'nonzero'; } const centerBoundingBox = new Vector2(); simplePath.boundingBox.getCenter( centerBoundingBox ); const scanline = [ new Vector2( scanlineMinX, centerBoundingBox.y ), new Vector2( scanlineMaxX, centerBoundingBox.y ) ]; const scanlineIntersections = getScanlineIntersections( scanline, simplePath.boundingBox, allPaths ); scanlineIntersections.sort( ( i1, i2 ) => { return i1.point.x - i2.point.x; } ); const baseIntersections = []; const otherIntersections = []; scanlineIntersections.forEach( i => { if ( i.identifier === simplePath.identifier ) { baseIntersections.push( i ); } else { otherIntersections.push( i ); } } ); const firstXOfPath = baseIntersections[ 0 ].point.x; // build up the path hierarchy const stack = []; let i = 0; while ( i < otherIntersections.length && otherIntersections[ i ].point.x < firstXOfPath ) { if ( stack.length > 0 && stack[ stack.length - 1 ] === otherIntersections[ i ].identifier ) { stack.pop(); } else { stack.push( otherIntersections[ i ].identifier ); } i ++; } stack.push( simplePath.identifier ); if ( _fillRule === 'evenodd' ) { const isHole = stack.length % 2 === 0 ? true : false; const isHoleFor = stack[ stack.length - 2 ]; return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor }; } else if ( _fillRule === 'nonzero' ) { // check if path is a hole by counting the amount of paths with alternating rotations it has to cross. let isHole = true; let isHoleFor = null; let lastCWValue = null; for ( let i = 0; i < stack.length; i ++ ) { const identifier = stack[ i ]; if ( isHole ) { lastCWValue = allPaths[ identifier ].isCW; isHole = false; isHoleFor = identifier; } else if ( lastCWValue !== allPaths[ identifier ].isCW ) { lastCWValue = allPaths[ identifier ].isCW; isHole = true; } } return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor }; } else { console.warn( 'fill-rule: "' + _fillRule + '" is currently not implemented.' ); } } // check for self intersecting paths // TODO // check intersecting paths // TODO // prepare paths for hole detection let identifier = 0; let scanlineMinX = BIGNUMBER; let scanlineMaxX = - BIGNUMBER; let simplePaths = shapePath.subPaths.map( p => { const points = p.getPoints(); let maxY = - BIGNUMBER; let minY = BIGNUMBER; let maxX = - BIGNUMBER; let minX = BIGNUMBER; //points.forEach(p => p.y *= -1); for ( let i = 0; i < points.length; i ++ ) { const p = points[ i ]; if ( p.y > maxY ) { maxY = p.y; } if ( p.y < minY ) { minY = p.y; } if ( p.x > maxX ) { maxX = p.x; } if ( p.x < minX ) { minX = p.x; } } // if ( scanlineMaxX <= maxX ) { scanlineMaxX = maxX + 1; } if ( scanlineMinX >= minX ) { scanlineMinX = minX - 1; } return { points: points, isCW: ShapeUtils.isClockWise( points ), identifier: identifier ++, boundingBox: new Box2( new Vector2( minX, minY ), new Vector2( maxX, maxY ) ) }; } ); simplePaths = simplePaths.filter( sp => sp.points.length > 0 ); // check if path is solid or a hole const isAHole = simplePaths.map( p => isHoleTo( p, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData.style.fillRule ) ); const shapesToReturn = []; simplePaths.forEach( p => { const amIAHole = isAHole[ p.identifier ]; if ( ! amIAHole.isHole ) { const shape = new Shape( p.points ); const holes = isAHole.filter( h => h.isHole && h.for === p.identifier ); holes.forEach( h => { const path = simplePaths[ h.identifier ]; shape.holes.push( new Path( path.points ) ); } ); shapesToReturn.push( shape ); } } ); return shapesToReturn; }; SVGLoader.getStrokeStyle = function ( width, color, lineJoin, lineCap, miterLimit ) { // Param width: Stroke width // Param color: As returned by THREE.Color.getStyle() // Param lineJoin: One of "round", "bevel", "miter" or "miter-limit" // Param lineCap: One of "round", "square" or "butt" // Param miterLimit: Maximum join length, in multiples of the "width" parameter (join is truncated if it exceeds that distance) // Returns style object width = width !== undefined ? width : 1; color = color !== undefined ? color : '#000'; lineJoin = lineJoin !== undefined ? lineJoin : 'miter'; lineCap = lineCap !== undefined ? lineCap : 'butt'; miterLimit = miterLimit !== undefined ? miterLimit : 4; return { strokeColor: color, strokeWidth: width, strokeLineJoin: lineJoin, strokeLineCap: lineCap, strokeMiterLimit: miterLimit }; }; SVGLoader.pointsToStroke = function ( points, style, arcDivisions, minDistance ) { // Generates a stroke with some witdh around the given path. // The path can be open or closed (last point equals to first point) // Param points: Array of Vector2D (the path). Minimum 2 points. // Param style: Object with SVG properties as returned by SVGLoader.getStrokeStyle(), or SVGLoader.parse() in the path.userData.style object // Params arcDivisions: Arc divisions for round joins and endcaps. (Optional) // Param minDistance: Points closer to this distance will be merged. (Optional) // Returns BufferGeometry with stroke triangles (In plane z = 0). UV coordinates are generated ('u' along path. 'v' across it, from left to right) var vertices = []; var normals = []; var uvs = []; if ( SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) { return null; } var geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); return geometry; }; SVGLoader.pointsToStrokeWithBuffers = function () { var tempV2_1 = new Vector2(); var tempV2_2 = new Vector2(); var tempV2_3 = new Vector2(); var tempV2_4 = new Vector2(); var tempV2_5 = new Vector2(); var tempV2_6 = new Vector2(); var tempV2_7 = new Vector2(); var lastPointL = new Vector2(); var lastPointR = new Vector2(); var point0L = new Vector2(); var point0R = new Vector2(); var currentPointL = new Vector2(); var currentPointR = new Vector2(); var nextPointL = new Vector2(); var nextPointR = new Vector2(); var innerPoint = new Vector2(); var outerPoint = new Vector2(); return function ( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset ) { // This function can be called to update existing arrays or buffers. // Accepts same parameters as pointsToStroke, plus the buffers and optional offset. // Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs) // Returns number of written vertices / normals / uvs pairs // if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers) // 'normals' and 'uvs' buffers are optional arcDivisions = arcDivisions !== undefined ? arcDivisions : 12; minDistance = minDistance !== undefined ? minDistance : 0.001; vertexOffset = vertexOffset !== undefined ? vertexOffset : 0; // First ensure there are no duplicated points points = removeDuplicatedPoints( points ); var numPoints = points.length; if ( numPoints < 2 ) return 0; var isClosed = points[ 0 ].equals( points[ numPoints - 1 ] ); var currentPoint; var previousPoint = points[ 0 ]; var nextPoint; var strokeWidth2 = style.strokeWidth / 2; var deltaU = 1 / ( numPoints - 1 ); var u0 = 0; var innerSideModified; var joinIsOnLeftSide; var isMiter; var initialJoinIsOnLeftSide = false; var numVertices = 0; var currentCoordinate = vertexOffset * 3; var currentCoordinateUV = vertexOffset * 2; // Get initial left and right stroke points getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 ); lastPointL.copy( points[ 0 ] ).sub( tempV2_1 ); lastPointR.copy( points[ 0 ] ).add( tempV2_1 ); point0L.copy( lastPointL ); point0R.copy( lastPointR ); for ( var iPoint = 1; iPoint < numPoints; iPoint ++ ) { currentPoint = points[ iPoint ]; // Get next point if ( iPoint === numPoints - 1 ) { if ( isClosed ) { // Skip duplicated initial point nextPoint = points[ 1 ]; } else nextPoint = undefined; } else { nextPoint = points[ iPoint + 1 ]; } // Normal of previous segment in tempV2_1 var normal1 = tempV2_1; getNormal( previousPoint, currentPoint, normal1 ); tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 ); currentPointL.copy( currentPoint ).sub( tempV2_3 ); currentPointR.copy( currentPoint ).add( tempV2_3 ); var u1 = u0 + deltaU; innerSideModified = false; if ( nextPoint !== undefined ) { // Normal of next segment in tempV2_2 getNormal( currentPoint, nextPoint, tempV2_2 ); tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 ); nextPointL.copy( currentPoint ).sub( tempV2_3 ); nextPointR.copy( currentPoint ).add( tempV2_3 ); joinIsOnLeftSide = true; tempV2_3.subVectors( nextPoint, previousPoint ); if ( normal1.dot( tempV2_3 ) < 0 ) { joinIsOnLeftSide = false; } if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide; tempV2_3.subVectors( nextPoint, currentPoint ); tempV2_3.normalize(); var dot = Math.abs( normal1.dot( tempV2_3 ) ); // If path is straight, don't create join if ( dot !== 0 ) { // Compute inner and outer segment intersections var miterSide = strokeWidth2 / dot; tempV2_3.multiplyScalar( - miterSide ); tempV2_4.subVectors( currentPoint, previousPoint ); tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 ); innerPoint.copy( tempV2_5 ).negate(); var miterLength2 = tempV2_5.length(); var segmentLengthPrev = tempV2_4.length(); tempV2_4.divideScalar( segmentLengthPrev ); tempV2_6.subVectors( nextPoint, currentPoint ); var segmentLengthNext = tempV2_6.length(); tempV2_6.divideScalar( segmentLengthNext ); // Check that previous and next segments doesn't overlap with the innerPoint of intersection if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) { innerSideModified = true; } outerPoint.copy( tempV2_5 ).add( currentPoint ); innerPoint.add( currentPoint ); isMiter = false; if ( innerSideModified ) { if ( joinIsOnLeftSide ) { nextPointR.copy( innerPoint ); currentPointR.copy( innerPoint ); } else { nextPointL.copy( innerPoint ); currentPointL.copy( innerPoint ); } } else { // The segment triangles are generated here if there was overlapping makeSegmentTriangles(); } switch ( style.strokeLineJoin ) { case 'bevel': makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 ); break; case 'round': // Segment triangles createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ); // Join triangles if ( joinIsOnLeftSide ) { makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 ); } else { makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 ); } break; case 'miter': case 'miter-clip': default: var miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2; if ( miterFraction < 1 ) { // The join miter length exceeds the miter limit if ( style.strokeLineJoin !== 'miter-clip' ) { makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 ); break; } else { // Segment triangles createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ); // Miter-clip join triangles if ( joinIsOnLeftSide ) { tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL ); tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL ); addVertex( currentPointL, u1, 0 ); addVertex( tempV2_6, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_6, u1, 0 ); addVertex( tempV2_7, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_7, u1, 0 ); addVertex( nextPointL, u1, 0 ); } else { tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR ); tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR ); addVertex( currentPointR, u1, 1 ); addVertex( tempV2_6, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_6, u1, 1 ); addVertex( tempV2_7, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_7, u1, 1 ); addVertex( nextPointR, u1, 1 ); } } } else { // Miter join segment triangles if ( innerSideModified ) { // Optimized segment + join triangles if ( joinIsOnLeftSide ) { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( outerPoint, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( outerPoint, u1, 0 ); addVertex( innerPoint, u1, 1 ); } else { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( outerPoint, u1, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( innerPoint, u1, 0 ); addVertex( outerPoint, u1, 1 ); } if ( joinIsOnLeftSide ) { nextPointL.copy( outerPoint ); } else { nextPointR.copy( outerPoint ); } } else { // Add extra miter join triangles if ( joinIsOnLeftSide ) { addVertex( currentPointL, u1, 0 ); addVertex( outerPoint, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( outerPoint, u1, 0 ); addVertex( nextPointL, u1, 0 ); } else { addVertex( currentPointR, u1, 1 ); addVertex( outerPoint, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( outerPoint, u1, 1 ); addVertex( nextPointR, u1, 1 ); } } isMiter = true; } break; } } else { // The segment triangles are generated here when two consecutive points are collinear makeSegmentTriangles(); } } else { // The segment triangles are generated here if it is the ending segment makeSegmentTriangles(); } if ( ! isClosed && iPoint === numPoints - 1 ) { // Start line endcap addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 ); } // Increment loop variables u0 = u1; previousPoint = currentPoint; lastPointL.copy( nextPointL ); lastPointR.copy( nextPointR ); } if ( ! isClosed ) { // Ending line endcap addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 ); } else if ( innerSideModified && vertices ) { // Modify path first segment vertices to adjust to the segments inner and outer intersections var lastOuter = outerPoint; var lastInner = innerPoint; if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) { lastOuter = innerPoint; lastInner = outerPoint; } if ( joinIsOnLeftSide ) { if ( isMiter || initialJoinIsOnLeftSide ) { lastInner.toArray( vertices, 0 * 3 ); lastInner.toArray( vertices, 3 * 3 ); if ( isMiter ) { lastOuter.toArray( vertices, 1 * 3 ); } } } else { if ( isMiter || ! initialJoinIsOnLeftSide ) { lastInner.toArray( vertices, 1 * 3 ); lastInner.toArray( vertices, 3 * 3 ); if ( isMiter ) { lastOuter.toArray( vertices, 0 * 3 ); } } } } return numVertices; // -- End of algorithm // -- Functions function getNormal( p1, p2, result ) { result.subVectors( p2, p1 ); return result.set( - result.y, result.x ).normalize(); } function addVertex( position, u, v ) { if ( vertices ) { vertices[ currentCoordinate ] = position.x; vertices[ currentCoordinate + 1 ] = position.y; vertices[ currentCoordinate + 2 ] = 0; if ( normals ) { normals[ currentCoordinate ] = 0; normals[ currentCoordinate + 1 ] = 0; normals[ currentCoordinate + 2 ] = 1; } currentCoordinate += 3; if ( uvs ) { uvs[ currentCoordinateUV ] = u; uvs[ currentCoordinateUV + 1 ] = v; currentCoordinateUV += 2; } } numVertices += 3; } function makeCircularSector( center, p1, p2, u, v ) { // param p1, p2: Points in the circle arc. // p1 and p2 are in clockwise direction. tempV2_1.copy( p1 ).sub( center ).normalize(); tempV2_2.copy( p2 ).sub( center ).normalize(); var angle = Math.PI; var dot = tempV2_1.dot( tempV2_2 ); if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) ); angle /= arcDivisions; tempV2_3.copy( p1 ); for ( var i = 0, il = arcDivisions - 1; i < il; i ++ ) { tempV2_4.copy( tempV2_3 ).rotateAround( center, angle ); addVertex( tempV2_3, u, v ); addVertex( tempV2_4, u, v ); addVertex( center, u, 0.5 ); tempV2_3.copy( tempV2_4 ); } addVertex( tempV2_4, u, v ); addVertex( p2, u, v ); addVertex( center, u, 0.5 ); } function makeSegmentTriangles() { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointL, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( currentPointL, u1, 1 ); addVertex( currentPointR, u1, 0 ); } function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) { if ( innerSideModified ) { // Optimized segment + bevel triangles if ( joinIsOnLeftSide ) { // Path segments triangles addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointL, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( currentPointL, u1, 0 ); addVertex( innerPoint, u1, 1 ); // Bevel join triangle addVertex( currentPointL, u, 0 ); addVertex( nextPointL, u, 0 ); addVertex( innerPoint, u, 0.5 ); } else { // Path segments triangles addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointR, u1, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( innerPoint, u1, 0 ); addVertex( currentPointR, u1, 1 ); // Bevel join triangle addVertex( currentPointR, u, 1 ); addVertex( nextPointR, u, 0 ); addVertex( innerPoint, u, 0.5 ); } } else { // Bevel join triangle. The segment triangles are done in the main loop if ( joinIsOnLeftSide ) { addVertex( currentPointL, u, 0 ); addVertex( nextPointL, u, 0 ); addVertex( currentPoint, u, 0.5 ); } else { addVertex( currentPointR, u, 1 ); addVertex( nextPointR, u, 0 ); addVertex( currentPoint, u, 0.5 ); } } } function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) { if ( innerSideModified ) { if ( joinIsOnLeftSide ) { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointL, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( currentPointL, u1, 0 ); addVertex( innerPoint, u1, 1 ); addVertex( currentPointL, u0, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( innerPoint, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( nextPointL, u0, 0 ); addVertex( innerPoint, u1, 1 ); } else { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointR, u1, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( innerPoint, u1, 0 ); addVertex( currentPointR, u1, 1 ); addVertex( currentPointR, u0, 1 ); addVertex( innerPoint, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( innerPoint, u1, 0 ); addVertex( nextPointR, u0, 1 ); } } } function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) { // param center: End point of the path // param p1, p2: Left and right cap points switch ( style.strokeLineCap ) { case 'round': if ( start ) { makeCircularSector( center, p2, p1, u, 0.5 ); } else { makeCircularSector( center, p1, p2, u, 0.5 ); } break; case 'square': if ( start ) { tempV2_1.subVectors( p1, center ); tempV2_2.set( tempV2_1.y, - tempV2_1.x ); tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center ); tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center ); // Modify already existing vertices if ( joinIsOnLeftSide ) { tempV2_3.toArray( vertices, 1 * 3 ); tempV2_4.toArray( vertices, 0 * 3 ); tempV2_4.toArray( vertices, 3 * 3 ); } else { tempV2_3.toArray( vertices, 1 * 3 ); tempV2_3.toArray( vertices, 3 * 3 ); tempV2_4.toArray( vertices, 0 * 3 ); } } else { tempV2_1.subVectors( p2, center ); tempV2_2.set( tempV2_1.y, - tempV2_1.x ); tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center ); tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center ); var vl = vertices.length; // Modify already existing vertices if ( joinIsOnLeftSide ) { tempV2_3.toArray( vertices, vl - 1 * 3 ); tempV2_4.toArray( vertices, vl - 2 * 3 ); tempV2_4.toArray( vertices, vl - 4 * 3 ); } else { tempV2_3.toArray( vertices, vl - 2 * 3 ); tempV2_4.toArray( vertices, vl - 1 * 3 ); tempV2_4.toArray( vertices, vl - 4 * 3 ); } } break; case 'butt': default: // Nothing to do here break; } } function removeDuplicatedPoints( points ) { // Creates a new array if necessary with duplicated points removed. // This does not remove duplicated initial and ending points of a closed path. var dupPoints = false; for ( var i = 1, n = points.length - 1; i < n; i ++ ) { if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) { dupPoints = true; break; } } if ( ! dupPoints ) return points; var newPoints = []; newPoints.push( points[ 0 ] ); for ( var i = 1, n = points.length - 1; i < n; i ++ ) { if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) { newPoints.push( points[ i ] ); } } newPoints.push( points[ points.length - 1 ] ); return newPoints; } }; }(); export { SVGLoader };
import gwpy import numpy as np def compute_asd(signal): asd = signal.spectrogram2(fftlength=4, overlap=2, window='hanning') ** (1/2.) asd = asd.percentile(50) return asd def load_asd_from_file(filename): asd = np.loadtxt(filename) f = asd[:,0] asd = asd[:,1] asd= gwpy.frequencyseries.FrequencySeries(asd,frequencies=f) return asd def asd_calculation(signal,gps_ini,gps_end,file_path,det): import os dur = gps_end - gps_ini filename = det + '_ASD_'+str(gps_ini)+'_'+str(dur)+'.dat' #Check if file exists if os.path.exists(file_path+filename): print('File exists - loading') asd = load_asd_from_file(file_path+filename) else: print('Computing ASD for %s'%det) asd = compute_asd(signal) np.savetxt(file_path+filename,np.c_[asd.frequencies.value,asd.value], fmt='%.18e', delimiter=' ', newline='\n') return asd def Q_to_image(sig_qt,m=-1): sig_qt_norm=sig_qt-sig_qt.min() if m == -1: sig_qt_norm=np.uint8(sig_qt_norm*255/sig_qt_norm.max()) else: sig_qt_norm=np.uint8(sig_qt_norm*255/m) return sig_qt_norm
'use strict'; var util = require('./util.js'); module.exports = function(client){ var marketplace = {}; /** * Copy the getInventory function from the user module */ marketplace.getInventory = require('./user.js')(client).getInventory; /** * Get a marketplace listing * @param {(number|string)} listing - The listing ID * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.getListing = function(listing, callback){ return client.get('/marketplace/listings/'+listing, callback); }; /** * Create a marketplace listing * @param {object} data - The data for the listing * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.addListing = function(data, callback){ return client.post({url: '/marketplace/listings', authLevel: 2}, data, callback); }; /** * Edit a marketplace listing * @param {(number|string)} listing - The listing ID * @param {object} data - The data for the listing * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.editListing = function(listing, data, callback){ return client.post({url: '/marketplace/listings/'+listing, authLevel: 2}, data, callback); }; /** * Delete a marketplace listing * @param {(number|string)} [listing] - The listing ID * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.deleteListing = function(listing, callback){ return client.delete({url: '/marketplace/listings/'+listing, authLevel: 2}, callback); }; /** * Get a list of the authenticated user's orders * @param {object} [params] - Optional sorting and pagination params * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.getOrders = function(params, callback){ var path = '/marketplace/orders'; if((arguments.length === 1) && (typeof params === 'function')){ callback = params; }else if(typeof params === 'object'){ path = util.addParams(path, params); } return client.get({url: path, authLevel: 2}, callback); }; /** * Get details of a marketplace order * @param {string} order - The order ID * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.getOrder = function(order, callback){ return client.get({url: '/marketplace/orders/'+order, authLevel: 2}, callback); }; /** * Edit a marketplace order * @param {string} order - The order ID * @param {object} data - The data for the order * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.editOrder = function(order, data, callback){ return client.post({url: '/marketplace/orders/'+order, authLevel: 2}, data, callback); }; /** * List the messages for the given order ID * @param {string} order - The order ID * @param {object} [params] - Optional pagination parameters * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.getOrderMessages = function(order, params, callback){ var path = '/marketplace/orders/'+order+'/messages'; if((arguments.length === 2) && (typeof params === 'function')){ callback = params; }else{ path = util.addParams(path, params); } return client.get({url: path, authLevel: 2}, callback); }; /** * Add a message to the given order ID * @param {string} order - The order ID * @param {object} data - The message data * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.addOrderMessage = function(order, data, callback){ return client.post({url: '/marketplace/orders/'+order+'/messages', authLevel: 2}, data, callback); }; /** * Get the marketplace fee for a given price * @param {(number|string)} price - The price as a number or string * @param {string} [currency] - Optional currency as one of USD, GBP, EUR, CAD, AUD, or JPY. Defaults to USD. * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.getFee = function(price, currency, callback){ var path = '/marketplace/fee/'+((typeof price === 'number') ? price.toFixed(2) : price); if((arguments.length === 2) && (typeof currency === 'function')){ callback = currency; }else if(currency){ // Get the fee in a given currency path += '/'+currency; } return client.get(path, callback); }; /** * Get price suggestions for a given release ID in the user's selling currency * @param {(number|string)} release - The release ID * @param {function} [callback] - The callback * @return {DiscogsClient|Promise} */ marketplace.getPriceSuggestions = function(release, callback){ return client.get({url: '/marketplace/price_suggestions/'+release, authLevel: 2}, callback); }; marketplace.search = function(release, callback){ return client.get({url: '/marketplace/search?release_id='+release+'&sort=price&order=asc&per_page=500', authLevel: 2}, callback); }; return marketplace; };
from flask import Flask, send_file, request from generator import gen app = Flask(__name__) @app.route('/api/v1/generator', methods=['GET']) def gen_meme(): try: base = request.args['base'] logo = request.args['logo'] logo_pos = request.args['logo_pos'] text = request.args['text'] meme_quality = int(request.args['meme_quality']) logo_opacity = int(request.args['logo_opacity']) tempFileObj = gen(base, logo, logo_pos, text, meme_quality, logo_opacity) response = send_file(tempFileObj, as_attachment=False, attachment_filename='meme.jpg') return response except: return "<h1 align='center'>Uepa!</h1><p align='center'>Algo deu errado.</p>" @app.route('/api/v1/generator/download', methods=['GET']) def download_meme(): try: base = request.args['base'] logo = request.args['logo'] logo_pos = request.args['logo_pos'] text = request.args['text'] meme_quality = int(request.args['meme_quality']) logo_opacity = int(request.args['logo_opacity']) tempFileObj = gen(base, logo, logo_pos, text, meme_quality, logo_opacity) response = send_file(tempFileObj, as_attachment=True, attachment_filename='meme.jpg') return response except: return "<h1 align='center'>Uepa!</h1><p align='center'>Algo deu errado.</p>"
exports.seed = function(knex) { return knex("role") .del() .then(function() { return knex("role").insert([ { name: "admin" }, { name: "individuel" }, { name: "prepose" }, { name: "ti" }, { name: "service" }, { name: "direction" }, { name: "direction_national" }, { name: "direction_regional" }, { name: "direction_departemental" } ]); }); };
import pytest from plenum.common.messages.fields import SerializedValueField validator = SerializedValueField() def test_non_empty_string(): assert not validator.validate("x") def test_empty_string(): assert validator.validate("") def test_non_empty_bytes(): assert not validator.validate(b"hello") def test_empty_bytes(): assert validator.validate(b"")
"""Course description Coloumn now uses TEXT instead of VARCHAR Revision ID: 04ac99d8a7ab Revises: 35195e81a197 Create Date: 2022-03-16 20:31:14.198726 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = "04ac99d8a7ab" down_revision = "35195e81a197" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### try: op.alter_column( "course", "description", existing_type=mysql.VARCHAR(length=255), type_=sa.Text(), existing_nullable=True, ) op.add_column("task", sa.Column("can_be_solved", sa.Boolean(), nullable=True)) except Exception as e: print(e) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("task", "can_be_solved") op.alter_column( "course", "description", existing_type=sa.Text(), type_=mysql.VARCHAR(length=255), existing_nullable=True, ) # ### end Alembic commands ###
import traceback import cea.inputlocator from legacy.arcgis import arcpy import pandas as pd __author__ = "Jimeno A. Fonseca" __copyright__ = "Copyright 2013, Architecture and Building Systems - ETH Zurich" __credits__ = ["Jimeno A. Fonseca", "Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" def calculate_radiation_for_all_days(daily_transmissivity, dem_rasterfinal_path, latitude, locator, observers_path, path_arcgis_db): # let's just be sure this is set arcpy.env.workspace = path_arcgis_db arcpy.env.overwriteOutput = True arcpy.CheckOutExtension("spatial") aspect_slope = "FROM_DEM" heightoffset = 1 temporary_folder = locator.get_temporary_folder() for day in range(1, 366): calculate_radiation_single_day(day, dem_rasterfinal_path, observers_path, daily_transmissivity, latitude, temporary_folder, aspect_slope, heightoffset, path_arcgis_db) def calculate_radiation_single_day(day, in_surface_raster, in_points_feature, T_G_day, latitude, locationtemp1, aspect_slope, heightoffset, path_arcgis_db): # Local Variables Latitude = str(latitude) skySize = '1400' # max 10000 dayInterval = '1' hourInterval = '1' calcDirections = '32' zenithDivisions = '512' # max 1200cor hlaf the skysize azimuthDivisions = '80' # max 160 diffuseProp = str(T_G_day.loc[day, 'diff']) transmittivity = str(T_G_day.loc[day, 'trr']) heightoffset = str(heightoffset) global_radiation = locationtemp1 + '\\' + 'Day_' + str(day) + '.shp' timeConfig = 'WithinDay ' + str(day) + ', 0, 24' arcpy.env.workspace = path_arcgis_db arcpy.env.overwriteOutput = True arcpy.CheckOutExtension("spatial") # Run the extension of arcgis, retry max_retries times before giving up... max_retries = 3 for _ in range(max_retries): try: arcpy.sa.PointsSolarRadiation(in_surface_raster, in_points_feature, global_radiation, heightoffset, Latitude, skySize, timeConfig, dayInterval, hourInterval, "INTERVAL", "1", aspect_slope, calcDirections, zenithDivisions, azimuthDivisions, "STANDARD_OVERCAST_SKY", diffuseProp, transmittivity, "#", "#", "#") print('complete calculating radiation of day No. %(day)i' % locals()) return arcpy.GetMessages() except: print(traceback.format_exc()) raise AssertionError('CalcRadiation failed %(max_retries)i times... giving up!' % locals()) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--scenario', help='Path to the scenario folder') parser.add_argument('--daily-transmissivity-pickle', help='Path to a pickle of the daily_transmissivity dataframe') parser.add_argument('--latitude', help='Latitude', type=float) parser.add_argument('--observers-path', help='path to observers feature layer') parser.add_argument('--dem-rasterfinal-path', help='path to the DEM with the burnt-in buildings') parser.add_argument('--arcgis_db', help='path to arcgis geodatabase') args = parser.parse_args() locator = cea.inputlocator.InputLocator(args.scenario) daily_transmissivity = pd.read_pickle(args.daily_transmissivity_pickle) calculate_radiation_for_all_days(daily_transmissivity=daily_transmissivity, dem_rasterfinal_path=args.dem_rasterfinal_path, latitude=args.latitude, locator=locator, observers_path=args.observers_path, path_arcgis_db=args.arcgis_db)
#pragma once #include <string> #include <iostream> using namespace std; enum eHidStatus; /// <summary> /// Stores and retrieves information about the currently focused window /// </summary> class CFocusAppInfo { public: CFocusAppInfo(void); ~CFocusAppInfo(void); public: /// <summary> /// A handle to the window that currently has focus /// </summary> HWND m_hFocus; /// <summary> /// The process ID of the process that owns this window /// </summary> DWORD m_pid; /// <summary> /// The thread ID of the thread that owns this window /// </summary> DWORD m_tid; // Window extent information RECT m_rcWindow; RECT m_rcClient; /// <summary> /// The title of the target window /// </summary> wstring m_windowTitle; /// <summary> /// The name of the process that owns the focus window /// </summary> wstring m_ownerExeName; /// <summary> /// The full path to the process's executable /// </summary> wstring m_ownerExePath; public: /// <summary> /// Gets information about the currently focused window /// </summary> eHidStatus Update(void); }; /// <summary> /// Debug stream manipulator for dumping the contents of this structure /// </summary> wostream& operator<<(wostream& os, CFocusAppInfo& rhs);
from .roleerror import RoleError class PasswordError(RoleError): ''' Password exception class '''
from .triangle import Triangle
import getpass import json import sys import warnings import click from . import main from .pretty import print_done, print_error, print_fail, print_warn from .. import __version__ from ..config import get_config, local_state_path from ..exceptions import BackendClientError from ..session import Session @main.command() def config(): ''' Shows the current configuration. ''' config = get_config() click.echo('API endpoint: {0} (mode: {1})'.format( click.style(str(config.endpoint), bold=True), click.style(str(config.endpoint_type), fg='cyan', bold=True))) click.echo('Client version: {0} (API: {1})'.format( click.style(__version__, bold=True), click.style(config.version, bold=True), )) if sys.stdout.isatty(): click.echo('Server version: ...') click.echo('Negotiated API version: ...') else: with Session() as sess: try: versions = sess.System.get_versions() except BackendClientError: click.echo('Server version: (failed to fetch)') else: click.echo('Server version: {0} (API: {1})'.format( versions.get('manager', 'pre-19.03'), versions['version'], )) click.echo('Negotiated API version: {0}'.format(sess.api_version)) nrows = 1 if config.domain: click.echo('Domain name: "{0}"'.format(click.style(config.domain, bold=True))) nrows += 1 if config.group: click.echo('Group name: "{0}"'.format(click.style(config.group, bold=True))) nrows += 1 if config.is_anonymous: click.echo('Access key: (this is an anonymous session)') nrows += 1 elif config.endpoint_type == 'docker': pass elif config.endpoint_type == 'session': if (local_state_path / 'cookie.dat').exists() and \ (local_state_path / 'config.json').exists(): sess_config = json.loads((local_state_path / 'config.json').read_text()) click.echo('Username: "{0}"'.format(click.style(sess_config.get('username', ''), bold=True))) nrows += 1 else: click.echo('Access key: "{0}"'.format(click.style(config.access_key, bold=True))) nrows += 1 masked_skey = config.secret_key[:6] + ('*' * 24) + config.secret_key[-10:] click.echo('Secret key: "{0}"'.format(click.style(masked_skey, bold=True))) nrows += 1 click.echo('Signature hash type: {0}'.format( click.style(config.hash_type, bold=True))) nrows += 1 click.echo('Skip SSL certificate validation? {0}'.format( click.style(str(config.skip_sslcert_validation), bold=True))) nrows += 1 if sys.stdout.isatty(): sys.stdout.flush() with warnings.catch_warnings(record=True) as captured_warnings, Session() as sess: click.echo('\u001b[{0}A\u001b[2K'.format(nrows + 1), nl=False) try: versions = sess.System.get_versions() except BackendClientError: click.echo('Server version: {0}'.format( click.style('(failed to fetch)', fg='red', bold=True), )) else: click.echo('Server version: {0} (API: {1})'.format( click.style(versions.get('manager', 'pre-19.03'), bold=True), click.style(versions['version'], bold=True), )) click.echo('\u001b[2K', nl=False) click.echo('Negotiated API version: {0}'.format( click.style('v{0[0]}.{0[1]}'.format(sess.api_version), bold=True), )) click.echo('\u001b[{0}B'.format(nrows), nl=False) sys.stdout.flush() for w in captured_warnings: warnings.showwarning(w.message, w.category, w.filename, w.lineno, w.line) @main.command() def login(): ''' Log-in to the console API proxy. It stores the current session cookie in the OS-default local application data location. ''' user_id = input('User ID: ') password = getpass.getpass() config = get_config() if config.endpoint_type != 'session': print_warn('To use login, your endpoint type must be "session".') raise click.Abort() with Session() as session: try: result = session.Auth.login(user_id, password) if not result['authenticated']: print_fail('Login failed.') sys.exit(1) print_done('Login succeeded.') local_state_path.mkdir(parents=True, exist_ok=True) session.aiohttp_session.cookie_jar.update_cookies(result['cookies']) session.aiohttp_session.cookie_jar.save(local_state_path / 'cookie.dat') (local_state_path / 'config.json').write_text(json.dumps(result.get('config', {}))) except Exception as e: print_error(e) @main.command() def logout(): ''' Log-out from the console API proxy and clears the local cookie data. ''' config = get_config() if config.endpoint_type != 'session': print_warn('To use logout, your endpoint type must be "session".') raise click.Abort() with Session() as session: try: session.Auth.logout() print_done('Logout done.') try: (local_state_path / 'cookie.dat').unlink() (local_state_path / 'config.json').unlink() except (IOError, PermissionError): pass except Exception as e: print_error(e) @main.command() @click.argument('old_password', metavar='OLD_PASSWORD') @click.argument('new_password', metavar='NEW_PASSWORD') @click.argument('new_password2', metavar='NEW_PASSWORD2') def update_password(old_password, new_password, new_password2): ''' Update user's password. ''' config = get_config() if config.endpoint_type != 'session': print_warn('To update password, your endpoint type must be "session".') raise click.Abort() with Session() as session: try: session.Auth.update_password(old_password, new_password, new_password2) print_done('Password updated.') except Exception as e: print_error(e)
export const USER_LOGIN = 'USER_LOGIN'; export function userLogin(user) { return { type: USER_LOGIN, user }; } export const USER_LOGOUT = 'USER_LOGOUT'; export function userLogout() { return { type: USER_LOGOUT }; }
""" Add the exit_code column to the Job and Task tables. """ import logging from sqlalchemy import ( Column, Integer, MetaData, Table, ) log = logging.getLogger(__name__) metadata = MetaData() # There was a bug when only one column was used for both tables, # so create separate columns. exit_code_job_col = Column("exit_code", Integer, nullable=True) exit_code_task_col = Column("exit_code", Integer, nullable=True) def upgrade(migrate_engine): print(__doc__) metadata.bind = migrate_engine metadata.reflect() # Add the exit_code column to the Job table. try: job_table = Table("job", metadata, autoload=True) exit_code_job_col.create(job_table) assert exit_code_job_col is job_table.c.exit_code except Exception: log.exception("Adding column 'exit_code' to job table failed.") # Add the exit_code column to the Task table. try: task_table = Table("task", metadata, autoload=True) exit_code_task_col.create(task_table) assert exit_code_task_col is task_table.c.exit_code except Exception: log.exception("Adding column 'exit_code' to task table failed.") def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() # Drop the Job table's exit_code column. try: job_table = Table("job", metadata, autoload=True) exit_code_col = job_table.c.exit_code exit_code_col.drop() except Exception: log.exception("Dropping 'exit_code' column from job table failed.") # Drop the Job table's exit_code column. try: task_table = Table("task", metadata, autoload=True) exit_code_col = task_table.c.exit_code exit_code_col.drop() except Exception: log.exception("Dropping 'exit_code' column from task table failed.")
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var React = require('React'); var Site = require('Site'); var center = require('center'); var H2 = require('H2'); var support = React.createClass({ render: function() { return ( <Site section="support" title="Support"> <section className="content wrap documentationContent nosidebar"> <div className="inner-content"> <h1>Need help?</h1> <div className="subHeader"></div> <p> <strong>React Native</strong> is worked on full-time by Facebook&#39;s product infrastructure user interface engineering teams. They&#39;re often around and available for questions. </p> <H2>Community translation</H2> <p>The following is a list of translated docs offered by community volunteers. Send a pull request to fill the list!</p> <ul> <li><a href="http://reactnative.cn">Chinese</a> (<a href="https://github.com/reactnativecn/react-native-docs-cn">source</a>)</li> </ul> <H2>Stack Overflow</H2> <p>Many members of the community use Stack Overflow to ask questions. Read through the <a href="http://stackoverflow.com/questions/tagged/react-native">existing questions</a> tagged with <strong>react-native</strong> or <a href="http://stackoverflow.com/questions/ask">ask your own</a>!</p> <H2>Chat</H2> <p>Join us in <strong><a href="irc://chat.freenode.net/reactnative">#reactnative on Reactiflux</a></strong>.</p> <H2>Twitter</H2> <p><a href="https://twitter.com/search?q=%23reactnative"><strong>#reactnative</strong> hash tag on Twitter</a> is used to keep up with the latest React Native news.</p> <p><center><a className="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactnative" data-widget-id="565960513457098753"></a></center></p> </div> </section> </Site> ); } }); module.exports = support;
"""MobileNet and MobileNetV2.""" import torch import torch.nn as nn from core.nn import _ConvBNReLU, _DepthwiseConv, InvertedResidual __all__ = ['MobileNet', 'MobileNetV2', 'get_mobilenet', 'get_mobilenet_v2', 'mobilenet1_0', 'mobilenet_v2_1_0', 'mobilenet0_75', 'mobilenet_v2_0_75', 'mobilenet0_5', 'mobilenet_v2_0_5', 'mobilenet0_25', 'mobilenet_v2_0_25'] class MobileNet(nn.Module): def __init__(self, num_classes=1000, multiplier=1.0, norm_layer=nn.BatchNorm2d, **kwargs): super(MobileNet, self).__init__() conv_dw_setting = [ [64, 1, 1], [128, 2, 2], [256, 2, 2], [512, 6, 2], [1024, 2, 2]] input_channels = int(32 * multiplier) if multiplier > 1.0 else 32 features = [_ConvBNReLU(3, input_channels, 3, 2, 1, norm_layer=norm_layer)] for c, n, s in conv_dw_setting: out_channels = int(c * multiplier) for i in range(n): stride = s if i == 0 else 1 features.append(_DepthwiseConv(input_channels, out_channels, stride, norm_layer)) input_channels = out_channels features.append(nn.AdaptiveAvgPool2d(1)) self.features = nn.Sequential(*features) self.classifier = nn.Linear(int(1024 * multiplier), num_classes) # weight initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out') if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.BatchNorm2d): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.zeros_(m.bias) def forward(self, x): x = self.features(x) x = self.classifier(x.view(x.size(0), x.size(1))) return x class MobileNetV2(nn.Module): def __init__(self, num_classes=1000, multiplier=1.0, norm_layer=nn.BatchNorm2d, **kwargs): super(MobileNetV2, self).__init__() inverted_residual_setting = [ # t, c, n, s [1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1]] # building first layer input_channels = int(32 * multiplier) if multiplier > 1.0 else 32 last_channels = int(1280 * multiplier) if multiplier > 1.0 else 1280 # features = [_ConvBNReLU(3, input_channels, 3, 2, 1, relu6=True, norm_layer=norm_layer)] # # building inverted residual blocks # for t, c, n, s in inverted_residual_setting: # out_channels = int(c * multiplier) # for i in range(n): # stride = s if i == 0 else 1 # features.append(InvertedResidual(input_channels, out_channels, stride, t, norm_layer)) # input_channels = out_channels # # building last several layers # features.append(_ConvBNReLU(input_channels, last_channels, 1, relu6=True, norm_layer=norm_layer)) # features.append(nn.AdaptiveAvgPool2d(1)) down8 = [_ConvBNReLU(3, input_channels, 3, 2, 1, relu6=True, norm_layer=norm_layer)] for t, c, n, s in inverted_residual_setting[:3]: out_channels = int(c * multiplier) for i in range(n): stride = s if i == 0 else 1 down8.append(InvertedResidual(input_channels, out_channels, stride, t, norm_layer)) input_channels = out_channels self.down8 = nn.Sequential(*down8) down16 = [] for t, c, n, s in inverted_residual_setting[3:5]: out_channels = int(c * multiplier) for i in range(n): stride = s if i == 0 else 1 down16.append(InvertedResidual(input_channels, out_channels, stride, t, norm_layer)) input_channels = out_channels self.down16 = nn.Sequential(*down16) down32 = [] for t, c, n, s in inverted_residual_setting[5:]: out_channels = int(c * multiplier) for i in range(n): stride = s if i == 0 else 1 down32.append(InvertedResidual(input_channels, out_channels, stride, t, norm_layer)) input_channels = out_channels down32.append(_ConvBNReLU(input_channels, last_channels, 1, relu6=True, norm_layer=norm_layer)) # down32.append(nn.AdaptiveAvgPool2d(1)) self.down32 = nn.Sequential(*down32) # self.features = nn.Sequential(*features) self.classifier = nn.Sequential( nn.Dropout2d(0.2), nn.Linear(last_channels, num_classes)) # weight initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out') if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.BatchNorm2d): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) if m.bias is not None: nn.init.zeros_(m.bias) def forward(self, x): x = self.down8(x) x = self.down16(x) x = self.down32(x) x = self.classifier(x.view(x.size(0), x.size(1))) return x # Constructor def get_mobilenet(multiplier=1.0, pretrained=False, root='~/.torch/models', **kwargs): model = MobileNet(multiplier=multiplier, **kwargs) if pretrained: raise ValueError("Not support pretrained") return model def get_mobilenet_v2(multiplier=1.0, pretrained=False, root='~/.torch/models', **kwargs): model = MobileNetV2(multiplier=multiplier, **kwargs) if pretrained: raise ValueError("Not support pretrained") return model def mobilenet1_0(**kwargs): return get_mobilenet(1.0, **kwargs) def mobilenet_v2_1_0(**kwargs): return get_mobilenet_v2(1.0, **kwargs) def mobilenet0_75(**kwargs): return get_mobilenet(0.75, **kwargs) def mobilenet_v2_0_75(**kwargs): return get_mobilenet_v2(0.75, **kwargs) def mobilenet0_5(**kwargs): return get_mobilenet(0.5, **kwargs) def mobilenet_v2_0_5(**kwargs): return get_mobilenet_v2(0.5, **kwargs) def mobilenet0_25(**kwargs): return get_mobilenet(0.25, **kwargs) def mobilenet_v2_0_25(**kwargs): return get_mobilenet_v2(0.25, **kwargs) if __name__ == '__main__': model = mobilenet0_5()
''' Module used to validate the input ''' # validate fields from validators import ipv4, domain # used to get the current public IP from json import load from urllib2 import urlopen # colors from vars import ccolors # validate the input based on the passed args def validateInput(args): if not args.victim or not args.targetDomain or not args.addressToForge: return False if not ipv4(args.victim): print ccolors.WARNING + 'Victim is not a valid IP address\n' + ccolors.FAIL + 'Terminating...' + ccolors.NC return False if not domain(args.targetDomain): #supports IDN print ccolors.WARNING + 'Target is not a valid domain\n' + ccolors.FAIL + 'Terminating...' + ccolors.NC return False if args.addressToForge == 'myip' or args.addressToForge == 'myIP': # get user's current IP address from this URL args.addressToForge = load(urlopen('http://jsonip.com'))['ip'] elif not ipv4(args.addressToForge): print ccolors.WARNING + 'Spoofing IP is not a valid IP address\n' + ccolors.FAIL + 'Terminating...' + ccolors.NC return False if args.demo and not ipv4(args.demo): print ccolors.WARNING + 'Demo IP is not a valid IP address\n' + ccolors.FAIL + 'Terminating...' + ccolors.NC return False return True
"use strict"; require("should"); function customImporter(path, prev) { path.should.equal("import-with-custom-logic"); prev.should.match(/(sass|scss)[/\\]custom-importer\.(scss|sass)/); this.should.have.property("options"); // eslint-disable-line no-invalid-this return customImporter.returnValue; } customImporter.returnValue = { contents: ".custom-imported {}" }; module.exports = customImporter;
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # 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. """Contains the data classes of the Yahoo! Media RSS Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core MEDIA_TEMPLATE = '{http://search.yahoo.com/mrss//}%s' class MediaCategory(atom.core.XmlElement): """Describes a media category.""" _qname = MEDIA_TEMPLATE % 'category' scheme = 'scheme' label = 'label' class MediaCopyright(atom.core.XmlElement): """Describes a media copyright.""" _qname = MEDIA_TEMPLATE % 'copyright' url = 'url' class MediaCredit(atom.core.XmlElement): """Describes a media credit.""" _qname = MEDIA_TEMPLATE % 'credit' role = 'role' scheme = 'scheme' class MediaDescription(atom.core.XmlElement): """Describes a media description.""" _qname = MEDIA_TEMPLATE % 'description' type = 'type' class MediaHash(atom.core.XmlElement): """Describes a media hash.""" _qname = MEDIA_TEMPLATE % 'hash' algo = 'algo' class MediaKeywords(atom.core.XmlElement): """Describes a media keywords.""" _qname = MEDIA_TEMPLATE % 'keywords' class MediaPlayer(atom.core.XmlElement): """Describes a media player.""" _qname = MEDIA_TEMPLATE % 'player' height = 'height' width = 'width' url = 'url' class MediaRating(atom.core.XmlElement): """Describes a media rating.""" _qname = MEDIA_TEMPLATE % 'rating' scheme = 'scheme' class MediaRestriction(atom.core.XmlElement): """Describes a media restriction.""" _qname = MEDIA_TEMPLATE % 'restriction' relationship = 'relationship' type = 'type' class MediaText(atom.core.XmlElement): """Describes a media text.""" _qname = MEDIA_TEMPLATE % 'text' end = 'end' lang = 'lang' type = 'type' start = 'start' class MediaThumbnail(atom.core.XmlElement): """Describes a media thumbnail.""" _qname = MEDIA_TEMPLATE % 'thumbnail' time = 'time' url = 'url' width = 'width' height = 'height' class MediaTitle(atom.core.XmlElement): """Describes a media title.""" _qname = MEDIA_TEMPLATE % 'title' type = 'type' class MediaContent(atom.core.XmlElement): """Describes a media content.""" _qname = MEDIA_TEMPLATE % 'content' bitrate = 'bitrate' is_default = 'isDefault' medium = 'medium' height = 'height' credit = [MediaCredit] language = 'language' hash = MediaHash width = 'width' player = MediaPlayer url = 'url' file_size = 'fileSize' channels = 'channels' expression = 'expression' text = [MediaText] samplingrate = 'samplingrate' title = MediaTitle category = [MediaCategory] rating = [MediaRating] type = 'type' description = MediaDescription framerate = 'framerate' thumbnail = [MediaThumbnail] duration = 'duration' copyright = MediaCopyright keywords = MediaKeywords restriction = [MediaRestriction] class MediaGroup(atom.core.XmlElement): """Describes a media group.""" _qname = MEDIA_TEMPLATE % 'group' credit = [MediaCredit] content = [MediaContent] copyright = MediaCopyright description = MediaDescription category = [MediaCategory] player = MediaPlayer rating = [MediaRating] hash = MediaHash title = MediaTitle keywords = MediaKeywords restriction = [MediaRestriction] thumbnail = [MediaThumbnail] text = [MediaText]
import pytest import json from hamcrest import * from vinyldns_python import VinylDNSClient def test_list_group_members_success(shared_zone_test_context): """ Test that we can list all the members of a group """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: new_group = { 'name': 'test-list-group-members-success', 'email': 'test@test.com', 'members': [ { 'id': 'ok'}, { 'id': 'dummy' } ], 'admins': [ { 'id': 'ok'} ] } members = sorted(['dummy', 'ok']) saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) assert_that(result['members'], has_length(len(members))) result_member_ids = map(lambda member: member['id'], result['members']) for id in members: assert_that(result_member_ids, has_item(id)) result = client.list_members_group(saved_group['id'], status=200) result = sorted(result['members'], key=lambda user: user['id']) assert_that(result, has_length(len(members))) dummy = result[0] assert_that(dummy['id'], is_('dummy')) assert_that(dummy['userName'], is_('dummy')) assert_that(dummy['isAdmin'], is_(False)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) ok = result[1] assert_that(ok['id'], is_('ok')) assert_that(ok['userName'], is_('ok')) assert_that(ok['isAdmin'], is_(True)) assert_that(ok['firstName'], is_('ok')) assert_that(ok['lastName'], is_('ok')) assert_that(ok['email'], is_('test@test.com')) assert_that(ok['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_not_found(shared_zone_test_context): """ Tests that we can not list the members of a non-existent group """ client = shared_zone_test_context.ok_vinyldns_client client.list_members_group('not_found', status=404) def test_list_group_members_start_from(shared_zone_test_context): """ Test that we can list the members starting from a given user """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-start-from', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) assert_that(result['members'], has_item({ 'id': 'ok'})) result_member_ids = map(lambda member: member['id'], result['members']) for user in members: assert_that(result_member_ids, has_item(user['id'])) result = client.list_members_group(saved_group['id'], start_from='dummy050', status=200) group_members = sorted(result['members'], key=lambda user: user['id']) assert_that(result['startFrom'], is_('dummy050')) assert_that(result['nextId'], is_('dummy150')) assert_that(group_members, has_length(100)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i+51) #starts from dummy051 user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy['isAdmin'], is_(False)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_start_from_non_user(shared_zone_test_context): """ Test that we can list the members starting from a non existent username """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-start-from-nonexistent', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) result = client.list_members_group(saved_group['id'], start_from='abc', status=200) group_members = sorted(result['members'], key=lambda user: user['id']) assert_that(result['startFrom'], is_('abc')) assert_that(result['nextId'], is_('dummy099')) assert_that(group_members, has_length(100)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy['isAdmin'], is_(False)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_max_item(shared_zone_test_context): """ Test that we can chose the number of items to list """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-max-items', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) result = client.list_members_group(saved_group['id'], max_items=10, status=200) group_members = sorted(result['members'], key=lambda user: user['id']) assert_that(result['nextId'], is_('dummy009')) assert_that(result['maxItems'], is_(10)) assert_that(group_members, has_length(10)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy['isAdmin'], is_(False)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_max_item_default(shared_zone_test_context): """ Test that the default for max_item is 100 items """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-max-items-default', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) result = client.list_members_group(saved_group['id'], status=200) group_members = sorted(result['members'], key=lambda user: user['id']) assert_that(result['nextId'], is_('dummy099')) assert_that(group_members, has_length(100)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy['isAdmin'], is_(False)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_max_item_zero(shared_zone_test_context): """ Test that the call fails when max_item is 0 """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-max-items-zero', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) client.list_members_group(saved_group['id'], max_items=0, status=400) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_max_item_over_1000(shared_zone_test_context): """ Test that the call fails when max_item is over 1000 """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-max-items-over-limit', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) client.list_members_group(saved_group['id'], max_items=1001, status=400) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_next_id_correct(shared_zone_test_context): """ Test that the correct next_id is returned """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 200): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-next-id', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) result = client.list_members_group(saved_group['id'], status=200) group_members = sorted(result['members'], key=lambda user: user['id']) assert_that(result['nextId'], is_('dummy099')) assert_that(group_members, has_length(100)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy['isAdmin'], is_(False)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_next_id_exhausted(shared_zone_test_context): """ Test that the next_id is null when the list is exhausted """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 5): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-next-id-exhausted', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) result = client.list_members_group(saved_group['id'], status=200) group_members = sorted(result['members'], key=lambda user: user['id']) assert_that(result, is_not(has_key('nextId'))) assert_that(group_members, has_length(6)) # add one more for the admin for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_next_id_exhausted_two_pages(shared_zone_test_context): """ Test that the next_id is null when the list is exhausted over 2 pages """ client = shared_zone_test_context.ok_vinyldns_client saved_group = None try: members = [] for runner in range(0, 19): id = "dummy{0:0>3}".format(runner) members.append({ 'id': id }) members = sorted(members) new_group = { 'name': 'test-list-group-members-next-id-exhausted-two-pages', 'email': 'test@test.com', 'members': members, 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) result = client.get_group(saved_group['id'], status=200) # members has one more because admins are added as members assert_that(result['members'], has_length(len(members) + 1)) result_member_ids = map(lambda member: member['id'], result['members']) assert_that(result_member_ids, has_item('ok')) for user in members: assert_that(result_member_ids, has_item(user['id'])) first_page = client.list_members_group(saved_group['id'], max_items=10, status=200) group_members = sorted(first_page['members'], key=lambda user: user['id']) assert_that(first_page['nextId'], is_('dummy009')) assert_that(first_page['maxItems'], is_(10)) assert_that(group_members, has_length(10)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) second_page = client.list_members_group(saved_group['id'], start_from=first_page['nextId'], max_items=10, status=200) group_members = sorted(second_page['members'], key=lambda user: user['id']) assert_that(second_page, is_not(has_key('nextId'))) assert_that(second_page['maxItems'], is_(10)) assert_that(group_members, has_length(10)) for i in range(0, len(group_members)-1): dummy = group_members[i] id = "dummy{0:0>3}".format(i+10) user_name = "name-"+id assert_that(dummy['id'], is_(id)) assert_that(dummy['userName'], is_(user_name)) assert_that(dummy, is_not(has_key('firstName'))) assert_that(dummy, is_not(has_key('lastName'))) assert_that(dummy, is_not(has_key('email'))) assert_that(dummy['created'], is_not(none())) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404)) def test_list_group_members_unauthed(shared_zone_test_context): """ Tests that we cant list members without access """ client = shared_zone_test_context.ok_vinyldns_client dummy_client = shared_zone_test_context.dummy_vinyldns_client saved_group = None try: new_group = { 'name': 'test-list-group-members-unauthed', 'email': 'test@test.com', 'members': [ { 'id': 'ok'} ], 'admins': [ { 'id': 'ok'} ] } saved_group = client.create_group(new_group, status=200) dummy_client.list_members_group(saved_group['id'], status=403) client.list_members_group(saved_group['id'], status=200) finally: if saved_group: client.delete_group(saved_group['id'], status=(200,404))
"""Configuration Addon.""" # Copyright 2015-present Scikit Flow Authors. All Rights Reserved. # # 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. from __future__ import division, print_function, absolute_import import tensorflow as tf class ConfigAddon(object): """This class specifies the specific configurations for a session. Parameters: num_cores: Number of cores to be used. (default: 4) verbose: Controls the verbosity, possible values: 0: the algorithm and debug information is muted. 1: trainer prints the progress. 2: log device placement is printed. gpu_memory_fraction: Fraction of GPU memory used by the process on each GPU uniformly on the same machine. """ def __init__(self, num_cores=4, verbose=1, gpu_memory_fraction=1): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction) self.config = tf.ConfigProto(log_device_placement=(verbose > 1), inter_op_parallelism_threads=num_cores, intra_op_parallelism_threads=num_cores, gpu_options=gpu_options)
import request from '@/utils/request' export function fetchList(data) { return request({ url: '/vue-admin-template/user/list', method: 'post', data }) } export function createListItem(data) { console.log(data) return request({ url: '/vue-admin-template/user/create', method: 'post', data }) } export function updateListItem(data) { return request({ url: '/vue-admin-template/user/update', method: 'post', data }) } export function fetchListItem(data) { return request({ url: '/vue-admin-template/user/searchdate', method: 'post', params: data }) } export function deleteListItem(data) { return request({ url: `/vue-admin-template/user/delete`, method: 'post', data }) } /*export function deleteList(data) { return request({ url: '/vue-admin-template/user/delete', method: 'post', data }) }*/ export function checkSameName(data) { return request({ url: '/vue-admin-template/user/check', method: 'post', data }) }
export default { name: 'Funnel', props: [ { name: 'data', type: 'Array', defaultVal: 'undefined', isOptional: false, desc: { 'en-US': 'The source data, in which each element is an object.', 'zh-CN': '输入数据,现在支持的类型是对象数组。', }, format: [ '[{ name: \'a\', value: 12 }]', '[{ name: \'a\', value: [5, 12] }]', ], }, { name: 'dataKey', type: 'String | Number | Function', defaultVal: 'null', isOptional: false, desc: { 'en-US': 'The key or getter of a group of data which should be unique in a LineChart.', 'zh-CN': '每个区域图对应一个唯一的 key,需要在 FunnelChart 中保证唯一。', }, }, { name: 'nameKey', type: 'String', defaultVal: '\'name\'', isOptional: false, desc: { 'en-US': "The key of each sector's name.", 'zh-CN': '"name" 属性对应的 key 。', }, }, { name: 'legendType', type: '\'line\' | \'square\' | \'rect\'| \'circle\' | \'cross\' | \'diamond\' | \'square\' | \'star\' | \'triangle\' | \'wye\' | \'none\'', defaultVal: '\'line\'', isOptional: true, desc: { 'en-US': 'The type of icon in legend. If set to \'none\', no legend item will be rendered.', 'zh-CN': '对应的图例 icon 的类型。', }, }, { name: 'activeShape', type: 'Object | ReactElement | Function', defaultVal: 'true', isOptional: false, }, { name: 'trapezoids', type: 'Array', defaultVal: 'null', isOptional: false, desc: { 'en-US': 'The coordinates of all the trapezoids in the funnel, usually calculated internally.', 'zh-CN': '梯形的坐标点。当使用 FunnelChart 作为父组件的时候,不需要自己计算,父组件会计算好。', }, format: ['[{x: 12, y: 12, upperWidth: 240, lowerWidth: 22, height: 80,}]'], }, { name: 'isAnimationActive', type: 'Boolean', defaultVal: 'true in CSR, and false in SSR', isOptional: false, desc: { 'en-US': 'If set false, animation of line will be disabled.', 'zh-CN': '当值为 false,不开启动画。', }, }, { name: 'animationBegin', type: 'Number', defaultVal: 0, isOptional: false, desc: { 'en-US': 'Specifies when the animation should begin, the unit of this option is ms.', 'zh-CN': '声明组件挂载后,开始运行动画的间隔时长,单位为毫秒。', }, }, { name: 'animationDuration', type: 'Number', defaultVal: 1500, isOptional: false, desc: { 'en-US': 'Specifies the duration of animation, the unit of this option is ms.', 'zh-CN': '声明动画的运行时长,单位为毫秒。', }, }, { name: 'animationEasing', type: '\'ease\' | \'ease-in\' | \'ease-out\' | \'ease-in-out\' | \'linear\'', defaultVal: '\'ease\'', isOptional: false, desc: { 'en-US': 'The type of easing function.', 'zh-CN': '动画缓动函数的类型。', }, }, { name: 'id', type: 'String', defaultVal: 'null', isOptional: true, desc: { 'en-US': 'The unique id of this component, which will be used to generate unique clip path id internally. This props is suggested to be set in SSR.', 'zh-CN': '唯一的id,会用于生成内部的clip path id 等,建议使用SSR的时候设置这个属性。', }, }, { name: 'onAnimationStart', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of animation start', 'zh-CN': '区域图动画 start 事件的回调函数。', }, }, { name: 'onAnimationEnd', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of animation end', 'zh-CN': '区域图动画 end 事件的回调函数。', }, }, { name: 'onClick', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of click on the area in this group', 'zh-CN': '曲线 click 事件的回调函数。', }, examples: [{ name: 'A BarChart with customized click event handler', url: '/examples/BarChartWithCustomizedEvent', }], }, { name: 'onMouseDown', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of mousedown on the area in this group', 'zh-CN': '曲线 mousedown 事件的回调函数。', }, }, { name: 'onMouseUp', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of mouseup on the area in this group', 'zh-CN': '曲线 mouseup 事件的回调函数。', }, }, { name: 'onMouseMove', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of mousemove on the area in this group', 'zh-CN': '曲线 mousemove 事件的回调函数。', }, }, { name: 'onMouseOver', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of mouseover on the area in this group', 'zh-CN': '曲线 mouseover 事件的回调函数。', }, }, { name: 'onMouseOut', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of mouseout on the area in this group', 'zh-CN': '曲线 mouseout 事件的回调函数。', }, }, { name: 'onMouseEnter', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of moustenter on the area in this group', 'zh-CN': '曲线 moustenter 事件的回调函数。', }, }, { name: 'onMouseLeave', type: 'Function', isOptional: true, desc: { 'en-US': 'The customized event handler of mouseleave on the area in this group', 'zh-CN': '曲线 mouseleave 事件的回调函数。', }, }, ], parentComponents: [ 'FunnelChart', ], childrenComponents: [ 'LabelList', 'Cell', ], };
import csv import numpy as np import matplotlib.pyplot as plt markers = { 'heuristic': { 'x': [], 'y': [] }, 'optimal': { 'x': [], 'y': [] }, 'normal': { 'x': [], 'y': [] } } with open('./time-data.csv', 'r') as csvfile: reader = csv.reader(csvfile, delimiter="\t") for row in reader: markers[row[0]]['x'].append(float(row[2])) markers[row[0]]['y'].append(float(row[4].replace(',', ''))) plt.figure(figsize=(20, 10)) plt.scatter(markers['heuristic']['x'], markers['heuristic']['y'], color = 'r', alpha=0.5, label="heuristic") plt.scatter(markers['normal']['x'], markers['normal']['y'], color = 'm', alpha=0.5, label="normal") plt.scatter(markers['optimal']['x'], markers['optimal']['y'], color = 'c', alpha=0.5, label="optimal") plt.grid() plt.legend() plt.xlabel('Number of RRHs') plt.ylabel('Simulation time (s)') plt.savefig('scatter.png')
/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** */ /* ** Author: Eric Veach, July 1994. ** */ /* $XFree86$ */ #ifndef __tessmono_h_ #define __tessmono_h_ /* __gl_meshTessellateMonoRegion( face ) tessellates a monotone region * (what else would it do?) The region must consist of a single * loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this * case means that any vertical line intersects the interior of the * region in a single interval. * * Tessellation consists of adding interior edges (actually pairs of * half-edges), to split the region into non-overlapping triangles. * * __gl_meshTessellateInterior( mesh ) tessellates each region of * the mesh which is marked "inside" the polygon. Each such region * must be monotone. * * __gl_meshDiscardExterior( mesh ) zaps (ie. sets to NULL) all faces * which are not marked "inside" the polygon. Since further mesh operations * on NULL faces are not allowed, the main purpose is to clean up the * mesh so that exterior loops are not represented in the data structure. * * __gl_meshSetWindingNumber( mesh, value, keepOnlyBoundary ) resets the * winding numbers on all edges so that regions marked "inside" the * polygon have a winding number of "value", and regions outside * have a winding number of 0. * * If keepOnlyBoundary is TRUE, it also deletes all edges which do not * separate an interior region from an exterior one. */ int __gl_meshTessellateMonoRegion( GLUface *face ); int __gl_meshTessellateInterior( GLUmesh *mesh ); void __gl_meshDiscardExterior( GLUmesh *mesh ); int __gl_meshSetWindingNumber( GLUmesh *mesh, int value, GLboolean keepOnlyBoundary ); #endif
;(function () { let mtButton = mtComponents.mtButton let mtButtonWrapper = mtComponents.mtButtonWrapper Mt_Util.router.addTag = Vue.extend({ name: 'addTag', template: ` <div class="addTag"> <div class="addTagBox"> <p class="title">企业标签</p> <div v-for="item in allTagList" :key="item.id"> <p class="tagTitle">{{item.name}}</p> <div class="tagList"> <mtButton size="small" class="tag" v-for="subItem in item.tag" :key="subItem.id" :type="getTagTypeClass(item, subItem)" @click="changeTag(subItem)">{{subItem.name}}</mtButton> </div> </div> </div> <mt-buttonWrapper> <mt-button class="cancelBtn" size="medium" type="whiteGrey" @click="cancelFollow">取消</mt-button> <mt-button size="medium" type="mainColor" @click="sureTag">确定</mt-button> </mt-buttonWrapper> </div> `, data() { return { allTagList: [], //所有显示标签 selectedTagList: [], //选中标签 customId: 0, //客户id type: 1 } }, components: { mtButton, mtButtonWrapper }, created() { this.selectedTagList = this.$route.query.selectedTagList console.log(this.selectedTagList) this.customId = this.$route.query.id this.type = this.$route.query.type this.getTagList() }, methods: { /** * 获取标签组的数据集合 * @author waldon * @date 2020/8/5 */ getGroupWithTagList() { let selectedGroupWithTagList = [] this.selectedTagList.forEach((item) => { let group = { id: item.groupId, name: item.groupName, tag: [item] } let findGroup = selectedGroupWithTagList.find((subItem) => subItem.id === item.groupId) if (findGroup) { findGroup.tag.push(item) } else { selectedGroupWithTagList.push(group) } }) return selectedGroupWithTagList }, /** * 取消返回上一页 * @author guoyijie * @date 2020/8/13 */ cancelFollow() { window.history.go(-1) }, /** * 确认 * @author guoyijie * @date 2020/8/13 */ sureTag() { if (this.type === 1) { var params = { id: this.customId, labelIdJson: JSON.stringify(this.selectedTagList) } Mt_Util.post('/ajax/client/tsClient_h.jsp?cmd=setTsClientTagRelList', params).then( (res) => { if (res.data && res.data.success) { this.$parent.getCustomInfo() window.history.go(-1) } else { this.$messagebox('提示', res.data.msg || '网络错误,请稍候重试') } } ) } else { this.$parent.selectedTagList = this.selectedTagList let tagList = [] for (let item of this.selectedTagList) { tagList.push(item.name) } this.$parent.tagList = tagList window.history.go(-1) } }, /** * 获取标签列表 * @author guoyijie * @date 2020/8/13 */ getTagList() { let parmes = { type: 0, isGetAll: true } Mt_Util.post('/ajax/wxWork/tag/tsTag_h.jsp?cmd=getCorpTagList', parmes).then((res) => { if (res.data && res.data.success) { this.allTagList = res.data.data } else { this.$messagebox('提示', res.data.msg || '网络错误,请稍候重试') } }) }, /** * 计算选中样式 * @author guoyijie * @date 2020/8/13 */ getTagTypeClass(group, tag) { let index = this.selectedTagList.findIndex((item) => { return item.groupId === group.id && item.name === tag.name }) return index > -1 ? 'mainColor' : 'unSelected' }, /** * 选中标签插入列表 * @author guoyijie * @date 2020/8/13 */ changeTag(tag) { let initLength = this.selectedTagList.length this.selectedTagList = this.selectedTagList.filter((item) => item.id !== tag.id) if (initLength === 0 || initLength === this.selectedTagList.length) { this.selectedTagList.push(Object.assign({}, tag)) } } } }) })()
import unittest import query import re # # unit tests for query parser # class TestQueryParser(unittest.TestCase): def setUp(self): self.seq = range(10) def test_valid(self): queries = {'mass~gt~0~and~mass~lt~100~or~atomCount~gt~2': {'$or': [{'$and': [{'properties.mass': {'$gt': 0}},{'properties.mass': {'$lt': 100}}]}, {'properties.atomCount': {'$gt': 2}}]} , 'atomCount~lt~10~or~mass~lt~10~and~mass~gt~100': {'$or': [{'properties.atomCount': {'$lt': 10}}, {'$and': [{'properties.mass': {'$lt': 10}}, {'properties.mass': {'$gt': 100}}]}]}, 'mass~gt~100': {'properties.mass': {'$gt': 100}}, 'mass~gt~1~and~mass~gt~2~and~mass~gt~3': {'$and': [{'properties.mass': {'$gt': 1}}, {'properties.mass': {'$gt': 2}}, {'properties.mass': {'$gt': 3}}]} , 'mass~gt~1~and~mass~gt~2~and~mass~gt~3~or~mass~lt~1': {'$or': [{'$and': [{'properties.mass': {'$gt': 1}}, {'properties.mass': {'$gt': 2}}, {'properties.mass': {'$gt': 3}}]}, {'properties.mass': {'$lt': 1}}]}, 'mass~gt~10~or~mass~gt~11~or~mass~gt~12': {'$or': [{'properties.mass': {'$gt': 10}}, {'properties.mass': {'$gt': 11}}, {'properties.mass': {'$gt': 12}}]} , 'mass~gt~2~or~mass~gt~3': {'$or': [{'properties.mass': {'$gt': 2}}, {'properties.mass': {'$gt': 3}}]}, 'mass~lt~1~and~atomCount~gt~23~or~atomCount~lt~1~and~mass~lt~0': {'$or': [{'$and': [{'properties.mass': {'$lt': 1}}, {'properties.atomCount': {'$gt': 23}}]}, {'$and': [{'properties.atomCount': {'$lt': 1}}, {'properties.mass': {'$lt': 0}}]}]}, 'mass~ne~1': {'properties.mass': {'$ne': 1}}, 'mass~eq~1': {'properties.mass': 1}, 'mass~eq~3.14159': {'properties.mass': 3.14159}, 'atomCount~eq~3.14159': {'properties.atomCount': 3.14159}, 'inchi~eq~CH': {'inchi': 'CH'}, 'inchi~eq~CH*': {'inchi': re.compile('^CH.*$')}, 'inchi~ne~CH': {'inchi': {'$ne': 'CH'}}, 'inchi~ne~CH*': {'inchi': {'$ne': 'CH*'}}, 'name~eq~test test~and~mass~gt~1': {'$and': [{'name': 'test test'}, {'properties.mass': {'$gt': 1}}]}, 'name~eq~3-hydroxymyristic acid [2-[[[5-(2,4-diketopyrimidin-1-yl)-3,4-dihydroxy-tetrahydrofuran-2-yl]methoxy-hydroxy-phosphoryl]oxy-hydroxy-phosphoryl]oxy-5-hydroxy-3-(3-hydroxytetradecanoylamino)-6-methylol-tetrahydropyran-4-yl] ester': {'name': '3-hydroxymyristic acid [2-[[[5-(2,4-diketopyrimidin-1-yl)-3,4-dihydroxy-tetrahydrofuran-2-yl]methoxy-hydroxy-phosphoryl]oxy-hydroxy-phosphoryl]oxy-5-hydroxy-3-(3-hydroxytetradecanoylamino)-6-methylol-tetrahydropyran-4-yl] ester'}, 'atomCount~lte~3.14159': {'properties.atomCount': {'$lte': 3.14159}}, 'atomCount~gte~3.14159': {'properties.atomCount': {'$gte': 3.14159}}, 'inchi~eq~InChI=1S/Na.H\n': {'inchi': 'InChI=1S/Na.H'} } for test_query, expected in queries.items(): mongo_query = query.to_mongo_query(test_query) print(test_query) self.assertEqual(mongo_query , expected) def test_invalid(self): queries = ['mass~eq~asdfa', 'mass~eq~2342gh,mass~eq~~eq~3', 'mass~eq~2342gh'] for test_query in queries: self.assertRaises(query.InvalidQuery, query.to_mongo_query, test_query) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "module_name": "Frappe Barcode", "color": "grey", "icon": "octicon octicon-file-directory", "type": "module", "label": _("Frappe Barcode") } ]
const users = require('../../app/controllers/users.server.controller.js'); const passport = require('passport') module.exports = app => { app .route('/signup') .get(users.renderSignup) .post(users.signup); app .route('/signin') .get(users.renderSignin) .post(passport.authenticate('local', { successRedirect: '/', failureRedirect: '/signin', failureFlash: true })); app.get('/signout', users.signout); };
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # 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 # # https://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. from __future__ import absolute_import import sys from google.api_core.protobuf_helpers import get_messages from dialogflow_v2beta1.proto import agent_pb2 from dialogflow_v2beta1.proto import audio_config_pb2 from dialogflow_v2beta1.proto import context_pb2 from dialogflow_v2beta1.proto import document_pb2 from dialogflow_v2beta1.proto import entity_type_pb2 from dialogflow_v2beta1.proto import gcs_pb2 from dialogflow_v2beta1.proto import intent_pb2 from dialogflow_v2beta1.proto import knowledge_base_pb2 from dialogflow_v2beta1.proto import session_entity_type_pb2 from dialogflow_v2beta1.proto import session_pb2 from dialogflow_v2beta1.proto import validation_result_pb2 from dialogflow_v2beta1.proto import webhook_pb2 from google.longrunning import operations_pb2 from google.protobuf import any_pb2 from google.protobuf import duration_pb2 from google.protobuf import empty_pb2 from google.protobuf import field_mask_pb2 from google.protobuf import struct_pb2 from google.rpc import status_pb2 from google.type import latlng_pb2 _shared_modules = [ operations_pb2, any_pb2, duration_pb2, empty_pb2, field_mask_pb2, struct_pb2, status_pb2, latlng_pb2, ] _local_modules = [ agent_pb2, audio_config_pb2, context_pb2, document_pb2, entity_type_pb2, gcs_pb2, intent_pb2, knowledge_base_pb2, session_entity_type_pb2, session_pb2, validation_result_pb2, webhook_pb2, ] names = [] for module in _shared_modules: # pragma: NO COVER for name, message in get_messages(module).items(): setattr(sys.modules[__name__], name, message) names.append(name) for module in _local_modules: for name, message in get_messages(module).items(): message.__module__ = "google.cloud.dialogflow_v2beta1.types" setattr(sys.modules[__name__], name, message) names.append(name) __all__ = tuple(sorted(names))
import stateFactory from '../state' const RB_CONTEXT = { getModule: (type) => { if (type === 'asUtils') { return { getAuth: () => { return {} } } } } } describe('custom/as/stores/auth/state', () => { it('should render correctly', async () => { const state = await stateFactory(RB_CONTEXT) expect(state).toMatchSnapshot() }) })
from dcard import Dcard import json, sys topic = sys.argv[1] num = int(sys.argv[2]) dcard = Dcard() ariticle_metas = dcard.forums(topic).get_metas(num=num, sort='new') articles = dcard.posts(ariticle_metas).get() with open('result.json', 'w', encoding='utf-8') as f: json.dump(articles.result(), f, ensure_ascii=False) with open('output.kcm', 'w', encoding='utf-8') as f: for i in articles.results: f.write(i['title'] + '\n' + i['content'] + '\n'.join(map(lambda x: x.get('content', ''), i['comments'])) + '\n')
// // YWP2PConversation.h // // // Created by huanglei on 14/12/17. // Copyright (c) 2014年 taobao. All rights reserved. // #import "YWConversation.h" @class YWPerson; @class YWIMCore; /** 单聊会话 */ @interface YWP2PConversation : YWConversation /** * 获取某个单聊会话 * @param WXOPerson 会话对象 * @param aCreateIfNotExist 如果还不存在,则创建会话 * @return 需要获取的会话。如果本地不存在该会话且不需要新建,则返回nil */ + (instancetype)fetchConversationByPerson:(YWPerson *)person creatIfNotExist:(BOOL)aCreateIfNotExist baseContext:(YWIMCore *)aBaseContext; /** * 该单聊会话的person对象 */ @property (nonatomic, strong, readonly) YWPerson *person; @end
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:49:01 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/FitnessUI.framework/FitnessUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @protocol UIScrollViewDelegate <NSObject> @optional -(void)scrollViewDidScroll:(id)arg1; -(void)scrollViewDidZoom:(id)arg1; -(void)scrollViewWillBeginDragging:(id)arg1; -(void)scrollViewWillEndDragging:(id)arg1 withVelocity:(CGPoint)arg2 targetContentOffset:(inout CGPoint*)arg3; -(void)scrollViewDidEndDragging:(id)arg1 willDecelerate:(BOOL)arg2; -(void)scrollViewWillBeginDecelerating:(id)arg1; -(void)scrollViewDidEndDecelerating:(id)arg1; -(void)scrollViewDidEndScrollingAnimation:(id)arg1; -(id)viewForZoomingInScrollView:(id)arg1; -(void)scrollViewWillBeginZooming:(id)arg1 withView:(id)arg2; -(void)scrollViewDidEndZooming:(id)arg1 withView:(id)arg2 atScale:(double)arg3; -(BOOL)scrollViewShouldScrollToTop:(id)arg1; -(void)scrollViewDidScrollToTop:(id)arg1; -(void)scrollViewDidChangeAdjustedContentInset:(id)arg1; @end
from os.path import isfile from netCDF4 import Dataset as netCDF4_Dataset from ..constants import _file_to_fh from ..functions import open_files_threshold_exceeded, close_one_file #from ..read_write.umread_lib.umfile import File #, UMFileException from ..umread_lib.umfile import File #, UMFileException #if 'netCDF' not in _file_to_fh: # _file_to_fh['netCDF'] = {} _file_to_UM = _file_to_fh.setdefault('UM', {}) _file_to_Dataset = _file_to_fh.setdefault('netCDF', {}) def _open_netcdf_file(filename, mode, fmt='NETCDF4'): #set_auto_mask=True): '''Open a netCDF file and read it into a netCDF4.Dataset object. If the file is already open then the existing netCDF4.Dataset object will be returned. :Parameters: filename: `str` The netCDF file to be opened. # set_auto_mask: `bool`, optional # Turn on or off automatic conversion of variable data to and # from masked arrays. :Returns: `netCDF4.Dataset` A netCDF4.Dataset instance for the netCDF file. **Examples:** >>> nc1 = _open_netcdf_file('file.nc') >>> nc1 <netCDF4.Dataset at 0x1a7dad0> >>> nc2 = _open_netcdf_file('file.nc') >>> nc2 is nc1 True ''' if filename in _file_to_Dataset and mode == 'r': # File is already open return _file_to_Dataset[filename] elif open_files_threshold_exceeded(): # Close a random data file to make way for this one close_one_file() if mode in ('a', 'r+'): if not isfile(filename): nc = netCDF4_Dataset(filename, 'w', format=fmt) nc.close() elif filename in _file_to_Dataset: _close_netcdf_file(filename) try: nc = netCDF4_Dataset(filename, mode, format=fmt) except RuntimeError as runtime_error: raise RuntimeError("{0}: {1}".format(runtime_error, filename)) if mode == 'r': # Update the _file_to_Dataset dictionary _file_to_Dataset[filename] = nc return nc def _close_netcdf_file(filename): '''Close a netCDF file does nothing if the file is already closed. :Parameters: filename: `str` The netCDF file to be closed. :Returns: `None` **Examples:** ''' nc = _file_to_Dataset.pop(filename, None) if nc is not None: nc.close() def _open_um_file(filename, aggregate=True, fmt=None, word_size=None, byte_ordering=None): '''Open a UM fields file or PP file and read it into a `umfile.File` object. If there is already a `umfile.File` object for the file then it is returned with an open file descriptor. :Parameters: filename: `str` The file to be opened. :Returns: `umfile.File` The opened file with an open file descriptor. **Examples:** ''' # filename = abspath(filename) f = _file_to_UM.get(filename) if f is not None: if f.fd is None: if open_files_threshold_exceeded(): # Close a random data array file to make way for this # one close_one_file() f.open_fd() #--- End: if return f if open_files_threshold_exceeded(): # Close a random data array file to make way for this one close_one_file() try: f = File(filename, byte_ordering=byte_ordering, word_size=word_size, format=fmt) except Exception as error: try: f.close_fd() except: pass raise Exception(error) # Add a close method to the file object f.close = f.close_fd # Update the _file_to_UM dictionary _file_to_UM[filename] = f return f def _close_um_file(filename): '''Close a PP or UM fields file. Does nothing if the file is already closed. :Parameters: filename : str The file to be closed. :Returns: None **Examples:** ''' f = _file_to_UM.pop(filename, None) if f is not None: f.close_fd()
import pyhiveapi import getpass import json from pyhiveapi.helper.hive_exceptions import NoApiToken username = input("Username: ") password = getpass.getpass('Password:') auth = pyhiveapi.Auth(username, password) session = auth.login() if session.get("ChallengeName") == pyhiveapi.SMS_REQUIRED: # Complete SMS 2FA. code = input("Enter your 2FA code: ") session = auth.sms_2fa(code, session) if "AuthenticationResult" in session: print(json.dumps(session["AuthenticationResult"], indent=2)) else: raise NoApiToken
/* net/atm/clip.c - RFC1577 Classical IP over ATM */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__ #include <linux/string.h> #include <linux/errno.h> #include <linux/kernel.h> /* for UINT_MAX */ #include <linux/module.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/wait.h> #include <linux/timer.h> #include <linux/if_arp.h> /* for some manifest constants */ #include <linux/notifier.h> #include <linux/atm.h> #include <linux/atmdev.h> #include <linux/atmclip.h> #include <linux/atmarp.h> #include <linux/capability.h> #include <linux/ip.h> /* for net/route.h */ #include <linux/in.h> /* for struct sockaddr_in */ #include <linux/if.h> /* for IFF_UP */ #include <linux/inetdevice.h> #include <linux/bitops.h> #include <linux/poison.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/rcupdate.h> #include <linux/jhash.h> #include <linux/slab.h> #include <net/route.h> /* for struct rtable and routing */ #include <net/icmp.h> /* icmp_send */ #include <net/arp.h> #include <linux/param.h> /* for HZ */ #include <linux/uaccess.h> #include <asm/byteorder.h> /* for htons etc. */ #include <linux/atomic.h> #include "common.h" #include "resources.h" #include <net/atmclip.h> static struct net_device *clip_devs; static struct atm_vcc *atmarpd; static struct timer_list idle_timer; static const struct neigh_ops clip_neigh_ops; static int to_atmarpd(enum atmarp_ctrl_type type, int itf, __be32 ip) { struct sock *sk; struct atmarp_ctrl *ctrl; struct sk_buff *skb; pr_debug("(%d)\n", type); if (!atmarpd) return -EUNATCH; skb = alloc_skb(sizeof(struct atmarp_ctrl), GFP_ATOMIC); if (!skb) return -ENOMEM; ctrl = skb_put(skb, sizeof(struct atmarp_ctrl)); ctrl->type = type; ctrl->itf_num = itf; ctrl->ip = ip; atm_force_charge(atmarpd, skb->truesize); sk = sk_atm(atmarpd); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_data_ready(sk); return 0; } static void link_vcc(struct clip_vcc *clip_vcc, struct atmarp_entry *entry) { pr_debug("%p to entry %p (neigh %p)\n", clip_vcc, entry, entry->neigh); clip_vcc->entry = entry; clip_vcc->xoff = 0; /* @@@ may overrun buffer by one packet */ clip_vcc->next = entry->vccs; entry->vccs = clip_vcc; entry->neigh->used = jiffies; } static void unlink_clip_vcc(struct clip_vcc *clip_vcc) { struct atmarp_entry *entry = clip_vcc->entry; struct clip_vcc **walk; if (!entry) { pr_crit("!clip_vcc->entry (clip_vcc %p)\n", clip_vcc); return; } netif_tx_lock_bh(entry->neigh->dev); /* block clip_start_xmit() */ entry->neigh->used = jiffies; for (walk = &entry->vccs; *walk; walk = &(*walk)->next) if (*walk == clip_vcc) { int error; *walk = clip_vcc->next; /* atomic */ clip_vcc->entry = NULL; if (clip_vcc->xoff) netif_wake_queue(entry->neigh->dev); if (entry->vccs) goto out; entry->expires = jiffies - 1; /* force resolution or expiration */ error = neigh_update(entry->neigh, NULL, NUD_NONE, NEIGH_UPDATE_F_ADMIN, 0); if (error) pr_crit("neigh_update failed with %d\n", error); goto out; } pr_crit("ATMARP: failed (entry %p, vcc 0x%p)\n", entry, clip_vcc); out: netif_tx_unlock_bh(entry->neigh->dev); } /* The neighbour entry n->lock is held. */ static int neigh_check_cb(struct neighbour *n) { struct atmarp_entry *entry = neighbour_priv(n); struct clip_vcc *cv; if (n->ops != &clip_neigh_ops) return 0; for (cv = entry->vccs; cv; cv = cv->next) { unsigned long exp = cv->last_use + cv->idle_timeout; if (cv->idle_timeout && time_after(jiffies, exp)) { pr_debug("releasing vcc %p->%p of entry %p\n", cv, cv->vcc, entry); vcc_release_async(cv->vcc, -ETIMEDOUT); } } if (entry->vccs || time_before(jiffies, entry->expires)) return 0; if (refcount_read(&n->refcnt) > 1) { struct sk_buff *skb; pr_debug("destruction postponed with ref %d\n", refcount_read(&n->refcnt)); while ((skb = skb_dequeue(&n->arp_queue)) != NULL) dev_kfree_skb(skb); return 0; } pr_debug("expired neigh %p\n", n); return 1; } static void idle_timer_check(unsigned long dummy) { write_lock(&arp_tbl.lock); __neigh_for_each_release(&arp_tbl, neigh_check_cb); mod_timer(&idle_timer, jiffies + CLIP_CHECK_INTERVAL * HZ); write_unlock(&arp_tbl.lock); } static int clip_arp_rcv(struct sk_buff *skb) { struct atm_vcc *vcc; pr_debug("\n"); vcc = ATM_SKB(skb)->vcc; if (!vcc || !atm_charge(vcc, skb->truesize)) { dev_kfree_skb_any(skb); return 0; } pr_debug("pushing to %p\n", vcc); pr_debug("using %p\n", CLIP_VCC(vcc)->old_push); CLIP_VCC(vcc)->old_push(vcc, skb); return 0; } static const unsigned char llc_oui[] = { 0xaa, /* DSAP: non-ISO */ 0xaa, /* SSAP: non-ISO */ 0x03, /* Ctrl: Unnumbered Information Command PDU */ 0x00, /* OUI: EtherType */ 0x00, 0x00 }; static void clip_push(struct atm_vcc *vcc, struct sk_buff *skb) { struct clip_vcc *clip_vcc = CLIP_VCC(vcc); pr_debug("\n"); if (!clip_devs) { atm_return(vcc, skb->truesize); kfree_skb(skb); return; } if (!skb) { pr_debug("removing VCC %p\n", clip_vcc); if (clip_vcc->entry) unlink_clip_vcc(clip_vcc); clip_vcc->old_push(vcc, NULL); /* pass on the bad news */ kfree(clip_vcc); return; } atm_return(vcc, skb->truesize); skb->dev = clip_vcc->entry ? clip_vcc->entry->neigh->dev : clip_devs; /* clip_vcc->entry == NULL if we don't have an IP address yet */ if (!skb->dev) { dev_kfree_skb_any(skb); return; } ATM_SKB(skb)->vcc = vcc; skb_reset_mac_header(skb); if (!clip_vcc->encap || skb->len < RFC1483LLC_LEN || memcmp(skb->data, llc_oui, sizeof(llc_oui))) skb->protocol = htons(ETH_P_IP); else { skb->protocol = ((__be16 *)skb->data)[3]; skb_pull(skb, RFC1483LLC_LEN); if (skb->protocol == htons(ETH_P_ARP)) { skb->dev->stats.rx_packets++; skb->dev->stats.rx_bytes += skb->len; clip_arp_rcv(skb); return; } } clip_vcc->last_use = jiffies; skb->dev->stats.rx_packets++; skb->dev->stats.rx_bytes += skb->len; memset(ATM_SKB(skb), 0, sizeof(struct atm_skb_data)); netif_rx(skb); } /* * Note: these spinlocks _must_not_ block on non-SMP. The only goal is that * clip_pop is atomic with respect to the critical section in clip_start_xmit. */ static void clip_pop(struct atm_vcc *vcc, struct sk_buff *skb) { struct clip_vcc *clip_vcc = CLIP_VCC(vcc); struct net_device *dev = skb->dev; int old; unsigned long flags; pr_debug("(vcc %p)\n", vcc); clip_vcc->old_pop(vcc, skb); /* skb->dev == NULL in outbound ARP packets */ if (!dev) return; spin_lock_irqsave(&PRIV(dev)->xoff_lock, flags); if (atm_may_send(vcc, 0)) { old = xchg(&clip_vcc->xoff, 0); if (old) netif_wake_queue(dev); } spin_unlock_irqrestore(&PRIV(dev)->xoff_lock, flags); } static void clip_neigh_solicit(struct neighbour *neigh, struct sk_buff *skb) { __be32 *ip = (__be32 *) neigh->primary_key; pr_debug("(neigh %p, skb %p)\n", neigh, skb); to_atmarpd(act_need, PRIV(neigh->dev)->number, *ip); } static void clip_neigh_error(struct neighbour *neigh, struct sk_buff *skb) { #ifndef CONFIG_ATM_CLIP_NO_ICMP icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); #endif kfree_skb(skb); } static const struct neigh_ops clip_neigh_ops = { .family = AF_INET, .solicit = clip_neigh_solicit, .error_report = clip_neigh_error, .output = neigh_direct_output, .connected_output = neigh_direct_output, }; static int clip_constructor(struct net_device *dev, struct neighbour *neigh) { struct atmarp_entry *entry = neighbour_priv(neigh); if (neigh->tbl->family != AF_INET) return -EINVAL; if (neigh->type != RTN_UNICAST) return -EINVAL; neigh->nud_state = NUD_NONE; neigh->ops = &clip_neigh_ops; neigh->output = neigh->ops->output; entry->neigh = neigh; entry->vccs = NULL; entry->expires = jiffies - 1; return 0; } /* @@@ copy bh locking from arp.c -- need to bh-enable atm code before */ /* * We play with the resolve flag: 0 and 1 have the usual meaning, but -1 means * to allocate the neighbour entry but not to ask atmarpd for resolution. Also, * don't increment the usage count. This is used to create entries in * clip_setentry. */ static int clip_encap(struct atm_vcc *vcc, int mode) { if (!CLIP_VCC(vcc)) return -EBADFD; CLIP_VCC(vcc)->encap = mode; return 0; } static netdev_tx_t clip_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct clip_priv *clip_priv = PRIV(dev); struct dst_entry *dst = skb_dst(skb); struct atmarp_entry *entry; struct neighbour *n; struct atm_vcc *vcc; struct rtable *rt; __be32 *daddr; int old; unsigned long flags; pr_debug("(skb %p)\n", skb); if (!dst) { pr_err("skb_dst(skb) == NULL\n"); dev_kfree_skb(skb); dev->stats.tx_dropped++; return NETDEV_TX_OK; } rt = (struct rtable *) dst; if (rt->rt_gateway) daddr = &rt->rt_gateway; else daddr = &ip_hdr(skb)->daddr; n = dst_neigh_lookup(dst, daddr); if (!n) { pr_err("NO NEIGHBOUR !\n"); dev_kfree_skb(skb); dev->stats.tx_dropped++; return NETDEV_TX_OK; } entry = neighbour_priv(n); if (!entry->vccs) { if (time_after(jiffies, entry->expires)) { /* should be resolved */ entry->expires = jiffies + ATMARP_RETRY_DELAY * HZ; to_atmarpd(act_need, PRIV(dev)->number, *((__be32 *)n->primary_key)); } if (entry->neigh->arp_queue.qlen < ATMARP_MAX_UNRES_PACKETS) skb_queue_tail(&entry->neigh->arp_queue, skb); else { dev_kfree_skb(skb); dev->stats.tx_dropped++; } goto out_release_neigh; } pr_debug("neigh %p, vccs %p\n", entry, entry->vccs); ATM_SKB(skb)->vcc = vcc = entry->vccs->vcc; pr_debug("using neighbour %p, vcc %p\n", n, vcc); if (entry->vccs->encap) { void *here; here = skb_push(skb, RFC1483LLC_LEN); memcpy(here, llc_oui, sizeof(llc_oui)); ((__be16 *) here)[3] = skb->protocol; } refcount_add(skb->truesize, &sk_atm(vcc)->sk_wmem_alloc); ATM_SKB(skb)->atm_options = vcc->atm_options; entry->vccs->last_use = jiffies; pr_debug("atm_skb(%p)->vcc(%p)->dev(%p)\n", skb, vcc, vcc->dev); old = xchg(&entry->vccs->xoff, 1); /* assume XOFF ... */ if (old) { pr_warn("XOFF->XOFF transition\n"); goto out_release_neigh; } dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; vcc->send(vcc, skb); if (atm_may_send(vcc, 0)) { entry->vccs->xoff = 0; goto out_release_neigh; } spin_lock_irqsave(&clip_priv->xoff_lock, flags); netif_stop_queue(dev); /* XOFF -> throttle immediately */ barrier(); if (!entry->vccs->xoff) netif_start_queue(dev); /* Oh, we just raced with clip_pop. netif_start_queue should be good enough, because nothing should really be asleep because of the brief netif_stop_queue. If this isn't true or if it changes, use netif_wake_queue instead. */ spin_unlock_irqrestore(&clip_priv->xoff_lock, flags); out_release_neigh: neigh_release(n); return NETDEV_TX_OK; } static int clip_mkip(struct atm_vcc *vcc, int timeout) { struct clip_vcc *clip_vcc; if (!vcc->push) return -EBADFD; clip_vcc = kmalloc(sizeof(struct clip_vcc), GFP_KERNEL); if (!clip_vcc) return -ENOMEM; pr_debug("%p vcc %p\n", clip_vcc, vcc); clip_vcc->vcc = vcc; vcc->user_back = clip_vcc; set_bit(ATM_VF_IS_CLIP, &vcc->flags); clip_vcc->entry = NULL; clip_vcc->xoff = 0; clip_vcc->encap = 1; clip_vcc->last_use = jiffies; clip_vcc->idle_timeout = timeout * HZ; clip_vcc->old_push = vcc->push; clip_vcc->old_pop = vcc->pop; vcc->push = clip_push; vcc->pop = clip_pop; /* re-process everything received between connection setup and MKIP */ vcc_process_recv_queue(vcc); return 0; } static int clip_setentry(struct atm_vcc *vcc, __be32 ip) { struct neighbour *neigh; struct atmarp_entry *entry; int error; struct clip_vcc *clip_vcc; struct rtable *rt; if (vcc->push != clip_push) { pr_warn("non-CLIP VCC\n"); return -EBADF; } clip_vcc = CLIP_VCC(vcc); if (!ip) { if (!clip_vcc->entry) { pr_err("hiding hidden ATMARP entry\n"); return 0; } pr_debug("remove\n"); unlink_clip_vcc(clip_vcc); return 0; } rt = ip_route_output(&init_net, ip, 0, 1, 0); if (IS_ERR(rt)) return PTR_ERR(rt); neigh = __neigh_lookup(&arp_tbl, &ip, rt->dst.dev, 1); ip_rt_put(rt); if (!neigh) return -ENOMEM; entry = neighbour_priv(neigh); if (entry != clip_vcc->entry) { if (!clip_vcc->entry) pr_debug("add\n"); else { pr_debug("update\n"); unlink_clip_vcc(clip_vcc); } link_vcc(clip_vcc, entry); } error = neigh_update(neigh, llc_oui, NUD_PERMANENT, NEIGH_UPDATE_F_OVERRIDE | NEIGH_UPDATE_F_ADMIN, 0); neigh_release(neigh); return error; } static const struct net_device_ops clip_netdev_ops = { .ndo_start_xmit = clip_start_xmit, .ndo_neigh_construct = clip_constructor, }; static void clip_setup(struct net_device *dev) { dev->netdev_ops = &clip_netdev_ops; dev->type = ARPHRD_ATM; dev->neigh_priv_len = sizeof(struct atmarp_entry); dev->hard_header_len = RFC1483LLC_LEN; dev->mtu = RFC1626_MTU; dev->tx_queue_len = 100; /* "normal" queue (packets) */ /* When using a "real" qdisc, the qdisc determines the queue */ /* length. tx_queue_len is only used for the default case, */ /* without any more elaborate queuing. 100 is a reasonable */ /* compromise between decent burst-tolerance and protection */ /* against memory hogs. */ netif_keep_dst(dev); } static int clip_create(int number) { struct net_device *dev; struct clip_priv *clip_priv; int error; if (number != -1) { for (dev = clip_devs; dev; dev = PRIV(dev)->next) if (PRIV(dev)->number == number) return -EEXIST; } else { number = 0; for (dev = clip_devs; dev; dev = PRIV(dev)->next) if (PRIV(dev)->number >= number) number = PRIV(dev)->number + 1; } dev = alloc_netdev(sizeof(struct clip_priv), "", NET_NAME_UNKNOWN, clip_setup); if (!dev) return -ENOMEM; clip_priv = PRIV(dev); sprintf(dev->name, "atm%d", number); spin_lock_init(&clip_priv->xoff_lock); clip_priv->number = number; error = register_netdev(dev); if (error) { free_netdev(dev); return error; } clip_priv->next = clip_devs; clip_devs = dev; pr_debug("registered (net:%s)\n", dev->name); return number; } static int clip_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); if (!net_eq(dev_net(dev), &init_net)) return NOTIFY_DONE; if (event == NETDEV_UNREGISTER) return NOTIFY_DONE; /* ignore non-CLIP devices */ if (dev->type != ARPHRD_ATM || dev->netdev_ops != &clip_netdev_ops) return NOTIFY_DONE; switch (event) { case NETDEV_UP: pr_debug("NETDEV_UP\n"); to_atmarpd(act_up, PRIV(dev)->number, 0); break; case NETDEV_GOING_DOWN: pr_debug("NETDEV_DOWN\n"); to_atmarpd(act_down, PRIV(dev)->number, 0); break; case NETDEV_CHANGE: case NETDEV_CHANGEMTU: pr_debug("NETDEV_CHANGE*\n"); to_atmarpd(act_change, PRIV(dev)->number, 0); break; } return NOTIFY_DONE; } static int clip_inet_event(struct notifier_block *this, unsigned long event, void *ifa) { struct in_device *in_dev; struct netdev_notifier_info info; in_dev = ((struct in_ifaddr *)ifa)->ifa_dev; /* * Transitions are of the down-change-up type, so it's sufficient to * handle the change on up. */ if (event != NETDEV_UP) return NOTIFY_DONE; netdev_notifier_info_init(&info, in_dev->dev); return clip_device_event(this, NETDEV_CHANGE, &info); } static struct notifier_block clip_dev_notifier = { .notifier_call = clip_device_event, }; static struct notifier_block clip_inet_notifier = { .notifier_call = clip_inet_event, }; static void atmarpd_close(struct atm_vcc *vcc) { pr_debug("\n"); rtnl_lock(); atmarpd = NULL; skb_queue_purge(&sk_atm(vcc)->sk_receive_queue); rtnl_unlock(); pr_debug("(done)\n"); module_put(THIS_MODULE); } static const struct atmdev_ops atmarpd_dev_ops = { .close = atmarpd_close }; static struct atm_dev atmarpd_dev = { .ops = &atmarpd_dev_ops, .type = "arpd", .number = 999, .lock = __SPIN_LOCK_UNLOCKED(atmarpd_dev.lock) }; static int atm_init_atmarp(struct atm_vcc *vcc) { rtnl_lock(); if (atmarpd) { rtnl_unlock(); return -EADDRINUSE; } mod_timer(&idle_timer, jiffies + CLIP_CHECK_INTERVAL * HZ); atmarpd = vcc; set_bit(ATM_VF_META, &vcc->flags); set_bit(ATM_VF_READY, &vcc->flags); /* allow replies and avoid getting closed if signaling dies */ vcc->dev = &atmarpd_dev; vcc_insert_socket(sk_atm(vcc)); vcc->push = NULL; vcc->pop = NULL; /* crash */ vcc->push_oam = NULL; /* crash */ rtnl_unlock(); return 0; } static int clip_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct atm_vcc *vcc = ATM_SD(sock); int err = 0; switch (cmd) { case SIOCMKCLIP: case ATMARPD_CTRL: case ATMARP_MKIP: case ATMARP_SETENTRY: case ATMARP_ENCAP: if (!capable(CAP_NET_ADMIN)) return -EPERM; break; default: return -ENOIOCTLCMD; } switch (cmd) { case SIOCMKCLIP: err = clip_create(arg); break; case ATMARPD_CTRL: err = atm_init_atmarp(vcc); if (!err) { sock->state = SS_CONNECTED; __module_get(THIS_MODULE); } break; case ATMARP_MKIP: err = clip_mkip(vcc, arg); break; case ATMARP_SETENTRY: err = clip_setentry(vcc, (__force __be32)arg); break; case ATMARP_ENCAP: err = clip_encap(vcc, arg); break; } return err; } static struct atm_ioctl clip_ioctl_ops = { .owner = THIS_MODULE, .ioctl = clip_ioctl, }; #ifdef CONFIG_PROC_FS static void svc_addr(struct seq_file *seq, struct sockaddr_atmsvc *addr) { static int code[] = { 1, 2, 10, 6, 1, 0 }; static int e164[] = { 1, 8, 4, 6, 1, 0 }; if (*addr->sas_addr.pub) { seq_printf(seq, "%s", addr->sas_addr.pub); if (*addr->sas_addr.prv) seq_putc(seq, '+'); } else if (!*addr->sas_addr.prv) { seq_printf(seq, "%s", "(none)"); return; } if (*addr->sas_addr.prv) { unsigned char *prv = addr->sas_addr.prv; int *fields; int i, j; fields = *prv == ATM_AFI_E164 ? e164 : code; for (i = 0; fields[i]; i++) { for (j = fields[i]; j; j--) seq_printf(seq, "%02X", *prv++); if (fields[i + 1]) seq_putc(seq, '.'); } } } /* This means the neighbour entry has no attached VCC objects. */ #define SEQ_NO_VCC_TOKEN ((void *) 2) static void atmarp_info(struct seq_file *seq, struct neighbour *n, struct atmarp_entry *entry, struct clip_vcc *clip_vcc) { struct net_device *dev = n->dev; unsigned long exp; char buf[17]; int svc, llc, off; svc = ((clip_vcc == SEQ_NO_VCC_TOKEN) || (sk_atm(clip_vcc->vcc)->sk_family == AF_ATMSVC)); llc = ((clip_vcc == SEQ_NO_VCC_TOKEN) || clip_vcc->encap); if (clip_vcc == SEQ_NO_VCC_TOKEN) exp = entry->neigh->used; else exp = clip_vcc->last_use; exp = (jiffies - exp) / HZ; seq_printf(seq, "%-6s%-4s%-4s%5ld ", dev->name, svc ? "SVC" : "PVC", llc ? "LLC" : "NULL", exp); off = scnprintf(buf, sizeof(buf) - 1, "%pI4", n->primary_key); while (off < 16) buf[off++] = ' '; buf[off] = '\0'; seq_printf(seq, "%s", buf); if (clip_vcc == SEQ_NO_VCC_TOKEN) { if (time_before(jiffies, entry->expires)) seq_printf(seq, "(resolving)\n"); else seq_printf(seq, "(expired, ref %d)\n", refcount_read(&entry->neigh->refcnt)); } else if (!svc) { seq_printf(seq, "%d.%d.%d\n", clip_vcc->vcc->dev->number, clip_vcc->vcc->vpi, clip_vcc->vcc->vci); } else { svc_addr(seq, &clip_vcc->vcc->remote); seq_putc(seq, '\n'); } } struct clip_seq_state { /* This member must be first. */ struct neigh_seq_state ns; /* Local to clip specific iteration. */ struct clip_vcc *vcc; }; static struct clip_vcc *clip_seq_next_vcc(struct atmarp_entry *e, struct clip_vcc *curr) { if (!curr) { curr = e->vccs; if (!curr) return SEQ_NO_VCC_TOKEN; return curr; } if (curr == SEQ_NO_VCC_TOKEN) return NULL; curr = curr->next; return curr; } static void *clip_seq_vcc_walk(struct clip_seq_state *state, struct atmarp_entry *e, loff_t * pos) { struct clip_vcc *vcc = state->vcc; vcc = clip_seq_next_vcc(e, vcc); if (vcc && pos != NULL) { while (*pos) { vcc = clip_seq_next_vcc(e, vcc); if (!vcc) break; --(*pos); } } state->vcc = vcc; return vcc; } static void *clip_seq_sub_iter(struct neigh_seq_state *_state, struct neighbour *n, loff_t * pos) { struct clip_seq_state *state = (struct clip_seq_state *)_state; if (n->dev->type != ARPHRD_ATM) return NULL; return clip_seq_vcc_walk(state, neighbour_priv(n), pos); } static void *clip_seq_start(struct seq_file *seq, loff_t * pos) { struct clip_seq_state *state = seq->private; state->ns.neigh_sub_iter = clip_seq_sub_iter; return neigh_seq_start(seq, pos, &arp_tbl, NEIGH_SEQ_NEIGH_ONLY); } static int clip_seq_show(struct seq_file *seq, void *v) { static char atm_arp_banner[] = "IPitf TypeEncp Idle IP address ATM address\n"; if (v == SEQ_START_TOKEN) { seq_puts(seq, atm_arp_banner); } else { struct clip_seq_state *state = seq->private; struct clip_vcc *vcc = state->vcc; struct neighbour *n = v; atmarp_info(seq, n, neighbour_priv(n), vcc); } return 0; } static const struct seq_operations arp_seq_ops = { .start = clip_seq_start, .next = neigh_seq_next, .stop = neigh_seq_stop, .show = clip_seq_show, }; static int arp_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &arp_seq_ops, sizeof(struct clip_seq_state)); } static const struct file_operations arp_seq_fops = { .open = arp_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, .owner = THIS_MODULE }; #endif static void atm_clip_exit_noproc(void); static int __init atm_clip_init(void) { register_atm_ioctl(&clip_ioctl_ops); register_netdevice_notifier(&clip_dev_notifier); register_inetaddr_notifier(&clip_inet_notifier); setup_timer(&idle_timer, idle_timer_check, 0); #ifdef CONFIG_PROC_FS { struct proc_dir_entry *p; p = proc_create("arp", S_IRUGO, atm_proc_root, &arp_seq_fops); if (!p) { pr_err("Unable to initialize /proc/net/atm/arp\n"); atm_clip_exit_noproc(); return -ENOMEM; } } #endif return 0; } static void atm_clip_exit_noproc(void) { struct net_device *dev, *next; unregister_inetaddr_notifier(&clip_inet_notifier); unregister_netdevice_notifier(&clip_dev_notifier); deregister_atm_ioctl(&clip_ioctl_ops); /* First, stop the idle timer, so it stops banging * on the table. */ del_timer_sync(&idle_timer); dev = clip_devs; while (dev) { next = PRIV(dev)->next; unregister_netdev(dev); free_netdev(dev); dev = next; } } static void __exit atm_clip_exit(void) { remove_proc_entry("arp", atm_proc_root); atm_clip_exit_noproc(); } module_init(atm_clip_init); module_exit(atm_clip_exit); MODULE_AUTHOR("Werner Almesberger"); MODULE_DESCRIPTION("Classical/IP over ATM interface"); MODULE_LICENSE("GPL");
const mongoose = require("mongoose"); const { isEmail } = require("validator"); const bcrypt = require("bcrypt"); const userSchema = new mongoose.Schema({ email: { type: String, required: [true, "email is required"], unique: true, lowercase: true, validate: [isEmail, "Please insert a valid email"], }, password: { type: String, required: [true, "Password is requried"], minLength: [6, "Minimum password length is 6 characters"], }, }); /* Mongoose Hooks */ // Execute this function before doc saved to db userSchema.pre("save", async function (next) { const salt = await bcrypt.genSalt(); this.password = await bcrypt.hash(this.password, salt); next(); }); // Execute this function after doc saved to db // userSchema.post("save", async function(doc, next){ // next(); // }); userSchema.methods.checkPassword = function (password) { const passwordHash = this.password; return new Promise((resolve, reject) => { bcrypt.compare(password, passwordHash, (err, same) => { if (err){ return reject(err); } return resolve(same); }); }); }; const User = mongoose.model("user", userSchema); module.exports = User;
import os import yaml import abc import inspect from gym import spaces from gym_mupen64plus.envs.mupen64plus_env import Mupen64PlusEnv class Mario64_Env(Mupen64PlusEnv): __metaclass__ = abc.ABCMeta def __init__(self, save_state=None): self.save_state = None if save_state: self.save_state = os.path.join(self._saves_dir(), save_state) super().__init__() self.action_space = spaces.MultiDiscrete([[-80, 80], # Joystick X-axis [-80, 80], # Joystick Y-axis [ 0, 1], # A Button [ 0, 1], # B Button [ 0, 1], # RB Button [ 0, 1], # LB Button [ 0, 1], # Z Button [ 0, 1], # C Right Button [ 0, 1], # C Left Button [ 0, 1], # C Down Button [ 0, 1], # C Up Button [ 0, 0], # D-Pad Right Button [ 0, 0], # D-Pad Left Button [ 0, 0], # D-Pad Down Button [ 0, 0], # D-Pad Up Button [ 0, 0], # Start Button ]) def _get_save_state(self): return self.save_state def _load_config(self): dirname = os.path.dirname(inspect.stack()[0][1]) config_path = os.path.join(dirname, "mario64_config.yml") with open(config_path, 'r') as f: config = yaml.safe_load(f) self.config.update(config) def _validate_config(self): pass def _navigate_menu(self): pass def _get_reward(self): return 0 def _evaluate_end_state(self): return False def _reset(self): save_state = self._get_save_state() # self._load_save_state(save_state)
! function(t, e) { "use strict"; "function" == typeof define && define.amd ? define(function() { return e() }) : "object" == typeof module && module.exports ? module.exports = e() : t.getSize = e() }(window, function() { "use strict"; function t(t) { var e = parseFloat(t), i = t.indexOf("%") == -1 && !isNaN(e); return i && e } function e() {} function i() { for (var t = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 }, e = 0; e < g; e++) { var i = a[e]; t[i] = 0 } return t } function r(t) { var e = getComputedStyle(t); return e || h("Style returned " + e + ". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"), e } function o() { if (!u) { u = !0; var e = document.createElement("div"); e.style.width = "200px", e.style.padding = "1px 2px 3px 4px", e.style.borderStyle = "solid", e.style.borderWidth = "1px 2px 3px 4px", e.style.boxSizing = "border-box"; var i = document.body || document.documentElement; i.appendChild(e); var o = r(e); n.isBoxSizeOuter = d = 200 == t(o.width), i.removeChild(e) } } function n(e) { if (o(), "string" == typeof e && (e = document.querySelector(e)), e && "object" == typeof e && e.nodeType) { var n = r(e); if ("none" == n.display) return i(); var h = {}; h.width = e.offsetWidth, h.height = e.offsetHeight; for (var u = h.isBorderBox = "border-box" == n.boxSizing, p = 0; p < g; p++) { var f = a[p], m = n[f], s = parseFloat(m); h[f] = isNaN(s) ? 0 : s } var c = h.paddingLeft + h.paddingRight, l = h.paddingTop + h.paddingBottom, b = h.marginLeft + h.marginRight, x = h.marginTop + h.marginBottom, y = h.borderLeftWidth + h.borderRightWidth, v = h.borderTopWidth + h.borderBottomWidth, W = u && d, w = t(n.width); w !== !1 && (h.width = w + (W ? 0 : c + y)); var B = t(n.height); return B !== !1 && (h.height = B + (W ? 0 : l + v)), h.innerWidth = h.width - (c + y), h.innerHeight = h.height - (l + v), h.outerWidth = h.width + b, h.outerHeight = h.height + x, h } } var d, h = "undefined" == typeof console ? e : function(t) { console.error(t) }, a = ["paddingLeft", "paddingRight", "paddingTop", "paddingBottom", "marginLeft", "marginRight", "marginTop", "marginBottom", "borderLeftWidth", "borderRightWidth", "borderTopWidth", "borderBottomWidth"], g = a.length, u = !1; return n }); ! function(e, t) { "use strict"; "function" == typeof define && define.amd ? define(t) : "object" == typeof module && module.exports ? module.exports = t() : e.matchesSelector = t() }(window, function() { "use strict"; var e = function() { var e = window.Element.prototype; if (e.matches) return "matches"; if (e.matchesSelector) return "matchesSelector"; for (var t = ["webkit", "moz", "ms", "o"], o = 0; o < t.length; o++) { var r = t[o], n = r + "MatchesSelector"; if (e[n]) return n } }(); return function(t, o) { return t[e](o) } }); ! function(e, t) { "function" == typeof define && define.amd ? define(t) : "object" == typeof module && module.exports ? module.exports = t() : e.EvEmitter = t() }("undefined" != typeof window ? window : this, function() { "use strict"; function e() {} var t = e.prototype; return t.on = function(e, t) { if (e && t) { var n = this._events = this._events || {}, i = n[e] = n[e] || []; return i.indexOf(t) == -1 && i.push(t), this } }, t.once = function(e, t) { if (e && t) { this.on(e, t); var n = this._onceEvents = this._onceEvents || {}, i = n[e] = n[e] || {}; return i[t] = !0, this } }, t.off = function(e, t) { var n = this._events && this._events[e]; if (n && n.length) { var i = n.indexOf(t); return i != -1 && n.splice(i, 1), this } }, t.emitEvent = function(e, t) { var n = this._events && this._events[e]; if (n && n.length) { n = n.slice(0), t = t || []; for (var i = this._onceEvents && this._onceEvents[e], s = 0; s < n.length; s++) { var o = n[s], f = i && i[o]; f && (this.off(e, o), delete i[o]), o.apply(this, t) } return this } }, t.allOff = function() { delete this._events, delete this._onceEvents }, e }); ! function(e, t) { "function" == typeof define && define.amd ? define(["desandro-matches-selector/matches-selector"], function(r) { return t(e, r) }) : "object" == typeof module && module.exports ? module.exports = t(e, require("desandro-matches-selector")) : e.fizzyUIUtils = t(e, e.matchesSelector) }(window, function(e, t) { "use strict"; var r = {}; r.extend = function(e, t) { for (var r in t) e[r] = t[r]; return e }, r.modulo = function(e, t) { return (e % t + t) % t }; var n = Array.prototype.slice; r.makeArray = function(e) { if (Array.isArray(e)) return e; if (null === e || void 0 === e) return []; var t = "object" == typeof e && "number" == typeof e.length; return t ? n.call(e) : [e] }, r.removeFrom = function(e, t) { var r = e.indexOf(t); r != -1 && e.splice(r, 1) }, r.getParent = function(e, r) { for (; e.parentNode && e != document.body;) if (e = e.parentNode, t(e, r)) return e }, r.getQueryElement = function(e) { return "string" == typeof e ? document.querySelector(e) : e }, r.handleEvent = function(e) { var t = "on" + e.type; this[t] && this[t](e) }, r.filterFindElements = function(e, n) { e = r.makeArray(e); var o = []; return e.forEach(function(e) { if (e instanceof HTMLElement) { if (!n) return void o.push(e); t(e, n) && o.push(e); for (var r = e.querySelectorAll(n), u = 0; u < r.length; u++) o.push(r[u]) } }), o }, r.debounceMethod = function(e, t, r) { r = r || 100; var n = e.prototype[t], o = t + "Timeout"; e.prototype[t] = function() { var e = this[o]; clearTimeout(e); var t = arguments, u = this; this[o] = setTimeout(function() { n.apply(u, t), delete u[o] }, r) } }, r.docReady = function(e) { var t = document.readyState; "complete" == t || "interactive" == t ? setTimeout(e) : document.addEventListener("DOMContentLoaded", e) }, r.toDashed = function(e) { return e.replace(/(.)([A-Z])/g, function(e, t, r) { return t + "-" + r }).toLowerCase() }; var o = e.console; return r.htmlInit = function(t, n) { r.docReady(function() { var u = r.toDashed(n), a = "data-" + u, i = document.querySelectorAll("[" + a + "]"), c = document.querySelectorAll(".js-" + u), d = r.makeArray(i).concat(r.makeArray(c)), f = a + "-options", s = e.jQuery; d.forEach(function(e) { var r, u = e.getAttribute(a) || e.getAttribute(f); try { r = u && JSON.parse(u) } catch (i) { return void(o && o.error("Error parsing " + a + " on " + e.className + ": " + i)) } var c = new t(e, r); s && s.data(e, n, c) }) }) }, r }); ! function(t, n) { "function" == typeof define && define.amd ? define(["jquery"], function(i) { return n(t, i) }) : "object" == typeof module && module.exports ? module.exports = n(t, require("jquery")) : t.jQueryBridget = n(t, t.jQuery) }(window, function(t, n) { "use strict"; function i(i, r, a) { function f(t, n, e) { var o, r = "$()." + i + '("' + n + '")'; return t.each(function(t, f) { var d = a.data(f, i); if (!d) return void u(i + " not initialized. Cannot call methods, i.e. " + r); var c = d[n]; if (!c || "_" == n.charAt(0)) return void u(r + " is not a valid method"); var p = c.apply(d, e); o = void 0 === o ? p : o }), void 0 !== o ? o : t } function d(t, n) { t.each(function(t, e) { var o = a.data(e, i); o ? (o.option(n), o._init()) : (o = new r(e, n), a.data(e, i, o)) }) } a = a || n || t.jQuery, a && (r.prototype.option || (r.prototype.option = function(t) { a.isPlainObject(t) && (this.options = a.extend(!0, this.options, t)) }), a.fn[i] = function(t) { if ("string" == typeof t) { var n = o.call(arguments, 1); return f(this, t, n) } return d(this, t), this }, e(a)) } function e(t) { !t || t && t.bridget || (t.bridget = i) } var o = Array.prototype.slice, r = t.console, u = "undefined" == typeof r ? function() {} : function(t) { r.error(t) }; return e(n || t.jQuery), i }); ! function(t, i) { "function" == typeof define && define.amd ? define(["ev-emitter/ev-emitter", "get-size/get-size"], i) : "object" == typeof module && module.exports ? module.exports = i(require("ev-emitter"), require("get-size")) : (t.Outlayer = {}, t.Outlayer.Item = i(t.EvEmitter, t.getSize)) }(window, function(t, i) { "use strict"; function n(t) { for (var i in t) return !1; return i = null, !0 } function o(t, i) { t && (this.element = t, this.layout = i, this.position = { x: 0, y: 0 }, this._create()) } function e(t) { return t.replace(/([A-Z])/g, function(t) { return "-" + t.toLowerCase() }) } var s = document.documentElement.style, r = "string" == typeof s.transition ? "transition" : "WebkitTransition", a = "string" == typeof s.transform ? "transform" : "WebkitTransform", h = { WebkitTransition: "webkitTransitionEnd", transition: "transitionend" }[r], l = { transform: a, transition: r, transitionDuration: r + "Duration", transitionProperty: r + "Property", transitionDelay: r + "Delay" }, u = o.prototype = Object.create(t.prototype); u.constructor = o, u._create = function() { this._transn = { ingProperties: {}, clean: {}, onEnd: {} }, this.css({ position: "absolute" }) }, u.handleEvent = function(t) { var i = "on" + t.type; this[i] && this[i](t) }, u.getSize = function() { this.size = i(this.element) }, u.css = function(t) { var i = this.element.style; for (var n in t) { var o = l[n] || n; i[o] = t[n] } }, u.getPosition = function() { var t = getComputedStyle(this.element), i = this.layout._getOption("originLeft"), n = this.layout._getOption("originTop"), o = t[i ? "left" : "right"], e = t[n ? "top" : "bottom"], s = parseFloat(o), r = parseFloat(e), a = this.layout.size; o.indexOf("%") != -1 && (s = s / 100 * a.width), e.indexOf("%") != -1 && (r = r / 100 * a.height), s = isNaN(s) ? 0 : s, r = isNaN(r) ? 0 : r, s -= i ? a.paddingLeft : a.paddingRight, r -= n ? a.paddingTop : a.paddingBottom, this.position.x = s, this.position.y = r }, u.layoutPosition = function() { var t = this.layout.size, i = {}, n = this.layout._getOption("originLeft"), o = this.layout._getOption("originTop"), e = n ? "paddingLeft" : "paddingRight", s = n ? "left" : "right", r = n ? "right" : "left", a = this.position.x + t[e]; i[s] = this.getXValue(a), i[r] = ""; var h = o ? "paddingTop" : "paddingBottom", l = o ? "top" : "bottom", u = o ? "bottom" : "top", d = this.position.y + t[h]; i[l] = this.getYValue(d), i[u] = "", this.css(i), this.emitEvent("layout", [this]) }, u.getXValue = function(t) { var i = this.layout._getOption("horizontal"); return this.layout.options.percentPosition && !i ? t / this.layout.size.width * 100 + "%" : t + "px" }, u.getYValue = function(t) { var i = this.layout._getOption("horizontal"); return this.layout.options.percentPosition && i ? t / this.layout.size.height * 100 + "%" : t + "px" }, u._transitionTo = function(t, i) { this.getPosition(); var n = this.position.x, o = this.position.y, e = t == this.position.x && i == this.position.y; if (this.setPosition(t, i), e && !this.isTransitioning) return void this.layoutPosition(); var s = t - n, r = i - o, a = {}; a.transform = this.getTranslate(s, r), this.transition({ to: a, onTransitionEnd: { transform: this.layoutPosition }, isCleaning: !0 }) }, u.getTranslate = function(t, i) { var n = this.layout._getOption("originLeft"), o = this.layout._getOption("originTop"); return t = n ? t : -t, i = o ? i : -i, "translate3d(" + t + "px, " + i + "px, 0)" }, u.goTo = function(t, i) { this.setPosition(t, i), this.layoutPosition() }, u.moveTo = u._transitionTo, u.setPosition = function(t, i) { this.position.x = parseFloat(t), this.position.y = parseFloat(i) }, u._nonTransition = function(t) { this.css(t.to), t.isCleaning && this._removeStyles(t.to); for (var i in t.onTransitionEnd) t.onTransitionEnd[i].call(this) }, u.transition = function(t) { if (!parseFloat(this.layout.options.transitionDuration)) return void this._nonTransition(t); var i = this._transn; for (var n in t.onTransitionEnd) i.onEnd[n] = t.onTransitionEnd[n]; for (n in t.to) i.ingProperties[n] = !0, t.isCleaning && (i.clean[n] = !0); if (t.from) { this.css(t.from); var o = this.element.offsetHeight; o = null } this.enableTransition(t.to), this.css(t.to), this.isTransitioning = !0 }; var d = "opacity," + e(a); u.enableTransition = function() { if (!this.isTransitioning) { var t = this.layout.options.transitionDuration; t = "number" == typeof t ? t + "ms" : t, this.css({ transitionProperty: d, transitionDuration: t, transitionDelay: this.staggerDelay || 0 }), this.element.addEventListener(h, this, !1) } }, u.onwebkitTransitionEnd = function(t) { this.ontransitionend(t) }, u.onotransitionend = function(t) { this.ontransitionend(t) }; var p = { "-webkit-transform": "transform" }; u.ontransitionend = function(t) { if (t.target === this.element) { var i = this._transn, o = p[t.propertyName] || t.propertyName; if (delete i.ingProperties[o], n(i.ingProperties) && this.disableTransition(), o in i.clean && (this.element.style[t.propertyName] = "", delete i.clean[o]), o in i.onEnd) { var e = i.onEnd[o]; e.call(this), delete i.onEnd[o] } this.emitEvent("transitionEnd", [this]) } }, u.disableTransition = function() { this.removeTransitionStyles(), this.element.removeEventListener(h, this, !1), this.isTransitioning = !1 }, u._removeStyles = function(t) { var i = {}; for (var n in t) i[n] = ""; this.css(i) }; var f = { transitionProperty: "", transitionDuration: "", transitionDelay: "" }; return u.removeTransitionStyles = function() { this.css(f) }, u.stagger = function(t) { t = isNaN(t) ? 0 : t, this.staggerDelay = t + "ms" }, u.removeElem = function() { this.element.parentNode.removeChild(this.element), this.css({ display: "" }), this.emitEvent("remove", [this]) }, u.remove = function() { return r && parseFloat(this.layout.options.transitionDuration) ? (this.once("transitionEnd", function() { this.removeElem() }), void this.hide()) : void this.removeElem() }, u.reveal = function() { delete this.isHidden, this.css({ display: "" }); var t = this.layout.options, i = {}, n = this.getHideRevealTransitionEndProperty("visibleStyle"); i[n] = this.onRevealTransitionEnd, this.transition({ from: t.hiddenStyle, to: t.visibleStyle, isCleaning: !0, onTransitionEnd: i }) }, u.onRevealTransitionEnd = function() { this.isHidden || this.emitEvent("reveal") }, u.getHideRevealTransitionEndProperty = function(t) { var i = this.layout.options[t]; if (i.opacity) return "opacity"; for (var n in i) return n }, u.hide = function() { this.isHidden = !0, this.css({ display: "" }); var t = this.layout.options, i = {}, n = this.getHideRevealTransitionEndProperty("hiddenStyle"); i[n] = this.onHideTransitionEnd, this.transition({ from: t.visibleStyle, to: t.hiddenStyle, isCleaning: !0, onTransitionEnd: i }) }, u.onHideTransitionEnd = function() { this.isHidden && (this.css({ display: "none" }), this.emitEvent("hide")) }, u.destroy = function() { this.css({ position: "", left: "", right: "", top: "", bottom: "", transition: "", transform: "" }) }, o }); ! function(t, e) { "use strict"; "function" == typeof define && define.amd ? define(["ev-emitter/ev-emitter", "get-size/get-size", "fizzy-ui-utils/utils", "./item"], function(i, n, s, o) { return e(t, i, n, s, o) }) : "object" == typeof module && module.exports ? module.exports = e(t, require("ev-emitter"), require("get-size"), require("fizzy-ui-utils"), require("./item")) : t.Outlayer = e(t, t.EvEmitter, t.getSize, t.fizzyUIUtils, t.Outlayer.Item) }(window, function(t, e, i, n, s) { "use strict"; function o(t, e) { var i = n.getQueryElement(t); if (!i) return void(h && h.error("Bad element for " + this.constructor.namespace + ": " + (i || t))); this.element = i, u && (this.$element = u(this.element)), this.options = n.extend({}, this.constructor.defaults), this.option(e); var s = ++c; this.element.outlayerGUID = s, f[s] = this, this._create(); var o = this._getOption("initLayout"); o && this.layout() } function r(t) { function e() { t.apply(this, arguments) } return e.prototype = Object.create(t.prototype), e.prototype.constructor = e, e } function a(t) { if ("number" == typeof t) return t; var e = t.match(/(^\d*\.?\d*)(\w*)/), i = e && e[1], n = e && e[2]; if (!i.length) return 0; i = parseFloat(i); var s = d[n] || 1; return i * s } var h = t.console, u = t.jQuery, m = function() {}, c = 0, f = {}; o.namespace = "outlayer", o.Item = s, o.defaults = { containerStyle: { position: "relative" }, initLayout: !0, originLeft: !0, originTop: !0, resize: !0, resizeContainer: !0, transitionDuration: "0.4s", hiddenStyle: { opacity: 0, transform: "scale(0.001)" }, visibleStyle: { opacity: 1, transform: "scale(1)" } }; var l = o.prototype; n.extend(l, e.prototype), l.option = function(t) { n.extend(this.options, t) }, l._getOption = function(t) { var e = this.constructor.compatOptions[t]; return e && void 0 !== this.options[e] ? this.options[e] : this.options[t] }, o.compatOptions = { initLayout: "isInitLayout", horizontal: "isHorizontal", layoutInstant: "isLayoutInstant", originLeft: "isOriginLeft", originTop: "isOriginTop", resize: "isResizeBound", resizeContainer: "isResizingContainer" }, l._create = function() { this.reloadItems(), this.stamps = [], this.stamp(this.options.stamp), n.extend(this.element.style, this.options.containerStyle); var t = this._getOption("resize"); t && this.bindResize() }, l.reloadItems = function() { this.items = this._itemize(this.element.children) }, l._itemize = function(t) { for (var e = this._filterFindItemElements(t), i = this.constructor.Item, n = [], s = 0; s < e.length; s++) { var o = e[s], r = new i(o, this); n.push(r) } return n }, l._filterFindItemElements = function(t) { return n.filterFindElements(t, this.options.itemSelector) }, l.getItemElements = function() { return this.items.map(function(t) { return t.element }) }, l.layout = function() { this._resetLayout(), this._manageStamps(); var t = this._getOption("layoutInstant"), e = void 0 !== t ? t : !this._isLayoutInited; this.layoutItems(this.items, e), this._isLayoutInited = !0 }, l._init = l.layout, l._resetLayout = function() { this.getSize() }, l.getSize = function() { this.size = i(this.element) }, l._getMeasurement = function(t, e) { var n, s = this.options[t]; s ? ("string" == typeof s ? n = this.element.querySelector(s) : s instanceof HTMLElement && (n = s), this[t] = n ? i(n)[e] : s) : this[t] = 0 }, l.layoutItems = function(t, e) { t = this._getItemsForLayout(t), this._layoutItems(t, e), this._postLayout() }, l._getItemsForLayout = function(t) { return t.filter(function(t) { return !t.isIgnored }) }, l._layoutItems = function(t, e) { if (this._emitCompleteOnItems("layout", t), t && t.length) { var i = []; t.forEach(function(t) { var n = this._getItemLayoutPosition(t); n.item = t, n.isInstant = e || t.isLayoutInstant, i.push(n) }, this), this._processLayoutQueue(i) } }, l._getItemLayoutPosition = function() { return { x: 0, y: 0 } }, l._processLayoutQueue = function(t) { this.updateStagger(), t.forEach(function(t, e) { this._positionItem(t.item, t.x, t.y, t.isInstant, e) }, this) }, l.updateStagger = function() { var t = this.options.stagger; return null === t || void 0 === t ? void(this.stagger = 0) : (this.stagger = a(t), this.stagger) }, l._positionItem = function(t, e, i, n, s) { n ? t.goTo(e, i) : (t.stagger(s * this.stagger), t.moveTo(e, i)) }, l._postLayout = function() { this.resizeContainer() }, l.resizeContainer = function() { var t = this._getOption("resizeContainer"); if (t) { var e = this._getContainerSize(); e && (this._setContainerMeasure(e.width, !0), this._setContainerMeasure(e.height, !1)) } }, l._getContainerSize = m, l._setContainerMeasure = function(t, e) { if (void 0 !== t) { var i = this.size; i.isBorderBox && (t += e ? i.paddingLeft + i.paddingRight + i.borderLeftWidth + i.borderRightWidth : i.paddingBottom + i.paddingTop + i.borderTopWidth + i.borderBottomWidth), t = Math.max(t, 0), this.element.style[e ? "width" : "height"] = t + "px" } }, l._emitCompleteOnItems = function(t, e) { function i() { s.dispatchEvent(t + "Complete", null, [e]) } function n() { r++, r == o && i() } var s = this, o = e.length; if (!e || !o) return void i(); var r = 0; e.forEach(function(e) { e.once(t, n) }) }, l.dispatchEvent = function(t, e, i) { var n = e ? [e].concat(i) : i; if (this.emitEvent(t, n), u) if (this.$element = this.$element || u(this.element), e) { var s = u.Event(e); s.type = t, this.$element.trigger(s, i) } else this.$element.trigger(t, i) }, l.ignore = function(t) { var e = this.getItem(t); e && (e.isIgnored = !0) }, l.unignore = function(t) { var e = this.getItem(t); e && delete e.isIgnored }, l.stamp = function(t) { t = this._find(t), t && (this.stamps = this.stamps.concat(t), t.forEach(this.ignore, this)) }, l.unstamp = function(t) { t = this._find(t), t && t.forEach(function(t) { n.removeFrom(this.stamps, t), this.unignore(t) }, this) }, l._find = function(t) { if (t) return "string" == typeof t && (t = this.element.querySelectorAll(t)), t = n.makeArray(t) }, l._manageStamps = function() { this.stamps && this.stamps.length && (this._getBoundingRect(), this.stamps.forEach(this._manageStamp, this)) }, l._getBoundingRect = function() { var t = this.element.getBoundingClientRect(), e = this.size; this._boundingRect = { left: t.left + e.paddingLeft + e.borderLeftWidth, top: t.top + e.paddingTop + e.borderTopWidth, right: t.right - (e.paddingRight + e.borderRightWidth), bottom: t.bottom - (e.paddingBottom + e.borderBottomWidth) } }, l._manageStamp = m, l._getElementOffset = function(t) { var e = t.getBoundingClientRect(), n = this._boundingRect, s = i(t), o = { left: e.left - n.left - s.marginLeft, top: e.top - n.top - s.marginTop, right: n.right - e.right - s.marginRight, bottom: n.bottom - e.bottom - s.marginBottom }; return o }, l.handleEvent = n.handleEvent, l.bindResize = function() { t.addEventListener("resize", this), this.isResizeBound = !0 }, l.unbindResize = function() { t.removeEventListener("resize", this), this.isResizeBound = !1 }, l.onresize = function() { this.resize() }, n.debounceMethod(o, "onresize", 100), l.resize = function() { this.isResizeBound && this.needsResizeLayout() && this.layout() }, l.needsResizeLayout = function() { var t = i(this.element), e = this.size && t; return e && t.innerWidth !== this.size.innerWidth }, l.addItems = function(t) { var e = this._itemize(t); return e.length && (this.items = this.items.concat(e)), e }, l.appended = function(t) { var e = this.addItems(t); e.length && (this.layoutItems(e, !0), this.reveal(e)) }, l.prepended = function(t) { var e = this._itemize(t); if (e.length) { var i = this.items.slice(0); this.items = e.concat(i), this._resetLayout(), this._manageStamps(), this.layoutItems(e, !0), this.reveal(e), this.layoutItems(i) } }, l.reveal = function(t) { if (this._emitCompleteOnItems("reveal", t), t && t.length) { var e = this.updateStagger(); t.forEach(function(t, i) { t.stagger(i * e), t.reveal() }) } }, l.hide = function(t) { if (this._emitCompleteOnItems("hide", t), t && t.length) { var e = this.updateStagger(); t.forEach(function(t, i) { t.stagger(i * e), t.hide() }) } }, l.revealItemElements = function(t) { var e = this.getItems(t); this.reveal(e) }, l.hideItemElements = function(t) { var e = this.getItems(t); this.hide(e) }, l.getItem = function(t) { for (var e = 0; e < this.items.length; e++) { var i = this.items[e]; if (i.element == t) return i } }, l.getItems = function(t) { t = n.makeArray(t); var e = []; return t.forEach(function(t) { var i = this.getItem(t); i && e.push(i) }, this), e }, l.remove = function(t) { var e = this.getItems(t); this._emitCompleteOnItems("remove", e), e && e.length && e.forEach(function(t) { t.remove(), n.removeFrom(this.items, t) }, this) }, l.destroy = function() { var t = this.element.style; t.height = "", t.position = "", t.width = "", this.items.forEach(function(t) { t.destroy() }), this.unbindResize(); var e = this.element.outlayerGUID; delete f[e], delete this.element.outlayerGUID, u && u.removeData(this.element, this.constructor.namespace) }, o.data = function(t) { t = n.getQueryElement(t); var e = t && t.outlayerGUID; return e && f[e] }, o.create = function(t, e) { var i = r(o); return i.defaults = n.extend({}, o.defaults), n.extend(i.defaults, e), i.compatOptions = n.extend({}, o.compatOptions), i.namespace = t, i.data = o.data, i.Item = r(s), n.htmlInit(i, t), u && u.bridget && u.bridget(t, i), i }; var d = { ms: 1, s: 1e3 }; return o.Item = s, o }); ! function(e, t) { "function" == typeof define && define.amd ? define(["get-size/get-size", "outlayer/outlayer"], t) : "object" == typeof module && module.exports ? module.exports = t(require("get-size"), require("outlayer")) : (e.Isotope = e.Isotope || {}, e.Isotope.LayoutMode = t(e.getSize, e.Outlayer)) }(window, function(e, t) { "use strict"; function i(e) { this.isotope = e, e && (this.options = e.options[this.namespace], this.element = e.element, this.items = e.filteredItems, this.size = e.size) } var o = i.prototype, s = ["_resetLayout", "_getItemLayoutPosition", "_manageStamp", "_getContainerSize", "_getElementOffset", "needsResizeLayout", "_getOption"]; return s.forEach(function(e) { o[e] = function() { return t.prototype[e].apply(this.isotope, arguments) } }), o.needsVerticalResizeLayout = function() { var t = e(this.isotope.element), i = this.isotope.size && t; return i && t.innerHeight != this.isotope.size.innerHeight }, o._getMeasurement = function() { this.isotope._getMeasurement.apply(this, arguments) }, o.getColumnWidth = function() { this.getSegmentSize("column", "Width") }, o.getRowHeight = function() { this.getSegmentSize("row", "Height") }, o.getSegmentSize = function(e, t) { var i = e + t, o = "outer" + t; if (this._getMeasurement(i, o), !this[i]) { var s = this.getFirstItemSize(); this[i] = s && s[o] || this.isotope.size["inner" + t] } }, o.getFirstItemSize = function() { var t = this.isotope.filteredItems[0]; return t && t.element && e(t.element) }, o.layout = function() { this.isotope.layout.apply(this.isotope, arguments) }, o.getSize = function() { this.isotope.getSize(), this.size = this.isotope.size }, i.modes = {}, i.create = function(e, t) { function s() { i.apply(this, arguments) } return s.prototype = Object.create(o), s.prototype.constructor = s, t && (s.options = t), s.prototype.namespace = e, i.modes[e] = s, s }, i }); ! function(t, o) { "function" == typeof define && define.amd ? define(["outlayer/outlayer"], o) : "object" == typeof module && module.exports ? module.exports = o(require("outlayer")) : (t.Isotope = t.Isotope || {}, t.Isotope.Item = o(t.Outlayer)) }(window, function(t) { "use strict"; function o() { t.Item.apply(this, arguments) } var e = o.prototype = Object.create(t.Item.prototype), i = e._create; e._create = function() { this.id = this.layout.itemGUID++, i.call(this), this.sortData = {} }, e.updateSortData = function() { if (!this.isIgnored) { this.sortData.id = this.id, this.sortData["original-order"] = this.id, this.sortData.random = Math.random(); var t = this.layout.options.getSortData, o = this.layout._sorters; for (var e in t) { var i = o[e]; this.sortData[e] = i(this.element, this) } } }; var a = e.destroy; return e.destroy = function() { a.apply(this, arguments), this.css({ display: "" }) }, o }); ! function(t, e) { "function" == typeof define && define.amd ? define(["outlayer/outlayer", "get-size/get-size", "desandro-matches-selector/matches-selector", "fizzy-ui-utils/utils", "./item", "./layout-mode", "./layout-modes/masonry", "./layout-modes/fit-rows", "./layout-modes/vertical"], function(i, r, o, s, n, a) { return e(t, i, r, o, s, n, a) }) : "object" == typeof module && module.exports ? module.exports = e(t, require("outlayer"), require("get-size"), require("desandro-matches-selector"), require("fizzy-ui-utils"), require("./item"), require("./layout-mode"), require("./layout-modes/masonry"), require("./layout-modes/fit-rows"), require("./layout-modes/vertical")) : t.Isotope = e(t, t.Outlayer, t.getSize, t.matchesSelector, t.fizzyUIUtils, t.Isotope.Item, t.Isotope.LayoutMode) }(window, function(t, e, i, r, o, s, n) { "use strict"; function a(t, e) { return function(i, r) { for (var o = 0; o < t.length; o++) { var s = t[o], n = i.sortData[s], a = r.sortData[s]; if (n > a || n < a) { var u = void 0 !== e[s] ? e[s] : e, h = u ? 1 : -1; return (n > a ? 1 : -1) * h } } return 0 } } var u = t.jQuery, h = String.prototype.trim ? function(t) { return t.trim() } : function(t) { return t.replace(/^\s+|\s+$/g, "") }, l = e.create("isotope", { layoutMode: "masonry", isJQueryFiltering: !0, sortAscending: !0 }); l.Item = s, l.LayoutMode = n; var m = l.prototype; m._create = function() { this.itemGUID = 0, this._sorters = {}, this._getSorters(), e.prototype._create.call(this), this.modes = {}, this.filteredItems = this.items, this.sortHistory = ["original-order"]; for (var t in n.modes) this._initLayoutMode(t) }, m.reloadItems = function() { this.itemGUID = 0, e.prototype.reloadItems.call(this) }, m._itemize = function() { for (var t = e.prototype._itemize.apply(this, arguments), i = 0; i < t.length; i++) { var r = t[i]; r.id = this.itemGUID++ } return this._updateItemsSortData(t), t }, m._initLayoutMode = function(t) { var e = n.modes[t], i = this.options[t] || {}; this.options[t] = e.options ? o.extend(e.options, i) : i, this.modes[t] = new e(this) }, m.layout = function() { return !this._isLayoutInited && this._getOption("initLayout") ? void this.arrange() : void this._layout() }, m._layout = function() { var t = this._getIsInstant(); this._resetLayout(), this._manageStamps(), this.layoutItems(this.filteredItems, t), this._isLayoutInited = !0 }, m.arrange = function(t) { this.option(t), this._getIsInstant(); var e = this._filter(this.items); this.filteredItems = e.matches, this._bindArrangeComplete(), this._isInstant ? this._noTransition(this._hideReveal, [e]) : this._hideReveal(e), this._sort(), this._layout() }, m._init = m.arrange, m._hideReveal = function(t) { this.reveal(t.needReveal), this.hide(t.needHide) }, m._getIsInstant = function() { var t = this._getOption("layoutInstant"), e = void 0 !== t ? t : !this._isLayoutInited; return this._isInstant = e, e }, m._bindArrangeComplete = function() { function t() { e && i && r && o.dispatchEvent("arrangeComplete", null, [o.filteredItems]) } var e, i, r, o = this; this.once("layoutComplete", function() { e = !0, t() }), this.once("hideComplete", function() { i = !0, t() }), this.once("revealComplete", function() { r = !0, t() }) }, m._filter = function(t) { var e = this.options.filter; e = e || "*"; for (var i = [], r = [], o = [], s = this._getFilterTest(e), n = 0; n < t.length; n++) { var a = t[n]; if (!a.isIgnored) { var u = s(a); u && i.push(a), u && a.isHidden ? r.push(a) : u || a.isHidden || o.push(a) } } return { matches: i, needReveal: r, needHide: o } }, m._getFilterTest = function(t) { return u && this.options.isJQueryFiltering ? function(e) { return u(e.element).is(t) } : "function" == typeof t ? function(e) { return t(e.element) } : function(e) { return r(e.element, t) } }, m.updateSortData = function(t) { var e; t ? (t = o.makeArray(t), e = this.getItems(t)) : e = this.items, this._getSorters(), this._updateItemsSortData(e) }, m._getSorters = function() { var t = this.options.getSortData; for (var e in t) { var i = t[e]; this._sorters[e] = d(i) } }, m._updateItemsSortData = function(t) { for (var e = t && t.length, i = 0; e && i < e; i++) { var r = t[i]; r.updateSortData() } }; var d = function() { function t(t) { if ("string" != typeof t) return t; var i = h(t).split(" "), r = i[0], o = r.match(/^\[(.+)\]$/), s = o && o[1], n = e(s, r), a = l.sortDataParsers[i[1]]; return t = a ? function(t) { return t && a(n(t)) } : function(t) { return t && n(t) } } function e(t, e) { return t ? function(e) { return e.getAttribute(t) } : function(t) { var i = t.querySelector(e); return i && i.textContent } } return t }(); l.sortDataParsers = { parseInt: function(t) { return parseInt(t, 10) }, parseFloat: function(t) { return parseFloat(t) } }, m._sort = function() { if (this.options.sortBy) { var t = o.makeArray(this.options.sortBy); this._getIsSameSortBy(t) || (this.sortHistory = t.concat(this.sortHistory)); var e = a(this.sortHistory, this.options.sortAscending); this.filteredItems.sort(e) } }, m._getIsSameSortBy = function(t) { for (var e = 0; e < t.length; e++) if (t[e] != this.sortHistory[e]) return !1; return !0 }, m._mode = function() { var t = this.options.layoutMode, e = this.modes[t]; if (!e) throw new Error("No layout mode: " + t); return e.options = this.options[t], e }, m._resetLayout = function() { e.prototype._resetLayout.call(this), this._mode()._resetLayout() }, m._getItemLayoutPosition = function(t) { return this._mode()._getItemLayoutPosition(t) }, m._manageStamp = function(t) { this._mode()._manageStamp(t) }, m._getContainerSize = function() { return this._mode()._getContainerSize() }, m.needsResizeLayout = function() { return this._mode().needsResizeLayout() }, m.appended = function(t) { var e = this.addItems(t); if (e.length) { var i = this._filterRevealAdded(e); this.filteredItems = this.filteredItems.concat(i) } }, m.prepended = function(t) { var e = this._itemize(t); if (e.length) { this._resetLayout(), this._manageStamps(); var i = this._filterRevealAdded(e); this.layoutItems(this.filteredItems), this.filteredItems = i.concat(this.filteredItems), this.items = e.concat(this.items) } }, m._filterRevealAdded = function(t) { var e = this._filter(t); return this.hide(e.needHide), this.reveal(e.matches), this.layoutItems(e.matches, !0), e.matches }, m.insert = function(t) { var e = this.addItems(t); if (e.length) { var i, r, o = e.length; for (i = 0; i < o; i++) r = e[i], this.element.appendChild(r.element); var s = this._filter(e).matches; for (i = 0; i < o; i++) e[i].isLayoutInstant = !0; for (this.arrange(), i = 0; i < o; i++) delete e[i].isLayoutInstant; this.reveal(s) } }; var f = m.remove; return m.remove = function(t) { t = o.makeArray(t); var e = this.getItems(t); f.call(this, t); for (var i = e && e.length, r = 0; i && r < i; r++) { var s = e[r]; o.removeFrom(this.filteredItems, s) } }, m.shuffle = function() { for (var t = 0; t < this.items.length; t++) { var e = this.items[t]; e.sortData.random = Math.random() } this.options.sortBy = "random", this._sort(), this._layout() }, m._noTransition = function(t, e) { var i = this.options.transitionDuration; this.options.transitionDuration = 0; var r = t.apply(this, e); return this.options.transitionDuration = i, r }, m.getFilteredItemElements = function() { return this.filteredItems.map(function(t) { return t.element }) }, l }); ! function(t, e) { "function" == typeof define && define.amd ? define(["../layout-mode"], e) : "object" == typeof exports ? module.exports = e(require("../layout-mode")) : e(t.Isotope.LayoutMode) }(window, function(t) { "use strict"; var e = t.create("fitRows"), i = e.prototype; return i._resetLayout = function() { this.x = 0, this.y = 0, this.maxY = 0, this._getMeasurement("gutter", "outerWidth") }, i._getItemLayoutPosition = function(t) { t.getSize(); var e = t.size.outerWidth + this.gutter, i = this.isotope.size.innerWidth + this.gutter; 0 !== this.x && e + this.x > i && (this.x = 0, this.y = this.maxY); var o = { x: this.x, y: this.y }; return this.maxY = Math.max(this.maxY, this.y + t.size.outerHeight), this.x += e, o }, i._getContainerSize = function() { return { height: this.maxY } }, e }); ! function(t, e) { "function" == typeof define && define.amd ? define(["../layout-mode"], e) : "object" == typeof module && module.exports ? module.exports = e(require("../layout-mode")) : e(t.Isotope.LayoutMode) }(window, function(t) { "use strict"; var e = t.create("vertical", { horizontalAlignment: 0 }), o = e.prototype; return o._resetLayout = function() { this.y = 0 }, o._getItemLayoutPosition = function(t) { t.getSize(); var e = (this.isotope.size.innerWidth - t.size.outerWidth) * this.options.horizontalAlignment, o = this.y; return this.y += t.size.outerHeight, { x: e, y: o } }, o._getContainerSize = function() { return { height: this.y } }, e }); ! function(t, i) { "function" == typeof define && define.amd ? define(["outlayer/outlayer", "get-size/get-size"], i) : "object" == typeof module && module.exports ? module.exports = i(require("outlayer"), require("get-size")) : t.Masonry = i(t.Outlayer, t.getSize) }(window, function(t, i) { "use strict"; var o = t.create("masonry"); o.compatOptions.fitWidth = "isFitWidth"; var e = o.prototype; return e._resetLayout = function() { this.getSize(), this._getMeasurement("columnWidth", "outerWidth"), this._getMeasurement("gutter", "outerWidth"), this.measureColumns(), this.colYs = []; for (var t = 0; t < this.cols; t++) this.colYs.push(0); this.maxY = 0, this.horizontalColIndex = 0 }, e.measureColumns = function() { if (this.getContainerWidth(), !this.columnWidth) { var t = this.items[0], o = t && t.element; this.columnWidth = o && i(o).outerWidth || this.containerWidth } var e = this.columnWidth += this.gutter, h = this.containerWidth + this.gutter, n = h / e, s = e - h % e, r = s && s < 1 ? "round" : "floor"; n = Math[r](n), this.cols = Math.max(n, 1) }, e.getContainerWidth = function() { var t = this._getOption("fitWidth"), o = t ? this.element.parentNode : this.element, e = i(o); this.containerWidth = e && e.innerWidth }, e._getItemLayoutPosition = function(t) { t.getSize(); var i = t.size.outerWidth % this.columnWidth, o = i && i < 1 ? "round" : "ceil", e = Math[o](t.size.outerWidth / this.columnWidth); e = Math.min(e, this.cols); for (var h = this.options.horizontalOrder ? "_getHorizontalColPosition" : "_getTopColPosition", n = this[h](e, t), s = { x: this.columnWidth * n.col, y: n.y }, r = n.y + t.size.outerHeight, a = e + n.col, u = n.col; u < a; u++) this.colYs[u] = r; return s }, e._getTopColPosition = function(t) { var i = this._getTopColGroup(t), o = Math.min.apply(Math, i); return { col: i.indexOf(o), y: o } }, e._getTopColGroup = function(t) { if (t < 2) return this.colYs; for (var i = [], o = this.cols + 1 - t, e = 0; e < o; e++) i[e] = this._getColGroupY(e, t); return i }, e._getColGroupY = function(t, i) { if (i < 2) return this.colYs[t]; var o = this.colYs.slice(t, t + i); return Math.max.apply(Math, o) }, e._getHorizontalColPosition = function(t, i) { var o = this.horizontalColIndex % this.cols, e = t > 1 && o + t > this.cols; o = e ? 0 : o; var h = i.size.outerWidth && i.size.outerHeight; return this.horizontalColIndex = h ? o + t : this.horizontalColIndex, { col: o, y: this._getColGroupY(o, t) } }, e._manageStamp = function(t) { var o = i(t), e = this._getElementOffset(t), h = this._getOption("originLeft"), n = h ? e.left : e.right, s = n + o.outerWidth, r = Math.floor(n / this.columnWidth); r = Math.max(0, r); var a = Math.floor(s / this.columnWidth); a -= s % this.columnWidth ? 0 : 1, a = Math.min(this.cols - 1, a); for (var u = this._getOption("originTop"), l = (u ? e.top : e.bottom) + o.outerHeight, c = r; c <= a; c++) this.colYs[c] = Math.max(l, this.colYs[c]) }, e._getContainerSize = function() { this.maxY = Math.max.apply(Math, this.colYs); var t = { height: this.maxY }; return this._getOption("fitWidth") && (t.width = this._getContainerFitWidth()), t }, e._getContainerFitWidth = function() { for (var t = 0, i = this.cols; --i && 0 === this.colYs[i];) t++; return (this.cols - t) * this.columnWidth - this.gutter }, e.needsResizeLayout = function() { var t = this.containerWidth; return this.getContainerWidth(), t != this.containerWidth }, o }); ! function(t, o) { "function" == typeof define && define.amd ? define(["../layout-mode", "masonry-layout/masonry"], o) : "object" == typeof module && module.exports ? module.exports = o(require("../layout-mode"), require("masonry-layout")) : o(t.Isotope.LayoutMode, t.Masonry) }(window, function(t, o) { "use strict"; var e = t.create("masonry"), i = e.prototype, s = { _getElementOffset: !0, layout: !0, _getMeasurement: !0 }; for (var n in o.prototype) s[n] || (i[n] = o.prototype[n]); var r = i.measureColumns; i.measureColumns = function() { this.items = this.isotope.filteredItems, r.call(this) }; var u = i._getOption; return i._getOption = function(t) { return "fitWidth" == t ? void 0 !== this.options.isFitWidth ? this.options.isFitWidth : this.options.fitWidth : u.apply(this.isotope, arguments) }, e }); ! function(t, e) { "function" == typeof define && define.amd ? define(["isotope/js/layout-mode"], e) : "object" == typeof exports ? module.exports = e(require("isotope-layout/js/layout-mode")) : e(t.Isotope.LayoutMode) }(window, function(t) { "use strict"; var e = t.create("cellsByColumn"), i = e.prototype; return i._resetLayout = function() { this.itemIndex = 0, this.getColumnWidth(), this.getRowHeight(), this.rows = Math.floor(this.isotope.size.innerHeight / this.rowHeight), this.rows = Math.max(this.rows, 1) }, i._getItemLayoutPosition = function(t) { t.getSize(); var e = Math.floor(this.itemIndex / this.rows), i = this.itemIndex % this.rows, o = (e + .5) * this.columnWidth - t.size.outerWidth / 2, s = (i + .5) * this.rowHeight - t.size.outerHeight / 2; return this.itemIndex++, { x: o, y: s } }, i._getContainerSize = function() { return { width: Math.ceil(this.itemIndex / this.rows) * this.columnWidth } }, i.needsResizeLayout = function() { return this.needsVerticalResizeLayout() }, e }); ! function(t, e) { "function" == typeof define && define.amd ? define(["isotope/js/layout-mode"], e) : "object" == typeof exports ? module.exports = e(require("isotope-layout/js/layout-mode")) : e(t.Isotope.LayoutMode) }(window, function(t) { "use strict"; var e = t.create("cellsByRow"), i = e.prototype; return i._resetLayout = function() { this.itemIndex = 0, this.getColumnWidth(), this.getRowHeight(), this.cols = Math.floor(this.isotope.size.innerWidth / this.columnWidth), this.cols = Math.max(this.cols, 1) }, i._getItemLayoutPosition = function(t) { t.getSize(); var e = this.itemIndex % this.cols, i = Math.floor(this.itemIndex / this.cols), o = (e + .5) * this.columnWidth - t.size.outerWidth / 2, s = (i + .5) * this.rowHeight - t.size.outerHeight / 2; return this.itemIndex++, { x: o, y: s } }, i._getContainerSize = function() { return { height: Math.ceil(this.itemIndex / this.cols) * this.rowHeight } }, e }); ! function(t, e) { "function" == typeof define && define.amd ? define(["isotope/js/layout-mode"], e) : "object" == typeof exports ? module.exports = e(require("isotope-layout/js/layout-mode")) : e(t.Isotope.LayoutMode) }(window, function(t) { "use strict"; var e = t.create("fitColumns"), i = e.prototype; return i._resetLayout = function() { this.x = 0, this.y = 0, this.maxX = 0 }, i._getItemLayoutPosition = function(t) { t.getSize(), 0 !== this.y && t.size.outerHeight + this.y > this.isotope.size.innerHeight && (this.y = 0, this.x = this.maxX); var e = { x: this.x, y: this.y }; return this.maxX = Math.max(this.maxX, this.x + t.size.outerWidth), this.y += t.size.outerHeight, e }, i._getContainerSize = function() { return { width: this.maxX } }, i.needsResizeLayout = function() { return this.needsVerticalResizeLayout() }, e }); ! function(e, t) { "function" == typeof define && define.amd ? define(["isotope/js/layout-mode"], t) : "object" == typeof exports ? module.exports = t(require("isotope-layout/js/layout-mode")) : t(e.Isotope.LayoutMode) }(window, function(e) { "use strict"; var t = e.create("horiz", { verticalAlignment: 0 }), i = t.prototype; return i._resetLayout = function() { this.x = 0 }, i._getItemLayoutPosition = function(e) { e.getSize(); var t = (this.isotope.size.innerHeight - e.size.outerHeight) * this.options.verticalAlignment, i = this.x; return this.x += e.size.outerWidth, { x: i, y: t } }, i._getContainerSize = function() { return { width: this.x } }, i.needsResizeLayout = function() { return this.needsVerticalResizeLayout() }, t }); ! function(t, e) { "use strict"; "function" == typeof define && define.amd ? define(["get-size/get-size", "isotope/js/layout-mode"], e) : "object" == typeof module && module.exports ? module.exports = e(require("get-size"), require("isotope-layout/js/layout-mode")) : e(t.getSize, t.Isotope.LayoutMode) }(window, function(t, e) { "use strict"; var i = e.create("masonryHorizontal"), o = i.prototype; return o._resetLayout = function() { this.getRowHeight(), this._getMeasurement("gutter", "outerHeight"), this.rowHeight += this.gutter, this.rows = Math.floor((this.isotope.size.innerHeight + this.gutter) / this.rowHeight), this.rows = Math.max(this.rows, 1); var t = this.rows; for (this.rowXs = []; t--;) this.rowXs.push(0); this.maxX = 0 }, o._getItemLayoutPosition = function(t) { t.getSize(); var e = t.size.outerHeight % this.rowHeight, i = e && e < 1 ? "round" : "ceil", o = Math[i](t.size.outerHeight / this.rowHeight); o = Math.min(o, this.rows); for (var r = this._getRowGroup(o), s = Math.min.apply(Math, r), h = r.indexOf(s), a = { x: s, y: this.rowHeight * h }, n = s + t.size.outerWidth, u = this.rows + 1 - r.length, g = 0; g < u; g++) this.rowXs[h + g] = n; return a }, o._getRowGroup = function(t) { if (t < 2) return this.rowXs; for (var e = [], i = this.rows + 1 - t, o = 0; o < i; o++) { var r = this.rowXs.slice(o, o + t); e[o] = Math.max.apply(Math, r) } return e }, o._manageStamp = function(e) { var i = t(e), o = this.isotope._getElementOffset(e), r = this._getOption("originTop") ? o.top : o.bottom, s = r + i.outerHeight, h = Math.floor(r / this.rowHeight); h = Math.max(0, h); var a = Math.floor(s / this.rowHeight); a = Math.min(this.rows - 1, a); for (var n = (this._getOption("originLeft") ? o.left : o.right) + i.outerWidth, u = h; u <= a; u++) this.rowXs[u] = Math.max(n, this.rowXs[u]) }, o._getContainerSize = function() { return this.maxX = Math.max.apply(Math, this.rowXs), { width: this.maxX } }, o.needsResizeLayout = function() { return this.needsVerticalResizeLayout() }, i }); ! function(t, h) { "function" == typeof define && define.amd ? define(h) : "object" == typeof module && module.exports ? module.exports = h() : (t.Packery = t.Packery || {}, t.Packery.Rect = h()) }(window, function() { "use strict"; function t(h) { for (var i in t.defaults) this[i] = t.defaults[i]; for (i in h) this[i] = h[i] } t.defaults = { x: 0, y: 0, width: 0, height: 0 }; var h = t.prototype; return h.contains = function(t) { var h = t.width || 0, i = t.height || 0; return this.x <= t.x && this.y <= t.y && this.x + this.width >= t.x + h && this.y + this.height >= t.y + i }, h.overlaps = function(t) { var h = this.x + this.width, i = this.y + this.height, e = t.x + t.width, s = t.y + t.height; return this.x < e && h > t.x && this.y < s && i > t.y }, h.getMaximalFreeRects = function(h) { if (!this.overlaps(h)) return !1; var i, e = [], s = this.x + this.width, n = this.y + this.height, r = h.x + h.width, y = h.y + h.height; return this.y < h.y && (i = new t({ x: this.x, y: this.y, width: this.width, height: h.y - this.y }), e.push(i)), s > r && (i = new t({ x: r, y: this.y, width: s - r, height: this.height }), e.push(i)), n > y && (i = new t({ x: this.x, y: y, width: this.width, height: n - y }), e.push(i)), this.x < h.x && (i = new t({ x: this.x, y: this.y, width: h.x - this.x, height: this.height }), e.push(i)), e }, h.canFit = function(t) { return this.width >= t.width && this.height >= t.height }, t }); ! function(t, e) { if ("function" == typeof define && define.amd) define(["./rect"], e); else if ("object" == typeof module && module.exports) module.exports = e(require("./rect")); else { var i = t.Packery = t.Packery || {}; i.Packer = e(i.Rect) } }(window, function(t) { "use strict"; function e(t, e, i) { this.width = t || 0, this.height = e || 0, this.sortDirection = i || "downwardLeftToRight", this.reset() } var i = e.prototype; i.reset = function() { this.spaces = []; var e = new t({ x: 0, y: 0, width: this.width, height: this.height }); this.spaces.push(e), this.sorter = s[this.sortDirection] || s.downwardLeftToRight }, i.pack = function(t) { for (var e = 0; e < this.spaces.length; e++) { var i = this.spaces[e]; if (i.canFit(t)) { this.placeInSpace(t, i); break } } }, i.columnPack = function(t) { for (var e = 0; e < this.spaces.length; e++) { var i = this.spaces[e], s = i.x <= t.x && i.x + i.width >= t.x + t.width && i.height >= t.height - .01; if (s) { t.y = i.y, this.placed(t); break } } }, i.rowPack = function(t) { for (var e = 0; e < this.spaces.length; e++) { var i = this.spaces[e], s = i.y <= t.y && i.y + i.height >= t.y + t.height && i.width >= t.width - .01; if (s) { t.x = i.x, this.placed(t); break } } }, i.placeInSpace = function(t, e) { t.x = e.x, t.y = e.y, this.placed(t) }, i.placed = function(t) { for (var e = [], i = 0; i < this.spaces.length; i++) { var s = this.spaces[i], r = s.getMaximalFreeRects(t); r ? e.push.apply(e, r) : e.push(s) } this.spaces = e, this.mergeSortSpaces() }, i.mergeSortSpaces = function() { e.mergeRects(this.spaces), this.spaces.sort(this.sorter) }, i.addSpace = function(t) { this.spaces.push(t), this.mergeSortSpaces() }, e.mergeRects = function(t) { var e = 0, i = t[e]; t: for (; i;) { for (var s = 0, r = t[e + s]; r;) { if (r == i) s++; else { if (r.contains(i)) { t.splice(e, 1), i = t[e]; continue t } i.contains(r) ? t.splice(e + s, 1) : s++ } r = t[e + s] } e++, i = t[e] } return t }; var s = { downwardLeftToRight: function(t, e) { return t.y - e.y || t.x - e.x }, rightwardTopToBottom: function(t, e) { return t.x - e.x || t.y - e.y } }; return e }); ! function(e, t) { "function" == typeof define && define.amd ? define(["outlayer/outlayer", "./rect"], t) : "object" == typeof module && module.exports ? module.exports = t(require("outlayer"), require("./rect")) : e.Packery.Item = t(e.Outlayer, e.Packery.Rect) }(window, function(e, t) { "use strict"; var i = document.documentElement.style, o = "string" == typeof i.transform ? "transform" : "WebkitTransform", s = function() { e.Item.apply(this, arguments) }, r = s.prototype = Object.create(e.Item.prototype), n = r._create; r._create = function() { n.call(this), this.rect = new t }; var a = r.moveTo; return r.moveTo = function(e, t) { var i = Math.abs(this.position.x - e), o = Math.abs(this.position.y - t), s = this.layout.dragItemCount && !this.isPlacing && !this.isTransitioning && i < 1 && o < 1; return s ? void this.goTo(e, t) : void a.apply(this, arguments) }, r.enablePlacing = function() { this.removeTransitionStyles(), this.isTransitioning && o && (this.element.style[o] = "none"), this.isTransitioning = !1, this.getSize(), this.layout._setRectSize(this.element, this.rect), this.isPlacing = !0 }, r.disablePlacing = function() { this.isPlacing = !1 }, r.removeElem = function() { this.element.parentNode.removeChild(this.element), this.layout.packer.addSpace(this.rect), this.emitEvent("remove", [this]) }, r.showDropPlaceholder = function() { var e = this.dropPlaceholder; e || (e = this.dropPlaceholder = document.createElement("div"), e.className = "packery-drop-placeholder", e.style.position = "absolute"), e.style.width = this.size.width + "px", e.style.height = this.size.height + "px", this.positionDropPlaceholder(), this.layout.element.appendChild(e) }, r.positionDropPlaceholder = function() { this.dropPlaceholder.style[o] = "translate(" + this.rect.x + "px, " + this.rect.y + "px)" }, r.hideDropPlaceholder = function() { var e = this.dropPlaceholder.parentNode; e && e.removeChild(this.dropPlaceholder) }, s }); ! function(t, i) { "function" == typeof define && define.amd ? define(["get-size/get-size", "outlayer/outlayer", "./rect", "./packer", "./item"], i) : "object" == typeof module && module.exports ? module.exports = i(require("get-size"), require("outlayer"), require("./rect"), require("./packer"), require("./item")) : t.Packery = i(t.getSize, t.Outlayer, t.Packery.Rect, t.Packery.Packer, t.Packery.Item) }(window, function(t, i, e, s, r) { "use strict"; function a(t, i) { return t.position.y - i.position.y || t.position.x - i.position.x } function h(t, i) { return t.position.x - i.position.x || t.position.y - i.position.y } function n(t, i) { var e = i.x - t.x, s = i.y - t.y; return Math.sqrt(e * e + s * s) } e.prototype.canFit = function(t) { return this.width >= t.width - 1 && this.height >= t.height - 1 }; var o = i.create("packery"); o.Item = r; var g = o.prototype; g._create = function() { i.prototype._create.call(this), this.packer = new s, this.shiftPacker = new s, this.isEnabled = !0, this.dragItemCount = 0; var t = this; this.handleDraggabilly = { dragStart: function() { t.itemDragStart(this.element) }, dragMove: function() { t.itemDragMove(this.element, this.position.x, this.position.y) }, dragEnd: function() { t.itemDragEnd(this.element) } }, this.handleUIDraggable = { start: function(i, e) { e && t.itemDragStart(i.currentTarget) }, drag: function(i, e) { e && t.itemDragMove(i.currentTarget, e.position.left, e.position.top) }, stop: function(i, e) { e && t.itemDragEnd(i.currentTarget) } } }, g._resetLayout = function() { this.getSize(), this._getMeasurements(); var t, i, e; this._getOption("horizontal") ? (t = 1 / 0, i = this.size.innerHeight + this.gutter, e = "rightwardTopToBottom") : (t = this.size.innerWidth + this.gutter, i = 1 / 0, e = "downwardLeftToRight"), this.packer.width = this.shiftPacker.width = t, this.packer.height = this.shiftPacker.height = i, this.packer.sortDirection = this.shiftPacker.sortDirection = e, this.packer.reset(), this.maxY = 0, this.maxX = 0 }, g._getMeasurements = function() { this._getMeasurement("columnWidth", "width"), this._getMeasurement("rowHeight", "height"), this._getMeasurement("gutter", "width") }, g._getItemLayoutPosition = function(t) { if (this._setRectSize(t.element, t.rect), this.isShifting || this.dragItemCount > 0) { var i = this._getPackMethod(); this.packer[i](t.rect) } else this.packer.pack(t.rect); return this._setMaxXY(t.rect), t.rect }, g.shiftLayout = function() { this.isShifting = !0, this.layout(), delete this.isShifting }, g._getPackMethod = function() { return this._getOption("horizontal") ? "rowPack" : "columnPack" }, g._setMaxXY = function(t) { this.maxX = Math.max(t.x + t.width, this.maxX), this.maxY = Math.max(t.y + t.height, this.maxY) }, g._setRectSize = function(i, e) { var s = t(i), r = s.outerWidth, a = s.outerHeight; (r || a) && (r = this._applyGridGutter(r, this.columnWidth), a = this._applyGridGutter(a, this.rowHeight)), e.width = Math.min(r, this.packer.width), e.height = Math.min(a, this.packer.height) }, g._applyGridGutter = function(t, i) { if (!i) return t + this.gutter; i += this.gutter; var e = t % i, s = e && e < 1 ? "round" : "ceil"; return t = Math[s](t / i) * i }, g._getContainerSize = function() { return this._getOption("horizontal") ? { width: this.maxX - this.gutter } : { height: this.maxY - this.gutter } }, g._manageStamp = function(t) { var i, s = this.getItem(t); if (s && s.isPlacing) i = s.rect; else { var r = this._getElementOffset(t); i = new e({ x: this._getOption("originLeft") ? r.left : r.right, y: this._getOption("originTop") ? r.top : r.bottom }) } this._setRectSize(t, i), this.packer.placed(i), this._setMaxXY(i) }, g.sortItemsByPosition = function() { var t = this._getOption("horizontal") ? h : a; this.items.sort(t) }, g.fit = function(t, i, e) { var s = this.getItem(t); s && (this.stamp(s.element), s.enablePlacing(), this.updateShiftTargets(s), i = void 0 === i ? s.rect.x : i, e = void 0 === e ? s.rect.y : e, this.shift(s, i, e), this._bindFitEvents(s), s.moveTo(s.rect.x, s.rect.y), this.shiftLayout(), this.unstamp(s.element), this.sortItemsByPosition(), s.disablePlacing()) }, g._bindFitEvents = function(t) { function i() { s++, 2 == s && e.dispatchEvent("fitComplete", null, [t]) } var e = this, s = 0; t.once("layout", i), this.once("layoutComplete", i) }, g.resize = function() { this.isResizeBound && this.needsResizeLayout() && (this.options.shiftPercentResize ? this.resizeShiftPercentLayout() : this.layout()) }, g.needsResizeLayout = function() { var i = t(this.element), e = this._getOption("horizontal") ? "innerHeight" : "innerWidth"; return i[e] != this.size[e] }, g.resizeShiftPercentLayout = function() { var i = this._getItemsForLayout(this.items), e = this._getOption("horizontal"), s = e ? "y" : "x", r = e ? "height" : "width", a = e ? "rowHeight" : "columnWidth", h = e ? "innerHeight" : "innerWidth", n = this[a]; if (n = n && n + this.gutter) { this._getMeasurements(); var o = this[a] + this.gutter; i.forEach(function(t) { var i = Math.round(t.rect[s] / n); t.rect[s] = i * o }) } else { var g = t(this.element)[h] + this.gutter, c = this.packer[r]; i.forEach(function(t) { t.rect[s] = t.rect[s] / c * g }) } this.shiftLayout() }, g.itemDragStart = function(t) { if (this.isEnabled) { this.stamp(t); var i = this.getItem(t); i && (i.enablePlacing(), i.showDropPlaceholder(), this.dragItemCount++, this.updateShiftTargets(i)) } }, g.updateShiftTargets = function(t) { this.shiftPacker.reset(), this._getBoundingRect(); var i = this._getOption("originLeft"), s = this._getOption("originTop"); this.stamps.forEach(function(t) { var r = this.getItem(t); if (!r || !r.isPlacing) { var a = this._getElementOffset(t), h = new e({ x: i ? a.left : a.right, y: s ? a.top : a.bottom }); this._setRectSize(t, h), this.shiftPacker.placed(h) } }, this); var r = this._getOption("horizontal"), a = r ? "rowHeight" : "columnWidth", h = r ? "height" : "width"; this.shiftTargetKeys = [], this.shiftTargets = []; var n, o = this[a]; if (o = o && o + this.gutter) { var g = Math.ceil(t.rect[h] / o), c = Math.floor((this.shiftPacker[h] + this.gutter) / o); n = (c - g) * o; for (var u = 0; u < c; u++) { var d = r ? 0 : u * o, f = r ? u * o : 0; this._addShiftTarget(d, f, n) } } else n = this.shiftPacker[h] + this.gutter - t.rect[h], this._addShiftTarget(0, 0, n); var l = this._getItemsForLayout(this.items), m = this._getPackMethod(); l.forEach(function(t) { var i = t.rect; this._setRectSize(t.element, i), this.shiftPacker[m](i), this._addShiftTarget(i.x, i.y, n); var e = r ? i.x + i.width : i.x, s = r ? i.y : i.y + i.height; if (this._addShiftTarget(e, s, n), o) for (var a = Math.round(i[h] / o), g = 1; g < a; g++) { var c = r ? e : i.x + o * g, u = r ? i.y + o * g : s; this._addShiftTarget(c, u, n) } }, this) }, g._addShiftTarget = function(t, i, e) { var s = this._getOption("horizontal") ? i : t; if (!(0 !== s && s > e)) { var r = t + "," + i, a = this.shiftTargetKeys.indexOf(r) != -1; a || (this.shiftTargetKeys.push(r), this.shiftTargets.push({ x: t, y: i })) } }, g.shift = function(t, i, e) { var s, r = 1 / 0, a = { x: i, y: e }; this.shiftTargets.forEach(function(t) { var i = n(t, a); i < r && (s = t, r = i) }), t.rect.x = s.x, t.rect.y = s.y }; var c = 120; g.itemDragMove = function(t, i, e) { function s() { a.shift(r, i, e), r.positionDropPlaceholder(), a.layout() } var r = this.isEnabled && this.getItem(t); if (r) { i -= this.size.paddingLeft, e -= this.size.paddingTop; var a = this, h = new Date; this._itemDragTime && h - this._itemDragTime < c ? (clearTimeout(this.dragTimeout), this.dragTimeout = setTimeout(s, c)) : (s(), this._itemDragTime = h) } }, g.itemDragEnd = function(t) { function i() { s++, 2 == s && (e.element.classList.remove("is-positioning-post-drag"), e.hideDropPlaceholder(), r.dispatchEvent("dragItemPositioned", null, [e])) } var e = this.isEnabled && this.getItem(t); if (e) { clearTimeout(this.dragTimeout), e.element.classList.add("is-positioning-post-drag"); var s = 0, r = this; e.once("layout", i), this.once("layoutComplete", i), e.moveTo(e.rect.x, e.rect.y), this.layout(), this.dragItemCount = Math.max(0, this.dragItemCount - 1), this.sortItemsByPosition(), e.disablePlacing(), this.unstamp(e.element) } }, g.bindDraggabillyEvents = function(t) { this._bindDraggabillyEvents(t, "on") }, g.unbindDraggabillyEvents = function(t) { this._bindDraggabillyEvents(t, "off") }, g._bindDraggabillyEvents = function(t, i) { var e = this.handleDraggabilly; t[i]("dragStart", e.dragStart), t[i]("dragMove", e.dragMove), t[i]("dragEnd", e.dragEnd) }, g.bindUIDraggableEvents = function(t) { this._bindUIDraggableEvents(t, "on") }, g.unbindUIDraggableEvents = function(t) { this._bindUIDraggableEvents(t, "off") }, g._bindUIDraggableEvents = function(t, i) { var e = this.handleUIDraggable; t[i]("dragstart", e.start)[i]("drag", e.drag)[i]("dragstop", e.stop) }; var u = g.destroy; return g.destroy = function() { u.apply(this, arguments), this.isEnabled = !1 }, o.Rect = e, o.Packer = s, o }); ! function(t, e) { "use strict"; "function" == typeof define && define.amd ? define(["isotope-layout/js/layout-mode", "packery/js/packery"], e) : "object" == typeof module && module.exports ? module.exports = e(require("isotope-layout/js/layout-mode"), require("packery")) : e(t.Isotope.LayoutMode, t.Packery) }(window, function(t, e) { "use strict"; var o = t.create("packery"), i = o.prototype, r = { _getElementOffset: !0, _getMeasurement: !0 }; for (var s in e.prototype) r[s] || (i[s] = e.prototype[s]); var n = i._resetLayout; i._resetLayout = function() { this.packer = this.packer || new e.Packer, this.shiftPacker = this.shiftPacker || new e.Packer, n.apply(this, arguments) }; var a = i._getItemLayoutPosition; i._getItemLayoutPosition = function(t) { return t.rect = t.rect || new e.Rect, a.call(this, t) }; var u = i.needsResizeLayout; i.needsResizeLayout = function() { return this._getOption("horizontal") ? this.needsVerticalResizeLayout() : u.call(this) }; var p = i._getOption; return i._getOption = function(t) { return "horizontal" == t ? void 0 !== this.options.isHorizontal ? this.options.isHorizontal : this.options.horizontal : p.apply(this.isotope, arguments) }, o }); ! function(t, e) { "use strict"; "function" == typeof define && define.amd ? define(["ev-emitter/ev-emitter"], function(i) { return e(t, i) }) : "object" == typeof module && module.exports ? module.exports = e(t, require("ev-emitter")) : t.imagesLoaded = e(t, t.EvEmitter) }("undefined" != typeof window ? window : this, function(t, e) { "use strict"; function i(t, e) { for (var i in e) t[i] = e[i]; return t } function o(t) { if (Array.isArray(t)) return t; var e = "object" == typeof t && "number" == typeof t.length; return e ? d.call(t) : [t] } function r(t, e, n) { if (!(this instanceof r)) return new r(t, e, n); var s = t; return "string" == typeof t && (s = document.querySelectorAll(t)), s ? (this.elements = o(s), this.options = i({}, this.options), "function" == typeof e ? n = e : i(this.options, e), n && this.on("always", n), this.getImages(), h && (this.jqDeferred = new h.Deferred), void setTimeout(this.check.bind(this))) : void a.error("Bad element for imagesLoaded " + (s || t)) } function n(t) { this.img = t } function s(t, e) { this.url = t, this.element = e, this.img = new Image } var h = t.jQuery, a = t.console, d = Array.prototype.slice; r.prototype = Object.create(e.prototype), r.prototype.options = {}, r.prototype.getImages = function() { this.images = [], this.elements.forEach(this.addElementImages, this) }, r.prototype.addElementImages = function(t) { "IMG" == t.nodeName && this.addImage(t), this.options.background === !0 && this.addElementBackgroundImages(t); var e = t.nodeType; if (e && m[e]) { for (var i = t.querySelectorAll("img"), o = 0; o < i.length; o++) { var r = i[o]; this.addImage(r) } if ("string" == typeof this.options.background) { var n = t.querySelectorAll(this.options.background); for (o = 0; o < n.length; o++) { var s = n[o]; this.addElementBackgroundImages(s) } } } }; var m = { 1: !0, 9: !0, 11: !0 }; return r.prototype.addElementBackgroundImages = function(t) { var e = getComputedStyle(t); if (e) for (var i = /url\((['"])?(.*?)\1\)/gi, o = i.exec(e.backgroundImage); null !== o;) { var r = o && o[2]; r && this.addBackground(r, t), o = i.exec(e.backgroundImage) } }, r.prototype.addImage = function(t) { var e = new n(t); this.images.push(e) }, r.prototype.addBackground = function(t, e) { var i = new s(t, e); this.images.push(i) }, r.prototype.check = function() { function t(t, i, o) { setTimeout(function() { e.progress(t, i, o) }) } var e = this; return this.progressedCount = 0, this.hasAnyBroken = !1, this.images.length ? void this.images.forEach(function(e) { e.once("progress", t), e.check() }) : void this.complete() }, r.prototype.progress = function(t, e, i) { this.progressedCount++, this.hasAnyBroken = this.hasAnyBroken || !t.isLoaded, this.emitEvent("progress", [this, t, e]), this.jqDeferred && this.jqDeferred.notify && this.jqDeferred.notify(this, t), this.progressedCount == this.images.length && this.complete(), this.options.debug && a && a.log("progress: " + i, t, e) }, r.prototype.complete = function() { var t = this.hasAnyBroken ? "fail" : "done"; if (this.isComplete = !0, this.emitEvent(t, [this]), this.emitEvent("always", [this]), this.jqDeferred) { var e = this.hasAnyBroken ? "reject" : "resolve"; this.jqDeferred[e](this) } }, n.prototype = Object.create(e.prototype), n.prototype.check = function() { var t = this.getIsImageComplete(); return t ? void this.confirm(0 !== this.img.naturalWidth, "naturalWidth") : (this.proxyImage = new Image, this.proxyImage.addEventListener("load", this), this.proxyImage.addEventListener("error", this), this.img.addEventListener("load", this), this.img.addEventListener("error", this), void(this.proxyImage.src = this.img.src)) }, n.prototype.getIsImageComplete = function() { return this.img.complete && this.img.naturalWidth }, n.prototype.confirm = function(t, e) { this.isLoaded = t, this.emitEvent("progress", [this, this.img, e]) }, n.prototype.handleEvent = function(t) { var e = "on" + t.type; this[e] && this[e](t) }, n.prototype.onload = function() { this.confirm(!0, "onload"), this.unbindEvents() }, n.prototype.onerror = function() { this.confirm(!1, "onerror"), this.unbindEvents() }, n.prototype.unbindEvents = function() { this.proxyImage.removeEventListener("load", this), this.proxyImage.removeEventListener("error", this), this.img.removeEventListener("load", this), this.img.removeEventListener("error", this) }, s.prototype = Object.create(n.prototype), s.prototype.check = function() { this.img.addEventListener("load", this), this.img.addEventListener("error", this), this.img.src = this.url; var t = this.getIsImageComplete(); t && (this.confirm(0 !== this.img.naturalWidth, "naturalWidth"), this.unbindEvents()) }, s.prototype.unbindEvents = function() { this.img.removeEventListener("load", this), this.img.removeEventListener("error", this) }, s.prototype.confirm = function(t, e) { this.isLoaded = t, this.emitEvent("progress", [this, this.element, e]) }, r.makeJQueryPlugin = function(e) { e = e || t.jQuery, e && (h = e, h.fn.imagesLoaded = function(t, e) { var i = new r(this, t, e); return i.jqDeferred.promise(h(this)) }) }, r.makeJQueryPlugin(), r }); ! function() { window.FizzyDocs = {}, window.filterBind = function(n, t, i, e) { n.addEventListener(t, function(n) { matchesSelector(n.target, i) && e(n) }) } }(); FizzyDocs["commercial-license-agreement"] = function(e) { "use strict"; function t(e) { var t = o.querySelector(".is-selected"); t && t.classList.remove("is-selected"), e.classList.add("is-selected"); var i = e.getAttribute("data-license-option"), n = r[i]; l.forEach(function(e) { e.element.textContent = n[e.property] }) } var r = { developer: { title: "Developer", "for-official": "one (1) Licensed Developer", "for-plain": "one individual Developer" }, team: { title: "Team", "for-official": "up to eight (8) Licensed Developer(s)", "for-plain": "up to 8 Developers" }, organization: { title: "Organization", "for-official": "an unlimited number of Licensed Developer(s)", "for-plain": "an unlimited number of Developers" } }, o = e.querySelector(".button-group"), i = e.querySelector("h2"), n = i.cloneNode(!0); n.style.borderTop = "none", n.style.marginTop = 0, n.id = "", n.innerHTML = n.innerHTML.replace("Commercial License", 'Commercial <span data-license-property="title"></span> License'), i.textContent = "", o.parentNode.insertBefore(n, o.nextSibling); for (var l = [], a = e.querySelectorAll("[data-license-property]"), c = 0, s = a.length; c < s; c++) { var p = a[c], u = { property: p.getAttribute("data-license-property"), element: p }; l.push(u) } t(o.querySelector(".button--developer")), filterBind(o, "click", ".button", function(e) { t(e.target) }) }; ! function() { var t = 0; FizzyDocs["gh-button"] = function(n) { function e(t) { return t.toString().replace(/(\d)(?=(\d{3})+$)/g, "$1,") } var a = n.href.split("/"), r = a[3], c = a[4], o = n.querySelector(".gh-button__stat__text"); t++; var u = "ghButtonCallback" + t; window[u] = function(t) { var n = e(t.data.stargazers_count); o.textContent = n }; var i = document.createElement("script"); i.src = "https://api.github.com/repos/" + r + "/" + c + "?callback=" + u, document.head.appendChild(i) } }(); FizzyDocs["shirt-promo"] = function(e) { var t = new Date(2017, 9, 6), o = Math.round((t - new Date) / 864e5), r = e.querySelector(".shirt-promo__title"); r.textContent += ". Only on sale for " + o + " more days." }; ! function(o) { "use strict"; o.IsotopeDocs = {} }(window); ! function(e) { var r = "object" == typeof window && window || "object" == typeof self && self; "undefined" != typeof exports ? e(exports) : r && (r.hljs = e({}), "function" == typeof define && define.amd && define([], function() { return r.hljs })) }(function(e) { function r(e) { return e.replace(/&/gm, "&amp;").replace(/</gm, "&lt;").replace(/>/gm, "&gt;") } function t(e) { return e.nodeName.toLowerCase() } function n(e, r) { var t = e && e.exec(r); return t && 0 == t.index } function a(e) { return /^(no-?highlight|plain|text)$/i.test(e) } function c(e) { var r, t, n, c = e.className + " "; if (c += e.parentNode ? e.parentNode.className : "", t = /\blang(?:uage)?-([\w-]+)\b/i.exec(c)) return E(t[1]) ? t[1] : "no-highlight"; for (c = c.split(/\s+/), r = 0, n = c.length; n > r; r++) if (E(c[r]) || a(c[r])) return c[r] } function i(e, r) { var t, n = {}; for (t in e) n[t] = e[t]; if (r) for (t in r) n[t] = r[t]; return n } function o(e) { var r = []; return function n(e, a) { for (var c = e.firstChild; c; c = c.nextSibling) 3 == c.nodeType ? a += c.nodeValue.length : 1 == c.nodeType && (r.push({ event: "start", offset: a, node: c }), a = n(c, a), t(c).match(/br|hr|img|input/) || r.push({ event: "stop", offset: a, node: c })); return a }(e, 0), r } function s(e, n, a) { function c() { return e.length && n.length ? e[0].offset != n[0].offset ? e[0].offset < n[0].offset ? e : n : "start" == n[0].event ? e : n : e.length ? e : n } function i(e) { function n(e) { return " " + e.nodeName + '="' + r(e.value) + '"' } l += "<" + t(e) + Array.prototype.map.call(e.attributes, n).join("") + ">" } function o(e) { l += "</" + t(e) + ">" } function s(e) { ("start" == e.event ? i : o)(e.node) } for (var u = 0, l = "", f = []; e.length || n.length;) { var b = c(); if (l += r(a.substr(u, b[0].offset - u)), u = b[0].offset, b == e) { f.reverse().forEach(o); do s(b.splice(0, 1)[0]), b = c(); while (b == e && b.length && b[0].offset == u); f.reverse().forEach(i) } else "start" == b[0].event ? f.push(b[0].node) : f.pop(), s(b.splice(0, 1)[0]) } return l + r(a.substr(u)) } function u(e) { function r(e) { return e && e.source || e } function t(t, n) { return new RegExp(r(t), "m" + (e.cI ? "i" : "") + (n ? "g" : "")) } function n(a, c) { if (!a.compiled) { if (a.compiled = !0, a.k = a.k || a.bK, a.k) { var o = {}, s = function(r, t) { e.cI && (t = t.toLowerCase()), t.split(" ").forEach(function(e) { var t = e.split("|"); o[t[0]] = [r, t[1] ? Number(t[1]) : 1] }) }; "string" == typeof a.k ? s("keyword", a.k) : Object.keys(a.k).forEach(function(e) { s(e, a.k[e]) }), a.k = o } a.lR = t(a.l || /\w+/, !0), c && (a.bK && (a.b = "\\b(" + a.bK.split(" ").join("|") + ")\\b"), a.b || (a.b = /\B|\b/), a.bR = t(a.b), a.e || a.eW || (a.e = /\B|\b/), a.e && (a.eR = t(a.e)), a.tE = r(a.e) || "", a.eW && c.tE && (a.tE += (a.e ? "|" : "") + c.tE)), a.i && (a.iR = t(a.i)), void 0 === a.r && (a.r = 1), a.c || (a.c = []); var u = []; a.c.forEach(function(e) { e.v ? e.v.forEach(function(r) { u.push(i(e, r)) }) : u.push("self" == e ? a : e) }), a.c = u, a.c.forEach(function(e) { n(e, a) }), a.starts && n(a.starts, c); var l = a.c.map(function(e) { return e.bK ? "\\.?(" + e.b + ")\\.?" : e.b }).concat([a.tE, a.i]).map(r).filter(Boolean); a.t = l.length ? t(l.join("|"), !0) : { exec: function() { return null } } } } n(e) } function l(e, t, a, c) { function i(e, r) { for (var t = 0; t < r.c.length; t++) if (n(r.c[t].bR, e)) return r.c[t] } function o(e, r) { if (n(e.eR, r)) { for (; e.endsParent && e.parent;) e = e.parent; return e } return e.eW ? o(e.parent, r) : void 0 } function s(e, r) { return !a && n(r.iR, e) } function b(e, r) { var t = N.cI ? r[0].toLowerCase() : r[0]; return e.k.hasOwnProperty(t) && e.k[t] } function g(e, r, t, n) { var a = n ? "" : w.classPrefix, c = '<span class="' + a, i = t ? "" : "</span>"; return c += e + '">', c + r + i } function p() { if (!C.k) return r(k); var e = "", t = 0; C.lR.lastIndex = 0; for (var n = C.lR.exec(k); n;) { e += r(k.substr(t, n.index - t)); var a = b(C, n); a ? (A += a[1], e += g(a[0], r(n[0]))) : e += r(n[0]), t = C.lR.lastIndex, n = C.lR.exec(k) } return e + r(k.substr(t)) } function d() { var e = "string" == typeof C.sL; if (e && !y[C.sL]) return r(k); var t = e ? l(C.sL, k, !0, R[C.sL]) : f(k, C.sL.length ? C.sL : void 0); return C.r > 0 && (A += t.r), e && (R[C.sL] = t.top), g(t.language, t.value, !1, !0) } function h() { x += void 0 !== C.sL ? d() : p(), k = "" } function m(e, r) { x += e.cN ? g(e.cN, "", !0) : "", C = Object.create(e, { parent: { value: C } }) } function v(e, r) { if (k += e, void 0 === r) return h(), 0; var t = i(r, C); if (t) return t.skip ? k += r : (t.eB && (k += r), h(), t.rB || t.eB || (k = r)), m(t, r), t.rB ? 0 : r.length; var n = o(C, r); if (n) { var a = C; a.skip ? k += r : (a.rE || a.eE || (k += r), h(), a.eE && (k = r)); do C.cN && (x += "</span>"), C.skip || (A += C.r), C = C.parent; while (C != n.parent); return n.starts && m(n.starts, ""), a.rE ? 0 : r.length } if (s(r, C)) throw new Error('Illegal lexeme "' + r + '" for mode "' + (C.cN || "<unnamed>") + '"'); return k += r, r.length || 1 } var N = E(e); if (!N) throw new Error('Unknown language: "' + e + '"'); u(N); var M, C = c || N, R = {}, x = ""; for (M = C; M != N; M = M.parent) M.cN && (x = g(M.cN, "", !0) + x); var k = "", A = 0; try { for (var S, B, L = 0; C.t.lastIndex = L, S = C.t.exec(t), S;) B = v(t.substr(L, S.index - L), S[0]), L = S.index + B; for (v(t.substr(L)), M = C; M.parent; M = M.parent) M.cN && (x += "</span>"); return { r: A, value: x, language: e, top: C } } catch (I) { if (-1 != I.message.indexOf("Illegal")) return { r: 0, value: r(t) }; throw I } } function f(e, t) { t = t || w.languages || Object.keys(y); var n = { r: 0, value: r(e) }, a = n; return t.filter(E).forEach(function(r) { var t = l(r, e, !1); t.language = r, t.r > a.r && (a = t), t.r > n.r && (a = n, n = t) }), a.language && (n.second_best = a), n } function b(e) { return w.tabReplace && (e = e.replace(/^((<[^>]+>|\t)+)/gm, function(e, r) { return r.replace(/\t/g, w.tabReplace) })), w.useBR && (e = e.replace(/\n/g, "<br>")), e } function g(e, r, t) { var n = r ? M[r] : t, a = [e.trim()]; return e.match(/\bhljs\b/) || a.push("hljs"), -1 === e.indexOf(n) && a.push(n), a.join(" ").trim() } function p(e) { var r = c(e); if (!a(r)) { var t; w.useBR ? (t = document.createElementNS("http://www.w3.org/1999/xhtml", "div"), t.innerHTML = e.innerHTML.replace(/\n/g, "").replace(/<br[ \/]*>/g, "\n")) : t = e; var n = t.textContent, i = r ? l(r, n, !0) : f(n), u = o(t); if (u.length) { var p = document.createElementNS("http://www.w3.org/1999/xhtml", "div"); p.innerHTML = i.value, i.value = s(u, o(p), n) } i.value = b(i.value), e.innerHTML = i.value, e.className = g(e.className, r, i.language), e.result = { language: i.language, re: i.r }, i.second_best && (e.second_best = { language: i.second_best.language, re: i.second_best.r }) } } function d(e) { w = i(w, e) } function h() { if (!h.called) { h.called = !0; var e = document.querySelectorAll("pre code"); Array.prototype.forEach.call(e, p) } } function m() { addEventListener("DOMContentLoaded", h, !1), addEventListener("load", h, !1) } function v(r, t) { var n = y[r] = t(e); n.aliases && n.aliases.forEach(function(e) { M[e] = r }) } function N() { return Object.keys(y) } function E(e) { return e = (e || "").toLowerCase(), y[e] || y[M[e]] } var w = { classPrefix: "hljs-", tabReplace: null, useBR: !1, languages: void 0 }, y = {}, M = {}; return e.highlight = l, e.highlightAuto = f, e.fixMarkup = b, e.highlightBlock = p, e.configure = d, e.initHighlighting = h, e.initHighlightingOnLoad = m, e.registerLanguage = v, e.listLanguages = N, e.getLanguage = E, e.inherit = i, e.IR = "[a-zA-Z]\\w*", e.UIR = "[a-zA-Z_]\\w*", e.NR = "\\b\\d+(\\.\\d+)?", e.CNR = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)", e.BNR = "\\b(0b[01]+)", e.RSR = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", e.BE = { b: "\\\\[\\s\\S]", r: 0 }, e.ASM = { cN: "string", b: "'", e: "'", i: "\\n", c: [e.BE] }, e.QSM = { cN: "string", b: '"', e: '"', i: "\\n", c: [e.BE] }, e.PWM = { b: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\b/ }, e.C = function(r, t, n) { var a = e.inherit({ cN: "comment", b: r, e: t, c: [] }, n || {}); return a.c.push(e.PWM), a.c.push({ cN: "doctag", b: "(?:TODO|FIXME|NOTE|BUG|XXX):", r: 0 }), a }, e.CLCM = e.C("//", "$"), e.CBCM = e.C("/\\*", "\\*/"), e.HCM = e.C("#", "$"), e.NM = { cN: "number", b: e.NR, r: 0 }, e.CNM = { cN: "number", b: e.CNR, r: 0 }, e.BNM = { cN: "number", b: e.BNR, r: 0 }, e.CSSNM = { cN: "number", b: e.NR + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?", r: 0 }, e.RM = { cN: "regexp", b: /\//, e: /\/[gimuy]*/, i: /\n/, c: [e.BE, { b: /\[/, e: /\]/, r: 0, c: [e.BE] }] }, e.TM = { cN: "title", b: e.IR, r: 0 }, e.UTM = { cN: "title", b: e.UIR, r: 0 }, e.METHOD_GUARD = { b: "\\.\\s*" + e.UIR, r: 0 }, e }), hljs.registerLanguage("css", function(e) { var r = "[a-zA-Z-][a-zA-Z0-9_-]*", t = { b: /[A-Z\_\.\-]+\s*:/, rB: !0, e: ";", eW: !0, c: [{ cN: "attribute", b: /\S/, e: ":", eE: !0, starts: { eW: !0, eE: !0, c: [{ b: /[\w-]+\(/, rB: !0, c: [{ cN: "built_in", b: /[\w-]+/ }, { b: /\(/, e: /\)/, c: [e.ASM, e.QSM] }] }, e.CSSNM, e.QSM, e.ASM, e.CBCM, { cN: "number", b: "#[0-9A-Fa-f]+" }, { cN: "meta", b: "!important" }] } }] }; return { cI: !0, i: /[=\/|'\$]/, c: [e.CBCM, { cN: "selector-id", b: /#[A-Za-z0-9_-]+/ }, { cN: "selector-class", b: /\.[A-Za-z0-9_-]+/ }, { cN: "selector-attr", b: /\[/, e: /\]/, i: "$" }, { cN: "selector-pseudo", b: /:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/ }, { b: "@(font-face|page)", l: "[a-z-]+", k: "font-face page" }, { b: "@", e: "[{;]", i: /:/, c: [{ cN: "keyword", b: /\w+/ }, { b: /\s/, eW: !0, eE: !0, r: 0, c: [e.ASM, e.QSM, e.CSSNM] }] }, { cN: "selector-tag", b: r, r: 0 }, { b: "{", e: "}", i: /\S/, c: [e.CBCM, t] }] } }), hljs.registerLanguage("javascript", function(e) { return { aliases: ["js", "jsx"], k: { keyword: "in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as", literal: "true false null undefined NaN Infinity", built_in: "eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise" }, c: [{ cN: "meta", r: 10, b: /^\s*['"]use (strict|asm)['"]/ }, { cN: "meta", b: /^#!/, e: /$/ }, e.ASM, e.QSM, { cN: "string", b: "`", e: "`", c: [e.BE, { cN: "subst", b: "\\$\\{", e: "\\}" }] }, e.CLCM, e.CBCM, { cN: "number", v: [{ b: "\\b(0[bB][01]+)" }, { b: "\\b(0[oO][0-7]+)" }, { b: e.CNR }], r: 0 }, { b: "(" + e.RSR + "|\\b(case|return|throw)\\b)\\s*", k: "return throw case", c: [e.CLCM, e.CBCM, e.RM, { b: /</, e: /(\/\w+|\w+\/)>/, sL: "xml", c: [{ b: /<\w+\s*\/>/, skip: !0 }, { b: /<\w+/, e: /(\/\w+|\w+\/)>/, skip: !0, c: ["self"] }] }], r: 0 }, { cN: "function", bK: "function", e: /\{/, eE: !0, c: [e.inherit(e.TM, { b: /[A-Za-z$_][0-9A-Za-z$_]*/ }), { cN: "params", b: /\(/, e: /\)/, eB: !0, eE: !0, c: [e.CLCM, e.CBCM] }], i: /\[|%/ }, { b: /\$[(.]/ }, e.METHOD_GUARD, { cN: "class", bK: "class", e: /[{;=]/, eE: !0, i: /[:"\[\]]/, c: [{ bK: "extends" }, e.UTM] }, { bK: "constructor", e: /\{/, eE: !0 }], i: /#(?!!)/ } }), hljs.registerLanguage("json", function(e) { var r = { literal: "true false null" }, t = [e.QSM, e.CNM], n = { e: ",", eW: !0, eE: !0, c: t, k: r }, a = { b: "{", e: "}", c: [{ cN: "attr", b: /"/, e: /"/, c: [e.BE], i: "\\n" }, e.inherit(n, { b: /:/ })], i: "\\S" }, c = { b: "\\[", e: "\\]", c: [e.inherit(n)], i: "\\S" }; return t.splice(t.length, 0, a, c), { c: t, k: r, i: "\\S" } }), hljs.registerLanguage("xml", function(e) { var r = "[A-Za-z0-9\\._:-]+", t = { eW: !0, i: /</, r: 0, c: [{ cN: "attr", b: r, r: 0 }, { b: /=\s*/, r: 0, c: [{ cN: "string", endsParent: !0, v: [{ b: /"/, e: /"/ }, { b: /'/, e: /'/ }, { b: /[^\s"'=<>`]+/ }] }] }] }; return { aliases: ["html", "xhtml", "rss", "atom", "xsl", "plist"], cI: !0, c: [{ cN: "meta", b: "<!DOCTYPE", e: ">", r: 10, c: [{ b: "\\[", e: "\\]" }] }, e.C("<!--", "-->", { r: 10 }), { b: "<\\!\\[CDATA\\[", e: "\\]\\]>", r: 10 }, { b: /<\?(php)?/, e: /\?>/, sL: "php", c: [{ b: "/\\*", e: "\\*/", skip: !0 }] }, { cN: "tag", b: "<style(?=\\s|>|$)", e: ">", k: { name: "style" }, c: [t], starts: { e: "</style>", rE: !0, sL: ["css", "xml"] } }, { cN: "tag", b: "<script(?=\\s|>|$)", e: ">", k: { name: "script" }, c: [t], starts: { e: "</script>", rE: !0, sL: ["actionscript", "javascript", "handlebars", "xml"] } }, { cN: "meta", v: [{ b: /<\?xml/, e: /\?>/, r: 10 }, { b: /<\?\w+/, e: /\?>/ }] }, { cN: "tag", b: "</?", e: "/?>", c: [{ cN: "name", b: /[^\/><\s]+/, r: 0 }, t] }] } }); ! function() { "use strict"; IsotopeDocs.getItemElement = function() { var t = document.createElement("div"), i = Math.random(), e = Math.random(), n = i > .8 ? "grid-item--width3" : i > .6 ? "grid-item--width2" : "", r = e > .8 ? "grid-item--height3" : e > .5 ? "grid-item--height2" : ""; return t.className = "grid-item " + n + " " + r, t }, hljs.configure({ classPrefix: "" }), $.fn.displayIsotopeCode = function(t, i, e) { e = e || 0, i = "string" == typeof i && i.indexOf("function") === -1 ? "'" + i + "'" : i; var n = "$grid.isotope({ " + t + ": " + i + " })", r = n.match(/\n/g); r = r && r.length || 0; for (var o = 0; r + o < e; o++) n += "\n"; n = hljs.highlight("js", n).value, this.html(n) } }(); IsotopeDocs["gh-button"] = function(t) { function e(t) { return t.toString().replace(/(\d)(?=(\d{3})+$)/g, "$1,") } var o = "metafizzy", a = "isotope", n = "ghButtonCallback" + Math.floor(1e4 * Math.random()); window[n] = function(o) { var a = e(o.data.stargazers_count); t.querySelector(".gh-button__stat__text").textContent = a }; var r = document.createElement("script"); r.src = "https://api.github.com/repos/" + o + "/" + a + "?callback=" + n, document.head.appendChild(r) }; IsotopeDocs["hero-demo"] = function(t) { "use strict"; var e = $(t), n = e.find(".grid").isotope({ itemSelector: ".element-item", layoutMode: "fitRows", transitionDuration: "0.6s", getSortData: { name: ".name", symbol: ".symbol", number: ".number parseInt", category: "[data-category]", weight: function(t) { var e = $(t).find(".weight").text(); return parseFloat(e.replace(/[\(\)]/g, "")) } } }), r = { numberGreaterThan50: function() { var t = $(this).find(".number").text(); return parseInt(t, 10) > 50 }, ium: function() { var t = $(this).find(".name").text(); return t.match(/ium$/) } }, i = { numberGreaterThan50: "function() {\n var number = $(this).find('.number').text();\n return parseInt( number, 10 ) > 50;\n}", ium: "function() {\n var name = $(this).find('.name').text();\n return name.match( /ium$/ );\n}" }, o = e.find(".code-display code"); e.find(".sort-by").on("click", "button", function() { var t = $(this).attr("data-sort-by"); n.isotope({ sortBy: t }), o.displayIsotopeCode("sortBy", t, 5) }), e.find(".filters").on("click", "button", function() { var t = $(this).attr("data-filter"), e = r[t] || t, a = i[t] || t; n.isotope({ filter: e }), o.displayIsotopeCode("filter", a, 5) }) }; IsotopeDocs["in-use-grid"] = function(e) { "use strict"; var i = $(e); i.find(".in-use-grid__item").hide(), i.isotope({ itemSelector: "none", masonry: { columnWidth: ".grid-sizer", gutter: ".gutter-sizer" } }), i.isotope("option", { itemSelector: ".in-use-grid__item" }), i.imagesLoaded().progress(function(e, t) { var o = $(t.img).parents(".in-use-grid__item"); o.show(), i.isotope("appended", o) }) }; IsotopeDocs.notification = function(t) { "use strict"; function n() { var t = new Date, n = e(t.getMinutes()), o = e(t.getSeconds()); return [t.getHours(), n, o].join(":") } function e(t) { return t < 10 ? "0" + t : t } function o() { t.style[c] = "opacity 1.0s", t.style.opacity = "0" } var i, s = document.documentElement, c = "string" == typeof s.style.transition ? "transition" : "WebkitTransition"; ID.notify = function(e) { t.textContent = e + " at " + n(), t.style[c] = "none", t.style.display = "block", t.style.opacity = "1", clearTimeout(i), i = setTimeout(o, 1e3) } }; ! function() { "use strict"; function t(t) { this.element = t, this.originalY = this.element.getBoundingClientRect().top + window.pageYOffset, window.addEventListener("scroll", this), this.isFixed = !1, this.onscroll() } function i(t, i, e) { var n = t.prototype[i], o = i + "Timeout"; t.prototype[i] = function() { if (!this[o]) { n.apply(this, arguments); var t = this; this[o] = setTimeout(function() { n.apply(t, arguments), delete t[o] }, e || 100) } } } IsotopeDocs["page-nav"] = function(i) { var e = getSize(i).outerHeight; window.innerWidth < 768 || e >= window.innerHeight || new t(i) }, t.prototype.handleEvent = function(t) { var i = "on" + t.type; this[i] && this[i](t) }, t.prototype.onscroll = function() { var t = window.pageYOffset >= this.originalY; t !== this.isFixed && (this.element.classList.toggle("is-fixed"), this.isFixed = t) }, i(t, "onscroll", 50) }(); IsotopeDocs["refactor-shirt"] = function(t) { "use strict"; var e = new Date(2016, 1, 10), r = Math.round((e - new Date) / 864e5); t.querySelector(".refactor-shirt__title").textContent = "Refactor shirts. Only on sale for " + r + " more days." }; IsotopeDocs["animate-item-size"] = function(i) { "use strict"; var t = $(i), e = t.find(".grid").isotope({ masonry: { columnWidth: 60 } }); e.on("click", ".animate-item-size-item", function() { $(this).toggleClass("is-expanded"), e.isotope("layout") }) }; IsotopeDocs["animate-item-size-responsive"] = function(t) { "use strict"; function i(t) { var i = getSize(t); t.style[o] = "none", t.style.width = i.width + "px", t.style.height = i.height + "px" } function e(t) { if (o) { var i = function() { t.style.width = "", t.style.height = "", t.removeEventListener(r, i, !1) }; t.addEventListener(r, i, !1) } } function n(t, i) { var e = getSize(i); t.style.width = e.width + "px", t.style.height = e.height + "px" } var s = document.documentElement.style, o = "string" == typeof s.transition ? "transition" : "WebkitTransition", r = { WebkitTransition: "webkitTransitionEnd", transition: "transitionend" }[o], a = $(t), d = a.find(".grid").isotope({ itemSelector: ".animate-item-size-item", percentPosition: !0, masonry: { columnWidth: ".grid-sizer" } }); d.on("click", ".animate-item-size-item__content", function() { var t = this; i(t); var s = t.parentNode; s.classList.toggle("is-expanded"); t.offsetWidth; t.style[o] = "", e(t), n(t, s), d.isotope("layout") }) }; IsotopeDocs.appended = function(e) { "use strict"; var o = $(e), t = o.find(".grid").isotope({ masonry: { columnWidth: 50 } }); o.find(".append-button").on("click", function() { var e = $([IsotopeDocs.getItemElement(), IsotopeDocs.getItemElement(), IsotopeDocs.getItemElement()]); t.append(e).isotope("appended", e) }) }; IsotopeDocs["arrange-complete"] = function(t) { "use strict"; var o = $(t), n = o.find(".grid").isotope({ masonry: { columnWidth: 50 } }); n.on("arrangeComplete", function(t, o) { ID.notify("Isotope arrange completed on " + o.length + " items") }), o.find(".button-group").on("click", "button", function() { var t = $(this).attr("data-filter"); n.isotope({ filter: t }) }) }; IsotopeDocs["combination-filters"] = function(t) { "use strict"; function o(t) { var o = ""; for (var i in t) o += t[i]; return o } var i = $(t), r = i.find(".grid").isotope({ itemSelector: ".color-shape", columnWidth: 80, transitionDuration: "0.6s" }), n = i.find(".code-display code"), e = {}; i.on("click", ".button", function() { var t = $(this), i = t.parents(".button-group"), a = i.attr("data-filter-group"); e[a] = t.attr("data-filter"); var s = o(e); r.isotope({ filter: s }), n.displayIsotopeCode("filter", s) }) }; IsotopeDocs.destroy = function(o) { "use strict"; var t = $(o), i = { masonry: { columnWidth: 50 } }, n = t.find(".grid").isotope(i), s = !0; t.find(".toggle-button").on("click", function() { s ? n.isotope("destroy") : n.isotope(i), s = !s }) }; IsotopeDocs["filtering-demo"] = function(t) { "use strict"; var n = $(t), e = n.find(".grid").isotope({ itemSelector: ".element-item", layoutMode: "fitRows", transitionDuration: "0.6s" }), i = { numberGreaterThan50: function() { var t = $(this).find(".number").text(); return parseInt(t, 10) > 50 }, ium: function() { var t = $(this).find(".name").text(); return t.match(/ium$/) } }, r = { numberGreaterThan50: "function() {\n var number = $(this).find('.number').text();\n return parseInt( number, 10 ) > 50;\n}", ium: "function() {\n var name = $(this).find('.name').text();\n return name.match( /ium$/ );\n}" }, o = n.find(".code-display code"); n.find(".filter-button-group").on("click", "button", function() { var t = $(this).attr("data-filter"), n = i[t] || t, a = r[t] || t; e.isotope({ filter: n }), o.displayIsotopeCode("filter", a) }) }; IsotopeDocs["imagesloaded-callback"] = function(e) { "use strict"; var i = $(e).imagesLoaded(function() { i.isotope({ itemSelector: ".grid-image-item", percentPosition: !0, masonry: { columnWidth: ".grid-sizer" } }) }) }; IsotopeDocs["imagesloaded-progress"] = function(o) { "use strict"; var e = $(o).isotope({ itemSelector: ".grid-image-item", percentPosition: !0, masonry: { columnWidth: ".grid-sizer" } }); e.imagesLoaded().progress(function() { e.isotope("layout") }) }; IsotopeDocs.insert = function(t) { "use strict"; var n = $(t), r = n.find(".grid").isotope({ masonry: { columnWidth: 50 }, filter: function() { var t = $(this).find(".number").text(); return parseInt(t, 10) % 2 }, sortBy: "number", getSortData: { number: ".number parseInt" } }); n.find(".insert-button").on("click", function() { for (var t = [], n = 0; n < 3; n++) { var e = IsotopeDocs.getItemElement(), o = Math.floor(100 * Math.random()); $(e).append('<p class="number">' + o + "</p>"), t.push(e) } r.isotope("insert", t) }) }; IsotopeDocs["layout-complete"] = function(o) { "use strict"; var t = $(o), i = t.find(".grid").isotope({ masonry: { columnWidth: 50 } }); i.on("layoutComplete", function(o, t) { ID.notify("Isotope layout completed on " + t.length + " items") }), i.on("click", ".grid-item", function() { $(this).toggleClass("grid-item--gigante"), i.isotope("layout") }) }; IsotopeDocs["layout-demo"] = function(o) { "use strict"; var i = $(o), t = i.find(".grid").isotope({ masonry: { columnWidth: 50 } }); t.on("click", ".grid-item", function() { $(this).toggleClass("grid-item--gigante"), t.isotope("layout") }) }; IsotopeDocs["layout-modes-demo"] = function(o) { "use strict"; var t = $(window), i = $(o), a = i.find(".grid").isotope({ itemSelector: ".grid-splash-item", layoutMode: "masonry", transitionDuration: "0.6s", masonry: { columnWidth: 110 }, cellsByRow: { columnWidth: 220, rowHeight: 220 }, masonryHorizontal: { rowHeight: 110 }, cellsByColumn: { columnWidth: 220, rowHeight: 220 } }), e = !1, d = i.find(".code-display code"); i.find(".button-group").on("click", "button", function() { var o = $(this), i = !!o.attr("data-is-horizontal"); if (e != i) { var n = i ? { height: .7 * t.height() } : { width: "auto" }; a.css(n), e = i } var s = o.attr("data-layout-mode"); a.isotope({ layoutMode: s }), d.displayIsotopeCode("layoutMode", s) }) }; IsotopeDocs["multiple-sort-by"] = function(t) { "use strict"; function o(t) { return t.split(",") } var r = $(t), i = r.find(".button-group"), e = r.find(".grid").isotope({ layoutMode: "fitRows", itemSelector: ".grid-multi-item", getSortData: { color: "[data-color]", number: ".number parseInt" }, sortBy: ["color", "number"] }); i.on("click", "button", function() { e.isotope({ sortBy: o(this.getAttribute("data-sort-by")) }) }) }; IsotopeDocs.prepended = function(e) { "use strict"; var o = $(e), t = o.find(".grid").isotope({ masonry: { columnWidth: 50 } }); o.find(".prepend-button").on("click", function() { var e = $([IsotopeDocs.getItemElement(), IsotopeDocs.getItemElement(), IsotopeDocs.getItemElement()]); t.prepend(e).isotope("prepended", e) }) }; IsotopeDocs.remove = function(o) { "use strict"; var i = $(o), t = i.find(".grid").isotope({ masonry: { columnWidth: 50 } }); t.on("click", ".grid-item", function() { t.isotope("remove", this).isotope("layout") }) }; IsotopeDocs["remove-complete"] = function(o) { "use strict"; var e = $(o), t = e.find(".grid").isotope({ masonry: { columnWidth: 50 } }); t.on("removeComplete", function(o, e) { ID.notify("Removed " + e.length + " items") }), t.on("click", ".grid-item", function() { t.isotope("remove", this).isotope("layout") }) }; IsotopeDocs.shuffle = function(o) { "use strict"; var f = $(o), i = f.find(".grid").isotope({ masonry: { columnWidth: 50 } }); f.find(".shuffle-button").on("click", function() { i.isotope("shuffle") }) }; IsotopeDocs["sorting-demo"] = function(t) { "use strict"; var o = $(t), e = o.find(".sort-by-button-group"), r = o.find(".grid").isotope({ itemSelector: ".element-item", layoutMode: "fitRows", transitionDuration: "0.6s", getSortData: { name: ".name", symbol: ".symbol", number: ".number parseInt", category: "[data-category]", weight: function(t) { var o = $(t).find(".weight").text(); return parseFloat(o.replace(/[\(\)]/g, "")) } } }), i = o.find(".code-display code"); e.on("click", "button", function() { var t = $(this).attr("data-sort-by"); r.isotope({ sortBy: t }), i.displayIsotopeCode("sortBy", t) }) }; IsotopeDocs.stagger = function(t) { "use strict"; var o = $(t), r = o.find(".grid").isotope({ layoutMode: "fitRows", stagger: 30 }); o.find(".button-group").on("click", ".button", function(t) { var o = $(t.currentTarget).attr("data-filter"); r.isotope({ filter: o }) }) }; IsotopeDocs["stamp-methods"] = function(t) { "use strict"; var o = $(t), i = o.find(".grid").isotope({ itemSelector: ".grid-item", masonry: { columnWidth: 50 } }), s = i.find(".stamp"), n = !1; o.find(".stamp-button").on("click", function() { n ? i.isotope("unstamp", s) : i.isotope("stamp", s), i.isotope("layout"), n = !n }) }; IsotopeDocs["vertical-list"] = function(t) { "use strict"; var o = $(t), e = o.find(".vertical-list").isotope({ itemSelector: "li", layoutMode: "vertical", transitionDuration: "0.6s", getSortData: { name: ".name", symbol: ".symbol", number: ".number parseInt", category: ".category", weight: function(t) { var o = $(t).find(".weight").text(); return parseFloat(o.replace(/[\(\)]/g, "")) } } }); o.find(".button-group").on("click", "button", function() { var t = $(this).attr("data-sort-by"); e.isotope({ sortBy: t }) }) }; IsotopeDocs["visible-hidden-style"] = function(t) { "use strict"; var i = $(t), o = i.find(".grid").isotope({ layoutMode: "fitRows", visibleStyle: { opacity: 1 }, hiddenStyle: { opacity: 0 } }); i.find(".button-group").on("click", ".button", function(t) { var i = $(t.currentTarget).attr("data-filter"); o.isotope({ filter: i }) }) }; ! function() { "use strict"; $("[data-js]").each(function(t, s) { var c = s.getAttribute("data-js"), e = IsotopeDocs[c] || FizzyDocs[c]; e && e(s) }), $(".js-radio-button-group").each(function(t, s) { var c = $(s); c.find(":checked").parent().addClass("is-checked"), c.on("click", "input, button", function() { c.find(".is-checked").removeClass("is-checked"); var t = $(this), s = t.hasClass("button") ? t : t.parents(".button"); s.addClass("is-checked") }) }) }();
import _extends from "@babel/runtime/helpers/extends"; import _objectSpread from "@babel/runtime/helpers/objectSpread"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf"; import _inherits from "@babel/runtime/helpers/inherits"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _pick from "lodash/pick"; import _includes from "lodash/includes"; import _reduce from "lodash/reduce"; import _isEmpty from "lodash/isEmpty"; import _invoke from "lodash/invoke"; import cx from 'classnames'; import PropTypes from 'prop-types'; import React, { isValidElement } from 'react'; import { AutoControlledComponent as Component, childrenUtils, customPropTypes, doesNodeContainClick, eventStack, getElementType, getUnhandledProps, isBrowser, useKeyOnly } from '../../lib'; import Icon from '../../elements/Icon'; import MountNode from '../../addons/MountNode'; import Portal from '../../addons/Portal'; import ModalHeader from './ModalHeader'; import ModalContent from './ModalContent'; import ModalActions from './ModalActions'; import ModalDescription from './ModalDescription'; import Ref from '../../addons/Ref'; /** * A modal displays content that temporarily blocks interactions with the main view of a site. * @see Confirm * @see Portal */ var Modal = /*#__PURE__*/ function (_Component) { _inherits(Modal, _Component); function Modal() { var _getPrototypeOf2; var _this; _classCallCheck(this, Modal); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Modal)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "getMountNode", function () { return isBrowser() ? _this.props.mountNode || document.body : null; }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleActionsOverrides", function (predefinedProps) { return { onActionClick: function onActionClick(e, actionProps) { _invoke(predefinedProps, 'onActionClick', e, actionProps); _invoke(_this.props, 'onActionClick', e, _this.props); _this.handleClose(e); } }; }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleClose", function (e) { _invoke(_this.props, 'onClose', e, _this.props); _this.trySetState({ open: false }); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleDocumentClick", function (e) { var closeOnDimmerClick = _this.props.closeOnDimmerClick; if (!closeOnDimmerClick || doesNodeContainClick(_this.ref, e)) return; _invoke(_this.props, 'onClose', e, _this.props); _this.trySetState({ open: false }); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleIconOverrides", function (predefinedProps) { return { onClick: function onClick(e) { _invoke(predefinedProps, 'onClick', e); _this.handleClose(e); } }; }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOpen", function (e) { _invoke(_this.props, 'onOpen', e, _this.props); _this.trySetState({ open: true }); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handlePortalMount", function (e) { var eventPool = _this.props.eventPool; _this.setState({ scrolling: false }); _this.setPositionAndClassNames(); eventStack.sub('click', _this.handleDocumentClick, { pool: eventPool, target: _this.dimmerRef }); _invoke(_this.props, 'onMount', e, _this.props); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handlePortalUnmount", function (e) { var eventPool = _this.props.eventPool; cancelAnimationFrame(_this.animationRequestId); eventStack.unsub('click', _this.handleDocumentClick, { pool: eventPool, target: _this.dimmerRef }); _invoke(_this.props, 'onUnmount', e, _this.props); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleRef", function (c) { return _this.ref = c; }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleDimmerRef", function (c) { return _this.dimmerRef = c; }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setDimmerNodeStyle", function () { if (_this.dimmerRef) { _this.dimmerRef.style.setProperty('display', 'flex', 'important'); } }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setPositionAndClassNames", function () { var dimmer = _this.props.dimmer; var classes; if (dimmer) { classes = 'dimmable dimmed'; if (dimmer === 'blurring') { classes += ' blurring'; } } var newState = {}; if (_this.ref) { var _this$ref$getBounding = _this.ref.getBoundingClientRect(), height = _this$ref$getBounding.height; // Leaving the old calculation here since we may need it as an older browser fallback // SEE: https://github.com/Semantic-Org/Semantic-UI/issues/6185#issuecomment-376725956 // const marginTop = -Math.round(height / 2) var marginTop = null; var scrolling = height > window.innerHeight; if (_this.state.marginTop !== marginTop) { newState.marginTop = marginTop; } if (_this.state.scrolling !== scrolling) { newState.scrolling = scrolling; } if (scrolling) classes += ' scrolling'; } if (_this.state.mountClasses !== classes) newState.mountClasses = classes; if (!_isEmpty(newState)) _this.setState(newState); _this.animationRequestId = requestAnimationFrame(_this.setPositionAndClassNames); _this.setDimmerNodeStyle(); }); _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "renderContent", function (rest) { var _this$props = _this.props, actions = _this$props.actions, basic = _this$props.basic, children = _this$props.children, className = _this$props.className, closeIcon = _this$props.closeIcon, content = _this$props.content, header = _this$props.header, mountNode = _this$props.mountNode, size = _this$props.size, style = _this$props.style; var _this$state = _this.state, marginTop = _this$state.marginTop, mountClasses = _this$state.mountClasses, scrolling = _this$state.scrolling; var classes = cx('ui', size, useKeyOnly(basic, 'basic'), useKeyOnly(scrolling, 'scrolling'), 'modal transition visible active', className); var ElementType = getElementType(Modal, _this.props); var closeIconName = closeIcon === true ? 'close' : closeIcon; var closeIconJSX = Icon.create(closeIconName, { overrideProps: _this.handleIconOverrides }); if (!childrenUtils.isNil(children)) { // TODO: remove when ref with "as" is resolved: PR #2306 return React.createElement(Ref, { innerRef: _this.handleRef }, React.createElement(ElementType, _extends({}, rest, { className: classes, style: _objectSpread({ marginTop: marginTop }, style) }), React.createElement(MountNode, { className: mountClasses, node: mountNode }), closeIconJSX, children)); } // TODO: remove when ref with "as" is resolved: PR #2306 return React.createElement(Ref, { innerRef: _this.handleRef }, React.createElement(ElementType, _extends({}, rest, { className: classes, style: _objectSpread({ marginTop: marginTop }, style) }), React.createElement(MountNode, { className: mountClasses, node: mountNode }), closeIconJSX, ModalHeader.create(header, { autoGenerateKey: false }), ModalContent.create(content, { autoGenerateKey: false }), ModalActions.create(actions, { overrideProps: _this.handleActionsOverrides }))); }); return _this; } _createClass(Modal, [{ key: "componentWillUnmount", value: function componentWillUnmount() { this.handlePortalUnmount(); } // Do not access document when server side rendering }, { key: "render", value: function render() { var open = this.state.open; var _this$props2 = this.props, centered = _this$props2.centered, closeOnDocumentClick = _this$props2.closeOnDocumentClick, dimmer = _this$props2.dimmer, eventPool = _this$props2.eventPool, trigger = _this$props2.trigger; var mountNode = this.getMountNode(); // Short circuit when server side rendering if (!isBrowser()) { return isValidElement(trigger) ? trigger : null; } var unhandled = getUnhandledProps(Modal, this.props); var portalPropNames = Portal.handledProps; var rest = _reduce(unhandled, function (acc, val, key) { if (!_includes(portalPropNames, key)) acc[key] = val; return acc; }, {}); var portalProps = _pick(unhandled, portalPropNames); // wrap dimmer modals var dimmerClasses = cx('ui', dimmer === 'inverted' && 'inverted', !centered && 'top aligned', 'page modals dimmer transition visible active'); // Heads up! // // The SUI CSS selector to prevent the modal itself from blurring requires an immediate .dimmer child: // .blurring.dimmed.dimmable>:not(.dimmer) { ... } // // The .blurring.dimmed.dimmable is the body, so that all body content inside is blurred. // We need the immediate child to be the dimmer to :not() blur the modal itself! // Otherwise, the portal div is also blurred, blurring the modal. // // We cannot them wrap the modalJSX in an actual <Dimmer /> instead, we apply the dimmer classes to the <Portal />. return React.createElement(Portal, _extends({ closeOnDocumentClick: closeOnDocumentClick }, portalProps, { trigger: trigger, eventPool: eventPool, mountNode: mountNode, open: open, onClose: this.handleClose, onMount: this.handlePortalMount, onOpen: this.handleOpen, onUnmount: this.handlePortalUnmount }), React.createElement("div", { className: dimmerClasses, ref: this.handleDimmerRef }, this.renderContent(rest))); } }]); return Modal; }(Component); _defineProperty(Modal, "defaultProps", { centered: true, dimmer: true, closeOnDimmerClick: true, closeOnDocumentClick: false, eventPool: 'Modal' }); _defineProperty(Modal, "autoControlledProps", ['open']); _defineProperty(Modal, "Header", ModalHeader); _defineProperty(Modal, "Content", ModalContent); _defineProperty(Modal, "Description", ModalDescription); _defineProperty(Modal, "Actions", ModalActions); _defineProperty(Modal, "handledProps", ["actions", "as", "basic", "centered", "children", "className", "closeIcon", "closeOnDimmerClick", "closeOnDocumentClick", "content", "defaultOpen", "dimmer", "eventPool", "header", "mountNode", "onActionClick", "onClose", "onMount", "onOpen", "onUnmount", "open", "size", "style", "trigger"]); Modal.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Shorthand for Modal.Actions. Typically an array of button shorthand. */ actions: customPropTypes.itemShorthand, /** A modal can reduce its complexity */ basic: PropTypes.bool, /** A modal can be vertically centered in the viewport */ centered: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for the close icon. Closes the modal on click. */ closeIcon: PropTypes.oneOfType([PropTypes.node, PropTypes.object, PropTypes.bool]), /** Whether or not the Modal should close when the dimmer is clicked. */ closeOnDimmerClick: PropTypes.bool, /** Whether or not the Modal should close when the document is clicked. */ closeOnDocumentClick: PropTypes.bool, /** Simple text content for the Modal. */ content: customPropTypes.itemShorthand, /** Initial value of open. */ defaultOpen: PropTypes.bool, /** A Modal can appear in a dimmer. */ dimmer: PropTypes.oneOf([true, 'inverted', 'blurring']), /** Event pool namespace that is used to handle component events */ eventPool: PropTypes.string, /** Modal displayed above the content in bold. */ header: customPropTypes.itemShorthand, /** The node where the modal should mount. Defaults to document.body. */ mountNode: PropTypes.any, /** * Action onClick handler when using shorthand `actions`. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onActionClick: PropTypes.func, /** * Called when a close event happens. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onClose: PropTypes.func, /** * Called when the portal is mounted on the DOM. * * @param {null} * @param {object} data - All props. */ onMount: PropTypes.func, /** * Called when an open event happens. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onOpen: PropTypes.func, /** * Called when the portal is unmounted from the DOM. * * @param {null} * @param {object} data - All props. */ onUnmount: PropTypes.func, /** Controls whether or not the Modal is displayed. */ open: PropTypes.bool, /** A modal can vary in size */ size: PropTypes.oneOf(['mini', 'tiny', 'small', 'large', 'fullscreen']), /** Custom styles. */ style: PropTypes.object, /** Element to be rendered in-place where the portal is defined. */ trigger: PropTypes.node /** * NOTE: Any unhandled props that are defined in Portal are passed-through * to the wrapping Portal. */ } : {}; export default Modal;
const ethers = require('ethers'); const RFOX_UTILITY_ABI = require('./abi'); const RFOX_UTILITY_CONTRACT = "0xD82F7e3956d3FF391C927Cd7d0A7A57C360DF5b9" module.exports = (api) => { api.eth.rfox = {} api.setGet('/eth/rfox/estimate_gas_claim_account_balances', async (req, res, next) => { try { res.send(JSON.stringify({ msg: 'success', result: await api.eth.rfox.estimateGasClaimAccountBalances() })); } catch (e) { res.send(JSON.stringify({ msg: 'error', result: e.message })); } }); api.setGet('/eth/rfox/get_account_balances', async (req, res, next) => { try { res.send(JSON.stringify({ msg: 'success', result: await api.eth.rfox.getAccountBalances() })); } catch (e) { res.send(JSON.stringify({ msg: 'error', result: e.message })); } }); api.setPost('/eth/rfox/claim_account_balances', async (req, res, next) => { try { res.send(JSON.stringify({ msg: 'success', result: await api.eth.rfox.claimAccountBalances() })); } catch (e) { res.send(JSON.stringify({ msg: 'error', result: e.message })); } }); /** * Estimates the gas required to claim the account balance of an RFOX account */ api.eth.rfox.estimateGasClaimAccountBalances = async () => { const coin = 'RFOX' if (api.eth.connect[coin]) { const contract = new ethers.Contract( RFOX_UTILITY_CONTRACT, RFOX_UTILITY_ABI, api.eth.connect[coin]); const uncompressedPubKey = api.eth.connect[coin].signingKey.publicKey const x = Buffer.from(uncompressedPubKey.slice(4, 68), 'hex') const y = Buffer.from(uncompressedPubKey.slice(68), 'hex') return ( await contract.estimate.withdrawBalance(x, y) ).mul(await api.eth.connect[coin].provider.getGasPrice()); } else { throw new Error("Could not connect to uninitialized coin RFOX.") } } /** * Claims claimable account balance of a RedFOX account */ api.eth.rfox.claimAccountBalances = async () => { const coin = 'RFOX' if (api.eth.connect[coin]) { const contract = new ethers.Contract( RFOX_UTILITY_CONTRACT, RFOX_UTILITY_ABI, api.eth.connect[coin]); const uncompressedPubKey = api.eth.connect[coin].signingKey.publicKey const x = Buffer.from(uncompressedPubKey.slice(4, 68), 'hex') const y = Buffer.from(uncompressedPubKey.slice(68), 'hex') return await contract.withdrawBalance(x, y) } else { throw new Error("Could not connect to uninitialized coin RFOX.") } } /** * Gets total account balance of a RedFOX account */ api.eth.rfox.getAccountBalances = async () => { const coin = 'RFOX' if (api.eth.connect[coin]) { const contract = new ethers.Contract( RFOX_UTILITY_CONTRACT, RFOX_UTILITY_ABI, api.eth.connect[coin]); const uncompressedPubKey = api.eth.connect[coin].signingKey.publicKey const x = Buffer.from(uncompressedPubKey.slice(4, 68), 'hex') const y = Buffer.from(uncompressedPubKey.slice(68), 'hex') return await contract.totalAccountBalance(x, y) } else { throw new Error("Could not connect to uninitialized coin RFOX.") } } return api; };
#! /usr/bin/env python2 import os from roboTraining.analysis import * if __name__ == "__main__": # Create Analysis object and load results folder an = Analysis(root=".", folder="CMA4")#cl/Machine-7/20161123_212706/") an.load() # General plots # for u in ["score", "distance", "power"]: # an.plot_all_raws(unit=u) # an.plot_all_raws_av(unit=u) #an.plot_all_gens() # an.plot_all_conv_errs() # an.plot_all_state_spaces() # an.plot_all_params() # Simulate best individu # score, index1, index2 = an.get_best_ind() # for a in [0.01]:#, 1, 0.001, 0.0001]:#, 0.001, 0.01, 0.1, 1]: # an.simulate_ind(index1, index2, simTime=50, movie=False, simNoise=0.01, \ # alpha=a, rc=True, openPhase=0.3, beta=0.95, trainingPhase=0.8) # Simtime analysis # an.simtime() # Pareto Anaysis # an.pareto() #an.pareto_dist() #an.pareto_power() # Spring Mass values analysis # an.km() # Omega value analysis #an.freq() #an.freq_av() # Nodes number value analysis #an.nodes() an.nodes_CL() #an.plot_LC() # Noise analysis #an.plot_all_noise_sims() #an.plot_all_noise_params() #an.plot_all_noise_control()
import numpy as np import matplotlib.pyplot as plt import os figures_i = 0 figures_N = 100 FOLDER = "" rocket_length = 0.2 thrust_length = 0.1 def my_plot(fig): global figures_i X = np.loadtxt(f"{FOLDER}/{figures_i}/X.txt", delimiter=",") U = np.loadtxt(f"{FOLDER}/{figures_i}/U.txt", delimiter=",") ax = fig.add_subplot(111) ax.set_xlabel('X, east') ax.set_ylabel('Y, up') rx = X[:, 0] ry = X[:, 1] dx = -np.sin(X[:, 4]) * rocket_length dy = np.cos(X[:, 4]) * rocket_length Fx = -np.sin(X[:, 4] + U[:, 0]) * U[:, 1] Fy = np.cos(X[:, 4] + U[:, 0]) * U[:, 1] max_thrust = np.max(np.sqrt(Fx**2+Fy**2)) Fx /= max_thrust Fy /= max_thrust Fx *= thrust_length Fy *= thrust_length # position vector ax.plot(X[:, 0], X[:, 1], color='lightgrey', zorder=0) # attitude vector ax.quiver(rx, ry, dx, dy, color='blue', width=0.004, headwidth=1, headlength=0, pivot="mid", scale_units="xy", scale=1) # force vector ax.quiver(rx-dx/2, ry-dy/2, Fx, Fy, color='red', width=0.004, pivot="tip", scale_units="xy", scale=1, headwidth=1, headlength=0) ax.set_title("Iteration " + str(figures_i)) ax.set_aspect("equal") def key_press_event(event): global figures_i, figures_N fig = event.canvas.figure if event.key == 'q' or event.key == 'escape': plt.close(event.canvas.figure) return if event.key == 'right': figures_i += 1 figures_i %= figures_N elif event.key == 'left': figures_i -= 1 figures_i %= figures_N fig.clear() my_plot(fig) plt.draw() def main(): global figures_i, figures_N, FOLDER model_folder = "output/Rocket2D/SC" folder_num = sorted(os.listdir(model_folder))[-1] print(folder_num) FOLDER = f"{model_folder}/{folder_num}" figures_N = len(os.listdir(FOLDER)) fig = plt.figure() figures_i = figures_N - 1 my_plot(fig) cid = fig.canvas.mpl_connect('key_press_event', key_press_event) plt.tight_layout() plt.show() if __name__ == '__main__': main()
import unittest import collections from typing import Type, NamedTuple from gym_jsbsim.assessors import AssessorImpl, ContinuousSequentialAssessor from gym_jsbsim.tests import stubs as stubs class TestAssessorImpl(unittest.TestCase): def setUp(self): pass def get_class_under_test(self): return AssessorImpl def get_assessor(self, *args, **kwargs): assessor_class = self.get_class_under_test() return assessor_class(*args, **kwargs) @staticmethod def get_dummy_state_class() -> Type[NamedTuple]: return collections.namedtuple('State', ['test_prop1', 'test_prop2']) def get_dummy_state(self, value1: float = 0.0, value2: float = 1.0): State = self.get_dummy_state_class() return State(value1, value2) def test_init_throws_error_on_empty_base_components(self): base_components = () with self.assertRaises(ValueError): _ = self.get_assessor(base_components) def test_init_throws_error_on_empty_base_components_non_empty_shaping_components(self): base_components = () shaping_components = (stubs.ConstantRewardComponentStub(),) with self.assertRaises(ValueError): _ = self.get_assessor(base_components, shaping_components) def test_calculate_single_base_component(self): for positive_rewards in (True, False): component = stubs.ConstantRewardComponentStub() assessor = self.get_assessor(base_components=(component,), positive_rewards=positive_rewards) state = self.get_dummy_state() reward = assessor.assess(state, state, True) if positive_rewards: expected_shaping_reward = component.get_return_value() else: expected_shaping_reward = 1 - component.get_return_value() expected_non_shaping_reward = expected_shaping_reward # should be same because not shaping self.assertAlmostEqual(expected_shaping_reward, reward.agent_reward()) self.assertAlmostEqual(expected_non_shaping_reward, reward.assessment_reward()) def test_calculate_multiple_base_components(self): for positive_rewards in (True, False): reward_values = [.1, .2, .4] components = tuple(stubs.ConstantRewardComponentStub(val) for val in reward_values) assessor = self.get_assessor(components, positive_rewards=positive_rewards) state = self.get_dummy_state_class() reward = assessor.assess(state, state, True) if positive_rewards: comp_values = [cmp.get_return_value() for cmp in components] else: comp_values = [cmp.get_return_value() - 1 for cmp in components] expected_shaping_reward = sum(comp_values) / len(comp_values) expected_non_shaping_reward = expected_shaping_reward # should be same because not shaping self.assertAlmostEqual(expected_shaping_reward, reward.agent_reward(), msg=f'positive reward {positive_rewards}') self.assertAlmostEqual(expected_non_shaping_reward, reward.assessment_reward(), msg=f'positive reward {positive_rewards}') def test_calculate_with_shaping_components(self): for positive_rewards in (True, False): base_reward_vals = [.0, .1] shaping_reward_vals = [.2, .3] base_components = tuple( stubs.ConstantRewardComponentStub(val) for val in base_reward_vals) shape_components = tuple( stubs.ConstantRewardComponentStub(val) for val in shaping_reward_vals) assessor = self.get_assessor(base_components, shape_components, positive_rewards=positive_rewards) state = self.get_dummy_state() reward = assessor.assess(state, state, True) if positive_rewards: expected_shaping_reward = (sum(base_reward_vals + shaping_reward_vals) / len(base_reward_vals + shaping_reward_vals)) expected_non_shaping_reward = sum(base_reward_vals) / len(base_reward_vals) else: base_negative_vals = list(base_val - 1 for base_val in base_reward_vals) expected_shaping_reward = (sum(base_negative_vals + shaping_reward_vals) / len(base_negative_vals + shaping_reward_vals)) expected_non_shaping_reward = sum(base_negative_vals) / len(base_negative_vals) self.assertAlmostEqual(expected_shaping_reward, reward.agent_reward(), msg=f'positive reward {positive_rewards}') self.assertAlmostEqual(expected_non_shaping_reward, reward.assessment_reward(), msg=f'positive reward {positive_rewards}') class TestContinuousSequentialAssessor(TestAssessorImpl): def get_class_under_test(self): return ContinuousSequentialAssessor def test_calculate_with_shaping_components(self): for positive_rewards in (True, False): num_state_vars = 3 DummyState, props = stubs.FlightTaskStub.get_dummy_state_class_and_properties( num_state_vars) base_reward = 0 base_component = stubs.ConstantRewardComponentStub(0) # create two states with a component that will recognise as low and high potential resp. state_low_potential = DummyState(*(1.0 for _ in range(num_state_vars))) state_high_potential = DummyState(*(2.0 for _ in range(num_state_vars))) low_potential, high_potential = 0.5, 1.0 potential_map = {state_low_potential: low_potential, state_high_potential: high_potential} shape_component = stubs.RewardComponentStub(potential_map) assessor = self.get_assessor((base_component,), (shape_component,), positive_rewards=positive_rewards) # if non-terminal, expect to see reward equal to potential increase terminal = False reward = assessor.assess(state_high_potential, state_low_potential, terminal) base_reward_as_configured = base_reward if positive_rewards else base_reward - 1 expected_shaping_reward = (base_reward_as_configured + (high_potential - low_potential)) / 2 expected_non_shaping_reward = base_reward_as_configured msg = f'positive reward {positive_rewards}' self.assertAlmostEqual(expected_shaping_reward, reward.agent_reward(), msg=msg) self.assertAlmostEqual(expected_non_shaping_reward, reward.assessment_reward(), msg=msg) # if terminal, expect to see reward as if terminal step potential was zero terminal = True terminal_potential = 0.0 reward = assessor.assess(state_high_potential, state_low_potential, terminal) expected_shaping_reward = (base_reward_as_configured + (terminal_potential - low_potential)) / 2 expected_non_shaping_reward = base_reward_as_configured self.assertAlmostEqual(expected_shaping_reward, reward.agent_reward(), msg=msg) self.assertAlmostEqual(expected_non_shaping_reward, reward.assessment_reward(), msg=msg) def assess_reward_for_potential_change_with_dependency(self, state_potential: float, prev_state_potential: float, dependency_potential: float, positive_rewards: bool): """ Calculates the reward given we transition from prev_state_potential to state_potential, and a dependant component unchanged at dependency_potential. Step is non-terminal and base reward is zero. """ num_state_vars = 3 terminal = False DummyState, props = stubs.FlightTaskStub.get_dummy_state_class_and_properties( num_state_vars) # want base reward to be zero so we can focus on shaped reward if positive_rewards: base_component = stubs.ConstantRewardComponentStub(0) else: base_component = stubs.ConstantRewardComponentStub(1) # create two states with a component that will recognise as low and high potential resp. state = DummyState(*(1.0 for _ in range(num_state_vars))) prev_state = DummyState(*(2.0 for _ in range(num_state_vars))) potential_map = {state: state_potential, prev_state: prev_state_potential} # make components shape_component = stubs.RewardComponentStub(potential_map) dependency_potential_map = {key: dependency_potential for key in potential_map} dependant_shape_component = stubs.RewardComponentStub(dependency_potential_map) dependency_map = {shape_component: (dependant_shape_component,)} assessor = self.get_assessor((base_component,), (shape_component, dependant_shape_component), potential_dependency_map=dependency_map, positive_rewards=positive_rewards) return assessor.assess(state, prev_state, terminal) def test_calculate_with_shaping_components_and_dependency_at_zero(self): for positive_rewards in (True, False): low_potential = 0.5 high_potential = 1.0 dependent_potential = 0.0 reward = self.assess_reward_for_potential_change_with_dependency(low_potential, high_potential, dependent_potential, positive_rewards) # we expect to have had a potential improvement, but because dependent component is at # zero potential, no reward is given expected_reward = 0.0 self.assertAlmostEqual(expected_reward, reward.agent_reward()) def test_calculate_with_shaping_components_and_dependency_at_fraction(self): for positive_rewards in (True, False): low_potential = 0.5 high_potential = 1.0 dependent_potential = 0.75 reward = self.assess_reward_for_potential_change_with_dependency(high_potential, low_potential, dependent_potential, positive_rewards) total_reward_values = (high_potential - low_potential) * dependent_potential # there are 3 components (incl. the dependant component and base # component with value 0) so divide averaged_reward_values = total_reward_values / ( len(reward.shaping_reward_elements) + len(reward.base_reward_elements)) self.assertAlmostEqual(averaged_reward_values, reward.agent_reward()) def test_calculate_with_shaping_components_and_dependency_at_one(self): for positive_rewards in (True, False): low_potential = 0.5 high_potential = 1.0 dependent_potential = 1.0 reward = self.assess_reward_for_potential_change_with_dependency(high_potential, low_potential, dependent_potential, positive_rewards) total_reward_values = (high_potential - low_potential) * dependent_potential # there are 3 components (incl. the dependant component and base # component with value 0) so divide averaged_reward_values = total_reward_values / ( len(reward.shaping_reward_elements) + len(reward.base_reward_elements)) self.assertAlmostEqual(averaged_reward_values, reward.agent_reward())
#!/usr/bin/python # custom_dialect.py import csv csv.register_dialect("hashes", delimiter="#") f = open('items3.csv', 'w') with f: writer = csv.writer(f, dialect="hashes") writer.writerow(("pencils", 2)) writer.writerow(("plates", 1)) writer.writerow(("books", 4))
/* $Id: VBoxVgaFont-8x16.h 48674 2013-09-25 08:26:15Z vboxsync $ */ /** @file * VGA-ROM.F16 from ftp://ftp.simtel.net/pub/simtelnet/msdos/screen/fntcol16.zip . * The package is (C) Joseph (Yossi) Gil. * The individual fonts are in the public domain. */ /* * This file was automatically generated * from VGA-ROM.F16 * by \coding\vbox\svn\trunk\out\win.amd64\debug\obj\bin2c\bin2c.exe. */ const unsigned char g_abVgaFont_8x16[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x81, 0xa5, 0x81, 0x81, 0xbd, 0x99, 0x81, 0x81, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xff, 0xdb, 0xff, 0xff, 0xc3, 0xe7, 0xff, 0xff, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0xfe, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0xe7, 0xe7, 0xe7, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x7e, 0xff, 0xff, 0x7e, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x1e, 0x0e, 0x1a, 0x32, 0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x33, 0x3f, 0x30, 0x30, 0x30, 0x30, 0x70, 0xf0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x63, 0x7f, 0x63, 0x63, 0x63, 0x63, 0x67, 0xe7, 0xe6, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0xdb, 0x3c, 0xe7, 0x3c, 0xdb, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfe, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0e, 0x1e, 0x3e, 0xfe, 0x3e, 0x1e, 0x0e, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xdb, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0x60, 0x38, 0x6c, 0xc6, 0xc6, 0x6c, 0x38, 0x0c, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x66, 0xff, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7c, 0x7c, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0x7c, 0x7c, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x3c, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x6c, 0xfe, 0x6c, 0x6c, 0x6c, 0xfe, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7c, 0xc6, 0xc2, 0xc0, 0x7c, 0x06, 0x06, 0x86, 0xc6, 0x7c, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc2, 0xc6, 0x0c, 0x18, 0x30, 0x60, 0xc6, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x76, 0xdc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0xc3, 0xc3, 0xdb, 0xdb, 0xc3, 0xc3, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0x06, 0x06, 0x3c, 0x06, 0x06, 0x06, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x0c, 0x0c, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc0, 0xc0, 0xc0, 0xfc, 0x06, 0x06, 0x06, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x60, 0xc0, 0xc0, 0xfc, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc6, 0x06, 0x06, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x06, 0x06, 0x0c, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0x0c, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xde, 0xde, 0xde, 0xdc, 0xc0, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x66, 0x66, 0x66, 0x66, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xc0, 0xc0, 0xc2, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x6c, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6c, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xde, 0xc6, 0xc6, 0x66, 0x3a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0xcc, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe6, 0x66, 0x66, 0x6c, 0x78, 0x78, 0x6c, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xe7, 0xff, 0xff, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xe6, 0xf6, 0xfe, 0xde, 0xce, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xd6, 0xde, 0x7c, 0x0c, 0x0e, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x66, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0x60, 0x38, 0x0c, 0x06, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xdb, 0x99, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xdb, 0xdb, 0xff, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x18, 0x3c, 0x66, 0xc3, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xc3, 0x86, 0x0c, 0x18, 0x30, 0x60, 0xc1, 0xc3, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xc0, 0xe0, 0x70, 0x38, 0x1c, 0x0e, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x60, 0x60, 0x78, 0x6c, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc0, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x0c, 0x0c, 0x3c, 0x6c, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x64, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xcc, 0x78, 0x00, 0x00, 0x00, 0xe0, 0x60, 0x60, 0x6c, 0x76, 0x66, 0x66, 0x66, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x00, 0x0e, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3c, 0x00, 0x00, 0x00, 0xe0, 0x60, 0x60, 0x66, 0x6c, 0x78, 0x78, 0x6c, 0x66, 0xe6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe6, 0xff, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0x0c, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdc, 0x76, 0x66, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0x60, 0x38, 0x0c, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xdb, 0xdb, 0xff, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x0c, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xcc, 0x18, 0x30, 0x60, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0e, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0xc2, 0xc0, 0xc0, 0xc0, 0xc2, 0x66, 0x3c, 0x0c, 0x06, 0x7c, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x38, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x66, 0x60, 0x60, 0x66, 0x3c, 0x0c, 0x06, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0xc0, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x38, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0xfe, 0x66, 0x60, 0x7c, 0x60, 0x60, 0x66, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6e, 0x3b, 0x1b, 0x7e, 0xd8, 0xdc, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x6c, 0xcc, 0xcc, 0xfe, 0xcc, 0xcc, 0xcc, 0xcc, 0xce, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x78, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7e, 0x06, 0x0c, 0x78, 0x00, 0x00, 0xc6, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0xc3, 0xc0, 0xc0, 0xc0, 0xc3, 0x7e, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x64, 0x60, 0xf0, 0x60, 0x60, 0x60, 0x60, 0xe6, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x66, 0x3c, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x66, 0x66, 0x7c, 0x62, 0x66, 0x6f, 0x66, 0x66, 0x66, 0xf3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x1b, 0x18, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0xc6, 0xe6, 0xf6, 0xfe, 0xde, 0xce, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x6c, 0x6c, 0x3e, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xc0, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0xc2, 0xc6, 0xcc, 0x18, 0x30, 0x60, 0xce, 0x9b, 0x06, 0x0c, 0x1f, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0xc2, 0xc6, 0xcc, 0x18, 0x30, 0x66, 0xce, 0x96, 0x3e, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x3c, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x6c, 0xd8, 0x6c, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0x6c, 0x36, 0x6c, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0xdd, 0x77, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0xd8, 0xd8, 0xd8, 0xdc, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0xd8, 0xcc, 0xc6, 0xc6, 0xc6, 0xcc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc6, 0xc6, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xc6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xc6, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x18, 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0x6c, 0x6c, 0x6c, 0x6c, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x30, 0x18, 0x0c, 0x3e, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xdb, 0xdb, 0xdb, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x7e, 0xdb, 0xdb, 0xf3, 0x7e, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x30, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x60, 0x30, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0xd8, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7e, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x6c, 0x3c, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0xd8, 0x30, 0x60, 0xc8, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const unsigned g_cbVgaFont_8x16 = sizeof(g_abVgaFont_8x16); /* end of file */
var Election = artifacts.require("./Election.sol"); contract("Election", function(accounts) { it("initializes with two candidates", function() { return Election.deployed().then(function(instance) { return instance.candidatesCount(); }).then(function(count) { assert.equal(count, 2); }); }); it("it initializes the candidates with the correct values", function() { return Election.deployed().then(function(instance) { electionInstance = instance; return electionInstance.candidates(1); }).then(function(candidate) { assert.equal(candidate[0], 1, "contains the correct id"); assert.equal(candidate[1], "Pepe Le Pew", "contains the correct name"); assert.equal(candidate[2], 0, "contains the correct votes count"); return electionInstance.candidates(2); }).then(function(candidate) { assert.equal(candidate[0], 2, "contains the correct id"); assert.equal(candidate[1], "Elmer Fudd", "contains the correct name"); assert.equal(candidate[2], 0, "contains the correct votes count"); }); }); it("allows a voter to cast a vote", function() { return Election.deployed().then(function(instance) { electionInstance = instance; candidateId = 1; return electionInstance.vote(candidateId, { from: accounts[0] }); }).then(function(receipt) { assert.equal(receipt.logs.length, 1, "an event was triggered"); assert.equal(receipt.logs[0].event, "votedEvent", "the event type is correct"); assert.equal(receipt.logs[0].args._candidateId.toNumber(), candidateId, "the candidate id is correct"); return electionInstance.voters(accounts[0]); }).then(function(voted) { assert(voted, "the voter was marked as voted"); return electionInstance.candidates(candidateId); }).then(function(candidate) { var voteCount = candidate[2]; assert.equal(voteCount, 1, "increments the candidate's vote count"); }) }); it("throws an exception for invalid candiates", function() { return Election.deployed().then(function(instance) { electionInstance = instance; return electionInstance.vote(99, { from: accounts[1] }) }).then(assert.fail).catch(function(error) { assert(error.message.indexOf('revert') >= 0, "error message must contain revert"); return electionInstance.candidates(1); }).then(function(candidate1) { var voteCount = candidate1[2]; assert.equal(voteCount, 1, "candidate 1 did not receive any votes"); return electionInstance.candidates(2); }).then(function(candidate2) { var voteCount = candidate2[2]; assert.equal(voteCount, 0, "candidate 2 did not receive any votes"); }); }); it("should not allow to vote twice", function() { return Election.deployed().then(function(instance) { electionInstance = instance; candidateId = 2; electionInstance.vote(candidateId, { from: accounts[1] }); return electionInstance.candidates(candidateId); }).then(function(candidate) { var voteCount = candidate[2]; assert.equal(voteCount, 1, "accepts first vote"); // Try to vote again return electionInstance.vote(candidateId, { from: accounts[1] }); }).then(assert.fail).catch(function(error) { assert(error.message.indexOf('revert') >= 0, "error message must contain revert"); return electionInstance.candidates(1); }).then(function(candidate1) { var voteCount = candidate1[2]; assert.equal(voteCount, 1, "candidate 1 did not receive any votes"); return electionInstance.candidates(2); }).then(function(candidate2) { var voteCount = candidate2[2]; assert.equal(voteCount, 1, "candidate 2 did not receive any votes"); }); }); });
var searchData= [ ['adv_5fflux_2ec',['adv_flux.c',['../adv__flux_8c.html',1,'']]], ['al_2eh',['al.h',['../al_8h.html',1,'']]], ['al_5falloc_2ec',['al_alloc.c',['../al__alloc_8c.html',1,'']]], ['al_5fboundary_2ec',['al_boundary.c',['../al__boundary_8c.html',1,'']]], ['al_5fcodes_2eh',['al_codes.h',['../al__codes_8h.html',1,'']]], ['al_5fdecomp_5f_2ec',['al_decomp_.c',['../al__decomp___8c.html',1,'']]], ['al_5fdecompose_2ec',['al_decompose.c',['../al__decompose_8c.html',1,'']]], ['al_5fdefs_2eh',['al_defs.h',['../al__defs_8h.html',1,'']]], ['al_5fexchange_2ec',['al_exchange.c',['../al__exchange_8c.html',1,'']]], ['al_5fexchange_5fdim_2ec',['al_exchange_dim.c',['../al__exchange__dim_8c.html',1,'']]], ['al_5ffinalize_2ec',['al_finalize.c',['../al__finalize_8c.html',1,'']]], ['al_5fhidden_2eh',['al_hidden.h',['../al__hidden_8h.html',1,'']]], ['al_5finit_2ec',['al_init.c',['../al__init_8c.html',1,'']]], ['al_5fio_2ec',['al_io.c',['../al__io_8c.html',1,'']]], ['al_5fproto_2eh',['al_proto.h',['../al__proto_8h.html',1,'']]], ['al_5fsort_5f_2ec',['al_sort_.c',['../al__sort___8c.html',1,'']]], ['al_5fsubarray_5f_2ec',['al_subarray_.c',['../al__subarray___8c.html',1,'']]], ['al_5fsz_5ffree_2ec',['al_sz_free.c',['../al__sz__free_8c.html',1,'']]], ['al_5fsz_5fget_2ec',['al_sz_get.c',['../al__sz__get_8c.html',1,'']]], ['al_5fsz_5finit_2ec',['al_sz_init.c',['../al__sz__init_8c.html',1,'']]], ['al_5fsz_5fset_2ec',['al_sz_set.c',['../al__sz__set_8c.html',1,'']]], ['al_5fszptr_5f_2ec',['al_szptr_.c',['../al__szptr___8c.html',1,'']]], ['al_5fwrite_5farray_5fasync_2ec',['al_write_array_async.c',['../al__write__array__async_8c.html',1,'']]], ['arrays_2ec',['arrays.c',['../arrays_8c.html',1,'']]] ];
import React from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; import { selectUser } from "../features/userSlice"; import db from "../private/firebase"; import StartImage from "./start.png"; import * as objectData from "../data/data.json"; function StartGamePopup({ setStartGamePopup, userInfo }) { const user = useSelector(selectUser); return ( <StyledStartGamePopup> <img src={StartImage} alt="start" /> <button onClick={() => { if (user && user.uid) { setStartGamePopup(false); db.collection("users").doc(user.uid).update({ startFlagged: true, startTime: new Date().getTime(), }); if (userInfo.hasPlayedBefore === true) { objectData.objects.map((object) => { db.collection("users").doc(user.uid).collection("objects").add({ lat: object.coords[0], lng: object.coords[1], name: object.name, image: object.image, description: object.description, isFound: false, question1: object.question3, answers1: object.answers3, correct1: object.correct3, question2: object.question4, answers2: object.answers4, correct2: object.correct4, extraImages: object.extraImages, }); }); } else { objectData.objects.map((object) => { db.collection("users").doc(user.uid).collection("objects").add({ lat: object.coords[0], lng: object.coords[1], name: object.name, image: object.image, description: object.description, isFound: false, question1: object.question1, answers1: object.answers1, correct1: object.correct1, question2: object.question2, answers2: object.answers2, correct2: object.correct2, extraImages: object.extraImages, }); }); } setTimeout(() => { window.location.reload(); }, 2000); } }} > Sākt </button> </StyledStartGamePopup> ); } const StyledStartGamePopup = styled.div` position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 100; width: 80%; max-width: 300px; height: fit-content; padding: 2rem; background-color: #f3f3f3; display: flex; flex-direction: column; align-items: center; > img { width: 100%; border-radius: 5px; } > button { margin-top: 20px; width: 150px; height: 40px; background: #333; color: #f2f2f2; font-size: 1rem; border-radius: 5px; } `; export default StartGamePopup;
'use strict'; const terminus = require('@godaddy/terminus'); const { expect } = require('chai'); const sinon = require('sinon'); const createSlayTerminus = require('./'); describe('slay-terminus', () => { let app; let createTerminusStub; let doneStub; beforeEach(() => { app = sinon.mock(); app.servers = sinon.mock(); app.servers.http = sinon.mock(); app.after = sinon.stub().callsArgWith(1, {}, {}, sinon.spy()); createTerminusStub = sinon.stub(terminus, 'createTerminus'); doneStub = sinon.stub(); }); it('creates a terminus preboot', () => { const slayTerminus = createSlayTerminus({ foo: 'bar' }); expect(typeof slayTerminus).equals('function'); }); it('plugs terminus', () => { const slayTerminus = createSlayTerminus({ foo: 'bar' }); slayTerminus(app, null, doneStub); expect(app.after.calledWith('start')).equals(true); expect(createTerminusStub.calledWith(app.servers.http, { foo: 'bar' })) .equals(true); expect(doneStub.called).equals(true); }); afterEach(() => { sinon.restore(); }); });
import Vue from 'vue' import VueI18n from 'vue-i18n' Vue.use(VueI18n) function loadLocaleMessages() { const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i) const messages = {} locales.keys().forEach(key => { const matched = key.match(/([A-Za-z0-9-_]+)\./i) if (matched && matched.length > 1) { const locale = matched[1] messages[locale] = locales(key) } }) return messages } export default new VueI18n({ locale: process.env.VUE_APP_I18N_LOCALE || 'pt_BR', fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'pt_BR', messages: loadLocaleMessages() })
<<<<<<< HEAD module.exports={A:{A:{"1":"E A B","2":"P F D rB"},B:{"1":"C I J K L M N v s Q VB GB"},C:{"1":"0 1 2 3 4 5 6 7 8 9 G T P F D E A B C I J K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z SB WB AB BB CB DB EB H FB MB NB OB PB QB RB IB TB UB v s Q kB","2":"uB LB jB iB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 G T P F D E A B C I J K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z SB WB AB BB CB DB EB H FB MB NB OB PB QB RB IB TB UB v s Q VB GB dB aB 1B bB"},E:{"1":"P F D E A B C I J eB fB gB hB XB S HB lB mB","2":"G cB YB","16":"T"},F:{"1":"0 1 2 3 4 5 6 7 8 9 B C K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z AB BB CB DB EB H FB S KB sB HB","2":"E nB oB pB qB"},G:{"1":"D tB JB vB wB xB yB zB 0B ZB 2B 3B 4B 5B 6B 7B 8B 9B AC BC","16":"YB"},H:{"1":"CC"},I:{"1":"LB G Q FC GC JB HC IC","16":"DC EC"},J:{"1":"F A"},K:{"1":"B C O S KB HB","2":"A"},L:{"1":"GB"},M:{"1":"H"},N:{"1":"A B"},O:{"1":"JC"},P:{"1":"G KC LC MC NC OC XB PC QC"},Q:{"1":"RC"},R:{"1":"SC"},S:{"1":"TC"}},B:1,C:"document.head"}; ======= module.exports={A:{A:{"1":"E A B","2":"I D F kB"},B:{"1":"C O H Q J K L M y N VB S"},C:{"1":"0 1 2 3 4 5 6 7 8 9 G W I D F E A B C O H Q J K L X Y Z a b c d e f g h i j k l m n o p q r s t u v w x P z AB XB CB KB EB FB GB HB IB DB BB U T LB MB NB OB PB QB JB SB M y N jB","2":"iB RB rB tB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 G W I D F E A B C O H Q J K L X Y Z a b c d e f g h i j k l m n o p q r s t u v w x P z AB XB CB KB EB FB GB HB IB DB BB U T LB MB NB OB PB QB JB SB M y N VB S uB ZB aB bB"},E:{"1":"I D F E A B C O H eB fB gB hB UB R V lB mB","2":"G cB TB","16":"W"},F:{"1":"0 1 2 3 4 5 6 7 8 9 B C Q J K L X Y Z a b c d e f g h i j k l m n o p q r s t u v w x P z AB CB EB FB GB HB IB DB BB U T R WB sB V","2":"E nB oB pB qB"},G:{"1":"F TC YB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC","16":"TB"},H:{"1":"CC"},I:{"1":"RB G N FC GC YB HC IC","16":"DC EC"},J:{"1":"D A"},K:{"1":"B C P R WB V","2":"A"},L:{"1":"S"},M:{"1":"M"},N:{"1":"A B"},O:{"1":"JC"},P:{"1":"G KC LC MC NC OC UB PC QC"},Q:{"1":"RC"},R:{"1":"SC"},S:{"1":"dB"}},B:1,C:"document.head"}; >>>>>>> 618d5a84e3460e9d830f42d69dd19295c6b2cbbd
# -*- coding: utf-8 -*- # Copyright 2019 Mateusz Klos # # 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. # """ OpenAPI spec generator for restible. """ from __future__ import absolute_import # package interface from .decorators import response from .decorators import response_200 from .decorators import response_201 from .decorators import response_204 from .decorators import response_401 from .decorators import response_403 from .decorators import response_404 from .decorators import response_500 from .decorators import responses from .decorators import route_params from .logic import extract_api_spec from .util import RESPONSE_401 from .util import RESPONSE_404 from .util import RESPONSE_500 __version__ = '0.3.3'
# (c) 2019 Red Hat Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ --- author: Ansible Security Automation Team httpapi : qradar short_description: HttpApi Plugin for IBM QRadar description: - This HttpApi plugin provides methods to connect to IBM QRadar over a HTTP(S)-based api. version_added: "1.0" """ import json from ansible.module_utils.basic import to_text from ansible.errors import AnsibleConnectionFailure from ansible.module_utils.six.moves.urllib.error import HTTPError from ansible.plugins.httpapi import HttpApiBase from ansible.module_utils.connection import ConnectionError from ansible_collections.ibm.qradar.plugins.module_utils.qradar import BASE_HEADERS class HttpApi(HttpApiBase): def send_request(self, request_method, path, payload=None, headers=None): headers = headers if headers else BASE_HEADERS try: self._display_request(request_method) response, response_data = self.connection.send( path, payload, method=request_method, headers=headers ) value = self._get_response_value(response_data) return response.getcode(), self._response_to_json(value) except HTTPError as e: error = json.loads(e.read()) return e.code, error def _display_request(self, request_method): self.connection.queue_message( "vvvv", "Web Services: %s %s" % (request_method, self.connection._url) ) def _get_response_value(self, response_data): return to_text(response_data.getvalue()) def _response_to_json(self, response_text): try: return json.loads(response_text) if response_text else {} # JSONDecodeError only available on Python 3.5+ except ValueError: raise ConnectionError("Invalid JSON response: %s" % response_text) def update_auth(self, response, response_text): cookie = response.info().get("Set-Cookie") # Set the 'SEC' header if "SEC" in cookie: return {"SEC": cookie.split(";")[0].split("=")[-1]} return None def logout(self): self.send_request("POST", "/auth/logout") # Clean up tokens self.connection._auth = None
import pytest import factrank @pytest.fixture def model(): return factrank.get_model() def test_inference_positive_example(model): (prob, sentence), = model.checkworthyness("Het aantal mensen dat sterft aan covid blijft zorgwekkend oplopen.") assert prob > 0.9 def test_inference_negative_example(model): # NOTE: Feitelijke bewering (Fransen en Nederlanders kopen op Belgische sites). # Woorden als “gelukkig”, “stilaan”, kunnen doen vermoeden dat het om een # relevante verandering gaat. Er is evenwel te weinig context om dat in te schatten. # De claim verraadt ook weinig controverse hierover. Dus Feitelijk Niet-Relevant. (prob, sentence), = model.checkworthyness( "De Fransen en de Nederlanders kopen gelukkig stilaan ook heel graag op Belgische sites.") assert prob < 0.7
export { default as activeIntimationReducer } from './activeIntimationReducer';
""" OpenAPI definition No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v0 Contact: support@gooddata.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from gooddata_metadata_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from gooddata_metadata_client.exceptions import ApiAttributeError def lazy_import(): from gooddata_metadata_client.model.json_api_attribute_to_many_linkage import JsonApiAttributeToManyLinkage globals()['JsonApiAttributeToManyLinkage'] = JsonApiAttributeToManyLinkage class JsonApiDatasetOutRelationshipsAttributes(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'data': (JsonApiAttributeToManyLinkage,), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'data': 'data', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, data, *args, **kwargs): # noqa: E501 """JsonApiDatasetOutRelationshipsAttributes - a model defined in OpenAPI Args: data (JsonApiAttributeToManyLinkage): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.data = data for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, data, *args, **kwargs): # noqa: E501 """JsonApiDatasetOutRelationshipsAttributes - a model defined in OpenAPI Args: data (JsonApiAttributeToManyLinkage): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.data = data for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
import pytest import pickle import ray from ray.dag import ( DAGNode, PARENT_CLASS_NODE_KEY, PREV_CLASS_METHOD_CALL_KEY, ) @ray.remote class Counter: def __init__(self, init_value=0): self.i = init_value def inc(self): self.i += 1 def get(self): return self.i @ray.remote class Actor: def __init__(self, init_value): self.i = init_value def inc(self, x): self.i += x def get(self): return self.i def test_serialize_warning(): node = DAGNode([], {}, {}, {}) with pytest.raises(ValueError): pickle.dumps(node) def test_basic_actor_dag(shared_ray_instance): @ray.remote def combine(x, y): return x + y a1 = Actor.bind(10) res = a1.get.bind() print(res) assert ray.get(res.execute()) == 10 a2 = Actor.bind(10) a1.inc.bind(2) a1.inc.bind(4) a2.inc.bind(6) dag = combine.bind(a1.get.bind(), a2.get.bind()) print(dag) assert ray.get(dag.execute()) == 32 def test_class_as_class_constructor_arg(shared_ray_instance): @ray.remote class OuterActor: def __init__(self, inner_actor): self.inner_actor = inner_actor def inc(self, x): self.inner_actor.inc.remote(x) def get(self): return ray.get(self.inner_actor.get.remote()) outer = OuterActor.bind(Actor.bind(10)) outer.inc.bind(2) dag = outer.get.bind() print(dag) assert ray.get(dag.execute()) == 12 def test_class_as_function_constructor_arg(shared_ray_instance): @ray.remote def f(actor_handle): return ray.get(actor_handle.get.remote()) dag = f.bind(Actor.bind(10)) print(dag) assert ray.get(dag.execute()) == 10 def test_basic_actor_dag_constructor_options(shared_ray_instance): a1 = Actor.bind(10) dag = a1.get.bind() print(dag) assert ray.get(dag.execute()) == 10 a1 = Actor.options(name="Actor", namespace="test", max_pending_calls=10).bind(10) dag = a1.get.bind() print(dag) # Ensure execution result is identical with .options() in init() assert ray.get(dag.execute()) == 10 # Ensure options are passed in assert a1.get_options().get("name") == "Actor" assert a1.get_options().get("namespace") == "test" assert a1.get_options().get("max_pending_calls") == 10 def test_actor_method_options(shared_ray_instance): a1 = Actor.bind(10) dag = a1.get.options(name="actor_method_options").bind() print(dag) assert ray.get(dag.execute()) == 10 assert dag.get_options().get("name") == "actor_method_options" def test_basic_actor_dag_constructor_invalid_options(shared_ray_instance): with pytest.raises( ValueError, match=r".*only accepts None, 0 or a positive number.*" ): a1 = Actor.options(num_cpus=-1).bind(10) invalid_dag = a1.get.bind() ray.get(invalid_dag.execute()) def test_actor_options_complicated(shared_ray_instance): """Test a more complicated setup where we apply .options() in both constructor and method call with overlapping keys, and ensure end to end options correctness. """ @ray.remote def combine(x, y): return x + y a1 = Actor.options(name="a1_v0").bind(10) res = a1.get.options(name="v1").bind() print(res) assert ray.get(res.execute()) == 10 assert a1.get_options().get("name") == "a1_v0" assert res.get_options().get("name") == "v1" a1 = Actor.options(name="a1_v1").bind(10) # Cannot a2 = Actor.options(name="a2_v0").bind(10) a1.inc.options(name="v1").bind(2) a1.inc.options(name="v2").bind(4) a2.inc.options(name="v3").bind(6) dag = combine.options(name="v4").bind(a1.get.bind(), a2.get.bind()) print(dag) assert ray.get(dag.execute()) == 32 test_a1 = dag.get_args()[0] # call graph for a1.get.bind() test_a2 = dag.get_args()[1] # call graph for a2.get.bind() assert test_a2.get_options() == {} # No .options() at outer call # refer to a2 constructor .options() call assert ( test_a2.get_other_args_to_resolve()[PARENT_CLASS_NODE_KEY] .get_options() .get("name") == "a2_v0" ) # refer to actor method a2.inc.options() call assert ( test_a2.get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_options() .get("name") == "v3" ) # refer to a1 constructor .options() call assert ( test_a1.get_other_args_to_resolve()[PARENT_CLASS_NODE_KEY] .get_options() .get("name") == "a1_v1" ) # refer to latest actor method a1.inc.options() call assert ( test_a1.get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_options() .get("name") == "v2" ) # refer to first bound actor method a1.inc.options() call assert ( test_a1.get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_options() .get("name") == "v1" ) def test_pass_actor_handle(shared_ray_instance): @ray.remote class Actor: def ping(self): return "hello" @ray.remote def caller(handle): assert isinstance(handle, ray.actor.ActorHandle), handle return ray.get(handle.ping.remote()) a1 = Actor.bind() dag = caller.bind(a1) print(dag) assert ray.get(dag.execute()) == "hello" def test_dynamic_pipeline(shared_ray_instance): @ray.remote class Model: def __init__(self, arg): self.arg = arg def forward(self, x): return self.arg + str(x) @ray.remote class ModelSelection: def is_even(self, x): return x % 2 == 0 @ray.remote def pipeline(x, m1, m2, selection): sel = selection.is_even.remote(x) if ray.get(sel): result = m1.forward.remote(x) else: result = m2.forward.remote(x) return ray.get(result) m1 = Model.bind("Even: ") m2 = Model.bind("Odd: ") selection = ModelSelection.bind() even_input = pipeline.bind(20, m1, m2, selection) print(even_input) assert ray.get(even_input.execute()) == "Even: 20" odd_input = pipeline.bind(21, m1, m2, selection) print(odd_input) assert ray.get(odd_input.execute()) == "Odd: 21" def test_unsupported_bind(): @ray.remote class Actor: def ping(self): return "hello" with pytest.raises( AttributeError, match=r"\.bind\(\) cannot be used again on", ): actor = Actor.bind() _ = actor.bind() with pytest.raises( AttributeError, match=r"\.remote\(\) cannot be used on ClassMethodNodes", ): actor = Actor.bind() _ = actor.ping.remote() def test_unsupported_remote(): @ray.remote class Actor: def ping(self): return "hello" with pytest.raises(AttributeError, match="'Actor' has no attribute 'remote'"): _ = Actor.bind().remote() @ray.remote def func(): return 1 with pytest.raises(AttributeError, match=r"\.remote\(\) cannot be used on"): _ = func.bind().remote() if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", __file__]))
/* All of the code within the ZingChart software is developed and copyrighted by ZingChart, Inc., and may not be copied, replicated, or used in any other software or application without prior permission from ZingChart. All usage must coincide with the ZingChart End User License Agreement which can be requested by email at support@zingchart.com. Build 2.6.3 */ eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('5.1k("1h-1a");5.B("1c",F(a,d){o(d.8 1e 1f){3 c=[];1d(3 b=0;b<d.8.1b;b++){c.1g("5-s-"+d.8[b])}5.z(a,"12",{4:"w",8:c})}H{3 e=d.8||"s";5.z(a,"12",{4:"w",8:"5-s-"+e})}});5.B("1m",F(k,f){3 g=f.8||"s";3 i=f.W||{};3 r=f.D||"";3 e=f.4||"";3 c=7(f.14||"0",10);3 n=7(f.Z||"0",10);3 m=7(f.S||"-1",10);3 a=f.R||"";3 j=7(f.x||"0",10);3 h=7(f.y||"0",10);3 l=7(f["6-x"]||"0",10);3 q=7(f["6-y"]||"-10",10);3 d={},p={};o(e!==""){N(e){v"L":d={4:e,G:c,t:n};p={4:e,G:c,t:n};u;v"O":o(m!==-1){d={4:e,t:m};p={4:e,t:m}}H{o(a!==""){d={4:e,C:a};p={4:e,C:a}}}u;v"K":d={4:e,x:j,y:h};p={4:e,x:j,y:h};u}o(13.Q(f["6-x"])!==Y){p["6-x"]=l}o(13.Q(f["6-y"])!==Y){p["6-y"]=q}}3 b={};5.J(i,b);o(r!==""){5.J({D:r},b)}5.M(b);o(e!==""){b.E=d;b["A-E"]=p}5.z(k,"1l",{4:"w",8:"5-s-"+g,X:b})});5.B("19",F(a){1i 5.z(a,"1j",{4:"w","U":"5-s"})});5.B("1o",F(k,f){3 r=f.D||"s";3 g=f.8||("s"+7(17+18*16.15(),10));3 e=f.4||"K";3 c=7(f.14||"0",10);3 n=7(f.Z||"0",10);3 m=7(f.S||"-1",10);3 a=f.R||"";3 j=7(f.x||"0",10);3 i=7(f.y||"0",10);3 l=7(f["6-x"]||"0",10);3 q=7(f["6-y"]||"-10",10);3 h=f.W||{"I-11":1,"I-T":"#1n","I-1t":9,V:P,"V-1x":1,"1y-T":"#1v #1u",1q:10,"6-y":2*q,"6-x":2*l,1r:"b",A:P,"A-1s":"1p","A-11":10};5.M(h);3 d={},p={};N(e){v"L":d={4:e,G:c,t:n};p={4:e,G:c,t:n,"6-x":l,"6-y":q};u;v"O":o(m!==-1){d={4:e,t:m};p={4:e,t:m,"6-x":l,"6-y":q}}H{o(a!==""){d={4:e,C:a};p={4:e,C:a,"6-x":l,"6-y":q}}}u;v"K":d={4:e,x:j,y:i};p={4:e,x:j,y:i,"6-x":l,"6-y":q};u}3 b={"U":"5-s",8:"5-s-"+g,D:r,E:d,"A-E":p};5.J(h,b);5.z(k,"1w",{4:"w",X:b})});',62,97,'|||var|type|zingchart|offset|parseInt|id||||||||||||||||if||||note|index|break|case|label|||exec|callout|extendAPI|value|text|hook|function|plot|else|border|copy|xy|node|normalize|switch|scale|true|_n_|scalevalue|scaleindex|color|class|shadow|style|data|null|nodeindex||width|removeobject|ZC|plotindex|random|Math|10000|89999|getnotes|annotations|length|removenote|for|instanceof|Array|push|api|return|getobjectsbyclass|setModule|updateobject|updatenote|666|addnote|bottom|padding|anchor|position|radius|eee|ccc|addobject|distance|background'.split('|'),0,{}));
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def get_unspent(listunspent, amount): for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount)) class RawTransactionsTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 4 def setup_network(self, split=False): self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() def run_test(self): print("Mining blocks...") min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee'] # This test is not meant to test fee estimation and we'd like # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) # if the fee's positive delta is higher than this value tests will fail, # neg. delta always fail the tests. # The size of the signature of every input may be at most 2 bytes larger # than a minimum sized signature. # = 2 bytes * minRelayTxFeePerByte feeTolerance = 2 * min_relay_tx_fee/1000 self.nodes[2].generate(1) self.sync_all() self.nodes[0].generate(121) self.sync_all() watchonly_address = self.nodes[0].getnewaddress() watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"] watchonly_amount = Decimal(200) self.nodes[3].importpubkey(watchonly_pubkey, "", True) watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount) self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.5) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0) self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 5.0) self.nodes[0].generate(1) self.sync_all() ############### # simple test # ############### inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) #test that we have enough inputs ############################## # simple test with two coins # ############################## inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.2 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) #test if we have enough inputs ############################## # simple test with two coins # ############################## inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.6 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ################################ # simple test with two outputs # ################################ inputs = [ ] outputs = { self.nodes[0].getnewaddress() : 2.6, self.nodes[1].getnewaddress() : 2.5 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert(len(dec_tx['vin']) > 0) assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '') ######################################################################### # test a fundrawtransaction with a VIN greater than the required amount # ######################################################################### utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee ##################################################################### # test a fundrawtransaction with which will not get a change output # ##################################################################### utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : Decimal(5.0) - fee - feeTolerance } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 for out in dec_tx['vout']: totalOut += out['value'] assert_equal(rawtxfund['changepos'], -1) assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee #################################################### # test a fundrawtransaction with an invalid option # #################################################### utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(4.0) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) try: self.nodes[2].fundrawtransaction(rawtx, {'foo': 'bar'}) raise AssertionError("Accepted invalid option foo") except JSONRPCException as e: assert("Unexpected key foo" in e.error['message']) ############################################################ # test a fundrawtransaction with an invalid change address # ############################################################ utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(4.0) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) try: self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': 'foobar'}) raise AssertionError("Accepted invalid pearlcoin address") except JSONRPCException as e: assert("changeAddress must be a valid pearlcoin address" in e.error['message']) ############################################################ # test a fundrawtransaction with a provided change address # ############################################################ utx = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']} ] outputs = { self.nodes[0].getnewaddress() : Decimal(4.0) } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) change = self.nodes[2].getnewaddress() try: rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 2}) except JSONRPCException as e: assert('changePosition out of bounds' == e.error['message']) else: assert(False) rawtxfund = self.nodes[2].fundrawtransaction(rawtx, {'changeAddress': change, 'changePosition': 0}) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) out = dec_tx['vout'][0]; assert_equal(change, out['scriptPubKey']['addresses'][0]) ######################################################################### # test a fundrawtransaction with a VIN smaller than the required amount # ######################################################################### utx = get_unspent(self.nodes[2].listunspent(), 1) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}] outputs = { self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) # 4-byte version + 1-byte vin count + 36-byte prevout then script_len rawtx = rawtx[:82] + "0100" + rawtx[84:] dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for i, out in enumerate(dec_tx['vout']): totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 else: assert_equal(i, rawtxfund['changepos']) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex']) assert_equal(matchingOuts, 1) assert_equal(len(dec_tx['vout']), 2) ########################################### # test a fundrawtransaction with two VINs # ########################################### utx = get_unspent(self.nodes[2].listunspent(), 1) utx2 = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 6.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for out in dec_tx['vout']: totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 assert_equal(matchingOuts, 1) assert_equal(len(dec_tx['vout']), 2) matchingIns = 0 for vinOut in dec_tx['vin']: for vinIn in inputs: if vinIn['txid'] == vinOut['txid']: matchingIns+=1 assert_equal(matchingIns, 2) #we now must see two vins identical to vins given as params ######################################################### # test a fundrawtransaction with two VINs and two vOUTs # ######################################################### utx = get_unspent(self.nodes[2].listunspent(), 1) utx2 = get_unspent(self.nodes[2].listunspent(), 5) inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ] outputs = { self.nodes[0].getnewaddress() : 6.0, self.nodes[0].getnewaddress() : 1.0 } rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(utx['txid'], dec_tx['vin'][0]['txid']) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) fee = rawtxfund['fee'] dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) totalOut = 0 matchingOuts = 0 for out in dec_tx['vout']: totalOut += out['value'] if out['scriptPubKey']['addresses'][0] in outputs: matchingOuts+=1 assert_equal(matchingOuts, 2) assert_equal(len(dec_tx['vout']), 3) ############################################## # test a fundrawtransaction with invalid vin # ############################################## listunspent = self.nodes[2].listunspent() inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin! outputs = { self.nodes[0].getnewaddress() : 1.0} rawtx = self.nodes[2].createrawtransaction(inputs, outputs) dec_tx = self.nodes[2].decoderawtransaction(rawtx) try: rawtxfund = self.nodes[2].fundrawtransaction(rawtx) raise AssertionError("Spent more than available") except JSONRPCException as e: assert("Insufficient" in e.error['message']) ############################################################ #compare fee of a standard pubkeyhash transaction inputs = [] outputs = {self.nodes[1].getnewaddress():1.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1.1) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a standard pubkeyhash transaction with multiple outputs inputs = [] outputs = {self.nodes[1].getnewaddress():1.1,self.nodes[1].getnewaddress():1.2,self.nodes[1].getnewaddress():0.1,self.nodes[1].getnewaddress():1.3,self.nodes[1].getnewaddress():0.2,self.nodes[1].getnewaddress():0.3} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendmany("", outputs) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a 2of2 multisig p2sh transaction # create 2of2 addr addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[1].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[1].validateaddress(addr2) mSigObj = self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) inputs = [] outputs = {mSigObj:1.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(mSigObj, 1.1) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ #compare fee of a standard pubkeyhash transaction # create 4of5 addr addr1 = self.nodes[1].getnewaddress() addr2 = self.nodes[1].getnewaddress() addr3 = self.nodes[1].getnewaddress() addr4 = self.nodes[1].getnewaddress() addr5 = self.nodes[1].getnewaddress() addr1Obj = self.nodes[1].validateaddress(addr1) addr2Obj = self.nodes[1].validateaddress(addr2) addr3Obj = self.nodes[1].validateaddress(addr3) addr4Obj = self.nodes[1].validateaddress(addr4) addr5Obj = self.nodes[1].validateaddress(addr5) mSigObj = self.nodes[1].addmultisigaddress(4, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey'], addr4Obj['pubkey'], addr5Obj['pubkey']]) inputs = [] outputs = {mSigObj:1.1} rawTx = self.nodes[0].createrawtransaction(inputs, outputs) fundedTx = self.nodes[0].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[0].sendtoaddress(mSigObj, 1.1) signedFee = self.nodes[0].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance) ############################################################ ############################################################ # spend a 2of2 multisig transaction over fundraw # create 2of2 addr addr1 = self.nodes[2].getnewaddress() addr2 = self.nodes[2].getnewaddress() addr1Obj = self.nodes[2].validateaddress(addr1) addr2Obj = self.nodes[2].validateaddress(addr2) mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) # send 1.2 BTC to msig addr txId = self.nodes[0].sendtoaddress(mSigObj, 1.2) self.sync_all() self.nodes[1].generate(1) self.sync_all() oldBalance = self.nodes[1].getbalance() inputs = [] outputs = {self.nodes[1].getnewaddress():1.1} rawTx = self.nodes[2].createrawtransaction(inputs, outputs) fundedTx = self.nodes[2].fundrawtransaction(rawTx) signedTx = self.nodes[2].signrawtransaction(fundedTx['hex']) txId = self.nodes[2].sendrawtransaction(signedTx['hex']) self.sync_all() self.nodes[1].generate(1) self.sync_all() # make sure funds are received at node1 assert_equal(oldBalance+Decimal('1.10000000'), self.nodes[1].getbalance()) ############################################################ # locked wallet test self.nodes[1].encryptwallet("test") self.nodes.pop(1) stop_nodes(self.nodes) self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) # This test is not meant to test fee estimation and we'd like # to be sure all txs are sent at a consistent desired feerate for node in self.nodes: node.settxfee(min_relay_tx_fee) connect_nodes_bi(self.nodes,0,1) connect_nodes_bi(self.nodes,1,2) connect_nodes_bi(self.nodes,0,2) connect_nodes_bi(self.nodes,0,3) self.is_network_split=False self.sync_all() # drain the keypool self.nodes[1].getnewaddress() inputs = [] outputs = {self.nodes[0].getnewaddress():1.1} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) # fund a transaction that requires a new key for the change output # creating the key must be impossible because the wallet is locked try: fundedTx = self.nodes[1].fundrawtransaction(rawTx) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: assert('Keypool ran out' in e.error['message']) #refill the keypool self.nodes[1].walletpassphrase("test", 100) self.nodes[1].walletlock() try: self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1.2) raise AssertionError("Wallet unlocked without passphrase") except JSONRPCException as e: assert('walletpassphrase' in e.error['message']) oldBalance = self.nodes[0].getbalance() inputs = [] outputs = {self.nodes[0].getnewaddress():1.1} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) #now we need to unlock self.nodes[1].walletpassphrase("test", 100) signedTx = self.nodes[1].signrawtransaction(fundedTx['hex']) txId = self.nodes[1].sendrawtransaction(signedTx['hex']) self.nodes[1].generate(1) self.sync_all() # make sure funds are received at node1 assert_equal(oldBalance+Decimal('51.10000000'), self.nodes[0].getbalance()) ############################################### # multiple (~19) inputs tx test | Compare fee # ############################################### #empty node1, send some small coins from node0 to node1 self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True) self.sync_all() self.nodes[0].generate(1) self.sync_all() for i in range(0,20): self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01) self.nodes[0].generate(1) self.sync_all() #fund a tx with ~20 small inputs inputs = [] outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) #create same transaction over sendtoaddress txId = self.nodes[1].sendmany("", outputs) signedFee = self.nodes[1].getrawmempool(True)[txId]['fee'] #compare fee feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee) assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs ############################################# # multiple (~19) inputs tx test | sign/send # ############################################# #again, empty node1, send some small coins from node0 to node1 self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True) self.sync_all() self.nodes[0].generate(1) self.sync_all() for i in range(0,20): self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01) self.nodes[0].generate(1) self.sync_all() #fund a tx with ~20 small inputs oldBalance = self.nodes[0].getbalance() inputs = [] outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04} rawTx = self.nodes[1].createrawtransaction(inputs, outputs) fundedTx = self.nodes[1].fundrawtransaction(rawTx) fundedAndSignedTx = self.nodes[1].signrawtransaction(fundedTx['hex']) txId = self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex']) self.sync_all() self.nodes[0].generate(1) self.sync_all() assert_equal(oldBalance+Decimal('50.19000000'), self.nodes[0].getbalance()) #0.19+block reward ##################################################### # test fundrawtransaction with OP_RETURN and no vin # ##################################################### rawtx = "0100000000010000000000000000066a047465737400000000" dec_tx = self.nodes[2].decoderawtransaction(rawtx) assert_equal(len(dec_tx['vin']), 0) assert_equal(len(dec_tx['vout']), 1) rawtxfund = self.nodes[2].fundrawtransaction(rawtx) dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex']) assert_greater_than(len(dec_tx['vin']), 0) # at least one vin assert_equal(len(dec_tx['vout']), 2) # one change output added ################################################## # test a fundrawtransaction using only watchonly # ################################################## inputs = [] outputs = {self.nodes[2].getnewaddress() : watchonly_amount / 2} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = self.nodes[3].fundrawtransaction(rawtx, {'includeWatching': True }) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 1) assert_equal(res_dec["vin"][0]["txid"], watchonly_txid) assert("fee" in result.keys()) assert_greater_than(result["changepos"], -1) ############################################################### # test fundrawtransaction using the entirety of watched funds # ############################################################### inputs = [] outputs = {self.nodes[2].getnewaddress() : watchonly_amount} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) # Backward compatibility test (2nd param is includeWatching) result = self.nodes[3].fundrawtransaction(rawtx, True) res_dec = self.nodes[0].decoderawtransaction(result["hex"]) assert_equal(len(res_dec["vin"]), 2) assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid) assert_greater_than(result["fee"], 0) assert_greater_than(result["changepos"], -1) assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10) signedtx = self.nodes[3].signrawtransaction(result["hex"]) assert(not signedtx["complete"]) signedtx = self.nodes[0].signrawtransaction(signedtx["hex"]) assert(signedtx["complete"]) self.nodes[0].sendrawtransaction(signedtx["hex"]) self.nodes[0].generate(1) self.sync_all() ####################### # Test feeRate option # ####################### # Make sure there is exactly one input so coin selection can't skew the result assert_equal(len(self.nodes[3].listunspent(1)), 1) inputs = [] outputs = {self.nodes[2].getnewaddress() : 1} rawtx = self.nodes[3].createrawtransaction(inputs, outputs) result = self.nodes[3].fundrawtransaction(rawtx) # uses min_relay_tx_fee (set by settxfee) result2 = self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 2*min_relay_tx_fee}) result3 = self.nodes[3].fundrawtransaction(rawtx, {"feeRate": 10*min_relay_tx_fee}) result_fee_rate = result['fee'] * 1000 / count_bytes(result['hex']) assert_fee_amount(result2['fee'], count_bytes(result2['hex']), 2 * result_fee_rate) assert_fee_amount(result3['fee'], count_bytes(result3['hex']), 10 * result_fee_rate) if __name__ == '__main__': RawTransactionsTest().main()
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/config/ConfigService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/config/model/OrganizationConfigRule.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace ConfigService { namespace Model { class AWS_CONFIGSERVICE_API DescribeOrganizationConfigRulesResult { public: DescribeOrganizationConfigRulesResult(); DescribeOrganizationConfigRulesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); DescribeOrganizationConfigRulesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline const Aws::Vector<OrganizationConfigRule>& GetOrganizationConfigRules() const{ return m_organizationConfigRules; } /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline void SetOrganizationConfigRules(const Aws::Vector<OrganizationConfigRule>& value) { m_organizationConfigRules = value; } /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline void SetOrganizationConfigRules(Aws::Vector<OrganizationConfigRule>&& value) { m_organizationConfigRules = std::move(value); } /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline DescribeOrganizationConfigRulesResult& WithOrganizationConfigRules(const Aws::Vector<OrganizationConfigRule>& value) { SetOrganizationConfigRules(value); return *this;} /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline DescribeOrganizationConfigRulesResult& WithOrganizationConfigRules(Aws::Vector<OrganizationConfigRule>&& value) { SetOrganizationConfigRules(std::move(value)); return *this;} /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline DescribeOrganizationConfigRulesResult& AddOrganizationConfigRules(const OrganizationConfigRule& value) { m_organizationConfigRules.push_back(value); return *this; } /** * <p>Returns a list of <code>OrganizationConfigRule</code> objects.</p> */ inline DescribeOrganizationConfigRulesResult& AddOrganizationConfigRules(OrganizationConfigRule&& value) { m_organizationConfigRules.push_back(std::move(value)); return *this; } /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline void SetNextToken(const Aws::String& value) { m_nextToken = value; } /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); } /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline void SetNextToken(const char* value) { m_nextToken.assign(value); } /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline DescribeOrganizationConfigRulesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline DescribeOrganizationConfigRulesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>The <code>nextToken</code> string returned on a previous page that you use to * get the next page of results in a paginated response. </p> */ inline DescribeOrganizationConfigRulesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::Vector<OrganizationConfigRule> m_organizationConfigRules; Aws::String m_nextToken; }; } // namespace Model } // namespace ConfigService } // namespace Aws
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. 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. import unittest from cm_api.endpoints.clusters import * from cm_api.endpoints.types import * from cm_api_tests import utils class TestCluster(unittest.TestCase): def test_add_hosts(self): resource = utils.MockResource(self) cluster = ApiCluster(resource, name="foo") data = ApiList([ ApiHostRef(resource, hostId='foo') ]) resource.expect("POST", "/clusters/foo/hosts", data=data, retdata={ 'items' : [ { 'hostId' : 'foo' } ] }) cluster.add_hosts(['foo']) def test_update_cdh_version(self): resource = utils.MockResource(self) cluster = ApiCluster(resource, name="foo") data = ApiCluster(resource, name='foo', fullVersion='4.2.1') resource.expect("PUT", "/clusters/foo", data=data, retdata={ 'name' : 'foo'}) cluster.update_cdh_version('4.2.1') def test_upgrade_cdh(self): resource = utils.MockResource(self) cluster = ApiCluster(resource, name="foo") data = dict() data['deployClientConfig'] = False data['startAllServices'] = True data['cdhParcelVersion'] = '5.0.0.1-cdh5-1.2.3' resource.expect("POST", "/clusters/foo/commands/upgradeCdh", data=data, retdata={ 'name' : 'foo'}) cluster.upgrade_cdh(False, True, data['cdhParcelVersion']) def test_restart(self): resource = utils.MockResource(self, version=5) cluster = ApiCluster(resource, name="foo") resource.expect( method="POST", reqpath="/clusters/foo/commands/restart", data=None, retdata={'name' : 'foo'}) cluster.restart(); resource = utils.MockResource(self, version=7) newCluster = ApiCluster(resource, name="bar") data = dict() data['restartOnlyStaleServices'] = False data['redeployClientConfiguration'] = True resource.expect( method="POST", reqpath="/clusters/bar/commands/restart", data=data, retdata={'name' : 'bar'}) newCluster.restart(False, True);
/* * Kendo UI v2014.3.1411 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ !function(e,define){define(["./kendo.core.min"],e)}(function(){return function(e,t){function n(n){var i=e(n.useButtonTag?"<button></button>":"<a></a>");return i.data({type:"button"}),i.attr($,n.uid),n.attributes&&i.attr(n.attributes),n.togglable&&(i.addClass(m),n.selected&&i.addClass(x)),n.enable===!1&&i.addClass(k),n.url===t||n.useButtonTag||(i.attr("href",n.url),n.mobile&&i.attr(c.attr("role"),"button")),n.group&&i.attr(c.attr("group"),n.group),!n.togglable&&n.click&&h(n.click)&&i.data("click",n.click),n.togglable&&n.toggle&&h(n.toggle)&&i.data("toggle",n.toggle),i}function i(e){var t,n=Y.button.base(e);return n.addClass(p),e.primary&&n.addClass(T),e.align&&n.addClass("k-align-"+e.align),e.id&&n.attr("id",e.id),"overflow"!=e.showText&&e.text&&n.html(e.mobile?'<span class="km-text">'+e.text+"</span>":e.text),t="overflow"!=e.showIcon&&(e.icon||e.spriteCssClass||e.imageUrl),t&&o(e,n),n}function r(e){var t,n=Y.button.base(e);return n.addClass(g+" "+p),e.primary&&n.addClass(T),e.id&&n.attr("id",e.id+"_overflow"),"toolbar"!=e.showText&&e.text&&n.html(e.mobile?'<span class="km-text">'+e.text+"</span>":e.text),t="toolbar"!=e.showIcon&&(e.icon||e.spriteCssClass||e.imageUrl),t&&o(e,n),n}function o(t,n){var i,r,o,a=t.icon,s=t.spriteCssClass,l=t.imageUrl;(s||l||a)&&(i=!0,n.contents().not("span.k-sprite,span."+A+",img.k-image").each(function(t,n){(1==n.nodeType||3==n.nodeType&&e.trim(n.nodeValue).length>0)&&(i=!1)}),n.addClass(i?M:E)),a?(r=n.children("span."+A).first(),r[0]||(r=e('<span class="'+A+'"></span>').prependTo(n)),r.addClass(D+a)):s?(r=n.children("span.k-sprite").first(),r[0]||(r=e('<span class="k-sprite"></span>').prependTo(n)),r.addClass(s)):l&&(o=n.children("img.k-image").first(),o[0]||(o=e('<img alt="icon" class="k-image" />').prependTo(n)),o.attr("src",l))}function a(){var e,t=this.options.anchor,n=t.outerWidth();c.wrap(this.element).addClass("k-split-wrapper"),e="border-box"!==this.element.css("box-sizing")?n-(this.element.outerWidth()-this.element.width()):n,this.element.css({fontFamily:t.css("font-family"),"min-width":e})}function s(e){e.target.is(".k-toggle-button")||e.target.toggleClass(x,"press"==e.type)}function l(t){return t=e(t),t.hasClass("km-actionsheet")?t.closest(".km-popup-wrapper"):t.addClass("km-widget km-actionsheet").wrap('<div class="km-actionsheet-wrapper km-actionsheet-tablet km-widget km-popup"></div>').parent().wrap('<div class="km-popup-wrapper k-popup"></div>').parent()}var c=window.kendo,d=c.ui.Widget,u=e.proxy,h=c.isFunction,f="k-toolbar",p="k-button",g="k-overflow-button",m="k-toggle-button",v="k-button-group",_="k-split-button",y="k-separator",w="k-popup",b="k-toolbar-resizable",x="k-state-active",k="k-state-disabled",S="k-group-start",C="k-group-end",T="k-primary",A="k-icon",D="k-i-",M="k-button-icon",E="k-button-icontext",P="k-list-container k-split-container",z="k-split-button-arrow",I="k-overflow-anchor",B="k-overflow-container",L="k-toolbar-first-visible",R="k-toolbar-last-visible",F="click",O="toggle",N="open",H="close",V="overflowOpen",U="overflowClose",W="never",j="auto",G="always",q="k-overflow-hidden",$=c.attr("uid"),Y={button:{base:n,toolbar:i,overflow:r},buttonGroup:{base:function(t,n,i){var r,o,a=t.buttons;if(a){for(t.attributes&&i.attr(t.attributes),i.data({type:"buttonGroup"}),i.attr($,t.uid),o=0;a.length>o;o++)a[o].uid||(a[o].uid=c.guid()),r=n(e.extend({mobile:t.mobile},a[o])),r.appendTo(i);i.children().first().addClass(S),i.children().last().addClass(C)}},toolbar:function(t){var n=e("<div></div>");return Y.buttonGroup.base(t,Y.button.toolbar,n),n.addClass(v),t.align&&n.addClass("k-align-"+t.align),t.id&&n.attr("id",t.id),n},overflow:function(t){var n=e("<li></li>");return Y.buttonGroup.base(t,Y.button.overflow,n),n.addClass((t.mobile?"":v)+" k-overflow-group"),t.id&&n.attr("id",t.id+"_overflow"),n}},splitButton:{toolbar:function(t){var n,i,r,o=e('<div class="'+_+'"></div>'),s=Y.button.toolbar(t),c=e('<a class="'+p+" "+z+'"><span class="'+(t.mobile?"km-icon km-arrowdown":"k-icon k-i-arrow-s")+'"></span></a>'),d=e('<ul class="'+P+'"></ul>'),u=t.menuButtons;for(s.appendTo(o),c.appendTo(o),d.appendTo(o),r=0;u.length>r;r++)i=Y.button.toolbar(e.extend({mobile:t.mobile,click:t.click},u[r])),i.wrap("<li></li>").parent().appendTo(d);return t.align&&o.addClass("k-align-"+t.align),t.id||(t.id=t.uid),o.attr("id",t.id+"_wrapper"),d.attr("id",t.id+"_optionlist").attr($,t.rootUid),t.mobile&&(d=l(d)),n=d.kendoPopup({appendTo:t.mobile?e(t.mobile).children(".km-pane"):null,anchor:o,copyAnchorStyles:!1,animation:t.animation,open:a}).data("kendoPopup"),o.data({type:"splitButton",kendoPopup:n}),o.attr($,t.uid),o},overflow:function(t){var n,i,r=e('<li class="'+_+'"></li>'),o=Y.button.overflow(t),a=t.menuButtons;for(o.appendTo(r),i=0;a.length>i;i++)n=Y.button.overflow(e.extend({mobile:t.mobile},a[i])),n.appendTo(r);return r.data({type:"splitButton"}),r.attr($,t.uid),r}},separator:{base:function(t,n){var i=e(n?"<li>&nbsp;</li>":"<div>&nbsp;</div>");return i.data({type:"separator"}),i.attr($,t.uid),t.attributes&&i.attr(t.attributes),i.addClass(y),i},toolbar:function(e){var t=Y.separator.base(e,!1);return e.id&&t.attr("id",e.id),t},overflow:function(e){var t=Y.separator.base(e,!0);return e.id&&t.attr("id",e.id+"_overflow"),t}},overflowAnchor:'<div class="k-overflow-anchor"></div>',overflowContainer:'<ul class="k-overflow-container k-list-container"></ul>'},K=d.extend({init:function(t,n){var i,r=this;if(d.fn.init.call(r,t,n),n=r.options,t=r.wrapper=r.element,t.addClass(f+" k-widget"),this.uid=c.guid(),t.attr($,this.uid),r.isMobile="boolean"==typeof n.mobile?n.mobile:r.element.closest(".km-root")[0],r.animation=r.isMobile?{open:{effects:"fade"}}:{},r.isMobile&&(t.addClass("km-widget"),A="km-icon",D="km-",p="km-button",v="km-buttongroup km-widget",x="km-state-active",k="km-state-disabled"),n.resizable?(r._renderOverflow(),t.addClass(b),r.overflowUserEvents=new c.UserEvents(r.element,{threshold:5,allowSelection:!0,filter:"."+I,tap:u(r._toggleOverflow,r)}),c.onResize(function(){r.resize()})):r.popup={element:e([])},n.items&&n.items.length)for(i=0;n.items.length>i;i++)r.add(n.items[i]);r.userEvents=new c.UserEvents(document,{threshold:5,allowSelection:!0,filter:"["+$+"="+this.uid+"] ."+p+", ["+$+"="+this.uid+"] ."+g,tap:u(r._buttonClick,r),press:s,release:s}),n.resizable&&this._toggleOverflowAnchor(),c.notify(r)},events:[F,O,N,H,V,U],options:{name:"ToolBar",items:[],resizable:!0,mobile:null},destroy:function(){var t=this;t.element.find("."+_).each(function(t,n){e(n).data("kendoPopup").destroy()}),t.userEvents.destroy(),t.options.resizable&&(t.overflowUserEvents.destroy(),t.popup.destroy()),d.fn.destroy.call(t)},add:function(t){var n,i,r=Y[t.type],o=t.template,a=this,s=a.isMobile?"":"k-item k-state-default",l=t.overflowTemplate;e.extend(t,{uid:c.guid(),animation:a.animation,mobile:a.isMobile,rootUid:a.uid}),o&&!l&&(t.overflow=W),t.overflow!==W&&a.options.resizable&&(l?(i=e(h(l)?l(t):l),t.id&&i.attr("id",t.id+"_overflow")):r&&(i=(r.overflow||e.noop)(t)),i&&i.length&&("LI"!==i.prop("tagName")&&(i.removeAttr($),i=i.wrap("<li></li>").parent(),i.attr($,t.uid)),a._attributes(i,t),i.addClass(s).appendTo(a.popup.container),i.data("overflow")===j&&i.addClass(q),a.angular("compile",function(){return{elements:i.get()}}))),t.overflow!==G&&(o?(n=h(o)?o(t):o,n instanceof jQuery||(n=e(n.replace(/^\s+|\s+$/g,""))),n=n.wrap("<div></div>").parent(),t.id&&n.attr("id",t.id),t.attributes&&n.attr(t.attributes),n.attr($,t.uid)):r&&(n=(r.toolbar||e.noop)(t)),n&&n.length&&(a._attributes(n,t),a.options.resizable?(n.appendTo(a.element).css("visibility","hidden"),a._shrink(a.element.innerWidth()),n.css("visibility","visible")):n.appendTo(a.element),a.angular("compile",function(){return{elements:n.get()}})))},remove:function(t){var n,i,r,o,a=this.options.resizable;n=this.element.find(t),a&&(i=this.popup.element.find(t)),n.length?(r=n.data("type"),o=n.attr($),"splitButton"===n.parent("."+_).data("type")&&(r="splitButton",n=n.parent()),i=a?this.popup.element.find("li["+$+"='"+o+"']"):e([])):i.length&&(r=i.data("type"),i=i.parent(),"splitButton"===i.data("type")&&(r="splitButton"),o=i.attr($),n=this.element.find("div."+_+"["+$+"='"+o+"']")),"splitButton"===r&&n.data("kendoPopup")&&n.data("kendoPopup").destroy(),n.remove(),i.remove()},enable:function(n,i){var r=this.element.find(n).attr($);!r&&this.popup&&(r=this.popup.element.find(n).parent("li").attr($)),t===i&&(i=!0),i?e("["+$+"='"+r+"']").removeClass(k):e("["+$+"='"+r+"']").addClass(k)},getSelectedFromGroup:function(e){return this.element.find("."+m+"[data-group='"+e+"']").filter("."+x)},toggle:function(t,n){var i,r=e(t),o=r.data("uid"),a=r.data("group");r.hasClass(m)&&(a&&this.element.add(this.popup.element).find("."+m+"[data-group='"+a+"']").filter("."+x).removeClass(x),e.contains(this.element[0],r[0])?(i=this.popup.element.find("["+$+"='"+o+"']"),"LI"===i.prop("tagName")&&(i=i.find("."+m+":first"))):(o=o?o:r.parent().data("uid"),i=this.element.find("["+$+"='"+o+"']")),r.add(i).toggleClass(x,n))},_attributes:function(e,t){e.attr(c.attr("overflow"),t.overflow||j)},_renderOverflow:function(){var t=this,n=Y.overflowContainer;t.overflowAnchor=e(Y.overflowAnchor).addClass(p),t.element.append(t.overflowAnchor),t.isMobile?(t.overflowAnchor.append('<span class="km-icon km-more"></span>'),n=l(n)):t.overflowAnchor.append('<span class="k-icon k-i-more"></span>'),t.popup=new c.ui.Popup(n,{origin:"bottom right",position:"top right",anchor:t.overflowAnchor,animation:t.animation,appendTo:t.isMobile?e(t.isMobile).children(".km-pane"):null,copyAnchorStyles:!1,open:function(n){var i=c.wrap(t.popup.element).addClass("k-overflow-wrapper");t.isMobile?t.popup.container.css("max-height",parseFloat(e(".km-content:visible").innerHeight())-15+"px"):i.css("margin-left",(i.outerWidth()-i.width())/2+1),t.trigger(V)&&n.preventDefault()},close:function(e){t.trigger(U)&&e.preventDefault()}}),t.popup.container=t.isMobile?t.popup.element.find("."+B):t.popup.element,t.popup.container.attr($,this.uid)},_toggleOverflowAnchor:function(){this.overflowAnchor.css(this.popup.element.children(":not(."+q+", ."+w+")").length>0?{visibility:"visible",width:""}:{visibility:"hidden",width:"1px"})},_buttonClick:function(n){var i,r,o,a,s,l,c,d,u,f=this;if(n.preventDefault(),r=e(n.target).closest("."+p,f.element),!r.hasClass(I)&&(!r.length&&f.popup&&(r=e(n.target).closest("."+g,f.popup.container)),a=r.hasClass(g)?r.parent("li").hasClass(k):r.hasClass(k),!a)){if(n.target.closest("."+z).length)return f._toggle(n),t;u=r.attr("id")?r.attr("id").replace(/(_overflow$)/,""):t,r.hasClass(m)?(l=r.data("group"),c=h(r.data("toggle"))?r.data("toggle"):null,f.toggle(r),s=r.hasClass(x),d={target:r,group:l,checked:s,id:u},c&&c.call(f,d),f.trigger(O,d)):(c=h(r.data("click"))?r.data("click"):null,d={target:r,id:u},c&&c.call(f,d),f.trigger(F,d)),r.hasClass(g)&&f.popup.close(),o=r.closest(".k-split-container"),o[0]&&(i=o.data("kendoPopup"),(i?i:o.parents(".km-popup-wrapper").data("kendoPopup")).close())}},_toggle:function(t){var n,i=e(t.target).closest("."+_),r=i.data("kendoPopup");t.preventDefault(),i.hasClass(k)||(n=r.element.is(":visible")?this.trigger(H,{target:i}):this.trigger(N,{target:i}),n||r.toggle())},_toggleOverflow:function(){this.popup.toggle()},_resize:function(e){var t=e.width;this.options.resizable&&(this.popup.close(),this._shrink(t),this._stretch(t),this._markVisibles(),this._toggleOverflowAnchor())},_childrenWidth:function(){var t=0;return this.element.children(":visible").each(function(){t+=e(this).outerWidth(!0)}),Math.ceil(t)},_shrink:function(e){var t,n,i;if(e<this._childrenWidth())for(n=this.element.children(":visible:not([data-overflow='never'], ."+I+")"),i=n.length-1;i>=0&&(t=n.eq(i),!(e>this._childrenWidth()));i--)this._hideItem(t)},_stretch:function(e){var t,n,i;if(e>this._childrenWidth())for(n=this.element.children(":hidden"),i=0;n.length>i&&(t=n.eq(i),!(e<this._childrenWidth())&&this._showItem(t,e));i++);},_hideItem:function(e){e.hide(),this.popup&&this.popup.container.find(">li[data-uid='"+e.data("uid")+"']").removeClass(q)},_showItem:function(e,t){return e.length&&t>this._childrenWidth()+e.outerWidth(!0)?(e.show(),this.popup&&this.popup.container.find(">li[data-uid='"+e.data("uid")+"']").addClass(q),!0):!1},_markVisibles:function(){var e=this.popup.container.children(),t=this.element.children(":not(.k-overflow-anchor)"),n=e.filter(":not(.k-overflow-hidden)"),i=t.filter(":visible");e.add(t).removeClass(L+" "+R),n.first().add(i.first()).addClass(L),n.last().add(i.last()).addClass(R)}});c.ui.plugin(K)}(window.kendo.jQuery),window.kendo},"function"==typeof define&&define.amd?define:function(e,t){t()});
// Copyright IBM Corp. 2014,2016. All Rights Reserved. // Node module: strong-remoting // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 var g = require('strong-globalize')(); /*! * Expose `HttpInvocation`. */ module.exports = HttpInvocation; /*! * Module dependencies. */ var EventEmitter = require('events').EventEmitter; var debug = require('debug')('strong-remoting:http-invocation'); var util = require('util'); var inherits = util.inherits; var path = require('path'); var assert = require('assert'); var request = require('request'); var ContextBase = require('./context-base'); var SUPPORTED_TYPES = ['json', 'application/javascript', 'text/javascript']; var qs = require('qs'); var urlUtil = require('url'); var ReadableStream = require('stream').Readable; var MuxDemux = require('mux-demux'); /*! * JSON Types */ var JSON_TYPES = ['boolean', 'string', 'object', 'number']; /** * Create a new `HttpInvocation`. * @class * @param {SharedMethod} method * @param {Array} [args] * @param {String} base The base URL * @property {String} base The base URL * @property {SharedMethod} method The `SharedMethod` which will be invoked * @property {Array} args The arguments to be used when invoking the `SharedMethod` */ function HttpInvocation(method, ctorArgs, args, baseUrl, auth, typeRegistry) { this.base = baseUrl; this.auth = auth; this.method = method; this.args = args || []; this.ctorArgs = ctorArgs || []; this.typeRegistry = typeRegistry; this.isStatic = (method.hasOwnProperty('isStatic') && method.isStatic) || (method.hasOwnProperty('sharedMethod') && method.sharedMethod.isStatic); var namedArgs = this.namedArgs = {}; var val; if (!this.isStatic) { method.restClass.ctor.accepts.forEach(function(accept) { val = ctorArgs.shift(); if (HttpInvocation.isAcceptable(val, accept)) { namedArgs[accept.arg || accept.name] = val; } }); } method.accepts.forEach(function(accept) { val = args.shift(); if (HttpInvocation.isAcceptable(val, accept)) { namedArgs[accept.arg || accept.name] = val; } }); this.context = new ContextBase(method, typeRegistry); } /** * Inherit from `EventEmitter`. */ inherits(HttpInvocation, EventEmitter); /** * Determine if the value matches the given accept definition. */ HttpInvocation.isAcceptable = function(val, accept) { var acceptArray = Array.isArray(accept.type) || accept.type.toLowerCase() === 'array'; var type = acceptArray ? 'array' : accept.type && accept.type.toLowerCase(); var strict = type && type !== 'any'; if (acceptArray) { return Array.isArray(val); } if (strict) { if (JSON_TYPES.indexOf(type) === -1) { return typeof val === 'object'; } return (typeof val).toLowerCase() === type; } else { return true; } }; HttpInvocation.prototype._processArg = function(req, verb, query, accept) { var httpFormat = accept.http; var name = accept.name || accept.arg; var val = this.getArgByName(name); if (httpFormat) { switch (typeof httpFormat) { case 'function': // ignore defined formatter break; case 'object': switch (httpFormat.source) { case 'body': req.body = val; break; case 'form': case 'formData': // From the form (body) req.body = req.body || {}; req.body[name] = val; break; case 'query': // From the query string if (val !== undefined) { query = query || {}; query[name] = val; } break; case 'header': if (val !== undefined) { req.headers = req.headers || {}; req.headers[name] = val; } break; case 'path': // From the url path req.url = req.url.replace(':' + name, val); break; } break; } } else if (verb.toLowerCase() === 'get') { // default to query string for GET if (val !== undefined) { query = query || {}; query[name] = val; } } else { // default to storing args on the body for !GET req.body = req.body || {}; req.body[name] = val; } return query; }; /** * Build args object from the http context's `req` and `res`. */ HttpInvocation.prototype.createRequest = function() { var method = this.method; var endpoint = method.getEndpoints()[0]; var verb = endpoint.verb; var req = this.req = { method: verb || 'GET' }; var accepts = method.accepts; var ctorAccepts = null; var query, i; var auth = this.auth; // initial url is the format req.url = this.base + endpoint.fullPath; var parsedUrl = urlUtil.parse(req.url); req.protocol = parsedUrl.protocol; // the body is json req.json = true; // add auth if it is set if (auth) { req.auth = {}; if (auth.username && auth.password) { req.auth.username = auth.username; req.auth.password = auth.password; } if (auth.bearer) { req.auth.bearer = auth.bearer; } if ('sendImmediately' in auth) { req.auth.sendImmediately = auth.sendImmediately; } else { req.auth.sendImmediately = false; } } // build request args and method options if (!this.isStatic) { ctorAccepts = method.restClass.ctor.accepts; for (i in ctorAccepts) { query = this._processArg(req, verb, query, ctorAccepts[i]); } } for (i in accepts) { query = this._processArg(req, verb, query, accepts[i]); } if (query) { req.url += '?' + qs.stringify(query); } return req; }; /** * Get an argument value by name. * * @param {String} name * @returns {*} Value of specified argument. */ HttpInvocation.prototype.getArgByName = function(name) { return this.namedArgs[name]; }; /** * Start the invocation. */ HttpInvocation.prototype.invoke = function(callback) { var self = this; if (!this.req) { this.createRequest(); } var method = this.method; var returnStreamDesc = method.sharedMethod.streams && method.sharedMethod.streams.returns; var methodReturnsStream = !!returnStreamDesc; if (methodReturnsStream) { if (returnStreamDesc.type === 'ReadableStream' && returnStreamDesc.json) { var mdm = new MuxDemux(); mdm.on('connection', function(stream) { callback(null, stream); }); request(this.req).pipe(mdm); } else { callback(new Error(g.f('unsupported stream type'))); } return; } request(this.req, function(err, res, body) { if (err instanceof SyntaxError) { if (res.status === 204) err = null; } if (err) return callback(err); self.res = self.context.res = res; self.transformResponse(res, body, callback); }); }; /* * Get Response object */ HttpInvocation.prototype.getResponse = function() { return this.res || null; }; /** * Transform the response into callback arguments * @param {HttpResponse} res * @param {Function} callback */ HttpInvocation.prototype.transformResponse = function(res, body, callback) { var self = this; var callbackArgs = [null]; // null => placeholder for err var method = this.method; var returns = method.returns; var isObject = typeof body === 'object'; var err; var hasError = res.statusCode >= 400; if (hasError) { if (isObject && body.error) { err = new Error(body.error.message); /* eslint-disable one-var */ for (var key in body.error) { err[key] = body.error[key]; } /* eslint-enable one-var */ } else { err = new Error(g.f('Error: %d', res.statusCode)); err.statusCode = res.statusCode; err.details = body; } return callback(err); } // build request args and method options for (var i = 0, n = returns.length; i < n; i++) { var ret = returns[i]; // eslint-disable-line one-var var name = ret.name || ret.arg; // eslint-disable-line one-var var val; // eslint-disable-line one-var var type = ret.type; // eslint-disable-line one-var if (ret.root) { val = res.body; } else { val = res.body[name]; } var converter = this.typeRegistry.getConverter(type); var result = converter.fromTypedValue(this.context, val); debug('return arg %j: converted %j to %j', name, val, result); if (result.error) { err = result.error; err.message = g.f('Invalid return argument %j. ', name) + err.message; return callback(err); } callbackArgs.push(result.value); /* eslint-enable one-var */ } callback.apply(this, callbackArgs); };
$("#modal-close").click(function() { $(".modal").removeClass("is-active"); }); $("#location-info").click(function() { $(".modal").addClass("is-active"); }); let incrementButton = $(".increment-button"); let decrementButton = $(".decrement-button"); let index=-1; let queryURL = "https://developer.nps.gov/api/v1/parks?stateCode=MD&limit=5&api_key=C20X2gP148EDeslk7stqM8BU6u6WmOqbAdPeKG8C"; let npsResponse; let fullName; let contactEmail; let contactPhone; let directionInfo; let directionURL; let standardHoursMonday; let standardHoursTuesday; let standardHoursWednesday; let standardHoursThursday; let standardHoursFriday; let standardHoursSaturday; let standardHoursSunday; let latitude; let longitude; let description; let addressType1; let addressType2; let addressLine1; let addressLine2; let addressLine3; let addressCity; let addressZip; let addressState; let displayAddress; let addressIndex; // helper functions // returns index of physical address - if first one is "physical", sets to 0, if second is "physical", sets to 1 function determinePhysical(addressType1,addressType2) { if (addressType1 == "Physical") { return addressIndex=0; } else { return addressIndex=1; } } incrementButton.on("click",function(){ index++; $.ajax({ // url: queryURL, method: "GET" }).then(function(response){ console.log(response); npsResponse=response; fullName = response.data[index].fullName; contactEmail = response.data[index].contacts["emailAddresses"][0].emailAddress; contactPhone = response.data[index].contacts.phoneNumbers[0].phoneNumber; directionInfo=response.data[index].directionsInfo; directionURL=response.data[index].directionsUrl; standardHoursMonday=response.data[index].operatingHours[0].standardHours.monday; standardHoursTuesday=response.data[index].operatingHours[0].standardHours.tuesday; standardHoursWednesday=response.data[index].operatingHours[0].standardHours.wednesday; standardHoursThursday=response.data[index].operatingHours[0].standardHours.thursday; standardHoursFriday=response.data[index].operatingHours[0].standardHours.friday; standardHoursSaturday=response.data[index].operatingHours[0].standardHours.saturday; standardHoursSunday=response.data[index].operatingHours[0].standardHours.sunday; latitude=response.data[index].latitude; longitude=response.data[index].longitude; description = response.data[index].description; addressType1=response.data[index].addresses[0].type; addressType2=response.data[index].addresses[1].type; // determine these based on the result from determinePhysical -> use this as the index console.log(determinePhysical(addressType1,addressType2)); addressLine1=response.data[index].addresses[determinePhysical(addressType1,addressType2)].line1; addressLine2=response.data[index].addresses[determinePhysical(addressType1,addressType2)].line2; addressLine3=response.data[index].addresses[determinePhysical(addressType1,addressType2)].line3; addressCity=response.data[index].addresses[determinePhysical(addressType1,addressType2)].city; addressZip=response.data[index].addresses[determinePhysical(addressType1,addressType2)].postalCode; addressState=response.data[index].addresses[determinePhysical(addressType1,addressType2)].stateCode; console.log("fullname: " + fullName + "\nEmail: " + contactEmail + "\nPhone: " + contactPhone + "\nDirections: " + directionInfo + "\nLink to Directions: " + directionURL); console.log("latitude: " + latitude + "\nlongitude: " + longitude + "\nDescription: " + description); console.log("Monday hours " + standardHoursMonday + "\nTuesday hours " + standardHoursTuesday +"\nWednesday hours " + standardHoursWednesday + "\nThursday hours " + standardHoursThursday + "\nFriday hours " + standardHoursFriday +"\nSaturday hours " + standardHoursSaturday + "\nSunday Hours " + standardHoursSunday) console.log("Address: " + "\n" + addressLine1 + "\n" + addressCity + " " + addressState + " " + addressZip); }) }) decrementButton.on("click",function(){ index--; if (index < 0) { index = 0; } $.ajax({ // url: queryURL, method: "GET" }).then(function(response){ // console.log(response); npsResponse=response; fullName = response.data[index].fullName; contactEmail = response.data[index].contacts["emailAddresses"][0].emailAddress; contactPhone = response.data[index].contacts.phoneNumbers[0].phoneNumber; directionInfo=response.data[index].directionsInfo; directionURL=response.data[index].directionsUrl; standardHoursMonday=response.data[index].operatingHours[0].standardHours.monday; standardHoursTuesday=response.data[index].operatingHours[0].standardHours.tuesday; standardHoursWednesday=response.data[index].operatingHours[0].standardHours.wednesday; standardHoursThursday=response.data[index].operatingHours[0].standardHours.thursday; standardHoursFriday=response.data[index].operatingHours[0].standardHours.friday; standardHoursSaturday=response.data[index].operatingHours[0].standardHours.saturday; standardHoursSunday=response.data[index].operatingHours[0].standardHours.sunday; latitude=response.data[index].latitude; longitude=response.data[index].longitude; description = response.data[index].description; addressType1=response.data[index].addresses[0].type; addressType2=response.data[index].addresses[1].type; // determine these based on the result from determinePhysical -> use this as the index console.log(determinePhysical(addressType1,addressType2)); addressLine1=response.data[index].addresses[determinePhysical(addressType1,addressType2)].line1; addressLine2=response.data[index].addresses[determinePhysical(addressType1,addressType2)].line2; addressLine3=response.data[index].addresses[determinePhysical(addressType1,addressType2)].line3; addressCity=response.data[index].addresses[determinePhysical(addressType1,addressType2)].city; addressZip=response.data[index].addresses[determinePhysical(addressType1,addressType2)].postalCode; addressState=response.data[index].addresses[determinePhysical(addressType1,addressType2)].stateCode; console.log("fullname: " + fullName + "\nEmail: " + contactEmail + "\nPhone: " + contactPhone + "\nDirections: " + directionInfo + "\nLink to Directions: " + directionURL); console.log("latitude: " + latitude + "\nlongitude: " + longitude + "\nDescription: " + description); console.log("Monday hours " + standardHoursMonday + "\nTuesday hours " + standardHoursTuesday +"\nWednesday hours " + standardHoursWednesday + "\nThursday hours " + standardHoursThursday + "\nFriday hours " + standardHoursFriday +"\nSaturday hours " + standardHoursSaturday + "\nSunday Hours " + standardHoursSunday) console.log("Address: " + addressLine1 + " " + addressLine2 + " " + addressLine3 + ", " + addressCity + ", " + addressState + " " + addressZip); }) }) // let parkButton = document.createElement("button"); // // $(parkButton).attr("class", "modal-button"); // // $(parkButton).attr("data-target", "modal-ter"); // // $(parkButton).attr("aria-haspopup","true"); // $(parkButton).attr("id", "location-info"); // $(parkButton).attr("class","button"); // $(parkButton).text(fullName); // $("#location-title").text(fullName); // $("#location-info").text(addressLine2); // $("#location-info") // $("#location-info").click(function() { // $(".modal").addClass("is-active"); // });
define( ({ _widgetLabel: "Beeldmeting" }) );
from system_simulator import SystemSimulator from behavior_model_executor import BehaviorModelExecutor from system_message import SysMessage from definition import * import datetime class Generator(BehaviorModelExecutor): #오토마타 구현 def __init__(self, instance_time, destruct_time, name, engine_name): BehaviorModelExecutor.__init__(self, instance_time, destruct_time, name, engine_name) self.init_state("IDLE") #IDLE 상태 self.insert_state("IDLE", Infinite) #대기 무한정 외부에서 입력을 받아야 상태가 변함 self.insert_state("MOVE", 1) # MOVE상태, 1초동안 기다린후 이벤트가 없으면 self.insert_input_port("start") #인풋 포트 self.insert_output_port("process") # 아우풋 포트 self.msg_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def ext_trans(self,port, msg): #외부에서 이벤트가 들어올때 를 정의 if port == "start": #START라는 포트에서 데이터가 들어오면 상태를 IDLE -> MOVE로 변경 print(f"[Gen][IN]: {datetime.datetime.now()}") self._cur_state = "MOVE" #start를 받으면 1초단위로 move 라는 상태를 반복 def output(self): # 메세지를 보냄, 프로세스를 지정, 프로세스포트와 연결된 에이전트는 전부 메세지를 받는다. 게임을 만드는 사람은 누가 메세지를받을지 포트를 지정 msg = SysMessage(self.get_name(), "process") #MOVE - 1초주기로 메세지를 보냄 print(f"[Gen][OUT]: {datetime.datetime.now()}") msg.insert(self.msg_list.pop(0)) #메세지 리스트에서 하나를 뽑아서 보낸다. return msg def int_trans(self): if self._cur_state == "MOVE" and not self.msg_list: #MOVE 상태, 메세지가 비어있는경우 IDLE상태로 가라 self._cur_state = "IDLE" #보내야할 메세지가 없으면 IDLE else: # 아니면 MOVE 상태 self._cur_state = "MOVE" class Processor(BehaviorModelExecutor): def __init__(self, instance_time, destruct_time, name, engine_name): BehaviorModelExecutor.__init__(self, instance_time, destruct_time, name, engine_name) self.init_state("IDLE") self.insert_state("IDLE", Infinite) #IDLE상태 대기 무한 self.insert_state("PROCESS", 2) # Process 상태, 2초 대기 self.insert_input_port("process") self.msg_list = [] def ext_trans(self,port, msg): if port == "process": print(f"[Proc][IN]: {datetime.datetime.now()}") self.cancel_rescheduling() #리스케줄링을 취소 data = msg.retrieve() self.msg_list.append(data[0]) #메세지를 받아서 append self._cur_state = "PROCESS" #메세지 받아서 처리 def output(self): #지금까지 받은것을 출력 print(f"[Proc][OUT]: {datetime.datetime.now()}") print("|".join(map(str, self.msg_list))) return None def int_trans(self): if self._cur_state == "PROCESS": self._cur_state = "IDLE" else: self._cur_state = "IDLE" # System Simulator Initialization se = SystemSimulator() #백엔드 생성(메안서버 ) se.register_engine("sname", "REAL_TIME", 1) #로비에서 방하나만든다..? REAL_TIME => 사람의 1초 = 컴퓨터의 1초 #버츄어타임 => 시간개념 x 우선순위 부여라는 느낌, 1=> time resolution 시간을 얼마나 잘게 볼것이냐 1= 1초마다 이벤트 유뮤를 확인 se.get_engine("sname").insert_input_port("start")# input_port("start) => 포트라는 개념, API를 String 형태로 정의..? gen = Generator(0, Infinite, "Gen", "sname")# Generator => npc, (0= npc 가 태어나는 순간, 수명,"Gen" 이름, sname =소속된방) se.get_engine("sname").register_entity(gen)#register_entity 에이전트 추가 proc = Processor(0, Infinite, "Proc", "sname") # se.get_engine("sname").register_entity(proc) #에이전트 추가 se.get_engine("sname").coupling_relation(None, "start", gen, "start") #방(start라는 포트와 )과 gen 의 start 연결 se.get_engine("sname").coupling_relation(gen, "process", proc, "process") #에이전트 간의 상호작용..? 입출력 연결 se.get_engine("sname").insert_external_event("start", None) #외부에서 이벤트를 꽂아줌 se.get_engine("sname").simulate() #게임시작
import re import constants class CC(object): def __init__(self, clusters): self.ccs = clusters.replace(constants.CONSONANT_SYMBOL, constants.CONSONANTS).replace( constants.TONE_SYMBOL, constants.TONES).split() class CCExtractor(CC): def __init__(self, clusters): super().__init__(clusters) self.ccp = re.compile(constants.PIPE_SYMBOL.join(self.ccs)) def gen_char_clusters(self, seq): p = 0 while p < len(seq): m = self.ccp.match(seq[p:]) if m: n = m.span()[1] else: n = 1 yield seq[p:p + n] p += n def create_all_char_clusters(self, seq): res = self.gen_char_clusters(seq) return list(res) def create_all_char_cluster_indexes(self, seq, max_length=None): p = 0 index_pairs = [] for cc in self.gen_char_clusters(seq): n = len(cc) + p index_pairs.append( (p, n)) if not max_length or (max_length and len(cc) <= max_length) else None p = n return index_pairs if __name__ == '__main__': CHAR_CLUSTERS = ''' เc็c เcctาะ เccีtยะ เccีtย(?=[เ-ไก-ฮ]|$) เccอะ เcc็c เcิc์c เcิtc เcีtยะ? เcืtอะ? เc[ิีุู]tย(?=[เ-ไก-ฮ]|$) เctา?ะ? cัtวะ c[ัื]tc[ุิะ]? c[ิุู]์ c[ะ-ู]t c็ ct[ะาำ]? แc็c แcc์ แctะ แcc็c แccc์ โctะ [เ-ไ]ct ๆ ฯลฯ ฯ ''' sent = 'ฉันกินข้าวที่บ้าน' max_len = 4 extractor = CCExtractor(CHAR_CLUSTERS) ccs = extractor.create_all_char_clusters(sent) print('sentence: {}'.format(ccs))
try: from detect_simd.core import detect except ImportError: raise ImportError("Run setup.py to build library before importing.") __all__ = ["detect_simd.core"]
// const express = require("express"); // const webpackDevMiddleware = require("webpack-dev-middleware"); // const webpack = require("webpack"); // const webpackConfig = require("./webpack.development.config"); // // const app = express(); // const compiler = webpack(webpackConfig); // const port = 5003; // // app.use(webpackDevMiddleware(compiler)); // // app.use('/static', express.static(__dirname)); // app.use('/api', require('./api/index')); // // app.listen(port, function () { // console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port); // }); const express = require("express"); const proxy = require('express-http-proxy'); const webpackDevMiddleware = require("webpack-dev-middleware"); const webpack = require("webpack"); const webpackConfig = require("./webpack.development.config"); const app = express(); const compiler = webpack(webpackConfig); const port = 5006; app.use(webpackDevMiddleware(compiler)); app.use('/static', express.static(__dirname)); // app.use('/api', require('./api/index')); app.use('/api', proxy('http://112.74.58.210:9001')); app.listen(port, function () { console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port); });
#!/usr/bin/env python # coding: utf-8 # coding: utf-8 import numpy as np import matplotlib.pylab as plt from gradient_2d import numerical_gradient def gradient_descent(f, init_x, lr=0.01, step_num=100): x = init_x x_history = [] for i in range(step_num): x_history.append( x.copy() ) grad = numerical_gradient(f, x) x -= lr * grad return x, np.array(x_history) def function_2(x): return x[0]**2 + x[1]**2 init_x = np.array([-3.0, 4.0]) lr = 0.1 step_num = 20 x, x_history = gradient_descent(function_2, init_x, lr=lr, step_num=step_num) plt.plot( [-5, 5], [0,0], '--b') plt.plot( [0,0], [-5, 5], '--b') plt.plot(x_history[:,0], x_history[:,1], 'o') plt.xlim(-3.5, 3.5) plt.ylim(-4.5, 4.5) plt.xlabel("X0") plt.ylabel("X1") plt.show()