text
stringlengths
3
1.05M
/* * This file is derived from crc32.c from the zlib-1.1.3 distribution * by Jean-loup Gailly and Mark Adler. */ /* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-1998 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #ifndef USE_HOSTCC /* Shut down "ANSI does not permit..." warnings */ #include <common.h> /* to get command definitions like CFG_CMD_JFFS2 */ #endif #include "zlib.h" #define local static #define ZEXPORT /* empty */ unsigned long crc32(unsigned long, const unsigned char *, unsigned int); #ifdef DYNAMIC_CRC_TABLE local int crc_table_empty = 1; local uLongf crc_table[256]; local void make_crc_table OF((void)); /* Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRC's on data a byte at a time for all combinations of CRC register values and incoming bytes. */ local void make_crc_table() { uLong c; int n, k; uLong poly; /* polynomial exclusive-or pattern */ /* terms of polynomial defining this crc (except x^32): */ static const Byte p[] = { 0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26 }; /* make exclusive-or pattern from polynomial (0xedb88320L) */ poly = 0L; for (n = 0; n < sizeof(p) / sizeof(Byte); n++) poly |= 1L << (31 - p[n]); for (n = 0; n < 256; n++) { c = (uLong) n; for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; crc_table[n] = c; } crc_table_empty = 0; } #else /* ======================================================================== * Table of CRC-32's of all single-byte values (made by make_crc_table) */ local const uLongf crc_table[256] = { 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL }; #endif #if 0 /* ========================================================================= * This function can be used by asm versions of crc32() */ const uLongf *ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif return (const uLongf *)crc_table; } #endif /* ========================================================================= */ #define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8); #define DO2(buf) DO1(buf); DO1(buf); #define DO4(buf) DO2(buf); DO2(buf); #define DO8(buf) DO4(buf); DO4(buf); /* ========================================================================= */ uLong ZEXPORT crc32(crc, buf, len) uLong crc; const Bytef *buf; uInt len; { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif crc = crc ^ 0xffffffffL; while (len >= 8) { DO8(buf); len -= 8; } if (len) do { DO1(buf); } while (--len); return crc ^ 0xffffffffL; } #if (CONFIG_COMMANDS & CFG_CMD_JFFS2) /* No ones complement version. JFFS2 (and other things ?) * don't use ones compliment in their CRC calculations. */ uLong ZEXPORT crc32_no_comp(uLong crc, const Bytef * buf, uInt len) { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif while (len >= 8) { DO8(buf); len -= 8; } if (len) do { DO1(buf); } while (--len); return crc; } #endif /* CFG_CMD_JFFS2 */
# For detailed comments on animation and the techniqes used here, see # the wiki entry http://www.scipy.org/Cookbook/Matplotlib/Animations import os import sys #import matplotlib #matplotlib.use('Qt4Agg') from matplotlib.figure import Figure from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from PyQt4 import QtCore, QtGui ITERS = 1000 import numpy as np import time class BlitQT(FigureCanvas): def __init__(self): FigureCanvas.__init__(self, Figure()) self.ax = self.figure.add_subplot(111) self.ax.grid() self.draw() self.old_size = self.ax.bbox.width, self.ax.bbox.height self.ax_background = self.copy_from_bbox(self.ax.bbox) self.cnt = 0 self.x = np.arange(0,2*np.pi,0.01) self.sin_line, = self.ax.plot(self.x, np.sin(self.x), animated=True) self.cos_line, = self.ax.plot(self.x, np.cos(self.x), animated=True) self.draw() self.tstart = time.time() self.startTimer(10) def timerEvent(self, evt): current_size = self.ax.bbox.width, self.ax.bbox.height if self.old_size != current_size: self.old_size = current_size self.ax.clear() self.ax.grid() self.draw() self.ax_background = self.copy_from_bbox(self.ax.bbox) self.restore_region(self.ax_background, bbox=self.ax.bbox) # update the data self.sin_line.set_ydata(np.sin(self.x+self.cnt/10.0)) self.cos_line.set_ydata(np.cos(self.x+self.cnt/10.0)) # just draw the animated artist self.ax.draw_artist(self.sin_line) self.ax.draw_artist(self.cos_line) # just redraw the axes rectangle self.blit(self.ax.bbox) if self.cnt == 0: # TODO: this shouldn't be necessary, but if it is excluded the # canvas outside the axes is not initially painted. self.draw() if self.cnt==ITERS: # print the timing info and quit print 'FPS:' , ITERS/(time.time()-self.tstart) sys.exit() else: self.cnt += 1 app = QtGui.QApplication(sys.argv) widget = BlitQT() widget.show() sys.exit(app.exec_())
/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Margo Seltzer. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(LIBC_SCCS) && !defined(lint) static char rcsid[] = "$OpenBSD: hsearch.c,v 1.3 1996/08/19 08:20:41 tholo Exp $"; #endif /* LIBC_SCCS and not lint */ #include <sys/types.h> #include <fcntl.h> #include <string.h> #include <db.h> #include "search.h" static DB *dbp = NULL; static ENTRY retval; extern int hcreate(nel) u_int nel; { HASHINFO info; info.nelem = nel; info.bsize = 256; info.ffactor = 8; info.cachesize = 0; info.hash = NULL; info.lorder = 0; dbp = (DB *)__hash_open(NULL, O_CREAT | O_RDWR, 0600, &info, 0); return (dbp != NULL); } extern ENTRY * hsearch(item, action) ENTRY item; ACTION action; { DBT key, val; int status; if (!dbp) return (NULL); key.data = (u_char *)item.key; key.size = strlen(item.key) + 1; if (action == ENTER) { val.data = (u_char *)item.data; val.size = strlen(item.data) + 1; status = (dbp->put)(dbp, &key, &val, R_NOOVERWRITE); if (status) return (NULL); } else { /* FIND */ status = (dbp->get)(dbp, &key, &val, 0); if (status) return (NULL); else item.data = (char *)val.data; } retval.key = item.key; retval.data = item.data; return (&retval); } extern void hdestroy() { if (dbp) { (void)(dbp->close)(dbp); dbp = NULL; } }
# Generated by Django 2.2.7 on 2019-11-30 18:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cars_rent_app', '0002_auto_20191130_2111'), ] operations = [ migrations.AlterField( model_name='user', name='first_name', field=models.CharField(max_length=100), ), ]
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = tslib_1.__importStar(require("react")); var StyledIconBase_1 = require("../../StyledIconBase"); exports.FileFind = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", }; return (React.createElement(StyledIconBase_1.StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { d: "M13.707 2.293A.996.996 0 0 0 13 2H6c-1.103 0-2 .897-2 2v16c0 1.103.897 2 2 2h12c1.103 0 2-.897 2-2V9a.996.996 0 0 0-.293-.707l-6-6zM6 4h6.586L18 9.414l.002 9.174-2.568-2.568c.35-.595.566-1.281.566-2.02 0-2.206-1.794-4-4-4s-4 1.794-4 4 1.794 4 4 4c.739 0 1.425-.216 2.02-.566L16.586 20H6V4zm6 12c-1.103 0-2-.897-2-2s.897-2 2-2 2 .897 2 2-.897 2-2 2z", key: "k0" }))); }); exports.FileFind.displayName = 'FileFind'; exports.FileFindDimensions = { height: 24, width: 24 };
// See LICENSE for license details. #ifndef RISCV_CSR_ENCODING_H #define RISCV_CSR_ENCODING_H #define MSTATUS_UIE 0x00000001 #define MSTATUS_SIE 0x00000002 #define MSTATUS_HIE 0x00000004 #define MSTATUS_MIE 0x00000008 #define MSTATUS_UPIE 0x00000010 #define MSTATUS_SPIE 0x00000020 #define MSTATUS_HPIE 0x00000040 #define MSTATUS_MPIE 0x00000080 #define MSTATUS_SPP 0x00000100 #define MSTATUS_MPP 0x00001800 #define MSTATUS_FS 0x00006000 #define MSTATUS_XS 0x00018000 #define MSTATUS_MPRV 0x00020000 #define MSTATUS_PUM 0x00040000 #define MSTATUS_MXR 0x00080000 #define MSTATUS_VM 0x1F000000 #define MSTATUS32_SD 0x80000000 #define MSTATUS64_SD 0x8000000000000000 #define SSTATUS_UIE 0x00000001 #define SSTATUS_SIE 0x00000002 #define SSTATUS_UPIE 0x00000010 #define SSTATUS_SPIE 0x00000020 #define SSTATUS_SPP 0x00000100 #define SSTATUS_FS 0x00006000 #define SSTATUS_XS 0x00018000 #define SSTATUS_PUM 0x00040000 #define SSTATUS32_SD 0x80000000 #define SSTATUS64_SD 0x8000000000000000 #define DCSR_XDEBUGVER (3U<<30) #define DCSR_NDRESET (1<<29) #define DCSR_FULLRESET (1<<28) #define DCSR_EBREAKM (1<<15) #define DCSR_EBREAKH (1<<14) #define DCSR_EBREAKS (1<<13) #define DCSR_EBREAKU (1<<12) #define DCSR_STOPCYCLE (1<<10) #define DCSR_STOPTIME (1<<9) #define DCSR_CAUSE (7<<6) #define DCSR_DEBUGINT (1<<5) #define DCSR_HALT (1<<3) #define DCSR_STEP (1<<2) #define DCSR_PRV (3<<0) #define DCSR_CAUSE_NONE 0 #define DCSR_CAUSE_SWBP 1 #define DCSR_CAUSE_HWBP 2 #define DCSR_CAUSE_DEBUGINT 3 #define DCSR_CAUSE_STEP 4 #define DCSR_CAUSE_HALT 5 #define MCONTROL_TYPE(xlen) (0xfULL<<((xlen)-4)) #define MCONTROL_DMODE(xlen) (1ULL<<((xlen)-5)) #define MCONTROL_MASKMAX(xlen) (0x3fULL<<((xlen)-11)) #define MCONTROL_SELECT (1<<19) #define MCONTROL_TIMING (1<<18) #define MCONTROL_ACTION (0x3f<<12) #define MCONTROL_CHAIN (1<<11) #define MCONTROL_MATCH (0xf<<7) #define MCONTROL_M (1<<6) #define MCONTROL_H (1<<5) #define MCONTROL_S (1<<4) #define MCONTROL_U (1<<3) #define MCONTROL_EXECUTE (1<<2) #define MCONTROL_STORE (1<<1) #define MCONTROL_LOAD (1<<0) #define MCONTROL_TYPE_NONE 0 #define MCONTROL_TYPE_MATCH 2 #define MCONTROL_ACTION_DEBUG_EXCEPTION 0 #define MCONTROL_ACTION_DEBUG_MODE 1 #define MCONTROL_ACTION_TRACE_START 2 #define MCONTROL_ACTION_TRACE_STOP 3 #define MCONTROL_ACTION_TRACE_EMIT 4 #define MCONTROL_MATCH_EQUAL 0 #define MCONTROL_MATCH_NAPOT 1 #define MCONTROL_MATCH_GE 2 #define MCONTROL_MATCH_LT 3 #define MCONTROL_MATCH_MASK_LOW 4 #define MCONTROL_MATCH_MASK_HIGH 5 #define MIP_SSIP (1 << IRQ_S_SOFT) #define MIP_HSIP (1 << IRQ_H_SOFT) #define MIP_MSIP (1 << IRQ_M_SOFT) #define MIP_STIP (1 << IRQ_S_TIMER) #define MIP_HTIP (1 << IRQ_H_TIMER) #define MIP_MTIP (1 << IRQ_M_TIMER) #define MIP_SEIP (1 << IRQ_S_EXT) #define MIP_HEIP (1 << IRQ_H_EXT) #define MIP_MEIP (1 << IRQ_M_EXT) #define MIE_SSIE MIP_SSIP #define MIE_HSIE MIP_HSIP #define MIE_MSIE MIP_MSIP #define MIE_STIE MIP_STIP #define MIE_HTIE MIP_HTIP #define MIE_MTIE MIP_MTIP #define MIE_SEIE MIP_SEIP #define MIE_HEIE MIP_HEIP #define MIE_MEIE MIP_MEIP #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP #define PRV_U 0 #define PRV_S 1 #define PRV_H 2 #define PRV_M 3 #define VM_MBARE 0 #define VM_MBB 1 #define VM_MBBID 2 #define VM_SV32 8 #define VM_SV39 9 #define VM_SV48 10 #define IRQ_S_SOFT 1 #define IRQ_H_SOFT 2 #define IRQ_M_SOFT 3 #define IRQ_S_TIMER 5 #define IRQ_H_TIMER 6 #define IRQ_M_TIMER 7 #define IRQ_S_EXT 9 #define IRQ_H_EXT 10 #define IRQ_M_EXT 11 #define IRQ_COP 12 #define IRQ_HOST 13 #define DEFAULT_RSTVEC 0x00001000 #define DEFAULT_NMIVEC 0x00001004 #define DEFAULT_MTVEC 0x00001010 #define CONFIG_STRING_ADDR 0x0000100C #define EXT_IO_BASE 0x40000000 #define DRAM_BASE 0x80000000 // page table entry (PTE) fields #define PTE_V 0x001 // Valid #define PTE_R 0x002 // Read #define PTE_W 0x004 // Write #define PTE_X 0x008 // Execute #define PTE_U 0x010 // User #define PTE_G 0x020 // Global #define PTE_A 0x040 // Accessed #define PTE_D 0x080 // Dirty #define PTE_SOFT 0x300 // Reserved for Software #define PTE_PPN_SHIFT 10 #define PTE_TABLE(PTE) (((PTE) & (PTE_V | PTE_R | PTE_W | PTE_X)) == PTE_V) #ifdef __riscv #ifdef __riscv64 # define MSTATUS_SD MSTATUS64_SD # define SSTATUS_SD SSTATUS64_SD # define RISCV_PGLEVEL_BITS 9 #else # define MSTATUS_SD MSTATUS32_SD # define SSTATUS_SD SSTATUS32_SD # define RISCV_PGLEVEL_BITS 10 #endif #define RISCV_PGSHIFT 12 #define RISCV_PGSIZE (1 << RISCV_PGSHIFT) #ifndef __ASSEMBLER__ #ifdef __GNUC__ #define asm __asm #define read_fpu(reg) ({ unsigned long __tmp; \ asm volatile ("fmv.x.w %0, " #reg : "=r"(__tmp)); \ __tmp; }) #define write_fpu(reg, val) ({ \ if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ asm volatile ("fmv.w.x " #reg ", %0" :: "i"(val)); \ else \ asm volatile ("fmv.w.x " #reg ", %0" :: "r"(val)); }) #define read_csr(reg) ({ unsigned long __tmp; \ asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ __tmp; }) #define write_csr(reg, val) ({ \ if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ asm volatile ("csrw " #reg ", %0" :: "i"(val)); \ else \ asm volatile ("csrw " #reg ", %0" :: "r"(val)); }) #define swap_csr(reg, val) ({ unsigned long __tmp; \ if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ asm volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "i"(val)); \ else \ asm volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "r"(val)); \ __tmp; }) #define set_csr(reg, bit) ({ unsigned long __tmp; \ if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ asm volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "i"(bit)); \ else \ asm volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "r"(bit)); \ __tmp; }) #define clear_csr(reg, bit) ({ unsigned long __tmp; \ if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ asm volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "i"(bit)); \ else \ asm volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "r"(bit)); \ __tmp; }) #define rdtime() read_csr(time) #define rdcycle() read_csr(cycle) #define rdinstret() read_csr(instret) #endif #endif #endif #endif /* Automatically generated by parse-opcodes */ #ifndef RISCV_ENCODING_H #define RISCV_ENCODING_H #define MATCH_BEQ 0x63 #define MASK_BEQ 0x707f #define MATCH_BNE 0x1063 #define MASK_BNE 0x707f #define MATCH_BLT 0x4063 #define MASK_BLT 0x707f #define MATCH_BGE 0x5063 #define MASK_BGE 0x707f #define MATCH_BLTU 0x6063 #define MASK_BLTU 0x707f #define MATCH_BGEU 0x7063 #define MASK_BGEU 0x707f #define MATCH_JALR 0x67 #define MASK_JALR 0x707f #define MATCH_JAL 0x6f #define MASK_JAL 0x7f #define MATCH_LUI 0x37 #define MASK_LUI 0x7f #define MATCH_AUIPC 0x17 #define MASK_AUIPC 0x7f #define MATCH_ADDI 0x13 #define MASK_ADDI 0x707f #define MATCH_SLLI 0x1013 #define MASK_SLLI 0xfc00707f #define MATCH_SLTI 0x2013 #define MASK_SLTI 0x707f #define MATCH_SLTIU 0x3013 #define MASK_SLTIU 0x707f #define MATCH_XORI 0x4013 #define MASK_XORI 0x707f #define MATCH_SRLI 0x5013 #define MASK_SRLI 0xfc00707f #define MATCH_SRAI 0x40005013 #define MASK_SRAI 0xfc00707f #define MATCH_ORI 0x6013 #define MASK_ORI 0x707f #define MATCH_ANDI 0x7013 #define MASK_ANDI 0x707f #define MATCH_ADD 0x33 #define MASK_ADD 0xfe00707f #define MATCH_SUB 0x40000033 #define MASK_SUB 0xfe00707f #define MATCH_SLL 0x1033 #define MASK_SLL 0xfe00707f #define MATCH_SLT 0x2033 #define MASK_SLT 0xfe00707f #define MATCH_SLTU 0x3033 #define MASK_SLTU 0xfe00707f #define MATCH_XOR 0x4033 #define MASK_XOR 0xfe00707f #define MATCH_SRL 0x5033 #define MASK_SRL 0xfe00707f #define MATCH_SRA 0x40005033 #define MASK_SRA 0xfe00707f #define MATCH_OR 0x6033 #define MASK_OR 0xfe00707f #define MATCH_AND 0x7033 #define MASK_AND 0xfe00707f #define MATCH_ADDIW 0x1b #define MASK_ADDIW 0x707f #define MATCH_SLLIW 0x101b #define MASK_SLLIW 0xfe00707f #define MATCH_SRLIW 0x501b #define MASK_SRLIW 0xfe00707f #define MATCH_SRAIW 0x4000501b #define MASK_SRAIW 0xfe00707f #define MATCH_ADDW 0x3b #define MASK_ADDW 0xfe00707f #define MATCH_SUBW 0x4000003b #define MASK_SUBW 0xfe00707f #define MATCH_SLLW 0x103b #define MASK_SLLW 0xfe00707f #define MATCH_SRLW 0x503b #define MASK_SRLW 0xfe00707f #define MATCH_SRAW 0x4000503b #define MASK_SRAW 0xfe00707f #define MATCH_LB 0x3 #define MASK_LB 0x707f #define MATCH_LH 0x1003 #define MASK_LH 0x707f #define MATCH_LW 0x2003 #define MASK_LW 0x707f #define MATCH_LD 0x3003 #define MASK_LD 0x707f #define MATCH_LBU 0x4003 #define MASK_LBU 0x707f #define MATCH_LHU 0x5003 #define MASK_LHU 0x707f #define MATCH_LWU 0x6003 #define MASK_LWU 0x707f #define MATCH_SB 0x23 #define MASK_SB 0x707f #define MATCH_SH 0x1023 #define MASK_SH 0x707f #define MATCH_SW 0x2023 #define MASK_SW 0x707f #define MATCH_SD 0x3023 #define MASK_SD 0x707f #define MATCH_FENCE 0xf #define MASK_FENCE 0x707f #define MATCH_FENCE_I 0x100f #define MASK_FENCE_I 0x707f #define MATCH_MUL 0x2000033 #define MASK_MUL 0xfe00707f #define MATCH_MULH 0x2001033 #define MASK_MULH 0xfe00707f #define MATCH_MULHSU 0x2002033 #define MASK_MULHSU 0xfe00707f #define MATCH_MULHU 0x2003033 #define MASK_MULHU 0xfe00707f #define MATCH_DIV 0x2004033 #define MASK_DIV 0xfe00707f #define MATCH_DIVU 0x2005033 #define MASK_DIVU 0xfe00707f #define MATCH_REM 0x2006033 #define MASK_REM 0xfe00707f #define MATCH_REMU 0x2007033 #define MASK_REMU 0xfe00707f #define MATCH_MULW 0x200003b #define MASK_MULW 0xfe00707f #define MATCH_DIVW 0x200403b #define MASK_DIVW 0xfe00707f #define MATCH_DIVUW 0x200503b #define MASK_DIVUW 0xfe00707f #define MATCH_REMW 0x200603b #define MASK_REMW 0xfe00707f #define MATCH_REMUW 0x200703b #define MASK_REMUW 0xfe00707f #define MATCH_AMOADD_W 0x202f #define MASK_AMOADD_W 0xf800707f #define MATCH_AMOXOR_W 0x2000202f #define MASK_AMOXOR_W 0xf800707f #define MATCH_AMOOR_W 0x4000202f #define MASK_AMOOR_W 0xf800707f #define MATCH_AMOAND_W 0x6000202f #define MASK_AMOAND_W 0xf800707f #define MATCH_AMOMIN_W 0x8000202f #define MASK_AMOMIN_W 0xf800707f #define MATCH_AMOMAX_W 0xa000202f #define MASK_AMOMAX_W 0xf800707f #define MATCH_AMOMINU_W 0xc000202f #define MASK_AMOMINU_W 0xf800707f #define MATCH_AMOMAXU_W 0xe000202f #define MASK_AMOMAXU_W 0xf800707f #define MATCH_AMOSWAP_W 0x800202f #define MASK_AMOSWAP_W 0xf800707f #define MATCH_LR_W 0x1000202f #define MASK_LR_W 0xf9f0707f #define MATCH_SC_W 0x1800202f #define MASK_SC_W 0xf800707f #define MATCH_AMOADD_D 0x302f #define MASK_AMOADD_D 0xf800707f #define MATCH_AMOXOR_D 0x2000302f #define MASK_AMOXOR_D 0xf800707f #define MATCH_AMOOR_D 0x4000302f #define MASK_AMOOR_D 0xf800707f #define MATCH_AMOAND_D 0x6000302f #define MASK_AMOAND_D 0xf800707f #define MATCH_AMOMIN_D 0x8000302f #define MASK_AMOMIN_D 0xf800707f #define MATCH_AMOMAX_D 0xa000302f #define MASK_AMOMAX_D 0xf800707f #define MATCH_AMOMINU_D 0xc000302f #define MASK_AMOMINU_D 0xf800707f #define MATCH_AMOMAXU_D 0xe000302f #define MASK_AMOMAXU_D 0xf800707f #define MATCH_AMOSWAP_D 0x800302f #define MASK_AMOSWAP_D 0xf800707f #define MATCH_LR_D 0x1000302f #define MASK_LR_D 0xf9f0707f #define MATCH_SC_D 0x1800302f #define MASK_SC_D 0xf800707f #define MATCH_ECALL 0x73 #define MASK_ECALL 0xffffffff #define MATCH_EBREAK 0x100073 #define MASK_EBREAK 0xffffffff #define MATCH_URET 0x200073 #define MASK_URET 0xffffffff #define MATCH_SRET 0x10200073 #define MASK_SRET 0xffffffff #define MATCH_HRET 0x20200073 #define MASK_HRET 0xffffffff #define MATCH_MRET 0x30200073 #define MASK_MRET 0xffffffff #define MATCH_DRET 0x7b200073 #define MASK_DRET 0xffffffff #define MATCH_SFENCE_VM 0x10400073 #define MASK_SFENCE_VM 0xfff07fff #define MATCH_WFI 0x10500073 #define MASK_WFI 0xffffffff #define MATCH_CSRRW 0x1073 #define MASK_CSRRW 0x707f #define MATCH_CSRRS 0x2073 #define MASK_CSRRS 0x707f #define MATCH_CSRRC 0x3073 #define MASK_CSRRC 0x707f #define MATCH_CSRRWI 0x5073 #define MASK_CSRRWI 0x707f #define MATCH_CSRRSI 0x6073 #define MASK_CSRRSI 0x707f #define MATCH_CSRRCI 0x7073 #define MASK_CSRRCI 0x707f #define MATCH_FADD_S 0x53 #define MASK_FADD_S 0xfe00007f #define MATCH_FSUB_S 0x8000053 #define MASK_FSUB_S 0xfe00007f #define MATCH_FMUL_S 0x10000053 #define MASK_FMUL_S 0xfe00007f #define MATCH_FDIV_S 0x18000053 #define MASK_FDIV_S 0xfe00007f #define MATCH_FSGNJ_S 0x20000053 #define MASK_FSGNJ_S 0xfe00707f #define MATCH_FSGNJN_S 0x20001053 #define MASK_FSGNJN_S 0xfe00707f #define MATCH_FSGNJX_S 0x20002053 #define MASK_FSGNJX_S 0xfe00707f #define MATCH_FMIN_S 0x28000053 #define MASK_FMIN_S 0xfe00707f #define MATCH_FMAX_S 0x28001053 #define MASK_FMAX_S 0xfe00707f #define MATCH_FSQRT_S 0x58000053 #define MASK_FSQRT_S 0xfff0007f #define MATCH_FADD_D 0x2000053 #define MASK_FADD_D 0xfe00007f #define MATCH_FSUB_D 0xa000053 #define MASK_FSUB_D 0xfe00007f #define MATCH_FMUL_D 0x12000053 #define MASK_FMUL_D 0xfe00007f #define MATCH_FDIV_D 0x1a000053 #define MASK_FDIV_D 0xfe00007f #define MATCH_FSGNJ_D 0x22000053 #define MASK_FSGNJ_D 0xfe00707f #define MATCH_FSGNJN_D 0x22001053 #define MASK_FSGNJN_D 0xfe00707f #define MATCH_FSGNJX_D 0x22002053 #define MASK_FSGNJX_D 0xfe00707f #define MATCH_FMIN_D 0x2a000053 #define MASK_FMIN_D 0xfe00707f #define MATCH_FMAX_D 0x2a001053 #define MASK_FMAX_D 0xfe00707f #define MATCH_FCVT_S_D 0x40100053 #define MASK_FCVT_S_D 0xfff0007f #define MATCH_FCVT_D_S 0x42000053 #define MASK_FCVT_D_S 0xfff0007f #define MATCH_FSQRT_D 0x5a000053 #define MASK_FSQRT_D 0xfff0007f #define MATCH_FLE_S 0xa0000053 #define MASK_FLE_S 0xfe00707f #define MATCH_FLT_S 0xa0001053 #define MASK_FLT_S 0xfe00707f #define MATCH_FEQ_S 0xa0002053 #define MASK_FEQ_S 0xfe00707f #define MATCH_FLE_D 0xa2000053 #define MASK_FLE_D 0xfe00707f #define MATCH_FLT_D 0xa2001053 #define MASK_FLT_D 0xfe00707f #define MATCH_FEQ_D 0xa2002053 #define MASK_FEQ_D 0xfe00707f #define MATCH_FCVT_W_S 0xc0000053 #define MASK_FCVT_W_S 0xfff0007f #define MATCH_FCVT_WU_S 0xc0100053 #define MASK_FCVT_WU_S 0xfff0007f #define MATCH_FCVT_L_S 0xc0200053 #define MASK_FCVT_L_S 0xfff0007f #define MATCH_FCVT_LU_S 0xc0300053 #define MASK_FCVT_LU_S 0xfff0007f #define MATCH_FMV_X_S 0xe0000053 #define MASK_FMV_X_S 0xfff0707f #define MATCH_FCLASS_S 0xe0001053 #define MASK_FCLASS_S 0xfff0707f #define MATCH_FCVT_W_D 0xc2000053 #define MASK_FCVT_W_D 0xfff0007f #define MATCH_FCVT_WU_D 0xc2100053 #define MASK_FCVT_WU_D 0xfff0007f #define MATCH_FCVT_L_D 0xc2200053 #define MASK_FCVT_L_D 0xfff0007f #define MATCH_FCVT_LU_D 0xc2300053 #define MASK_FCVT_LU_D 0xfff0007f #define MATCH_FMV_X_D 0xe2000053 #define MASK_FMV_X_D 0xfff0707f #define MATCH_FCLASS_D 0xe2001053 #define MASK_FCLASS_D 0xfff0707f #define MATCH_FCVT_S_W 0xd0000053 #define MASK_FCVT_S_W 0xfff0007f #define MATCH_FCVT_S_WU 0xd0100053 #define MASK_FCVT_S_WU 0xfff0007f #define MATCH_FCVT_S_L 0xd0200053 #define MASK_FCVT_S_L 0xfff0007f #define MATCH_FCVT_S_LU 0xd0300053 #define MASK_FCVT_S_LU 0xfff0007f #define MATCH_FMV_S_X 0xf0000053 #define MASK_FMV_S_X 0xfff0707f #define MATCH_FCVT_D_W 0xd2000053 #define MASK_FCVT_D_W 0xfff0007f #define MATCH_FCVT_D_WU 0xd2100053 #define MASK_FCVT_D_WU 0xfff0007f #define MATCH_FCVT_D_L 0xd2200053 #define MASK_FCVT_D_L 0xfff0007f #define MATCH_FCVT_D_LU 0xd2300053 #define MASK_FCVT_D_LU 0xfff0007f #define MATCH_FMV_D_X 0xf2000053 #define MASK_FMV_D_X 0xfff0707f #define MATCH_FLW 0x2007 #define MASK_FLW 0x707f #define MATCH_FLD 0x3007 #define MASK_FLD 0x707f #define MATCH_FSW 0x2027 #define MASK_FSW 0x707f #define MATCH_FSD 0x3027 #define MASK_FSD 0x707f #define MATCH_FMADD_S 0x43 #define MASK_FMADD_S 0x600007f #define MATCH_FMSUB_S 0x47 #define MASK_FMSUB_S 0x600007f #define MATCH_FNMSUB_S 0x4b #define MASK_FNMSUB_S 0x600007f #define MATCH_FNMADD_S 0x4f #define MASK_FNMADD_S 0x600007f #define MATCH_FMADD_D 0x2000043 #define MASK_FMADD_D 0x600007f #define MATCH_FMSUB_D 0x2000047 #define MASK_FMSUB_D 0x600007f #define MATCH_FNMSUB_D 0x200004b #define MASK_FNMSUB_D 0x600007f #define MATCH_FNMADD_D 0x200004f #define MASK_FNMADD_D 0x600007f #define MATCH_C_NOP 0x1 #define MASK_C_NOP 0xffff #define MATCH_C_ADDI16SP 0x6101 #define MASK_C_ADDI16SP 0xef83 #define MATCH_C_JR 0x8002 #define MASK_C_JR 0xf07f #define MATCH_C_JALR 0x9002 #define MASK_C_JALR 0xf07f #define MATCH_C_EBREAK 0x9002 #define MASK_C_EBREAK 0xffff #define MATCH_C_LD 0x6000 #define MASK_C_LD 0xe003 #define MATCH_C_SD 0xe000 #define MASK_C_SD 0xe003 #define MATCH_C_ADDIW 0x2001 #define MASK_C_ADDIW 0xe003 #define MATCH_C_LDSP 0x6002 #define MASK_C_LDSP 0xe003 #define MATCH_C_SDSP 0xe002 #define MASK_C_SDSP 0xe003 #define MATCH_C_ADDI4SPN 0x0 #define MASK_C_ADDI4SPN 0xe003 #define MATCH_C_FLD 0x2000 #define MASK_C_FLD 0xe003 #define MATCH_C_LW 0x4000 #define MASK_C_LW 0xe003 #define MATCH_C_FLW 0x6000 #define MASK_C_FLW 0xe003 #define MATCH_C_FSD 0xa000 #define MASK_C_FSD 0xe003 #define MATCH_C_SW 0xc000 #define MASK_C_SW 0xe003 #define MATCH_C_FSW 0xe000 #define MASK_C_FSW 0xe003 #define MATCH_C_ADDI 0x1 #define MASK_C_ADDI 0xe003 #define MATCH_C_JAL 0x2001 #define MASK_C_JAL 0xe003 #define MATCH_C_LI 0x4001 #define MASK_C_LI 0xe003 #define MATCH_C_LUI 0x6001 #define MASK_C_LUI 0xe003 #define MATCH_C_SRLI 0x8001 #define MASK_C_SRLI 0xec03 #define MATCH_C_SRAI 0x8401 #define MASK_C_SRAI 0xec03 #define MATCH_C_ANDI 0x8801 #define MASK_C_ANDI 0xec03 #define MATCH_C_SUB 0x8c01 #define MASK_C_SUB 0xfc63 #define MATCH_C_XOR 0x8c21 #define MASK_C_XOR 0xfc63 #define MATCH_C_OR 0x8c41 #define MASK_C_OR 0xfc63 #define MATCH_C_AND 0x8c61 #define MASK_C_AND 0xfc63 #define MATCH_C_SUBW 0x9c01 #define MASK_C_SUBW 0xfc63 #define MATCH_C_ADDW 0x9c21 #define MASK_C_ADDW 0xfc63 #define MATCH_C_J 0xa001 #define MASK_C_J 0xe003 #define MATCH_C_BEQZ 0xc001 #define MASK_C_BEQZ 0xe003 #define MATCH_C_BNEZ 0xe001 #define MASK_C_BNEZ 0xe003 #define MATCH_C_SLLI 0x2 #define MASK_C_SLLI 0xe003 #define MATCH_C_FLDSP 0x2002 #define MASK_C_FLDSP 0xe003 #define MATCH_C_LWSP 0x4002 #define MASK_C_LWSP 0xe003 #define MATCH_C_FLWSP 0x6002 #define MASK_C_FLWSP 0xe003 #define MATCH_C_MV 0x8002 #define MASK_C_MV 0xf003 #define MATCH_C_ADD 0x9002 #define MASK_C_ADD 0xf003 #define MATCH_C_FSDSP 0xa002 #define MASK_C_FSDSP 0xe003 #define MATCH_C_SWSP 0xc002 #define MASK_C_SWSP 0xe003 #define MATCH_C_FSWSP 0xe002 #define MASK_C_FSWSP 0xe003 #define MATCH_CUSTOM0 0xb #define MASK_CUSTOM0 0x707f #define MATCH_CUSTOM0_RS1 0x200b #define MASK_CUSTOM0_RS1 0x707f #define MATCH_CUSTOM0_RS1_RS2 0x300b #define MASK_CUSTOM0_RS1_RS2 0x707f #define MATCH_CUSTOM0_RD 0x400b #define MASK_CUSTOM0_RD 0x707f #define MATCH_CUSTOM0_RD_RS1 0x600b #define MASK_CUSTOM0_RD_RS1 0x707f #define MATCH_CUSTOM0_RD_RS1_RS2 0x700b #define MASK_CUSTOM0_RD_RS1_RS2 0x707f #define MATCH_CUSTOM1 0x2b #define MASK_CUSTOM1 0x707f #define MATCH_CUSTOM1_RS1 0x202b #define MASK_CUSTOM1_RS1 0x707f #define MATCH_CUSTOM1_RS1_RS2 0x302b #define MASK_CUSTOM1_RS1_RS2 0x707f #define MATCH_CUSTOM1_RD 0x402b #define MASK_CUSTOM1_RD 0x707f #define MATCH_CUSTOM1_RD_RS1 0x602b #define MASK_CUSTOM1_RD_RS1 0x707f #define MATCH_CUSTOM1_RD_RS1_RS2 0x702b #define MASK_CUSTOM1_RD_RS1_RS2 0x707f #define MATCH_CUSTOM2 0x5b #define MASK_CUSTOM2 0x707f #define MATCH_CUSTOM2_RS1 0x205b #define MASK_CUSTOM2_RS1 0x707f #define MATCH_CUSTOM2_RS1_RS2 0x305b #define MASK_CUSTOM2_RS1_RS2 0x707f #define MATCH_CUSTOM2_RD 0x405b #define MASK_CUSTOM2_RD 0x707f #define MATCH_CUSTOM2_RD_RS1 0x605b #define MASK_CUSTOM2_RD_RS1 0x707f #define MATCH_CUSTOM2_RD_RS1_RS2 0x705b #define MASK_CUSTOM2_RD_RS1_RS2 0x707f #define MATCH_CUSTOM3 0x7b #define MASK_CUSTOM3 0x707f #define MATCH_CUSTOM3_RS1 0x207b #define MASK_CUSTOM3_RS1 0x707f #define MATCH_CUSTOM3_RS1_RS2 0x307b #define MASK_CUSTOM3_RS1_RS2 0x707f #define MATCH_CUSTOM3_RD 0x407b #define MASK_CUSTOM3_RD 0x707f #define MATCH_CUSTOM3_RD_RS1 0x607b #define MASK_CUSTOM3_RD_RS1 0x707f #define MATCH_CUSTOM3_RD_RS1_RS2 0x707b #define MASK_CUSTOM3_RD_RS1_RS2 0x707f #define CSR_FFLAGS 0x1 #define CSR_FRM 0x2 #define CSR_FCSR 0x3 #define CSR_CYCLE 0xc00 #define CSR_TIME 0xc01 #define CSR_INSTRET 0xc02 #define CSR_HPMCOUNTER3 0xc03 #define CSR_HPMCOUNTER4 0xc04 #define CSR_HPMCOUNTER5 0xc05 #define CSR_HPMCOUNTER6 0xc06 #define CSR_HPMCOUNTER7 0xc07 #define CSR_HPMCOUNTER8 0xc08 #define CSR_HPMCOUNTER9 0xc09 #define CSR_HPMCOUNTER10 0xc0a #define CSR_HPMCOUNTER11 0xc0b #define CSR_HPMCOUNTER12 0xc0c #define CSR_HPMCOUNTER13 0xc0d #define CSR_HPMCOUNTER14 0xc0e #define CSR_HPMCOUNTER15 0xc0f #define CSR_HPMCOUNTER16 0xc10 #define CSR_HPMCOUNTER17 0xc11 #define CSR_HPMCOUNTER18 0xc12 #define CSR_HPMCOUNTER19 0xc13 #define CSR_HPMCOUNTER20 0xc14 #define CSR_HPMCOUNTER21 0xc15 #define CSR_HPMCOUNTER22 0xc16 #define CSR_HPMCOUNTER23 0xc17 #define CSR_HPMCOUNTER24 0xc18 #define CSR_HPMCOUNTER25 0xc19 #define CSR_HPMCOUNTER26 0xc1a #define CSR_HPMCOUNTER27 0xc1b #define CSR_HPMCOUNTER28 0xc1c #define CSR_HPMCOUNTER29 0xc1d #define CSR_HPMCOUNTER30 0xc1e #define CSR_HPMCOUNTER31 0xc1f #define CSR_SSTATUS 0x100 #define CSR_SIE 0x104 #define CSR_STVEC 0x105 #define CSR_SSCRATCH 0x140 #define CSR_SEPC 0x141 #define CSR_SCAUSE 0x142 #define CSR_SBADADDR 0x143 #define CSR_SIP 0x144 #define CSR_SPTBR 0x180 #define CSR_MSTATUS 0x300 #define CSR_MISA 0x301 #define CSR_MEDELEG 0x302 #define CSR_MIDELEG 0x303 #define CSR_MIE 0x304 #define CSR_MTVEC 0x305 #define CSR_MCOUNTEREN 0x306 #define CSR_MSCRATCH 0x340 #define CSR_MEPC 0x341 #define CSR_MCAUSE 0x342 #define CSR_MBADADDR 0x343 #define CSR_MIP 0x344 #define CSR_TSELECT 0x7a0 #define CSR_TDATA1 0x7a1 #define CSR_TDATA2 0x7a2 #define CSR_TDATA3 0x7a3 #define CSR_DCSR 0x7b0 #define CSR_DPC 0x7b1 #define CSR_DSCRATCH 0x7b2 #define CSR_MCYCLE 0xb00 #define CSR_MINSTRET 0xb02 #define CSR_MHPMCOUNTER3 0xb03 #define CSR_MHPMCOUNTER4 0xb04 #define CSR_MHPMCOUNTER5 0xb05 #define CSR_MHPMCOUNTER6 0xb06 #define CSR_MHPMCOUNTER7 0xb07 #define CSR_MHPMCOUNTER8 0xb08 #define CSR_MHPMCOUNTER9 0xb09 #define CSR_MHPMCOUNTER10 0xb0a #define CSR_MHPMCOUNTER11 0xb0b #define CSR_MHPMCOUNTER12 0xb0c #define CSR_MHPMCOUNTER13 0xb0d #define CSR_MHPMCOUNTER14 0xb0e #define CSR_MHPMCOUNTER15 0xb0f #define CSR_MHPMCOUNTER16 0xb10 #define CSR_MHPMCOUNTER17 0xb11 #define CSR_MHPMCOUNTER18 0xb12 #define CSR_MHPMCOUNTER19 0xb13 #define CSR_MHPMCOUNTER20 0xb14 #define CSR_MHPMCOUNTER21 0xb15 #define CSR_MHPMCOUNTER22 0xb16 #define CSR_MHPMCOUNTER23 0xb17 #define CSR_MHPMCOUNTER24 0xb18 #define CSR_MHPMCOUNTER25 0xb19 #define CSR_MHPMCOUNTER26 0xb1a #define CSR_MHPMCOUNTER27 0xb1b #define CSR_MHPMCOUNTER28 0xb1c #define CSR_MHPMCOUNTER29 0xb1d #define CSR_MHPMCOUNTER30 0xb1e #define CSR_MHPMCOUNTER31 0xb1f #define CSR_MUCOUNTEREN 0x320 #define CSR_MSCOUNTEREN 0x321 #define CSR_MHPMEVENT3 0x323 #define CSR_MHPMEVENT4 0x324 #define CSR_MHPMEVENT5 0x325 #define CSR_MHPMEVENT6 0x326 #define CSR_MHPMEVENT7 0x327 #define CSR_MHPMEVENT8 0x328 #define CSR_MHPMEVENT9 0x329 #define CSR_MHPMEVENT10 0x32a #define CSR_MHPMEVENT11 0x32b #define CSR_MHPMEVENT12 0x32c #define CSR_MHPMEVENT13 0x32d #define CSR_MHPMEVENT14 0x32e #define CSR_MHPMEVENT15 0x32f #define CSR_MHPMEVENT16 0x330 #define CSR_MHPMEVENT17 0x331 #define CSR_MHPMEVENT18 0x332 #define CSR_MHPMEVENT19 0x333 #define CSR_MHPMEVENT20 0x334 #define CSR_MHPMEVENT21 0x335 #define CSR_MHPMEVENT22 0x336 #define CSR_MHPMEVENT23 0x337 #define CSR_MHPMEVENT24 0x338 #define CSR_MHPMEVENT25 0x339 #define CSR_MHPMEVENT26 0x33a #define CSR_MHPMEVENT27 0x33b #define CSR_MHPMEVENT28 0x33c #define CSR_MHPMEVENT29 0x33d #define CSR_MHPMEVENT30 0x33e #define CSR_MHPMEVENT31 0x33f #define CSR_MVENDORID 0xf11 #define CSR_MARCHID 0xf12 #define CSR_MIMPID 0xf13 #define CSR_MHARTID 0xf14 #define CSR_CYCLEH 0xc80 #define CSR_TIMEH 0xc81 #define CSR_INSTRETH 0xc82 #define CSR_HPMCOUNTER3H 0xc83 #define CSR_HPMCOUNTER4H 0xc84 #define CSR_HPMCOUNTER5H 0xc85 #define CSR_HPMCOUNTER6H 0xc86 #define CSR_HPMCOUNTER7H 0xc87 #define CSR_HPMCOUNTER8H 0xc88 #define CSR_HPMCOUNTER9H 0xc89 #define CSR_HPMCOUNTER10H 0xc8a #define CSR_HPMCOUNTER11H 0xc8b #define CSR_HPMCOUNTER12H 0xc8c #define CSR_HPMCOUNTER13H 0xc8d #define CSR_HPMCOUNTER14H 0xc8e #define CSR_HPMCOUNTER15H 0xc8f #define CSR_HPMCOUNTER16H 0xc90 #define CSR_HPMCOUNTER17H 0xc91 #define CSR_HPMCOUNTER18H 0xc92 #define CSR_HPMCOUNTER19H 0xc93 #define CSR_HPMCOUNTER20H 0xc94 #define CSR_HPMCOUNTER21H 0xc95 #define CSR_HPMCOUNTER22H 0xc96 #define CSR_HPMCOUNTER23H 0xc97 #define CSR_HPMCOUNTER24H 0xc98 #define CSR_HPMCOUNTER25H 0xc99 #define CSR_HPMCOUNTER26H 0xc9a #define CSR_HPMCOUNTER27H 0xc9b #define CSR_HPMCOUNTER28H 0xc9c #define CSR_HPMCOUNTER29H 0xc9d #define CSR_HPMCOUNTER30H 0xc9e #define CSR_HPMCOUNTER31H 0xc9f #define CSR_MCYCLEH 0xb80 #define CSR_MINSTRETH 0xb82 #define CSR_MHPMCOUNTER3H 0xb83 #define CSR_MHPMCOUNTER4H 0xb84 #define CSR_MHPMCOUNTER5H 0xb85 #define CSR_MHPMCOUNTER6H 0xb86 #define CSR_MHPMCOUNTER7H 0xb87 #define CSR_MHPMCOUNTER8H 0xb88 #define CSR_MHPMCOUNTER9H 0xb89 #define CSR_MHPMCOUNTER10H 0xb8a #define CSR_MHPMCOUNTER11H 0xb8b #define CSR_MHPMCOUNTER12H 0xb8c #define CSR_MHPMCOUNTER13H 0xb8d #define CSR_MHPMCOUNTER14H 0xb8e #define CSR_MHPMCOUNTER15H 0xb8f #define CSR_MHPMCOUNTER16H 0xb90 #define CSR_MHPMCOUNTER17H 0xb91 #define CSR_MHPMCOUNTER18H 0xb92 #define CSR_MHPMCOUNTER19H 0xb93 #define CSR_MHPMCOUNTER20H 0xb94 #define CSR_MHPMCOUNTER21H 0xb95 #define CSR_MHPMCOUNTER22H 0xb96 #define CSR_MHPMCOUNTER23H 0xb97 #define CSR_MHPMCOUNTER24H 0xb98 #define CSR_MHPMCOUNTER25H 0xb99 #define CSR_MHPMCOUNTER26H 0xb9a #define CSR_MHPMCOUNTER27H 0xb9b #define CSR_MHPMCOUNTER28H 0xb9c #define CSR_MHPMCOUNTER29H 0xb9d #define CSR_MHPMCOUNTER30H 0xb9e #define CSR_MHPMCOUNTER31H 0xb9f #define CSR_MTVT 0x307 #define CSR_MNXTI 0x345 #define CSR_MCOUNTINHIBIT 0x320 #define CSR_MNVEC 0x7C3 #define CSR_MTVT2 0x7EC #define CSR_JALMNXTI 0x7ED #define CSR_PUSHMCAUSE 0x7EE #define CSR_PUSHMEPC 0x7EF #define CSR_PUSHMSUBM 0x7EB #define CSR_WFE 0x810 #define CSR_SLEEPVALUE 0x811 #define CSR_TXEVT 0x812 #define CSR_MMISC_CTL 0x7d0 #define CSR_MSUBM 0x7c4 #define CAUSE_MISALIGNED_FETCH 0x0 #define CAUSE_FAULT_FETCH 0x1 #define CAUSE_ILLEGAL_INSTRUCTION 0x2 #define CAUSE_BREAKPOINT 0x3 #define CAUSE_MISALIGNED_LOAD 0x4 #define CAUSE_FAULT_LOAD 0x5 #define CAUSE_MISALIGNED_STORE 0x6 #define CAUSE_FAULT_STORE 0x7 #define CAUSE_USER_ECALL 0x8 #define CAUSE_SUPERVISOR_ECALL 0x9 #define CAUSE_HYPERVISOR_ECALL 0xa #define CAUSE_MACHINE_ECALL 0xb #endif #ifdef DECLARE_INSN DECLARE_INSN(beq, MATCH_BEQ, MASK_BEQ) DECLARE_INSN(bne, MATCH_BNE, MASK_BNE) DECLARE_INSN(blt, MATCH_BLT, MASK_BLT) DECLARE_INSN(bge, MATCH_BGE, MASK_BGE) DECLARE_INSN(bltu, MATCH_BLTU, MASK_BLTU) DECLARE_INSN(bgeu, MATCH_BGEU, MASK_BGEU) DECLARE_INSN(jalr, MATCH_JALR, MASK_JALR) DECLARE_INSN(jal, MATCH_JAL, MASK_JAL) DECLARE_INSN(lui, MATCH_LUI, MASK_LUI) DECLARE_INSN(auipc, MATCH_AUIPC, MASK_AUIPC) DECLARE_INSN(addi, MATCH_ADDI, MASK_ADDI) DECLARE_INSN(slli, MATCH_SLLI, MASK_SLLI) DECLARE_INSN(slti, MATCH_SLTI, MASK_SLTI) DECLARE_INSN(sltiu, MATCH_SLTIU, MASK_SLTIU) DECLARE_INSN(xori, MATCH_XORI, MASK_XORI) DECLARE_INSN(srli, MATCH_SRLI, MASK_SRLI) DECLARE_INSN(srai, MATCH_SRAI, MASK_SRAI) DECLARE_INSN(ori, MATCH_ORI, MASK_ORI) DECLARE_INSN(andi, MATCH_ANDI, MASK_ANDI) DECLARE_INSN(add, MATCH_ADD, MASK_ADD) DECLARE_INSN(sub, MATCH_SUB, MASK_SUB) DECLARE_INSN(sll, MATCH_SLL, MASK_SLL) DECLARE_INSN(slt, MATCH_SLT, MASK_SLT) DECLARE_INSN(sltu, MATCH_SLTU, MASK_SLTU) DECLARE_INSN(xor, MATCH_XOR, MASK_XOR) DECLARE_INSN(srl, MATCH_SRL, MASK_SRL) DECLARE_INSN(sra, MATCH_SRA, MASK_SRA) DECLARE_INSN(or, MATCH_OR, MASK_OR) DECLARE_INSN(and, MATCH_AND, MASK_AND) DECLARE_INSN(addiw, MATCH_ADDIW, MASK_ADDIW) DECLARE_INSN(slliw, MATCH_SLLIW, MASK_SLLIW) DECLARE_INSN(srliw, MATCH_SRLIW, MASK_SRLIW) DECLARE_INSN(sraiw, MATCH_SRAIW, MASK_SRAIW) DECLARE_INSN(addw, MATCH_ADDW, MASK_ADDW) DECLARE_INSN(subw, MATCH_SUBW, MASK_SUBW) DECLARE_INSN(sllw, MATCH_SLLW, MASK_SLLW) DECLARE_INSN(srlw, MATCH_SRLW, MASK_SRLW) DECLARE_INSN(sraw, MATCH_SRAW, MASK_SRAW) DECLARE_INSN(lb, MATCH_LB, MASK_LB) DECLARE_INSN(lh, MATCH_LH, MASK_LH) DECLARE_INSN(lw, MATCH_LW, MASK_LW) DECLARE_INSN(ld, MATCH_LD, MASK_LD) DECLARE_INSN(lbu, MATCH_LBU, MASK_LBU) DECLARE_INSN(lhu, MATCH_LHU, MASK_LHU) DECLARE_INSN(lwu, MATCH_LWU, MASK_LWU) DECLARE_INSN(sb, MATCH_SB, MASK_SB) DECLARE_INSN(sh, MATCH_SH, MASK_SH) DECLARE_INSN(sw, MATCH_SW, MASK_SW) DECLARE_INSN(sd, MATCH_SD, MASK_SD) DECLARE_INSN(fence, MATCH_FENCE, MASK_FENCE) DECLARE_INSN(fence_i, MATCH_FENCE_I, MASK_FENCE_I) DECLARE_INSN(mul, MATCH_MUL, MASK_MUL) DECLARE_INSN(mulh, MATCH_MULH, MASK_MULH) DECLARE_INSN(mulhsu, MATCH_MULHSU, MASK_MULHSU) DECLARE_INSN(mulhu, MATCH_MULHU, MASK_MULHU) DECLARE_INSN(div, MATCH_DIV, MASK_DIV) DECLARE_INSN(divu, MATCH_DIVU, MASK_DIVU) DECLARE_INSN(rem, MATCH_REM, MASK_REM) DECLARE_INSN(remu, MATCH_REMU, MASK_REMU) DECLARE_INSN(mulw, MATCH_MULW, MASK_MULW) DECLARE_INSN(divw, MATCH_DIVW, MASK_DIVW) DECLARE_INSN(divuw, MATCH_DIVUW, MASK_DIVUW) DECLARE_INSN(remw, MATCH_REMW, MASK_REMW) DECLARE_INSN(remuw, MATCH_REMUW, MASK_REMUW) DECLARE_INSN(amoadd_w, MATCH_AMOADD_W, MASK_AMOADD_W) DECLARE_INSN(amoxor_w, MATCH_AMOXOR_W, MASK_AMOXOR_W) DECLARE_INSN(amoor_w, MATCH_AMOOR_W, MASK_AMOOR_W) DECLARE_INSN(amoand_w, MATCH_AMOAND_W, MASK_AMOAND_W) DECLARE_INSN(amomin_w, MATCH_AMOMIN_W, MASK_AMOMIN_W) DECLARE_INSN(amomax_w, MATCH_AMOMAX_W, MASK_AMOMAX_W) DECLARE_INSN(amominu_w, MATCH_AMOMINU_W, MASK_AMOMINU_W) DECLARE_INSN(amomaxu_w, MATCH_AMOMAXU_W, MASK_AMOMAXU_W) DECLARE_INSN(amoswap_w, MATCH_AMOSWAP_W, MASK_AMOSWAP_W) DECLARE_INSN(lr_w, MATCH_LR_W, MASK_LR_W) DECLARE_INSN(sc_w, MATCH_SC_W, MASK_SC_W) DECLARE_INSN(amoadd_d, MATCH_AMOADD_D, MASK_AMOADD_D) DECLARE_INSN(amoxor_d, MATCH_AMOXOR_D, MASK_AMOXOR_D) DECLARE_INSN(amoor_d, MATCH_AMOOR_D, MASK_AMOOR_D) DECLARE_INSN(amoand_d, MATCH_AMOAND_D, MASK_AMOAND_D) DECLARE_INSN(amomin_d, MATCH_AMOMIN_D, MASK_AMOMIN_D) DECLARE_INSN(amomax_d, MATCH_AMOMAX_D, MASK_AMOMAX_D) DECLARE_INSN(amominu_d, MATCH_AMOMINU_D, MASK_AMOMINU_D) DECLARE_INSN(amomaxu_d, MATCH_AMOMAXU_D, MASK_AMOMAXU_D) DECLARE_INSN(amoswap_d, MATCH_AMOSWAP_D, MASK_AMOSWAP_D) DECLARE_INSN(lr_d, MATCH_LR_D, MASK_LR_D) DECLARE_INSN(sc_d, MATCH_SC_D, MASK_SC_D) DECLARE_INSN(ecall, MATCH_ECALL, MASK_ECALL) DECLARE_INSN(ebreak, MATCH_EBREAK, MASK_EBREAK) DECLARE_INSN(uret, MATCH_URET, MASK_URET) DECLARE_INSN(sret, MATCH_SRET, MASK_SRET) DECLARE_INSN(hret, MATCH_HRET, MASK_HRET) DECLARE_INSN(mret, MATCH_MRET, MASK_MRET) DECLARE_INSN(dret, MATCH_DRET, MASK_DRET) DECLARE_INSN(sfence_vm, MATCH_SFENCE_VM, MASK_SFENCE_VM) DECLARE_INSN(wfi, MATCH_WFI, MASK_WFI) DECLARE_INSN(csrrw, MATCH_CSRRW, MASK_CSRRW) DECLARE_INSN(csrrs, MATCH_CSRRS, MASK_CSRRS) DECLARE_INSN(csrrc, MATCH_CSRRC, MASK_CSRRC) DECLARE_INSN(csrrwi, MATCH_CSRRWI, MASK_CSRRWI) DECLARE_INSN(csrrsi, MATCH_CSRRSI, MASK_CSRRSI) DECLARE_INSN(csrrci, MATCH_CSRRCI, MASK_CSRRCI) DECLARE_INSN(fadd_s, MATCH_FADD_S, MASK_FADD_S) DECLARE_INSN(fsub_s, MATCH_FSUB_S, MASK_FSUB_S) DECLARE_INSN(fmul_s, MATCH_FMUL_S, MASK_FMUL_S) DECLARE_INSN(fdiv_s, MATCH_FDIV_S, MASK_FDIV_S) DECLARE_INSN(fsgnj_s, MATCH_FSGNJ_S, MASK_FSGNJ_S) DECLARE_INSN(fsgnjn_s, MATCH_FSGNJN_S, MASK_FSGNJN_S) DECLARE_INSN(fsgnjx_s, MATCH_FSGNJX_S, MASK_FSGNJX_S) DECLARE_INSN(fmin_s, MATCH_FMIN_S, MASK_FMIN_S) DECLARE_INSN(fmax_s, MATCH_FMAX_S, MASK_FMAX_S) DECLARE_INSN(fsqrt_s, MATCH_FSQRT_S, MASK_FSQRT_S) DECLARE_INSN(fadd_d, MATCH_FADD_D, MASK_FADD_D) DECLARE_INSN(fsub_d, MATCH_FSUB_D, MASK_FSUB_D) DECLARE_INSN(fmul_d, MATCH_FMUL_D, MASK_FMUL_D) DECLARE_INSN(fdiv_d, MATCH_FDIV_D, MASK_FDIV_D) DECLARE_INSN(fsgnj_d, MATCH_FSGNJ_D, MASK_FSGNJ_D) DECLARE_INSN(fsgnjn_d, MATCH_FSGNJN_D, MASK_FSGNJN_D) DECLARE_INSN(fsgnjx_d, MATCH_FSGNJX_D, MASK_FSGNJX_D) DECLARE_INSN(fmin_d, MATCH_FMIN_D, MASK_FMIN_D) DECLARE_INSN(fmax_d, MATCH_FMAX_D, MASK_FMAX_D) DECLARE_INSN(fcvt_s_d, MATCH_FCVT_S_D, MASK_FCVT_S_D) DECLARE_INSN(fcvt_d_s, MATCH_FCVT_D_S, MASK_FCVT_D_S) DECLARE_INSN(fsqrt_d, MATCH_FSQRT_D, MASK_FSQRT_D) DECLARE_INSN(fle_s, MATCH_FLE_S, MASK_FLE_S) DECLARE_INSN(flt_s, MATCH_FLT_S, MASK_FLT_S) DECLARE_INSN(feq_s, MATCH_FEQ_S, MASK_FEQ_S) DECLARE_INSN(fle_d, MATCH_FLE_D, MASK_FLE_D) DECLARE_INSN(flt_d, MATCH_FLT_D, MASK_FLT_D) DECLARE_INSN(feq_d, MATCH_FEQ_D, MASK_FEQ_D) DECLARE_INSN(fcvt_w_s, MATCH_FCVT_W_S, MASK_FCVT_W_S) DECLARE_INSN(fcvt_wu_s, MATCH_FCVT_WU_S, MASK_FCVT_WU_S) DECLARE_INSN(fcvt_l_s, MATCH_FCVT_L_S, MASK_FCVT_L_S) DECLARE_INSN(fcvt_lu_s, MATCH_FCVT_LU_S, MASK_FCVT_LU_S) DECLARE_INSN(fmv_x_s, MATCH_FMV_X_S, MASK_FMV_X_S) DECLARE_INSN(fclass_s, MATCH_FCLASS_S, MASK_FCLASS_S) DECLARE_INSN(fcvt_w_d, MATCH_FCVT_W_D, MASK_FCVT_W_D) DECLARE_INSN(fcvt_wu_d, MATCH_FCVT_WU_D, MASK_FCVT_WU_D) DECLARE_INSN(fcvt_l_d, MATCH_FCVT_L_D, MASK_FCVT_L_D) DECLARE_INSN(fcvt_lu_d, MATCH_FCVT_LU_D, MASK_FCVT_LU_D) DECLARE_INSN(fmv_x_d, MATCH_FMV_X_D, MASK_FMV_X_D) DECLARE_INSN(fclass_d, MATCH_FCLASS_D, MASK_FCLASS_D) DECLARE_INSN(fcvt_s_w, MATCH_FCVT_S_W, MASK_FCVT_S_W) DECLARE_INSN(fcvt_s_wu, MATCH_FCVT_S_WU, MASK_FCVT_S_WU) DECLARE_INSN(fcvt_s_l, MATCH_FCVT_S_L, MASK_FCVT_S_L) DECLARE_INSN(fcvt_s_lu, MATCH_FCVT_S_LU, MASK_FCVT_S_LU) DECLARE_INSN(fmv_s_x, MATCH_FMV_S_X, MASK_FMV_S_X) DECLARE_INSN(fcvt_d_w, MATCH_FCVT_D_W, MASK_FCVT_D_W) DECLARE_INSN(fcvt_d_wu, MATCH_FCVT_D_WU, MASK_FCVT_D_WU) DECLARE_INSN(fcvt_d_l, MATCH_FCVT_D_L, MASK_FCVT_D_L) DECLARE_INSN(fcvt_d_lu, MATCH_FCVT_D_LU, MASK_FCVT_D_LU) DECLARE_INSN(fmv_d_x, MATCH_FMV_D_X, MASK_FMV_D_X) DECLARE_INSN(flw, MATCH_FLW, MASK_FLW) DECLARE_INSN(fld, MATCH_FLD, MASK_FLD) DECLARE_INSN(fsw, MATCH_FSW, MASK_FSW) DECLARE_INSN(fsd, MATCH_FSD, MASK_FSD) DECLARE_INSN(fmadd_s, MATCH_FMADD_S, MASK_FMADD_S) DECLARE_INSN(fmsub_s, MATCH_FMSUB_S, MASK_FMSUB_S) DECLARE_INSN(fnmsub_s, MATCH_FNMSUB_S, MASK_FNMSUB_S) DECLARE_INSN(fnmadd_s, MATCH_FNMADD_S, MASK_FNMADD_S) DECLARE_INSN(fmadd_d, MATCH_FMADD_D, MASK_FMADD_D) DECLARE_INSN(fmsub_d, MATCH_FMSUB_D, MASK_FMSUB_D) DECLARE_INSN(fnmsub_d, MATCH_FNMSUB_D, MASK_FNMSUB_D) DECLARE_INSN(fnmadd_d, MATCH_FNMADD_D, MASK_FNMADD_D) DECLARE_INSN(c_nop, MATCH_C_NOP, MASK_C_NOP) DECLARE_INSN(c_addi16sp, MATCH_C_ADDI16SP, MASK_C_ADDI16SP) DECLARE_INSN(c_jr, MATCH_C_JR, MASK_C_JR) DECLARE_INSN(c_jalr, MATCH_C_JALR, MASK_C_JALR) DECLARE_INSN(c_ebreak, MATCH_C_EBREAK, MASK_C_EBREAK) DECLARE_INSN(c_ld, MATCH_C_LD, MASK_C_LD) DECLARE_INSN(c_sd, MATCH_C_SD, MASK_C_SD) DECLARE_INSN(c_addiw, MATCH_C_ADDIW, MASK_C_ADDIW) DECLARE_INSN(c_ldsp, MATCH_C_LDSP, MASK_C_LDSP) DECLARE_INSN(c_sdsp, MATCH_C_SDSP, MASK_C_SDSP) DECLARE_INSN(c_addi4spn, MATCH_C_ADDI4SPN, MASK_C_ADDI4SPN) DECLARE_INSN(c_fld, MATCH_C_FLD, MASK_C_FLD) DECLARE_INSN(c_lw, MATCH_C_LW, MASK_C_LW) DECLARE_INSN(c_flw, MATCH_C_FLW, MASK_C_FLW) DECLARE_INSN(c_fsd, MATCH_C_FSD, MASK_C_FSD) DECLARE_INSN(c_sw, MATCH_C_SW, MASK_C_SW) DECLARE_INSN(c_fsw, MATCH_C_FSW, MASK_C_FSW) DECLARE_INSN(c_addi, MATCH_C_ADDI, MASK_C_ADDI) DECLARE_INSN(c_jal, MATCH_C_JAL, MASK_C_JAL) DECLARE_INSN(c_li, MATCH_C_LI, MASK_C_LI) DECLARE_INSN(c_lui, MATCH_C_LUI, MASK_C_LUI) DECLARE_INSN(c_srli, MATCH_C_SRLI, MASK_C_SRLI) DECLARE_INSN(c_srai, MATCH_C_SRAI, MASK_C_SRAI) DECLARE_INSN(c_andi, MATCH_C_ANDI, MASK_C_ANDI) DECLARE_INSN(c_sub, MATCH_C_SUB, MASK_C_SUB) DECLARE_INSN(c_xor, MATCH_C_XOR, MASK_C_XOR) DECLARE_INSN(c_or, MATCH_C_OR, MASK_C_OR) DECLARE_INSN(c_and, MATCH_C_AND, MASK_C_AND) DECLARE_INSN(c_subw, MATCH_C_SUBW, MASK_C_SUBW) DECLARE_INSN(c_addw, MATCH_C_ADDW, MASK_C_ADDW) DECLARE_INSN(c_j, MATCH_C_J, MASK_C_J) DECLARE_INSN(c_beqz, MATCH_C_BEQZ, MASK_C_BEQZ) DECLARE_INSN(c_bnez, MATCH_C_BNEZ, MASK_C_BNEZ) DECLARE_INSN(c_slli, MATCH_C_SLLI, MASK_C_SLLI) DECLARE_INSN(c_fldsp, MATCH_C_FLDSP, MASK_C_FLDSP) DECLARE_INSN(c_lwsp, MATCH_C_LWSP, MASK_C_LWSP) DECLARE_INSN(c_flwsp, MATCH_C_FLWSP, MASK_C_FLWSP) DECLARE_INSN(c_mv, MATCH_C_MV, MASK_C_MV) DECLARE_INSN(c_add, MATCH_C_ADD, MASK_C_ADD) DECLARE_INSN(c_fsdsp, MATCH_C_FSDSP, MASK_C_FSDSP) DECLARE_INSN(c_swsp, MATCH_C_SWSP, MASK_C_SWSP) DECLARE_INSN(c_fswsp, MATCH_C_FSWSP, MASK_C_FSWSP) DECLARE_INSN(custom0, MATCH_CUSTOM0, MASK_CUSTOM0) DECLARE_INSN(custom0_rs1, MATCH_CUSTOM0_RS1, MASK_CUSTOM0_RS1) DECLARE_INSN(custom0_rs1_rs2, MATCH_CUSTOM0_RS1_RS2, MASK_CUSTOM0_RS1_RS2) DECLARE_INSN(custom0_rd, MATCH_CUSTOM0_RD, MASK_CUSTOM0_RD) DECLARE_INSN(custom0_rd_rs1, MATCH_CUSTOM0_RD_RS1, MASK_CUSTOM0_RD_RS1) DECLARE_INSN(custom0_rd_rs1_rs2, MATCH_CUSTOM0_RD_RS1_RS2, MASK_CUSTOM0_RD_RS1_RS2) DECLARE_INSN(custom1, MATCH_CUSTOM1, MASK_CUSTOM1) DECLARE_INSN(custom1_rs1, MATCH_CUSTOM1_RS1, MASK_CUSTOM1_RS1) DECLARE_INSN(custom1_rs1_rs2, MATCH_CUSTOM1_RS1_RS2, MASK_CUSTOM1_RS1_RS2) DECLARE_INSN(custom1_rd, MATCH_CUSTOM1_RD, MASK_CUSTOM1_RD) DECLARE_INSN(custom1_rd_rs1, MATCH_CUSTOM1_RD_RS1, MASK_CUSTOM1_RD_RS1) DECLARE_INSN(custom1_rd_rs1_rs2, MATCH_CUSTOM1_RD_RS1_RS2, MASK_CUSTOM1_RD_RS1_RS2) DECLARE_INSN(custom2, MATCH_CUSTOM2, MASK_CUSTOM2) DECLARE_INSN(custom2_rs1, MATCH_CUSTOM2_RS1, MASK_CUSTOM2_RS1) DECLARE_INSN(custom2_rs1_rs2, MATCH_CUSTOM2_RS1_RS2, MASK_CUSTOM2_RS1_RS2) DECLARE_INSN(custom2_rd, MATCH_CUSTOM2_RD, MASK_CUSTOM2_RD) DECLARE_INSN(custom2_rd_rs1, MATCH_CUSTOM2_RD_RS1, MASK_CUSTOM2_RD_RS1) DECLARE_INSN(custom2_rd_rs1_rs2, MATCH_CUSTOM2_RD_RS1_RS2, MASK_CUSTOM2_RD_RS1_RS2) DECLARE_INSN(custom3, MATCH_CUSTOM3, MASK_CUSTOM3) DECLARE_INSN(custom3_rs1, MATCH_CUSTOM3_RS1, MASK_CUSTOM3_RS1) DECLARE_INSN(custom3_rs1_rs2, MATCH_CUSTOM3_RS1_RS2, MASK_CUSTOM3_RS1_RS2) DECLARE_INSN(custom3_rd, MATCH_CUSTOM3_RD, MASK_CUSTOM3_RD) DECLARE_INSN(custom3_rd_rs1, MATCH_CUSTOM3_RD_RS1, MASK_CUSTOM3_RD_RS1) DECLARE_INSN(custom3_rd_rs1_rs2, MATCH_CUSTOM3_RD_RS1_RS2, MASK_CUSTOM3_RD_RS1_RS2) #endif #ifdef DECLARE_CSR DECLARE_CSR(fflags, CSR_FFLAGS) DECLARE_CSR(frm, CSR_FRM) DECLARE_CSR(fcsr, CSR_FCSR) DECLARE_CSR(cycle, CSR_CYCLE) DECLARE_CSR(time, CSR_TIME) DECLARE_CSR(instret, CSR_INSTRET) DECLARE_CSR(hpmcounter3, CSR_HPMCOUNTER3) DECLARE_CSR(hpmcounter4, CSR_HPMCOUNTER4) DECLARE_CSR(hpmcounter5, CSR_HPMCOUNTER5) DECLARE_CSR(hpmcounter6, CSR_HPMCOUNTER6) DECLARE_CSR(hpmcounter7, CSR_HPMCOUNTER7) DECLARE_CSR(hpmcounter8, CSR_HPMCOUNTER8) DECLARE_CSR(hpmcounter9, CSR_HPMCOUNTER9) DECLARE_CSR(hpmcounter10, CSR_HPMCOUNTER10) DECLARE_CSR(hpmcounter11, CSR_HPMCOUNTER11) DECLARE_CSR(hpmcounter12, CSR_HPMCOUNTER12) DECLARE_CSR(hpmcounter13, CSR_HPMCOUNTER13) DECLARE_CSR(hpmcounter14, CSR_HPMCOUNTER14) DECLARE_CSR(hpmcounter15, CSR_HPMCOUNTER15) DECLARE_CSR(hpmcounter16, CSR_HPMCOUNTER16) DECLARE_CSR(hpmcounter17, CSR_HPMCOUNTER17) DECLARE_CSR(hpmcounter18, CSR_HPMCOUNTER18) DECLARE_CSR(hpmcounter19, CSR_HPMCOUNTER19) DECLARE_CSR(hpmcounter20, CSR_HPMCOUNTER20) DECLARE_CSR(hpmcounter21, CSR_HPMCOUNTER21) DECLARE_CSR(hpmcounter22, CSR_HPMCOUNTER22) DECLARE_CSR(hpmcounter23, CSR_HPMCOUNTER23) DECLARE_CSR(hpmcounter24, CSR_HPMCOUNTER24) DECLARE_CSR(hpmcounter25, CSR_HPMCOUNTER25) DECLARE_CSR(hpmcounter26, CSR_HPMCOUNTER26) DECLARE_CSR(hpmcounter27, CSR_HPMCOUNTER27) DECLARE_CSR(hpmcounter28, CSR_HPMCOUNTER28) DECLARE_CSR(hpmcounter29, CSR_HPMCOUNTER29) DECLARE_CSR(hpmcounter30, CSR_HPMCOUNTER30) DECLARE_CSR(hpmcounter31, CSR_HPMCOUNTER31) DECLARE_CSR(sstatus, CSR_SSTATUS) DECLARE_CSR(sie, CSR_SIE) DECLARE_CSR(stvec, CSR_STVEC) DECLARE_CSR(sscratch, CSR_SSCRATCH) DECLARE_CSR(sepc, CSR_SEPC) DECLARE_CSR(scause, CSR_SCAUSE) DECLARE_CSR(sbadaddr, CSR_SBADADDR) DECLARE_CSR(sip, CSR_SIP) DECLARE_CSR(sptbr, CSR_SPTBR) DECLARE_CSR(mstatus, CSR_MSTATUS) DECLARE_CSR(misa, CSR_MISA) DECLARE_CSR(medeleg, CSR_MEDELEG) DECLARE_CSR(mideleg, CSR_MIDELEG) DECLARE_CSR(mie, CSR_MIE) DECLARE_CSR(mtvec, CSR_MTVEC) DECLARE_CSR(mscratch, CSR_MSCRATCH) DECLARE_CSR(mepc, CSR_MEPC) DECLARE_CSR(mcause, CSR_MCAUSE) DECLARE_CSR(mbadaddr, CSR_MBADADDR) DECLARE_CSR(mip, CSR_MIP) DECLARE_CSR(tselect, CSR_TSELECT) DECLARE_CSR(tdata1, CSR_TDATA1) DECLARE_CSR(tdata2, CSR_TDATA2) DECLARE_CSR(tdata3, CSR_TDATA3) DECLARE_CSR(dcsr, CSR_DCSR) DECLARE_CSR(dpc, CSR_DPC) DECLARE_CSR(dscratch, CSR_DSCRATCH) DECLARE_CSR(mcycle, CSR_MCYCLE) DECLARE_CSR(minstret, CSR_MINSTRET) DECLARE_CSR(mhpmcounter3, CSR_MHPMCOUNTER3) DECLARE_CSR(mhpmcounter4, CSR_MHPMCOUNTER4) DECLARE_CSR(mhpmcounter5, CSR_MHPMCOUNTER5) DECLARE_CSR(mhpmcounter6, CSR_MHPMCOUNTER6) DECLARE_CSR(mhpmcounter7, CSR_MHPMCOUNTER7) DECLARE_CSR(mhpmcounter8, CSR_MHPMCOUNTER8) DECLARE_CSR(mhpmcounter9, CSR_MHPMCOUNTER9) DECLARE_CSR(mhpmcounter10, CSR_MHPMCOUNTER10) DECLARE_CSR(mhpmcounter11, CSR_MHPMCOUNTER11) DECLARE_CSR(mhpmcounter12, CSR_MHPMCOUNTER12) DECLARE_CSR(mhpmcounter13, CSR_MHPMCOUNTER13) DECLARE_CSR(mhpmcounter14, CSR_MHPMCOUNTER14) DECLARE_CSR(mhpmcounter15, CSR_MHPMCOUNTER15) DECLARE_CSR(mhpmcounter16, CSR_MHPMCOUNTER16) DECLARE_CSR(mhpmcounter17, CSR_MHPMCOUNTER17) DECLARE_CSR(mhpmcounter18, CSR_MHPMCOUNTER18) DECLARE_CSR(mhpmcounter19, CSR_MHPMCOUNTER19) DECLARE_CSR(mhpmcounter20, CSR_MHPMCOUNTER20) DECLARE_CSR(mhpmcounter21, CSR_MHPMCOUNTER21) DECLARE_CSR(mhpmcounter22, CSR_MHPMCOUNTER22) DECLARE_CSR(mhpmcounter23, CSR_MHPMCOUNTER23) DECLARE_CSR(mhpmcounter24, CSR_MHPMCOUNTER24) DECLARE_CSR(mhpmcounter25, CSR_MHPMCOUNTER25) DECLARE_CSR(mhpmcounter26, CSR_MHPMCOUNTER26) DECLARE_CSR(mhpmcounter27, CSR_MHPMCOUNTER27) DECLARE_CSR(mhpmcounter28, CSR_MHPMCOUNTER28) DECLARE_CSR(mhpmcounter29, CSR_MHPMCOUNTER29) DECLARE_CSR(mhpmcounter30, CSR_MHPMCOUNTER30) DECLARE_CSR(mhpmcounter31, CSR_MHPMCOUNTER31) DECLARE_CSR(mucounteren, CSR_MUCOUNTEREN) DECLARE_CSR(mscounteren, CSR_MSCOUNTEREN) DECLARE_CSR(mhpmevent3, CSR_MHPMEVENT3) DECLARE_CSR(mhpmevent4, CSR_MHPMEVENT4) DECLARE_CSR(mhpmevent5, CSR_MHPMEVENT5) DECLARE_CSR(mhpmevent6, CSR_MHPMEVENT6) DECLARE_CSR(mhpmevent7, CSR_MHPMEVENT7) DECLARE_CSR(mhpmevent8, CSR_MHPMEVENT8) DECLARE_CSR(mhpmevent9, CSR_MHPMEVENT9) DECLARE_CSR(mhpmevent10, CSR_MHPMEVENT10) DECLARE_CSR(mhpmevent11, CSR_MHPMEVENT11) DECLARE_CSR(mhpmevent12, CSR_MHPMEVENT12) DECLARE_CSR(mhpmevent13, CSR_MHPMEVENT13) DECLARE_CSR(mhpmevent14, CSR_MHPMEVENT14) DECLARE_CSR(mhpmevent15, CSR_MHPMEVENT15) DECLARE_CSR(mhpmevent16, CSR_MHPMEVENT16) DECLARE_CSR(mhpmevent17, CSR_MHPMEVENT17) DECLARE_CSR(mhpmevent18, CSR_MHPMEVENT18) DECLARE_CSR(mhpmevent19, CSR_MHPMEVENT19) DECLARE_CSR(mhpmevent20, CSR_MHPMEVENT20) DECLARE_CSR(mhpmevent21, CSR_MHPMEVENT21) DECLARE_CSR(mhpmevent22, CSR_MHPMEVENT22) DECLARE_CSR(mhpmevent23, CSR_MHPMEVENT23) DECLARE_CSR(mhpmevent24, CSR_MHPMEVENT24) DECLARE_CSR(mhpmevent25, CSR_MHPMEVENT25) DECLARE_CSR(mhpmevent26, CSR_MHPMEVENT26) DECLARE_CSR(mhpmevent27, CSR_MHPMEVENT27) DECLARE_CSR(mhpmevent28, CSR_MHPMEVENT28) DECLARE_CSR(mhpmevent29, CSR_MHPMEVENT29) DECLARE_CSR(mhpmevent30, CSR_MHPMEVENT30) DECLARE_CSR(mhpmevent31, CSR_MHPMEVENT31) DECLARE_CSR(mvendorid, CSR_MVENDORID) DECLARE_CSR(marchid, CSR_MARCHID) DECLARE_CSR(mimpid, CSR_MIMPID) DECLARE_CSR(mhartid, CSR_MHARTID) DECLARE_CSR(cycleh, CSR_CYCLEH) DECLARE_CSR(timeh, CSR_TIMEH) DECLARE_CSR(instreth, CSR_INSTRETH) DECLARE_CSR(hpmcounter3h, CSR_HPMCOUNTER3H) DECLARE_CSR(hpmcounter4h, CSR_HPMCOUNTER4H) DECLARE_CSR(hpmcounter5h, CSR_HPMCOUNTER5H) DECLARE_CSR(hpmcounter6h, CSR_HPMCOUNTER6H) DECLARE_CSR(hpmcounter7h, CSR_HPMCOUNTER7H) DECLARE_CSR(hpmcounter8h, CSR_HPMCOUNTER8H) DECLARE_CSR(hpmcounter9h, CSR_HPMCOUNTER9H) DECLARE_CSR(hpmcounter10h, CSR_HPMCOUNTER10H) DECLARE_CSR(hpmcounter11h, CSR_HPMCOUNTER11H) DECLARE_CSR(hpmcounter12h, CSR_HPMCOUNTER12H) DECLARE_CSR(hpmcounter13h, CSR_HPMCOUNTER13H) DECLARE_CSR(hpmcounter14h, CSR_HPMCOUNTER14H) DECLARE_CSR(hpmcounter15h, CSR_HPMCOUNTER15H) DECLARE_CSR(hpmcounter16h, CSR_HPMCOUNTER16H) DECLARE_CSR(hpmcounter17h, CSR_HPMCOUNTER17H) DECLARE_CSR(hpmcounter18h, CSR_HPMCOUNTER18H) DECLARE_CSR(hpmcounter19h, CSR_HPMCOUNTER19H) DECLARE_CSR(hpmcounter20h, CSR_HPMCOUNTER20H) DECLARE_CSR(hpmcounter21h, CSR_HPMCOUNTER21H) DECLARE_CSR(hpmcounter22h, CSR_HPMCOUNTER22H) DECLARE_CSR(hpmcounter23h, CSR_HPMCOUNTER23H) DECLARE_CSR(hpmcounter24h, CSR_HPMCOUNTER24H) DECLARE_CSR(hpmcounter25h, CSR_HPMCOUNTER25H) DECLARE_CSR(hpmcounter26h, CSR_HPMCOUNTER26H) DECLARE_CSR(hpmcounter27h, CSR_HPMCOUNTER27H) DECLARE_CSR(hpmcounter28h, CSR_HPMCOUNTER28H) DECLARE_CSR(hpmcounter29h, CSR_HPMCOUNTER29H) DECLARE_CSR(hpmcounter30h, CSR_HPMCOUNTER30H) DECLARE_CSR(hpmcounter31h, CSR_HPMCOUNTER31H) DECLARE_CSR(mcycleh, CSR_MCYCLEH) DECLARE_CSR(minstreth, CSR_MINSTRETH) DECLARE_CSR(mhpmcounter3h, CSR_MHPMCOUNTER3H) DECLARE_CSR(mhpmcounter4h, CSR_MHPMCOUNTER4H) DECLARE_CSR(mhpmcounter5h, CSR_MHPMCOUNTER5H) DECLARE_CSR(mhpmcounter6h, CSR_MHPMCOUNTER6H) DECLARE_CSR(mhpmcounter7h, CSR_MHPMCOUNTER7H) DECLARE_CSR(mhpmcounter8h, CSR_MHPMCOUNTER8H) DECLARE_CSR(mhpmcounter9h, CSR_MHPMCOUNTER9H) DECLARE_CSR(mhpmcounter10h, CSR_MHPMCOUNTER10H) DECLARE_CSR(mhpmcounter11h, CSR_MHPMCOUNTER11H) DECLARE_CSR(mhpmcounter12h, CSR_MHPMCOUNTER12H) DECLARE_CSR(mhpmcounter13h, CSR_MHPMCOUNTER13H) DECLARE_CSR(mhpmcounter14h, CSR_MHPMCOUNTER14H) DECLARE_CSR(mhpmcounter15h, CSR_MHPMCOUNTER15H) DECLARE_CSR(mhpmcounter16h, CSR_MHPMCOUNTER16H) DECLARE_CSR(mhpmcounter17h, CSR_MHPMCOUNTER17H) DECLARE_CSR(mhpmcounter18h, CSR_MHPMCOUNTER18H) DECLARE_CSR(mhpmcounter19h, CSR_MHPMCOUNTER19H) DECLARE_CSR(mhpmcounter20h, CSR_MHPMCOUNTER20H) DECLARE_CSR(mhpmcounter21h, CSR_MHPMCOUNTER21H) DECLARE_CSR(mhpmcounter22h, CSR_MHPMCOUNTER22H) DECLARE_CSR(mhpmcounter23h, CSR_MHPMCOUNTER23H) DECLARE_CSR(mhpmcounter24h, CSR_MHPMCOUNTER24H) DECLARE_CSR(mhpmcounter25h, CSR_MHPMCOUNTER25H) DECLARE_CSR(mhpmcounter26h, CSR_MHPMCOUNTER26H) DECLARE_CSR(mhpmcounter27h, CSR_MHPMCOUNTER27H) DECLARE_CSR(mhpmcounter28h, CSR_MHPMCOUNTER28H) DECLARE_CSR(mhpmcounter29h, CSR_MHPMCOUNTER29H) DECLARE_CSR(mhpmcounter30h, CSR_MHPMCOUNTER30H) DECLARE_CSR(mhpmcounter31h, CSR_MHPMCOUNTER31H) #endif #ifdef DECLARE_CAUSE DECLARE_CAUSE("misaligned fetch", CAUSE_MISALIGNED_FETCH) DECLARE_CAUSE("fault fetch", CAUSE_FAULT_FETCH) DECLARE_CAUSE("illegal instruction", CAUSE_ILLEGAL_INSTRUCTION) DECLARE_CAUSE("breakpoint", CAUSE_BREAKPOINT) DECLARE_CAUSE("misaligned load", CAUSE_MISALIGNED_LOAD) DECLARE_CAUSE("fault load", CAUSE_FAULT_LOAD) DECLARE_CAUSE("misaligned store", CAUSE_MISALIGNED_STORE) DECLARE_CAUSE("fault store", CAUSE_FAULT_STORE) DECLARE_CAUSE("user_ecall", CAUSE_USER_ECALL) DECLARE_CAUSE("supervisor_ecall", CAUSE_SUPERVISOR_ECALL) DECLARE_CAUSE("hypervisor_ecall", CAUSE_HYPERVISOR_ECALL) DECLARE_CAUSE("machine_ecall", CAUSE_MACHINE_ECALL) #endif
const Post = require("../models/post"); const { body, validationResult } = require("express-validator"); exports.getPosts = (req, res, next) => { const posts = Post.find() .then((posts) => { res.json({ posts: posts }); }) .catch((err) => console.log(err)); }; exports.createPost = (req, res, next) => { const post = new Post(req.body); post .save() .then((result) => { res.status(200).json({ post: result, }); }) .catch((error) => console.log(error)); next(); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CreateDocumentDialog = void 0; var _keyBy2 = _interopRequireDefault(require("lodash/keyBy")); var _react = _interopRequireWildcard(require("react")); var _ui = require("@sanity/ui"); var _components = require("@sanity/base/components"); var _hooks = require("@sanity/base/hooks"); var _internal = require("@sanity/base/_internal"); var _styledComponents = _interopRequireDefault(require("styled-components")); var _CreateDocumentItem = require("./CreateDocumentItem"); var _templateObject; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } var List = _styledComponents.default.ul(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n margin: 0;\n padding: 0;\n grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));\n"]))); var newDocumentOptions = (0, _internal.getNewDocumentOptions)(); var CreateDocumentDialog = /*#__PURE__*/(0, _react.memo)(_ref => { var templatePermissions = _ref.templatePermissions, isTemplatePermissionsLoading = _ref.isTemplatePermissionsLoading, onClose = _ref.onClose; var keyedPermissions = (0, _react.useMemo)(() => (0, _keyBy2.default)(templatePermissions, 'id'), [templatePermissions]); // note: this hook is called once in this component and passed via props for // performance reasons var _useCurrentUser = (0, _hooks.useCurrentUser)(), currentUser = _useCurrentUser.value; var content = newDocumentOptions.length <= 0 ? /*#__PURE__*/_react.default.createElement(_ui.Box, { paddingY: 5 }, /*#__PURE__*/_react.default.createElement(_ui.Text, { weight: "semibold", align: "center" }, "No initial value templates are configured.")) : /*#__PURE__*/_react.default.createElement(_ui.Grid, { gap: 3, as: List }, newDocumentOptions.map(item => { var _keyedPermissions$ite; var granted = Boolean(!isTemplatePermissionsLoading && ((_keyedPermissions$ite = keyedPermissions[item.id]) === null || _keyedPermissions$ite === void 0 ? void 0 : _keyedPermissions$ite.granted)); return /*#__PURE__*/_react.default.createElement(_ui.Box, { as: "li", key: item.id }, /*#__PURE__*/_react.default.createElement(_CreateDocumentItem.CreateDocumentItem, _extends({}, item, { granted: granted, currentUser: currentUser, onClick: onClose }))); })); return /*#__PURE__*/_react.default.createElement(_components.LegacyLayerProvider, { zOffset: "navbarDialog" }, /*#__PURE__*/_react.default.createElement(_ui.Dialog, { "data-testid": "default-layout-global-create-dialog", id: "create-document-dialog", onClickOutside: onClose, onClose: onClose, width: 2, header: "Create new document" }, /*#__PURE__*/_react.default.createElement(_ui.Box, { padding: 3 }, content))); }); exports.CreateDocumentDialog = CreateDocumentDialog; CreateDocumentDialog.displayName = 'CreateDocumentDialog';
import { wrapFontAwesomeIcon } from './icon-wrappers' import { faCarAlt } from '@fortawesome/free-solid-svg-icons/faCarAlt' const CarAltSolid = wrapFontAwesomeIcon(faCarAlt, 'Solid') export default CarAltSolid
import random from cards import initial_card_deck class CardDeck: def __init__(self): self.shuffled = False self.starting_cards = initial_card_deck self.cards = self.starting_cards @property def cards(self) -> list: return self._cards @cards.setter def cards(self, cards: tuple): self._cards = list(cards) def reset_cards(self) -> None: self.cards = self.starting_cards self.shuffled = False def shuffle(self) -> bool: cards = self.cards count = len(cards) for i in range(count): randindex = random.randrange(count) cards[i], cards[randindex] = cards[randindex], cards[i] self.cards = cards self.shuffled = True return self.shuffled def draw_card(self) -> str: return self.cards.pop(0) def draw_cards(self, size: int) -> list: hand = [] for i in range(size): hand.append(self.draw_card()) return hand def __repr__(self): return f"Cards: {self.cards}, Shuffled: {self.shuffled}"
/********************************************************************************************************************** * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the License). You may not use this file except in compliance * * with the License. A copy of the License is located at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * * and limitations under the License. * *********************************************************************************************************************/ import React, { useMemo, useState, useEffect, useCallback } from "react"; import { useDispatch, useSelector } from "react-redux"; import cs from "classnames"; import PropTypes from "prop-types"; import Joyride, { STATUS } from "react-joyride"; import KendraResultPage from "../../components/KendraResultPage/KendraResultPage"; import PersonaSelector from "../PersonaSelector/PersonaSelector"; import { MIN_SEARCH_QUERY_LENGTH } from "../../constants/configs"; import css from "./KendraResults.scss"; import { submitKendraFeedback } from "../../store/entities/searchResults/actions"; import { dismissWalkthrough } from "../../store/ui/actions"; import { getHasDismissedWalkthrough } from "../../store/ui/selectors"; KendraResults.propTypes = { className: PropTypes.string, results: PropTypes.array, searchQuery: PropTypes.string, searchStatus: PropTypes.string, searchTotalDocuments: PropTypes.number, searchTotalMatches: PropTypes.number, }; KendraResults.defaultProps = { results: [], }; export default function KendraResults({ className, results, filteredResults, searchQuery, searchStatus, searchPersona, searchTotalDocuments, searchTotalMatches, kendraQueryId, filteredQueryId, resultCount, filteredResultCount, showPersonaSelector, isComparing, ...rest }) { const dispatch = useDispatch(); const isQueryLongEnough = searchQuery && searchQuery.length >= MIN_SEARCH_QUERY_LENGTH; if (!searchStatus || !searchQuery) return null; const hasFilteredResults = searchStatus === "success" && filteredResults && searchPersona && showPersonaSelector; const [width, setWidth] = useState(window.innerWidth); useEffect(() => { function resized() { setWidth(window.innerWidth); } window.addEventListener("resize", resized); return () => { window.removeEventListener("resize", resized); }; }, []); const canShowSideBySide = useMemo(() => width >= 1000, [width]); return ( <div className={cs(css.base, hasFilteredResults && css.doubleWidth)}> <nav {...rest} className={css.topNav}> <header className={cs(isComparing && css.comparing)}> <h2>Amazon Kendra{!isComparing ? " Results" : ""}</h2> {isComparing ? <p>Semantic search results</p> : null} </header> {!isQueryLongEnough && ( <p className={css.noContent}> Enter a search query longer than {MIN_SEARCH_QUERY_LENGTH - 1}{" "} characters to initiate a search. </p> )} {/* {!searchTotalDocuments && searchStatus !== 'pending' && ( <p className={css.noContent}>No results found.</p> )} {!!searchTotalDocuments && searchStatus !== 'pending' && ( <div className={css.searchSummary}> {`Found about ${searchTotalMatches} ${ searchTotalMatches === 1 ? 'result' : 'results' } across ${searchTotalDocuments} ${ searchTotalDocuments === 1 ? 'document' : 'documents' }`} </div> )}*/} {showPersonaSelector && <PersonaSelector />} </nav> <div className={css.resultContainer}> {searchStatus === "success" && isQueryLongEnough && (!hasFilteredResults || canShowSideBySide) && ( <KendraResultPage title={hasFilteredResults ? "Unfiltered Results" : null} results={results} queryId={kendraQueryId} resultCount={resultCount} /> )} {hasFilteredResults ? ( <KendraResultPage title="Filtered Results" results={filteredResults} queryId={filteredQueryId} resultCount={filteredResultCount} persona={searchPersona} /> ) : null} </div> </div> ); }
__author__ = 'patras' from domain_exploreEnv import * from timer import DURATION from state import state DURATION.TIME = { 'survey': 5, # for domain EE 'monitor': 5, 'screen': 5, 'sample': 5, 'process': 5, 'fly': 3, 'deposit': 1, 'transferData': 1, 'take': 2, 'put': 2, 'move': 10, 'charge': 5, 'negotiate': 5, 'handleAlien': 5 } DURATION.COUNTER = { 'survey': 5, # for domain EE 'monitor': 5, 'screen': 5, 'sample': 5, 'process': 5, 'fly': 3, 'deposit': 1, 'transferData': 1, 'take': 2, 'put': 2, 'move': 10, 'charge': 5, 'negotiate': 5, 'handleAlien': 5 } rv.TYPE = {'e1': 'survey', 'e2': 'monitor', 'e3': 'screen', 'e4': 'sample', 'e5':'process'} rv.EQUIPMENT = {'survey': 'e1', 'monitor': 'e2', 'screen': 'e3', 'sample': 'e4', 'process': 'e5'} rv.LOCATIONS = ['base', 'z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7'] rv.EDGES = { 'base': { 'z1': 15, 'z4': 15, 'z5': 35, 'z6': 35, 'z7': 35 }, 'z1': { 'base': 15, 'z2': 30 }, 'z2': { 'z1': 30, 'z3': 30 }, 'z3': { 'z2': 30, 'z4': 30 }, 'z4': { 'z3': 30, 'base': 15 }, 'z5': { 'base': 35 }, 'z6': { 'base': 35 }, 'z7': { 'base': 35 } } def ResetState(): state.loc = {'r1': 'base', 'UAV': 'base'} state.charge = {'r1':75, 'UAV': 75} state.data = {'r1': 0, 'UAV': 0} state.load = {'r1': NIL, 'UAV': NIL} state.pos = {'c1': 'base', 'e1': 'base', 'e2': 'base', 'e3': 'base', 'e4': 'base', 'e5': 'base'} tasks = { 1: ['doActivities', 'UAV', [['survey', 'z1'], ['survey', 'z3'], ['survey', 'z7']]], } eventsEnv = {}
/** * Everything related to ajax calls resides in this script. All ajax calls * must go through the ajaxCall method. * * @author Robb Krasnow * @version 2.0 */ /********************* ***** HELPERS ***** *********************/ /** * Ajax utility used to make all ajax calls to server. * * @param getPost The type of method (GET or POST) used to make the ajax call * @param d The data being sent to the server {name:value, name2:val2} * @param callback The callback method used if the call was successful */ function ajaxCall(getPost, d, callback) { $.ajax({ type: getPost, url: 'mid.php', data: d, dataType: 'json', async: true, cache: false, success: callback, error: err }); } /** * Used as a utility to show any error messages on the console if the server * doesn't return the proper data in JSON format from the AJAX calls. * * @param jqXHR The jQuery XMLHttpRequest * @param textStatus The status of the error from the AJAX call * @param err The error coming back from the server */ function err(jqXHR, textStatus, e) { console.log('jqXHR:\n', jqXHR); console.log('textStatus:\n', textStatus); console.log('responseText:\n', jqXHR.responseText); console.log('err:\n', e); } /********************************** ***** LOGIN AJAX FUNCTIONS ***** **********************************/ /** * Used to send login data to server checking login credentials. * * Callback method: callbackLogin * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (username|password) */ function initLoginAjax(whatMethod, val) { ajaxCall("POST", { method:whatMethod, a:"login", data:val }, callbackLogin); } /** * Callback method from initLoginAjax telling app what to do if it receives * a proper JSON object back from the server. If false login, display error, * else display success message and log the user in. * * @param jsonObj The JSON object coming back from the server */ function callbackLogin(jsonObj) { var success, invalidLoginBox, successLoginBox; // Set valid variables success = jsonObj[0].success; invalidLoginBox = $('.invalid-login-box'); successLoginBox = $('.success-login-box'); // Check if the request was a success or failure. // If failure, set focus to the username input field again and show error // If success, hide any previous errors and welcome back user if(success === "false") { $("#username-field").focus(); invalidLoginBox.text(jsonObj[1].error).show(); } else if(success === "true") { invalidLoginBox.hide(); successLoginBox.text("Welcome back " + jsonObj[1].username + "!").show(); // Set quick redirect to the user's dashboard setTimeout(function() { window.location.href = 'dashboard.php'; }, 1000); } } /*********************************** ***** LOGOUT AJAX FUNCTIONS ***** ***********************************/ /** * Used to send data to service layer for logging user out. * * Callback method: callbackLogout * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (userId) */ function initLogoutAjax(whatMethod, val) { ajaxCall("POST", { method:whatMethod, a:"logout", data:val }, callbackLogout); } /** * Callback method from initLogoutAjax telling app what to do if it receives * a proper JSON object back from the server. If the logout was successful, * set a timer to be displayed for redirection to login page. * * @param jsonObj The JSON object coming back from the server */ function callbackLogout(jsonObj) { var success = jsonObj[0].success; if(success == "true") { // Set a timer for redirect timer( 5000, // 5 seconds function(timeleft) { // Called every step to update the visible countdown $("#timer").text(timeleft); }, function() { // Redirect to login after 5 seconds window.location = 'login.php'; } ); } } /************************************* ***** REGISTER AJAX FUNCTIONS ***** *************************************/ /** * Used to send data to service layer for checking to register a new user. * * Callback method: callbackRegister * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (newUsername|newPassword) */ function initRegisterAjax(whatMethod, val) { ajaxCall("POST", { method:whatMethod, a:"register", data:val }, callbackRegister); } /** * Callback method from initRegisterAjax telling app what to do if it receives * a proper JSON object back from the server. If the registration was unsuccessful, * meaning, there was a duplicate on the server, report back to user they must * change their registration credentials. If it was successful, grab the input from * the form, and register them in the system. * * @param jsonObj The JSON object coming back from the server */ function callbackRegister(jsonObj) { // Grab all alert divs and the success (true/false) from the object returned var success, successString, errorString, duplicateString; success = jsonObj[0].success; successString = $('.success-box'); errorString = $('.error-box'); // If the registration failed, grab the error message if(success === "false") { var error = jsonObj[1].error; // If the error message starts with "Duplicate entry", that user already exists // in the DB. Warn the user and have them create a new one if(/^Duplicate entry/.test(error)) { errorString.alert().html('<i class="icon-fix fa fa-exclamation-triangle"></i>Username already exists. Please choose a different one.').show(); $(".register-modal-form")[0].reset(); $("#new-username-field").focus(); } } else { // Otherwise, registration was successful. Show the user they are being logged in // and actually log them in. successString.alert().text("Success! Logging in...").show(); var obj = $('.register-modal-form').serializeObject(); initLoginAjax('start_login', obj['new-username'] + '|' + obj['new-password']); } } /************************************** ***** DASHBOARD AJAX FUNCTIONS ***** **************************************/ /** * Used to send data to service layer for pulling a user's mailboxes * from the database. * * Callback method: callbackDashboard * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (userId) */ function initDashboardAjax(whatMethod, val) { ajaxCall("POST", { method: whatMethod, a:"dashboard", data:val }, callbackDashboard); } /** * Callback method to display a nice table with all the user's mailboxes. * Each row in the table displays the mailbox's ID, Filename, Message Count, * File size, file type, date added, and last accessed. * * @param jsonObj The JSON object coming back from the server */ function callbackDashboard(jsonObj) { var mailboxes, dashboardDiv, userMailboxes; mailboxes = []; dashboardDiv = $('.dashboard'); userMailboxes = ''; // Check if the return from the server has mailboxes in its JSON if(jsonObj[1].mailboxes) { mailboxes = jsonObj[1].mailboxes; } if(mailboxes.length === 1) { userMailboxes += '<h1>You have 1 mailbox</h1>'; } else { userMailboxes += '<h1>You have ' + mailboxes.length + ' mailboxes</h1>'; } // Start table creation userMailboxes += '<h5>Select a mailbox to view its visualization</h5>' + '<table class="dashboard-table table table-striped table-hover">' + '<thead>' + '<tr class="info">' + '<th>ID</th>' + '<th>Filename</th>' + '<th>Message Count</th>' + '<th>Size (bytes)</th>' + '<th>Type</th>' + '<th>Date Added (CDT)</th>' + '<th>Last Accessed (CDT)</th>' + '</tr>' + '</thead>' + '<tbody>'; // If there was a failure, display the error if(jsonObj[0].success === 'false') { userMailboxes += '<tr id="dashboard-row">' + '<td colspan="7">' + jsonObj[1].error + '</td>' + '</tr>'; } else if(mailboxes.length > 0) { // If there is more than one mailbox, for each one, add a new row to the table // with each mailbox's details for(var m = 0; m < mailboxes.length; m++) { userMailboxes += '<tr class="left">' + '<td>' + mailboxes[m].mailbox_id + '</td>' + '<td>' + '<a href="mailbox.php?mailbox_id=' + mailboxes[m].mailbox_id + '">' + mailboxes[m].file_name + '</a>' + '</td>' + '<td>' + mailboxes[m].num_messages + '</td>' + '<td>' + mailboxes[m].file_size + '</td>' + '<td>' + mailboxes[m].file_type + '</td>' + '<td>' + mailboxes[m].date_added + '</td>' + '<td>' + mailboxes[m].last_accessed + '</td>' + '</tr>'; } userMailboxes += '</tbody>' + '</table>'; } // Display the table to the user dashboardDiv.html(userMailboxes); } /*********************************** ***** UPLOAD AJAX FUNCTIONS ***** ***********************************/ /** * Used to send the uploaded file's metadata to the server. This includes: * - User ID * - File hash * - File name * - MIME type * - File size in bytes * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (userId|fileHash|fileName|fileType|fileSize) */ function initUploadAjax(whatMethod, val) { ajaxCall("POST", { method: whatMethod, a:"upload", data:val }, callbackUpload); } /** * Callback function to determine what to do if there was a successful or failed * upload. If it was a failure, show error from server. If it was successful, * grab the success message and the mailbox ID, and redirect the user to their * recently uploaded mailbox's visualization. * * @param jsonObj The JSON object coming back from the server */ function callbackUpload(jsonObj) { var success, successString, errorString, progress, progressStatus; success = jsonObj[0].success; successString = $('.success-box'); errorString = $('.error-box'); progress = $('.progress'); progressStatus = $('.progress-status'); // Hide progress bar stuff in case it shows up progress.hide(); progressStatus.hide(); // If there was a failure with the upload, report the error // Otherwise, report successfull upload and redirect to user's visualization if(success === "false") { var error = jsonObj[1].error; errorString.empty() .append('<i class="icon-fix fa fa-exclamation-triangle"></i>' + error) .fadeIn(200); } else if(success === "true") { var message = jsonObj[1].message; var mailboxId = jsonObj[2].mailbox_id; errorString.css({ display: 'none' }); successString.append('<i class="icon-fix fa fa-check"></i>' + message) .fadeIn(200); // Set delay to redirect to visualization setTimeout(function() { window.location.href = 'mailbox.php?mailbox_id=' + mailboxId; }, 1500); } } /***************************************** ***** PARSE STATUS AJAX FUNCTIONS ***** *****************************************/ /** * Used to send a constant beacon asking the server if the parsing * completed or not. Indended for use to create progress bar for parsing. * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (userId|fileHash) */ function initGetParseStatusAjax(whatMethod, val) { ajaxCall('POST', { method:whatMethod, a:'upload', data:val }, callbackGetParseStatus); } /** * Callback function to determine what to do if the uploaded file * was successfully parsed or not * * @param jsonObj The JSON object coming back from the server */ function callbackGetParseStatus(jsonObj) { console.log(jsonObj[1].num_messages); } /************************************ ***** MAILBOX AJAX FUNCTIONS ***** ************************************/ /** * Used to request the mailbox for the user based on their selection * either from the dashboard or when a new file is uploaded. * * @param whatMethod The method to look for in the service layer * @param val The data to be sent to the server (userId|mailboxId) */ function initMailboxAjax(whatMethod, val) { ajaxCall("POST", { method: whatMethod, a:"mailbox", data:val }, callbackMailbox); } /** * Callback method for displaying the mailbox's visualization. First, the mailbox's * metadata is displayed for, then D3 takes over to draw the visualization. * * @param jsonObj The JSON object coming back from the server */ function callbackMailbox(jsonObj) { var success, mailboxInfo, loadingInfo; success = jsonObj[0].success; mailboxInfo = $('.mailbox-info'); loadingInfo = $('.loading-info'); // If there was a failure in grabbing the mailbox, display error to user // and redirect user to the dashboard. // Otherwise, display mailbox's metadata and draw viz if(success === 'false') { var error = jsonObj[1].error; loadingInfo.hide(); mailboxInfo.append('<h1 class="alert alert-danger">' + '<i class="icon-fix fa fa-exclamation-triangle"></i>' + error + '<br />' + 'Redirecting...</h1>') .fadeIn(200); // Redirect user to dashboard if they try to access a mailbox not belonging to them setTimeout(function() { window.location.href = 'dashboard.php'; }, 2000); } else if(success === 'true') { var json, fileProperties, mailboxId, fileName, fileType, fileSize, numMessages, dateAdded, lastAccessed; // Grab all data from JSON return json = jsonObj[2].json; fileProperties = jsonObj[1].file_properties; mailboxId = fileProperties.mailbox_id; fileName = fileProperties.file_name; fileType = fileProperties.file_type; fileSize = fileProperties.file_size; numMessages = fileProperties.num_messages; dateAdded = fileProperties.date_added; lastAccessed = fileProperties.last_accessed; loadingInfo.hide(); // Display mailbox's metadata to the user var currentMailbox = '<h1 class="alert alert-success">' + fileName + '</h1>' + '<table class="table table-striped selected-mailbox">' + '<thead>' + '<tr class="info">' + '<th>ID</th>' + '<th>Message Count</th>' + '<th>Size (bytes)</th>' + '<th>Type</th>' + '<th>Date Added (CDT)</th>' + '<th>Last Accessed (CDT)</th>' + '</tr>' + '</thead>' + '<tbody>' + '<tr class="left">' + '<td>' + mailboxId + '</td>' + '<td>' + numMessages + '</td>' + '<td>' + fileSize + '</td>' + '<td>' + fileType + '</td>' + '<td>' + dateAdded + '</td>' + '<td>' + lastAccessed + '</td>' + '</tr>' + '</tbody>' + '</table>'; mailboxInfo.html(currentMailbox) .fadeIn(200); /************************** ***** NETWORK OBJECT ***** **************************/ var Network; /** * The Network function is the overall function that draws the visualization. * It includes all the visualizations properties and interactivity methods. */ Network = function() { var viz, // Needs to be global for setting cursor styles width, // Width of the SVG height, // Height of the SVG allData, // All the data if not sorted curLinksData, // Current links curNodesData, // Current nodes curMessagesData, // Current messages linkedByIndex, // Mapping of all nodes to links nodesG, // SVG group element for all the nodes linksG, // SVG group element for all the links node, // Variable used for each specific node when looping link, // Variable used for each specific link when looping message, // Variable used for each specific message when looping messages, // Messages from JSON layout, // What type of layout (network graph/force layout) zoom, // Zoom object zoomMin, // Minimum amount of zoom zoomMax; // Maximum amount of zoom viz = null; width = 960; height = 600; allData = []; curLinksData = []; curNodesData = []; curMessagesData = []; linkedByIndex = {}; nodesG = null; linksG = null; nodesAndLinksG = null; node = null; link = null; message = null; messages = null; layout = "force"; zoom = null; zoomMin = 0.1; zoomMax = 10; var force, // Create force layout tooltip, // Create tooltip nodeColors; // Create set of node colors force = d3.layout.force(); // Set force layout tooltip = Tooltip("vis-tooltip", 300); // Set up tooltips with 300px width // Setup color scheme based on group. Each group has its own colors based on email count // Group 0 - #be90d4 - violet (light wisteria) // Group 1 - #663399 - indigo (rebeccapurple) // Group 2 - #2980b9 - blue (belize hole) // Group 3 - #27ae60 - green (nephritis) // Group 4 - #f1c40f - yellow (sun flower) // Group 5 - #e67e22 - orange (carrot) // Group 6 - #c0392b - red (pomegranate) nodeColors = d3.scale.ordinal() .range(["#be90d4" , "#663399", "#2980b9", "#27ae60", "#f1c40f", "#e67e22", "#c0392b"]) .domain([0, 1, 2, 3, 4, 5, 6]); var charge, // Used to create a charge of the force layout network, // Used to create the network itself update; // Used for updating the network if any selections have been made /** * Used for setting the viz's charge towards the center node. * * @param node The node to set the charge on * @return The newly calculated charge for the viz */ charge = function(node) { return -Math.pow(node.radius, 2.0) / 2; }; /** * This is the main method that makes the whole visualization come together. * It calls upon other methods to help draw necessary features and add interactivity. * * @param selection The part of the HTML where the viz is placed * @param data The data to be visualized * @return The entire visualization */ network = function(selection, data) { // Set variables to be used for a slim gray border around the svg to match // the column next to it var svgBorderStroke, svgBorderColor, svgBorderPath; svgBorderStroke = 1; svgBorderColor = "#464545"; svgBorderPath = null; // Set up the zoom behavior with min/mix scale, and call on zoom function zoom = d3.behavior.zoom() .scaleExtent([zoomMin, zoomMax]) .on("zoom", zoomed); // Get all data after all links have been mapped and modified allData = setupData(data); // Set up the vizualization svg by adding an svg element and setting its width and height viz = d3.select(selection) .append("svg") .attr("width", width) .attr("height", height) .attr("border", svgBorderStroke) .style("background-color", "#ffffff"); // Add very thin border around SVG container svgBorderPath = viz.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", width) .attr("height", height) .style("fill", "none") .style("stroke", svgBorderColor) .style("stroke-width", svgBorderStroke); // Declare and set up variables for the legend var legend, legendG, textInLegend, circleInLegend; legend = []; legendG = null; textInLegend = null; circleInLegend = null; // Set the legend to match the group numbers for the color scheme legend = [ {group: 0, target: "1 - 100"}, {group: 1, target: "101 - 500"}, {group: 2, target: "501 - 1,000"}, {group: 3, target: "1,001 - 5,000"}, {group: 4, target: "5,001 - 10,000"}, {group: 5, target: "10,001 - 50,000"}, {group: 6, target: "50,001+"} ]; // Create a group for the legend in order to translate the entire legend as a whole legendG = viz.append("g") .attr("id", "legend") .attr("transform", "translate(" + 20 + "," + 30 + ")"); // Add "Legend" to notify of the legend textInLegend = legendG.selectAll("textInLegend") .data([0], function(d) { return d; }) .enter() .append("text") .text("Legend") .style("font-weight", "bold") .style("font-size", "18px"); // Add the legend data to the legend group to create the circles circleInLegend = legendG.selectAll("circleInLegend") .data(legend); // Add all circles to the legend with associated colors for email count circleInLegend.enter() .append("circle") .attr("cx", 10) .attr("cy", function(d) { // 23 = spacing between circles, 20 = space between "Legend" and top circle return 23 * d.group + 20; }) .attr("r", 9) .style("fill", function(d) { return nodeColors(d.group); }); // Add all text values for email count to their circles circleInLegend.enter() .append("text") .attr("x", 25) .attr("y", function(d) { // 23 = spacing between circles, 26 = space between "Legend" and top circle return 23 * d.group + 26; }) .text(function(d) { return d.target; }) .style("font-size", "12px") .style("font-family", "sans-serif"); // Add to the legend group a set of instructions instructions = legendG.selectAll("instructions") .data([0], function(d) { return d; }); // Add the "Instructions" label to the section for instructions instructions.enter() .append("text") .attr("y", 200) .text("Instructions") .style("font-weight", "bold") .style("font-size", "18px"); // Add "Click to drag" to instructions list instructions.enter() .append("text") .attr("y", 220) .text("Click to drag") .style("font-size", "12px") .style("font-family", "sans-serif"); // Add "Double click to view emails" to instructions list instructions.enter() .append("text") .attr("y", 240) .text("Double click to view emails") .style("font-size", "12px") .style("font-family", "sans-serif"); // Add "Scroll to zoom" to instructions list instructions.enter() .append("text") .attr("y", 260) .text("Scroll to zoom") .style("font-size", "12px") .style("font-family", "sans-serif"); // Add "Mouse over circle to see details" to instructions list instructions.enter() .append("text") .attr("y", 280) .text("Mouse over circle to see details") .style("font-size", "12px") .style("font-family", "sans-serif"); // Add "Mouse over link to see communication" to instructions list instructions.enter() .append("text") .attr("y", 300) .text("Mouse over link to see communication") .style("font-size", "12px") .style("font-family", "sans-serif"); // Create group to house the group of links and the group of nodes nodesAndLinksG = viz.append("g"); // Add a group of links to the nodes and links group that all have an id of links linksG = nodesAndLinksG.append("g") .attr("id", "links"); // Add a group of nodes to the nodes and links group that all have an id of nodes nodesG = nodesAndLinksG.append("g") .attr("id", "nodes"); // Set the size of the force layout svg with the width and height force.size([width, height]); // Set the default layout to force setLayout("force"); // Call the zoom behavior, disable double-click to zoom and change cursor to arrow-crosshairs viz.call(zoom) .on("dblclick.zoom", null) .style("cursor", "move"); // Run the update function in case any options have been selected by the user return update(); }; /** * Used update the visualization with the current set of filtered nodes and * links. This method also starts the visualization. The filtereing has not * yet been implemented, so some code in this method is unnecessary for now. * * @return The starting of the visualization */ update = function() { // Get all current nodes curNodesData = filterNodes(allData.nodes); curMessagesData = filterMessages(allData.messages); curLinksData = filterLinks(allData.links, curNodesData, curMessagesData); force.nodes(curNodesData); updateNodes(); if(layout === "force") { force.links(curLinksData); updateLinks(); } // Start the viz! return force.start(); }; /** * Used to actually set up the visualization data. This includes: * - Setting circle radius * - Setting node placement * - Setting source and target mapping for links * * @param data The set of data to be visualized * @return data The new set of data */ setupData = function(data) { var circleRadius, countExtent, nodesMap; // Get the min and max values of all email counts from the nodes countExtent = d3.extent(data.nodes, function(d) { return d.email_count; }); // Set the node's radius to the sqrt of the email count to generate node size // based on amount of emails sent/received. Example: d3.scale.sqrt(7) circleRadius = d3.scale.sqrt() .range([5, 50]) .domain(countExtent); // For every node, create a random location for the node to end up within the SVG data.nodes.forEach(function(n) { var randomNumber; // Sets the x and y coordiantes randomly for each node n.x = randomNumber = Math.floor(Math.random() * width); n.y = randomNumber = Math.floor(Math.random() * height); // Send email count to create the node's radius size return n.radius = circleRadius(n.email_count); }); // Send data to map the nodes and get back mapping nodesMap = mapNodes(data.nodes, data.messages); // Turn the sources and targets into the mapping based on the id // mapping from the nodesMap data.links.forEach(function(l) { l.source = nodesMap.get(l.source); l.target = nodesMap.get(l.target); return linkedByIndex[l.source.id + "," + l.target.id] = 1; }); return data; }; /** * Creates a mapping of each node's ID to the node itself. This method * also maps messages of either "Sent" or "Received" to a specific node. * * @param nodes The set of nodes to be mapped * @param messages The set of messages to be mapped to nodes * @return nodesMap The new set of mapped nodes to messages */ mapNodes = function(nodes, messages) { var nodesMap, messageObject, sentMessageList, receivedMessageList; // Create the mapping for the nodes nodesMap = d3.map(); // For each node, create an object where the node's id is mapped // to the node itself nodes.forEach(function(n) { // Create the message object and an array for each type of message, sent or received // These need to be inside the forEach loop because they need to be reset every iteration messageObject = {}; sentMessageList = []; receivedMessageList = []; messages.forEach(function(m) { if(n.id === m.sender) { sentMessageList.push(m); } m.receivers.forEach(function(r) { if(n.id === r) { receivedMessageList.push(m); } }); }); // Turn sent and received message lists into objects sentMessageObject = Object.setPrototypeOf(sentMessageList, Object.prototype); receivedMessageObject = Object.setPrototypeOf(receivedMessageList, Object.prototype); // Create the message object and its sub objects of sent and received n.messages = messageObject; n.messages.sent = sentMessageObject; n.messages.received = receivedMessageObject; // Add all message objects to each node's message list nodesMap.get(messageObject); nodesMap.get(sentMessageObject); nodesMap.get(receivedMessageObject); // In the end, map each node by its respective id return nodesMap.set(n.id, n); }); // Return the mapping of the nodes return nodesMap; }; /** * Used to create an indexed listing of all nodes and how they are connected * to their neighbors. This method works with nodes from both sides to simplify * various other parts of drawing the visualization. * * @param a Node on one side * @param b Node on the other side * @return linkedByIndex An indexed listing of all the nodes and their immediate neighbors */ neighboring = function(a, b) { return linkedByIndex[a.id + "," + b.id] || linkedByIndex[b.id + "," + a.id]; }; /** * FUTURE FEATURE * * Used as a placeholder method for future feature of filtering nodes * based on a search criteria. * * @param allNodes The set of nodes to be filtered * @return filteredNodes The new set of filtered nodes */ filterNodes = function(allNodes) { var filteredNodes; filteredNodes = allNodes; return filteredNodes; }; /** * FUTURE FEATURE * * Used as a placeholder method for future feature of filtering links * based on a search criteria. * * @param allLinks The set of links to be filtered * @param curNodes The set of current nodes to be filtered * @param curMessages The set of current messages to be filtered * @return allLinks The new set of filtered links */ filterLinks = function(allLinks, curNodes, curMessages) { curNodes = mapNodes(curNodes, curMessages); return allLinks.filter(function(l) { return curNodes.get(l.source.id) && curNodes.get(l.target.id); }); }; /** * FUTURE FEATURE * * Used as a placeholder method for future feature of filtering messages * based on a search criteria. * * @param allMessages The set of messages to be filtered * @return filteredMessages The new set of filtered messages */ filterMessages = function(allMessages) { var filteredMessages; filteredMessages = allMessages; return filteredMessages; }; /** * Used to update how the nodes look and where they are placed in the viz. * * @return node The node to be drawn */ updateNodes = function() { node = nodesG.selectAll("circle.node") .data(curNodesData, function(d) { return d.id; }); // Set all nodes attributes node.enter() .append("circle") .attr("class", "node") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", function(d) { return d.radius; }) .style("fill", function(d) { return nodeColors(d.group); }) .style("stroke", function(d) { return strokeForNode(d); }) .style("stroke-width", 1.0); // Handle mouse events node.on("mouseover", showNodeDetails) .on("mouseout", hideNodeDetails) .on("dblclick", nodeDoubleClicked); // .call(force.drag) // Can be turned on to drag nodes around return node.exit().remove(); }; /** * Used to update how the links look and where they are placed in the viz. * * @return link The node to be drawn */ updateLinks = function() { link = linksG.selectAll("line.link") .data(curLinksData, function(d) { return d.source.id + "_" + d.target.id; }); // Set all links attributes link.enter() .append("line") .attr("class", "link") .attr("stroke", "#ccc") .attr("stroke-opacity", 0.8) .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); link.on("mouseover", showLinkDetails) .on("mouseout", hideLinkDetails) .on("dblclick", linkDoubleClicked); return link.exit().remove(); }; /** * FUTURE FEATURE * * Used to set the layout if changing between visualizations. In it's current * state, only the force layout is allowed. Future work will include adding * a radial tree visualization. If the selection is force layout, call on the * "forceTick" function to set the proper tick on the force. * * @param newLayout The selected layout * @return force The force layout */ setLayout = function(newLayout) { layout = newLayout; if(layout === "force") { return force.on("tick", forceTick) .charge(-300) // Change charge of force .linkDistance(100); // Change link distance } }; /** * Sets the tick on the force layout. */ forceTick = function() { node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); return link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); }; /** * Method to set the border of the node to a darker shade of the color * of the node itself to make it stand out. * * @param d The node object * @return The newly generated color for the specific node */ strokeForNode = function(d) { return d3.rgb(nodeColors(d.group)).darker().toString(); }; /*********************************** ***** MOUSE EVENT FUNCTIONS ***** ***********************************/ var showNodeDetails, hideNodeDetails, showLinkDetails, hideLinkDetails, nodeDoubleClicked, zoomed; /** * This method is used to show a tooltip with the node's email address * and email count. It will change the highlighting of the nodes and * their neighbors. * * @param d The node to add the details to * @return The current node that's selected */ showNodeDetails = function(d) { // Change the curser to the pointer finger on mouseover for tooltip viz.style("cursor", "pointer"); var content; // Set up tooltip content content = '<p class="tooltip-main tooltip-email-addr center">' + d.id + '</p>'; content += '<hr class="tooltip-hr">'; content += '<p class="tooltip-main tooltip-email-count center"><span class="tooltip-span">Email Count: </span>' + d.email_count + '</p>'; // Show the tooltip while listening to the mouseover event tooltip.showTooltip(content, d3.event); if(link) { // If so, set the stroke color darker to highlight link.attr("stroke", function(l) { return (l.source === d || l.target === d) ? "#555" : "#ddd"; }) .attr("stroke-opacity", function(l) { return (l.source === d || l.target === d) ? 1.0 : 0.5; }); } // Change node's stroke styling node.style("stroke", function(n) { return (n.searched || neighboring(n, d)) ? "#555" : strokeForNode(n); }) .style("stroke-width", function(n) { return (n.searched || neighboring(n, d)) ? 2.0 : 1.0; }); // Return the node with an increase in size animation return d3.select(this) .transition() .duration(750) .attr("r", function(n) { return n.radius + 10; }) .style("stroke", "#000") .style("stroke-width", 2.0); }; /** * This method is used to hide a tooltip. It will change the * highlighting of the nodes and their neighbors. * * @param d The node to hide the details for * @return The link's attributes of the connecting node */ hideNodeDetails = function(d) { // Change mouse back to move icon for panning/zooming viz.style("cursor", "move"); // Hide the tooltip when the mouse is no longer over the node tooltip.hideTooltip(); // Flip what happens from showNodeDetails: put node back to original size node.transition() .duration(750) .attr("r", function(n) { return n.radius; }) .style("stroke", function(n) { return (!n.searched) ? strokeForNode(n) : "#555"; }) .style("stroke-width", function(n) { return (!n.searched) ? 1.0 : 2.0; }); if(link) { return link.attr("stroke", "#ddd") .attr("stroke-width", 1.0) .attr("stroke-opacity", 1.0); } }; /** * This method is used to show a link's details including source and * target email addresses and total email count between them. It will * change the highlighting of the links and their neighboring nodes. * * @param d The link to add the details to * @return The current link that's selected */ showLinkDetails = function(d) { // Change the curser to the pointer finger on mouseover for tooltip viz.style("cursor", "pointer"); var content; // Set up tooltip content content = '<p class="tooltip-main tooltip-email-addr center"><span class="tooltip-span">From: </span>' + d.source.id + '</p>' + '<p class="tooltip-main tooltip-email-addr center"><span class="tooltip-span">To: </span>' + d.target.id + '</p>' + '<hr class="tooltip-hr">' + '<p class="tooltip-main tooltip-email-count center"><span class="tooltip-span">Email Count: </span>' + d.value + '</p>'; // Show the tooltip while listening to the mouseover event tooltip.showTooltip(content, d3.event); if(node) { // Set every node's stroke and stroke-width node.style("stroke", function(n) { return (n === d.source || n === d.target) ? "#555" : strokeForNode(n); }) .style("stroke-width", function(n) { return (n === d.source || n === d.target) ? 2.0 : 1.0; }); } // Set all non-highlighted links to a lighter faded color with a lower opacity link.attr("stroke", "#ddd") .attr("stroke-width", 1.0) .attr("stroke-opacity", 0.5); // Set the highlighted link's color darker, thicker width, and 100% opacity return d3.select(this) .attr("stroke", "#000") .attr("stroke-width", 2.0) .attr("stroke-opacity", 1.0); }; /** * This method is used to hide a link's details. It will * change the highlighting of the links and their neighboring nodes. * * @param d The link to hide the details to * @return The node's attributes of the connecting link */ hideLinkDetails = function(d) { // Change mouse back to move icon for panning/zooming viz.style("cursor", "move"); // Hide the tooltip when the mouse is no longer over the node tooltip.hideTooltip(); // For all links, including the highlighted one, reset back to normal link.attr("stroke", "#ccc") .attr("stroke-width", 1.0) .attr("stroke-opacity", 1.0); // For all nodes, reset back to normal if(node) { return node.style("stroke", function(n) { return strokeForNode(n); }) .style("stroke-width", 1.0) .style("stroke-opacity", 1.0); } }; // Used for checking whether a node is already highlighted var toggle = 0; /** * This method is used to display all the sent and received email messages * from the double-clicked node. * * @param d The node to show messages for * @return The highlighted node */ nodeDoubleClicked = function(d) { var messageDiv = $('.messages'); var email = ''; // Sent Email var sent = d.messages.sent; email = '<ul class="accordion-menu animate">' + '<li class="has-children sent-email">' + '<input type="checkbox" name="sent" id="sent">' + '<label for="sent"><i class="icon-fix fa fa-share"></i>SENT (' + sent.length + ')</label>' + '<ul>'; // Check the length of the sent emails. // If 0, display "NONE" // If more than 0, display them if(sent.length === 0) { email += '<li><p class="center empty-inbox">NONE</p></li>' + '</ul>' + '</li>'; } else if(sent.length > 0) { for(var m = 0; m < sent.length; m++) { var receivers = sent[m].receivers; email += '<li>' + '<table class="table table-hover">' + '<tr>' + '<td class="email-header active"><span class="email-span">From: </span></td>' + '<td class="success">' + sent[m].sender + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">To: </span></td>'; if(receivers.length === 0) { email += '<td class="success">N/A</td>'; } else if(receivers.length === 1) { email += '<td class="success">' + sent[m].receivers + '</td>'; } else if(receivers.length > 1) { email += '<td class="success">'; for(var r = 1; r < receivers.length; r++) { email += sent[m].receivers[r] + '<br />'; } email += '</td>' + '</tr>'; } email += '<tr>' + '<td class="email-header active"><span class="email-span">Date: </span></td>' + '<td class="success">' + sent[m].date_sent + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Subject: </span></td>' + '<td class="success">' + sent[m].subject + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Content: </span></td>' + '<td class="success">' + sent[m].content + '</td>' + '</tr>' + '</table>' + '</li>'; } email += '</ul>' + '</li>'; } // Received Email var received = d.messages.received; email += '<li class="has-children received-email">' + '<input type="checkbox" name="received" id="received">' + '<label for="received"><i class="icon-fix fa fa-reply"></i>RECEIVED (' + received.length + ')</label>' + '<ul>'; // Check the length of the received emails. // If 0, display "NONE" // If more than 0, display them if(received.length === 0) { email += '<li><p class="center empty-inbox">NONE</p></li>' + '</ul>' + '</li>'; } else if(received.length > 0) { for(var m = 0; m < received.length; m++) { var receivers = received[m].receivers; email += '<li>' + '<table class="table table-hover">' + '<tr>' + '<td class="email-header active"><span class="email-span">From: </span></td>' + '<td class="info">' + received[m].sender + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">To: </span></td>'; if(receivers.length === 0) { email += '<td class="info">N/A</td>'; } else if(receivers.length === 1) { email += '<td class="info">' + received[m].receivers + '</td>'; } else if(receivers.length > 1) { email += '<td class="info">'; for(var r = 1; r < receivers.length; r++) { email += received[m].receivers[r] + '<br />'; } email += '</td>' + '</tr>'; } email += '<tr>' + '<td class="email-header active"><span class="email-span">Date: </span></td>' + '<td class="info">' + received[m].date_sent + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Subject: </span></td>' + '<td class="info">' + received[m].subject + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Content: </span></td>' + '<td class="info">' + received[m].content + '</td>' + '</tr>' + '</table>' + '</li>'; } email += '</ul>' + '</li>' + '</ul>'; } // Append all email messages to the side panel next to the viz messageDiv.html(email); // Display messages messagesMenu(); // Check whether node and neighbors are already highlighted // Toggle = 0 for non-highlighted nodes and neighbors // Toggle = 1 for highlighted nodes and neighbors if(toggle === 0) { toggle = 1; // Set double-clicked node and immediate neighbors to be highlighted node.style("opacity", function(n) { return neighboring(n, d) ? 1 : 0.1; }); link.style("opacity", function(l) { return (l.source.index === d.index || l.target.index === d.index) ? 1.0 : 0.1; }); } else { // Reset toggle for next double-click event toggle = 0; // Reset every node's and link's opacity back to normal node.style("opacity", 1); link.style("opacity", 1); } // Return the highlighted node return d3.select(this) .style("opacity", 1) .style("stroke", "#000") .style("stroke-width", 2.0); }; /** * This method is used to display all the sent and received email messages * from the double-clicked node. * * BUG: Currently only the sent messages from the source and * received messages from the target are displayed. * BUG: After double-clicking a link, link stays highlighted bold * * @param d The link to show messages for * @return The highlighted link */ linkDoubleClicked = function(d) { var messageDiv = $('.messages'); var email = ''; // Sent Email var sent = d.source.messages.sent; email = '<ul class="accordion-menu animate">' + '<li class="has-children sent-email">' + '<input type="checkbox" name="sent" id="sent">' + '<label for="sent"><i class="icon-fix fa fa-share"></i>SENT (' + sent.length + ')</label>' + '<ul>'; if(sent.length === 0) { email += '<li><p class="center empty-inbox">NONE</p></li>' + '</ul>' + '</li>'; } else if(sent.length > 0) { for(var m = 0; m < sent.length; m++) { var receivers = sent[m].receivers; email += '<li>' + '<table class="table table-hover">' + '<tr>' + '<td class="email-header active"><span class="email-span">From: </span></td>' + '<td class="success">' + sent[m].sender + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">To: </span></td>'; if(receivers.length === 0) { email += '<td class="success">N/A</td>'; } else if(receivers.length === 1) { email += '<td class="success">' + sent[m].receivers + '</td>'; } else if(receivers.length > 1) { email += '<td class="success">'; for(var r = 1; r < receivers.length; r++) { email += sent[m].receivers[r] + '<br />'; } email += '</td>' + '</tr>'; } email += '<tr>' + '<td class="email-header active"><span class="email-span">Date: </span></td>' + '<td class="success">' + sent[m].date_sent + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Subject: </span></td>' + '<td class="success">' + sent[m].subject + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Content: </span></td>' + '<td class="success">' + sent[m].content + '</td>' + '</tr>' + '</table>' + '</li>'; } email += '</ul>' + '</li>'; } // Received Email var received = d.target.messages.received; email += '<li class="has-children received-email">' + '<input type="checkbox" name="received" id="received">' + '<label for="received"><i class="icon-fix fa fa-reply"></i>RECEIVED (' + received.length + ')</label>' + '<ul>'; if(received.length === 0) { email += '<li><p class="center empty-inbox">NONE</p></li>' + '</ul>' + '</li>'; } else if(received.length > 0) { for(var m = 0; m < received.length; m++) { var receivers = received[m].receivers; email += '<li>' + '<table class="table table-hover">' + '<tr>' + '<td class="email-header active"><span class="email-span">From: </span></td>' + '<td class="info">' + received[m].sender + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">To: </span></td>'; if(receivers.length === 0) { email += '<td class="info">N/A</td>'; } else if(receivers.length === 1) { email += '<td class="info">' + received[m].receivers + '</td>'; } else if(receivers.length > 1) { email += '<td class="info">'; for(var r = 1; r < receivers.length; r++) { email += received[m].receivers[r] + '<br />'; } email += '</td>' + '</tr>'; } email += '<tr>' + '<td class="email-header active"><span class="email-span">Date: </span></td>' + '<td class="info">' + received[m].date_sent + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Subject: </span></td>' + '<td class="info">' + received[m].subject + '</td>' + '</tr>' + '<tr>' + '<td class="email-header active"><span class="email-span">Content: </span></td>' + '<td class="info">' + received[m].content + '</td>' + '</tr>' + '</table>' + '</li>'; } email += '</ul>' + '</li>' + '</ul>'; } // Append all email messages to the side panel next to the viz messageDiv.html(email); // Display messages messagesMenu(); // Check whether node and neighbors are already highlighted // Toggle = 0 for non-highlighted nodes and neighbors // Toggle = 1 for highlighted nodes and neighbors if(toggle === 0) { toggle = 1; // Set double-clicked node and immediate neighbors to be highlighted node.style("opacity", function(n) { return neighboring(n, d) ? 1 : 0.1; }); link.style("opacity", function(l) { return (l.source.index === d.index || l.target.index === d.index) ? 1.0 : 0.1; }); } else { // Reset toggle for next double-click event toggle = 0; // Reset every node's and link's opacity back to normal node.style("opacity", 1); link.style("opacity", 1); } // Return the highlighted link return d3.select(this) .style("opacity", 1) .style("stroke", "#000") .style("stroke-width", 2.0); }; /** * This method is used to set the proper scaling and translation of the * visualization when it's zoomed in and out. */ zoomed = function() { var translate, scale; translate = d3.event.translate; scale = d3.event.scale; nodesAndLinksG.attr("transform", "translate(" + translate + ")scale(" + scale + ")"); }; // Return the entire network object return network; }; // Create network viz with data from callback $(function() { var myNetwork; myNetwork = Network(); // Return a new network visualization, in the "viz" div, and send in the json from // the callback for that particular mailbox return myNetwork(".viz", json); // FOR STATIC JSON FILES THAT ARE TOO BIG // return d3.json(encodeURI("demo_json/enron_Vincent Kaminski.json"), function(json) { // return myNetwork(".viz", json); // }); }); } }
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import azure.iot.device.common.mqtt_transport as mqtt_transport from azure.iot.device.common.mqtt_transport import MQTTTransport, OperationManager from azure.iot.device.common.models.x509 import X509 from azure.iot.device.common import transport_exceptions as errors import paho.mqtt.client as mqtt import ssl import copy import pytest import logging import socket import socks import threading import gc import weakref logging.basicConfig(level=logging.DEBUG) fake_hostname = "beauxbatons.academy-net" fake_device_id = "MyFirebolt" fake_password = "Fortuna Major" fake_username = fake_hostname + "/" + fake_device_id new_fake_password = "new fake password" fake_topic = "fake_topic" fake_payload = "Tarantallegra" fake_cipher = "DHE-RSA-AES128-SHA" fake_qos = 1 fake_mid = 52 fake_rc = 0 fake_success_rc = 0 fake_failed_rc = mqtt.MQTT_ERR_PROTOCOL failed_connack_rc = mqtt.CONNACK_REFUSED_IDENTIFIER_REJECTED fake_keepalive = 1234 # mapping of Paho connack rc codes to Error object classes connack_return_codes = [ { "name": "CONNACK_REFUSED_PROTOCOL_VERSION", "rc": mqtt.CONNACK_REFUSED_PROTOCOL_VERSION, "error": errors.ProtocolClientError, }, { "name": "CONNACK_REFUSED_IDENTIFIER_REJECTED", "rc": mqtt.CONNACK_REFUSED_IDENTIFIER_REJECTED, "error": errors.ProtocolClientError, }, { "name": "CONNACK_REFUSED_SERVER_UNAVAILABLE", "rc": mqtt.CONNACK_REFUSED_SERVER_UNAVAILABLE, "error": errors.ConnectionFailedError, }, { "name": "CONNACK_REFUSED_BAD_USERNAME_PASSWORD", "rc": mqtt.CONNACK_REFUSED_BAD_USERNAME_PASSWORD, "error": errors.UnauthorizedError, }, { "name": "CONNACK_REFUSED_NOT_AUTHORIZED", "rc": mqtt.CONNACK_REFUSED_NOT_AUTHORIZED, "error": errors.UnauthorizedError, }, ] # mapping of Paho rc codes to Error object classes operation_return_codes = [ {"name": "MQTT_ERR_NOMEM", "rc": mqtt.MQTT_ERR_NOMEM, "error": errors.ConnectionDroppedError}, { "name": "MQTT_ERR_PROTOCOL", "rc": mqtt.MQTT_ERR_PROTOCOL, "error": errors.ProtocolClientError, }, {"name": "MQTT_ERR_INVAL", "rc": mqtt.MQTT_ERR_INVAL, "error": errors.ProtocolClientError}, { "name": "MQTT_ERR_NO_CONN", "rc": mqtt.MQTT_ERR_NO_CONN, "error": errors.ConnectionDroppedError, }, { "name": "MQTT_ERR_CONN_REFUSED", "rc": mqtt.MQTT_ERR_CONN_REFUSED, "error": errors.ConnectionFailedError, }, { "name": "MQTT_ERR_NOT_FOUND", "rc": mqtt.MQTT_ERR_NOT_FOUND, "error": errors.ConnectionFailedError, }, { "name": "MQTT_ERR_CONN_LOST", "rc": mqtt.MQTT_ERR_CONN_LOST, "error": errors.ConnectionDroppedError, }, {"name": "MQTT_ERR_TLS", "rc": mqtt.MQTT_ERR_TLS, "error": errors.UnauthorizedError}, { "name": "MQTT_ERR_PAYLOAD_SIZE", "rc": mqtt.MQTT_ERR_PAYLOAD_SIZE, "error": errors.ProtocolClientError, }, { "name": "MQTT_ERR_NOT_SUPPORTED", "rc": mqtt.MQTT_ERR_NOT_SUPPORTED, "error": errors.ProtocolClientError, }, {"name": "MQTT_ERR_AUTH", "rc": mqtt.MQTT_ERR_AUTH, "error": errors.UnauthorizedError}, { "name": "MQTT_ERR_ACL_DENIED", "rc": mqtt.MQTT_ERR_ACL_DENIED, "error": errors.UnauthorizedError, }, {"name": "MQTT_ERR_UNKNOWN", "rc": mqtt.MQTT_ERR_UNKNOWN, "error": errors.ProtocolClientError}, {"name": "MQTT_ERR_ERRNO", "rc": mqtt.MQTT_ERR_ERRNO, "error": errors.ProtocolClientError}, { "name": "MQTT_ERR_QUEUE_SIZE", "rc": mqtt.MQTT_ERR_QUEUE_SIZE, "error": errors.ProtocolClientError, }, ] @pytest.fixture def mock_mqtt_client(mocker, fake_paho_thread): mock = mocker.patch.object(mqtt, "Client") mock_mqtt_client = mock.return_value mock_mqtt_client.subscribe = mocker.MagicMock(return_value=(fake_rc, fake_mid)) mock_mqtt_client.unsubscribe = mocker.MagicMock(return_value=(fake_rc, fake_mid)) mock_mqtt_client.publish = mocker.MagicMock(return_value=(fake_rc, fake_mid)) mock_mqtt_client.connect.return_value = 0 mock_mqtt_client.reconnect.return_value = 0 mock_mqtt_client.disconnect.return_value = 0 mock_mqtt_client._thread = fake_paho_thread return mock_mqtt_client @pytest.fixture def transport(mock_mqtt_client): # Implicitly imports the mocked Paho MQTT Client from mock_mqtt_client return MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username) @pytest.fixture def fake_paho_thread(mocker): thread = mocker.MagicMock(spec=threading.Thread) thread.name = "_fake_paho_thread_" return thread @pytest.fixture def mock_paho_thread_current(mocker, fake_paho_thread): return mocker.patch.object(threading, "current_thread", return_value=fake_paho_thread) @pytest.fixture def fake_non_paho_thread(mocker): thread = mocker.MagicMock(spec=threading.Thread) thread.name = "_fake_non_paho_thread_" return thread @pytest.fixture def mock_non_paho_thread_current(mocker, fake_non_paho_thread): return mocker.patch.object(threading, "current_thread", return_value=fake_non_paho_thread) @pytest.mark.describe("MQTTTransport - Instantiation") class TestInstantiation(object): @pytest.mark.it("Creates an instance of the Paho MQTT Client") def test_instantiates_mqtt_client(self, mocker): mock_mqtt_client_constructor = mocker.patch.object(mqtt, "Client") MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username) assert mock_mqtt_client_constructor.call_count == 1 assert mock_mqtt_client_constructor.call_args == mocker.call( client_id=fake_device_id, clean_session=False, protocol=mqtt.MQTTv311 ) @pytest.mark.it( "Creates an instance of the Paho MQTT Client using Websockets when websockets parameter is True" ) def test_configures_mqtt_websockets(self, mocker): mock_mqtt_client_constructor = mocker.patch.object(mqtt, "Client") mock_mqtt_client = mock_mqtt_client_constructor.return_value MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username, websockets=True, ) assert mock_mqtt_client_constructor.call_count == 1 assert mock_mqtt_client_constructor.call_args == mocker.call( client_id=fake_device_id, clean_session=False, protocol=mqtt.MQTTv311, transport="websockets", ) # Verify websockets options have been set assert mock_mqtt_client.ws_set_options.call_count == 1 assert mock_mqtt_client.ws_set_options.call_args == mocker.call(path="/$iothub/websocket") @pytest.mark.it( "Configures TLS/SSL context to use TLS 1.2, require certificates and check hostname" ) def test_configures_tls_context(self, mocker): mock_mqtt_client = mocker.patch.object(mqtt, "Client").return_value mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext") mock_ssl_context = mock_ssl_context_constructor.return_value MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username) # Verify correctness of TLS/SSL Context assert mock_ssl_context_constructor.call_count == 1 assert mock_ssl_context_constructor.call_args == mocker.call(protocol=ssl.PROTOCOL_TLSv1_2) assert mock_ssl_context.check_hostname is True assert mock_ssl_context.verify_mode == ssl.CERT_REQUIRED # Verify context has been set assert mock_mqtt_client.tls_set_context.call_count == 1 assert mock_mqtt_client.tls_set_context.call_args == mocker.call(context=mock_ssl_context) @pytest.mark.it( "Configures TLS/SSL context using default certificates if protocol wrapper not instantiated with a server verification certificate" ) def test_configures_tls_context_with_default_certs(self, mocker, mock_mqtt_client): mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext") mock_ssl_context = mock_ssl_context_constructor.return_value MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username) assert mock_ssl_context.load_default_certs.call_count == 1 assert mock_ssl_context.load_default_certs.call_args == mocker.call() @pytest.mark.it( "Configures TLS/SSL context with provided server verification certificate if protocol wrapper instantiated with a server verification certificate" ) def test_configures_tls_context_with_server_verification_certs(self, mocker, mock_mqtt_client): mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext") mock_ssl_context = mock_ssl_context_constructor.return_value server_verification_cert = "dummy_certificate" MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username, server_verification_cert=server_verification_cert, ) assert mock_ssl_context.load_verify_locations.call_count == 1 assert mock_ssl_context.load_verify_locations.call_args == mocker.call( cadata=server_verification_cert ) @pytest.mark.it( "Configures TLS/SSL context with provided cipher if present during instantiation" ) def test_confgures_tls_context_with_cipher(self, mocker, mock_mqtt_client): mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext") mock_ssl_context = mock_ssl_context_constructor.return_value MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username, cipher=fake_cipher, ) assert mock_ssl_context.set_ciphers.call_count == 1 assert mock_ssl_context.set_ciphers.call_args == mocker.call(fake_cipher) @pytest.mark.it("Configures TLS/SSL context with client-provided-certificate-chain like x509") def test_configures_tls_context_with_client_provided_certificate_chain( self, mocker, mock_mqtt_client ): mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext") mock_ssl_context = mock_ssl_context_constructor.return_value fake_client_cert = X509("fantastic_beasts", "where_to_find_them", "alohomora") MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username, x509_cert=fake_client_cert, ) assert mock_ssl_context.load_default_certs.call_count == 1 assert mock_ssl_context.load_cert_chain.call_count == 1 assert mock_ssl_context.load_cert_chain.call_args == mocker.call( fake_client_cert.certificate_file, fake_client_cert.key_file, fake_client_cert.pass_phrase, ) @pytest.mark.it("Sets Paho MQTT Client callbacks") def test_sets_paho_callbacks(self, mocker): mock_mqtt_client = mocker.patch.object(mqtt, "Client").return_value MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username) assert callable(mock_mqtt_client.on_connect) assert callable(mock_mqtt_client.on_disconnect) assert callable(mock_mqtt_client.on_subscribe) assert callable(mock_mqtt_client.on_unsubscribe) assert callable(mock_mqtt_client.on_publish) assert callable(mock_mqtt_client.on_message) @pytest.mark.it("Initializes event handlers to 'None'") def test_handler_callbacks_set_to_none(self, mocker): mocker.patch.object(mqtt, "Client") transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) assert transport.on_mqtt_connected_handler is None assert transport.on_mqtt_disconnected_handler is None assert transport.on_mqtt_message_received_handler is None @pytest.mark.it("Initializes internal operation tracking structures") def test_operation_infrastructure_set_up(self, mocker): transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) assert transport._op_manager._pending_operation_callbacks == {} assert transport._op_manager._unknown_operation_completions == {} @pytest.mark.it("Sets paho auto-reconnect interval to 2 hours") def test_sets_reconnect_interval(self, mocker, transport, mock_mqtt_client): MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username) # called once by the mqtt_client constructor and once by mqtt_transport.py assert mock_mqtt_client.reconnect_delay_set.call_count == 2 assert mock_mqtt_client.reconnect_delay_set.call_args == mocker.call(120 * 60) class ArbitraryConnectException(Exception): pass @pytest.mark.describe("MQTTTransport - .connect()") class TestConnect(object): @pytest.mark.it("Uses the stored username and provided password for Paho credentials") def test_use_provided_password(self, mocker, mock_mqtt_client, transport): transport.connect(fake_password) assert mock_mqtt_client.username_pw_set.call_count == 1 assert mock_mqtt_client.username_pw_set.call_args == mocker.call( username=transport._username, password=fake_password ) @pytest.mark.it( "Uses the stored username without a password for Paho credentials, if password is not provided" ) def test_use_no_password(self, mocker, mock_mqtt_client, transport): transport.connect() assert mock_mqtt_client.username_pw_set.call_count == 1 assert mock_mqtt_client.username_pw_set.call_args == mocker.call( username=transport._username, password=None ) @pytest.mark.it("Initiates MQTT connect via Paho") @pytest.mark.parametrize( "password", [ pytest.param(fake_password, id="Password provided"), pytest.param(None, id="No password provided"), ], ) @pytest.mark.parametrize( "websockets,port", [ pytest.param(False, 8883, id="Not using websockets"), pytest.param(True, 443, id="Using websockets"), ], ) def test_calls_paho_connect( self, mocker, mock_mqtt_client, transport, password, websockets, port ): # We don't want to use a special fixture for websockets, so instead we are overriding the attribute below. # However, we want to assert that this value is not undefined. For instance, the self._websockets convention private attribute # could be changed to self._websockets1, and all our tests would still pass without the below assert statement. assert transport._websockets is False transport._websockets = websockets transport.connect(password) assert mock_mqtt_client.connect.call_count == 1 assert mock_mqtt_client.connect.call_args == mocker.call( host=fake_hostname, port=port, keepalive=mocker.ANY ) @pytest.mark.it("Passes DEFAULT_KEEPALIVE to paho connect function") @pytest.mark.parametrize( "password", [ pytest.param(fake_password, id="Password provided"), pytest.param(None, id="No password provided"), ], ) def test_calls_paho_connect_with_keepalive(self, mocker, mock_mqtt_client, transport, password): mqtt_transport.DEFAULT_KEEPALIVE = fake_keepalive transport.connect(password) assert mock_mqtt_client.connect.call_count == 1 assert mock_mqtt_client.connect.call_args == mocker.call( host=fake_hostname, port=8883, keepalive=fake_keepalive ) @pytest.mark.it("Starts MQTT Network Loop") @pytest.mark.parametrize( "password", [ pytest.param(fake_password, id="Password provided"), pytest.param(None, id="No password provided"), ], ) def test_calls_loop_start(self, mocker, mock_mqtt_client, transport, password): transport.connect(password) assert mock_mqtt_client.loop_start.call_count == 1 assert mock_mqtt_client.loop_start.call_args == mocker.call() @pytest.mark.it("Raises a ProtocolClientError if Paho connect raises an unexpected Exception") def test_client_raises_unexpected_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): mock_mqtt_client.connect.side_effect = arbitrary_exception with pytest.raises(errors.ProtocolClientError) as e_info: transport.connect(fake_password) assert e_info.value.__cause__ is arbitrary_exception @pytest.mark.it( "Raises a ConnectionFailedError if Paho connect raises a socket.error Exception" ) def test_client_raises_socket_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): socket_error = socket.error() mock_mqtt_client.connect.side_effect = socket_error with pytest.raises(errors.ConnectionFailedError) as e_info: transport.connect(fake_password) assert e_info.value.__cause__ is socket_error @pytest.mark.it( "Raises a TlsExchangeAuthError if Paho connect raises a socket.error of type SSLCertVerificationError Exception" ) def test_client_raises_socket_tls_auth_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): socket_error = ssl.SSLError("socket error", "CERTIFICATE_VERIFY_FAILED") mock_mqtt_client.connect.side_effect = socket_error with pytest.raises(errors.TlsExchangeAuthError) as e_info: transport.connect(fake_password) assert e_info.value.__cause__ is socket_error print(e_info.value.__cause__.strerror) @pytest.mark.it( "Raises a ProtocolProxyError if Paho connect raises a socket error or a ProxyError exception" ) def test_client_raises_socket_error_or_proxy_error_as_proxy_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): socks_error = socks.SOCKS5Error( "it is a sock 5 error", socket_err="a general SOCKS5Error error" ) mock_mqtt_client.connect.side_effect = socks_error with pytest.raises(errors.ProtocolProxyError) as e_info: transport.connect(fake_password) assert e_info.value.__cause__ is socks_error print(e_info.value.__cause__.strerror) @pytest.mark.it( "Raises a UnauthorizedError if Paho connect raises a socket error or a ProxyError exception" ) def test_client_raises_socket_error_or_proxy_error_as_unauthorized_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): socks_error = socks.SOCKS5AuthError( "it is a sock 5 auth error", socket_err="an auth SOCKS5Error error" ) mock_mqtt_client.connect.side_effect = socks_error with pytest.raises(errors.UnauthorizedError) as e_info: transport.connect(fake_password) assert e_info.value.__cause__ is socks_error print(e_info.value.__cause__.strerror) @pytest.mark.it("Allows any BaseExceptions raised in Paho connect to propagate") def test_client_raises_base_exception( self, mock_mqtt_client, transport, arbitrary_base_exception ): mock_mqtt_client.connect.side_effect = arbitrary_base_exception with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.connect(fake_password) assert e_info.value is arbitrary_base_exception # NOTE: this test tests for all possible return codes, even ones that shouldn't be # possible on a connect operation. @pytest.mark.it("Raises a custom Exception if Paho connect returns a failing rc code") @pytest.mark.parametrize( "error_params", operation_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in operation_return_codes], ) def test_client_returns_failing_rc_code( self, mocker, mock_mqtt_client, transport, error_params ): mock_mqtt_client.connect.return_value = error_params["rc"] with pytest.raises(error_params["error"]): transport.connect(fake_password) @pytest.fixture( params=[ ArbitraryConnectException(), socket.error(), ssl.SSLError("socket error", "CERTIFICATE_VERIFY_FAILED"), socks.SOCKS5Error("it is a sock 5 error", socket_err="a general SOCKS5Error error"), socks.SOCKS5AuthError( "it is a sock 5 auth error", socket_err="an auth SOCKS5Error error" ), ], ids=[ "ArbitraryConnectException", "socket.error", "ssl.SSLError", "socks.SOCKS5Error", "socks.SOCKS5AuthError", ], ) def connect_exception(self, request): return request.param @pytest.mark.it("Calls _mqtt_client.disconnect if Paho raises an exception") def test_calls_disconnect_on_exception( self, mocker, mock_mqtt_client, transport, connect_exception ): mock_mqtt_client.connect.side_effect = connect_exception with pytest.raises(Exception): transport.connect(fake_password) assert mock_mqtt_client.disconnect.call_count == 1 @pytest.mark.it("Calls _mqtt_client.loop_stop if Paho raises an exception") def test_calls_loop_stop_on_exception( self, mocker, mock_mqtt_client, transport, connect_exception ): mock_mqtt_client.connect.side_effect = connect_exception with pytest.raises(Exception): transport.connect(fake_password) assert mock_mqtt_client.loop_stop.call_count == 1 @pytest.mark.it( "Sets Paho's _thread to None if Paho raises an exception while running in the Paho thread" ) def test_sets_thread_to_none_on_exception_in_paho_thread( self, mocker, mock_mqtt_client, transport, mock_paho_thread_current, connect_exception ): mock_mqtt_client.connect.side_effect = connect_exception with pytest.raises(Exception): transport.connect(fake_password) assert mock_mqtt_client._thread is None @pytest.mark.it( "Does not sets Paho's _thread to None if Paho raises an exception running outside the Paho thread" ) def test_does_not_set_thread_to_none_on_exception_not_in_paho_thread( self, mocker, mock_mqtt_client, transport, mock_non_paho_thread_current, connect_exception ): mock_mqtt_client.connect.side_effect = connect_exception with pytest.raises(Exception): transport.connect(fake_password) assert mock_mqtt_client._thread is not None @pytest.mark.describe("MQTTTransport - OCCURANCE: Connect Completed") class TestEventConnectComplete(object): @pytest.mark.it( "Triggers on_mqtt_connected_handler event handler upon successful connect completion" ) def test_calls_event_handler_callback(self, mocker, mock_mqtt_client, transport): callback = mocker.MagicMock() transport.on_mqtt_connected_handler = callback # Manually trigger Paho on_connect event_handler mock_mqtt_client.on_connect(client=mock_mqtt_client, userdata=None, flags=None, rc=fake_rc) # Verify transport.on_mqtt_connected_handler was called assert callback.call_count == 1 assert callback.call_args == mocker.call() @pytest.mark.it( "Skips on_mqtt_connected_handler event handler if set to 'None' upon successful connect completion" ) def test_skips_none_event_handler_callback(self, mocker, mock_mqtt_client, transport): assert transport.on_mqtt_connected_handler is None transport.connect(fake_password) mock_mqtt_client.on_connect(client=mock_mqtt_client, userdata=None, flags=None, rc=fake_rc) # No further asserts required - this is a test to show that it skips a callback. # Not raising an exception == test passed @pytest.mark.it("Recovers from Exception in on_mqtt_connected_handler event handler") def test_event_handler_callback_raises_exception( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_exception) transport.on_mqtt_connected_handler = event_cb transport.connect(fake_password) mock_mqtt_client.on_connect(client=mock_mqtt_client, userdata=None, flags=None, rc=fake_rc) # Callback was called, but exception did not propagate assert event_cb.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in on_mqtt_connected_handler event handler to propagate" ) def test_event_handler_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_base_exception) transport.on_mqtt_connected_handler = event_cb transport.connect(fake_password) with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_connect( client=mock_mqtt_client, userdata=None, flags=None, rc=fake_rc ) assert e_info.value is arbitrary_base_exception @pytest.mark.describe("MQTTTransport - OCCURANCE: Connection Failure") class TestEventConnectionFailure(object): @pytest.mark.parametrize( "error_params", connack_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in connack_return_codes], ) @pytest.mark.it( "Triggers on_mqtt_connection_failure_handler event handler with custom Exception upon failed connect completion" ) def test_calls_event_handler_callback_with_failed_rc( self, mocker, mock_mqtt_client, transport, error_params ): callback = mocker.MagicMock() transport.on_mqtt_connection_failure_handler = callback # Initiate connect transport.connect(fake_password) # Manually trigger Paho on_connect event_handler mock_mqtt_client.on_connect( client=mock_mqtt_client, userdata=None, flags=None, rc=error_params["rc"] ) # Verify transport.on_mqtt_connection_failure_handler was called assert callback.call_count == 1 assert isinstance(callback.call_args[0][0], error_params["error"]) @pytest.mark.it( "Skips on_mqtt_connection_failure_handler event handler if set to 'None' upon failed connect completion" ) def test_skips_none_event_handler_callback(self, mocker, mock_mqtt_client, transport): assert transport.on_mqtt_connection_failure_handler is None transport.connect(fake_password) mock_mqtt_client.on_connect( client=mock_mqtt_client, userdata=None, flags=None, rc=failed_connack_rc ) # No further asserts required - this is a test to show that it skips a callback. # Not raising an exception == test passed @pytest.mark.it("Recovers from Exception in on_mqtt_connection_failure_handler event handler") def test_event_handler_callback_raises_exception( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_exception) transport.on_mqtt_connection_failure_handler = event_cb transport.connect(fake_password) mock_mqtt_client.on_connect( client=mock_mqtt_client, userdata=None, flags=None, rc=failed_connack_rc ) # Callback was called, but exception did not propagate assert event_cb.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in on_mqtt_connection_failure_handler event handler to propagate" ) def test_event_handler_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_base_exception) transport.on_mqtt_connection_failure_handler = event_cb transport.connect(fake_password) with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_connect( client=mock_mqtt_client, userdata=None, flags=None, rc=failed_connack_rc ) assert e_info.value is arbitrary_base_exception @pytest.mark.describe("MQTTTransport - .disconnect()") class TestDisconnect(object): @pytest.mark.it("Initiates MQTT disconnect via Paho") def test_calls_paho_disconnect(self, mocker, mock_mqtt_client, transport): transport.disconnect() assert mock_mqtt_client.disconnect.call_count == 1 assert mock_mqtt_client.disconnect.call_args == mocker.call() @pytest.mark.it( "Raises a ProtocolClientError if Paho disconnect raises an unexpected Exception" ) def test_client_raises_unexpected_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): mock_mqtt_client.disconnect.side_effect = arbitrary_exception with pytest.raises(errors.ProtocolClientError) as e_info: transport.disconnect() assert e_info.value.__cause__ is arbitrary_exception @pytest.mark.it("Allows any BaseExceptions raised in Paho disconnect to propagate") def test_client_raises_base_exception( self, mock_mqtt_client, transport, arbitrary_base_exception ): mock_mqtt_client.disconnect.side_effect = arbitrary_base_exception with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.disconnect() assert e_info.value is arbitrary_base_exception @pytest.mark.it("Raises a custom Exception if Paho disconnect returns a failing rc code") @pytest.mark.parametrize( "error_params", operation_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in operation_return_codes], ) def test_client_returns_failing_rc_code( self, mocker, mock_mqtt_client, transport, error_params ): mock_mqtt_client.disconnect.return_value = error_params["rc"] with pytest.raises(error_params["error"]): transport.disconnect() @pytest.mark.it("Stops MQTT Network Loop when disconnect does not raise an exception") def test_calls_loop_stop_on_success(self, mocker, mock_mqtt_client, transport): transport.disconnect() assert mock_mqtt_client.loop_stop.call_count == 1 assert mock_mqtt_client.loop_stop.call_args == mocker.call() @pytest.mark.it("Stops MQTT Network Loop when disconnect raises an exception") def test_calls_loop_stop_on_exception( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): mock_mqtt_client.disconnect.side_effect = arbitrary_exception with pytest.raises(Exception): transport.disconnect() assert mock_mqtt_client.loop_stop.call_count == 1 assert mock_mqtt_client.loop_stop.call_args == mocker.call() @pytest.mark.it( "Sets Paho's _thread to None if disconnect does not raise an exception while running in the Paho thread" ) def test_sets_thread_to_none_on_success_in_paho_thread( self, mocker, mock_mqtt_client, transport, mock_paho_thread_current ): transport.disconnect() assert mock_mqtt_client._thread is None @pytest.mark.it( "Sets Paho's _thread to None if disconnect raises an exception while running in the Paho thread" ) def test_sets_thread_to_none_on_exception_in_paho_thread( self, mocker, mock_mqtt_client, transport, arbitrary_exception, mock_paho_thread_current ): mock_mqtt_client.disconnect.side_effect = arbitrary_exception with pytest.raises(Exception): transport.disconnect() assert mock_mqtt_client._thread is None @pytest.mark.it( "Does not set Paho's _thread to None if disconnect does not raise an exception while running outside the Paho thread" ) def test_does_not_set_thread_to_none_on_success_in_non_paho_thread( self, mocker, mock_mqtt_client, transport, mock_non_paho_thread_current ): transport.disconnect() assert mock_mqtt_client._thread is not None @pytest.mark.it( "Does not set Paho's _thread to None if disconnect raises an exception while running outside the Paho thread" ) def test_does_not_set_thread_to_none_on_exception_in_non_paho_thread( self, mocker, mock_mqtt_client, transport, arbitrary_exception, mock_non_paho_thread_current ): mock_mqtt_client.disconnect.side_effect = arbitrary_exception with pytest.raises(Exception): transport.disconnect() assert mock_mqtt_client._thread is not None @pytest.mark.describe("MQTTTransport - OCCURANCE: Disconnect Completed") class TestEventDisconnectCompleted(object): @pytest.fixture def collected_transport_weakref(self, mock_mqtt_client): # return a weak reference to an MQTTTransport that has already been collected transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) transport_weakref = weakref.ref(transport) transport = None gc.collect(2) # 2 == collect as much as possible assert transport_weakref() is None return transport_weakref @pytest.fixture( params=[fake_success_rc, fake_failed_rc], ids=["success rc code", "failed rc code"] ) def rc_success_or_failure(self, request): return request.param @pytest.mark.it( "Triggers on_mqtt_disconnected_handler event handler upon disconnect completion" ) def test_calls_event_handler_callback_externally_driven( self, mocker, mock_mqtt_client, transport ): callback = mocker.MagicMock() transport.on_mqtt_disconnected_handler = callback # Initiate disconnect transport.disconnect() # Manually trigger Paho on_connect event_handler mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_rc) # Verify transport.on_mqtt_connected_handler was called assert callback.call_count == 1 assert callback.call_args == mocker.call(None) @pytest.mark.parametrize( "error_params", operation_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in operation_return_codes], ) @pytest.mark.it( "Triggers on_mqtt_disconnected_handler event handler with custom Exception when an error RC is returned upon disconnect competion." ) def test_calls_event_handler_callback_with_failure_user_driven( self, mocker, mock_mqtt_client, transport, error_params ): callback = mocker.MagicMock() transport.on_mqtt_disconnected_handler = callback # Initiate disconnect transport.disconnect() # Manually trigger Paho on_disconnect event_handler mock_mqtt_client.on_disconnect( client=mock_mqtt_client, userdata=None, rc=error_params["rc"] ) # Verify transport.on_mqtt_disconnected_handler was called assert callback.call_count == 1 assert isinstance(callback.call_args[0][0], error_params["error"]) @pytest.mark.it( "Skips on_mqtt_disconnected_handler event handler if set to 'None' upon disconnect completion" ) def test_skips_none_event_handler_callback(self, mocker, mock_mqtt_client, transport): assert transport.on_mqtt_disconnected_handler is None transport.disconnect() mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_rc) # No further asserts required - this is a test to show that it skips a callback. # Not raising an exception == test passed @pytest.mark.it("Recovers from Exception in on_mqtt_disconnected_handler event handler") def test_event_handler_callback_raises_exception( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_exception) transport.on_mqtt_disconnected_handler = event_cb transport.disconnect() mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_rc) # Callback was called, but exception did not propagate assert event_cb.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in on_mqtt_disconnected_handler event handler to propagate" ) def test_event_handler_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_base_exception) transport.on_mqtt_disconnected_handler = event_cb transport.disconnect() with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_rc) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Calls Paho's disconnect() method if cause is not None") def test_calls_disconnect_with_cause(self, mock_mqtt_client, transport): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_failed_rc) assert mock_mqtt_client.disconnect.call_count == 1 @pytest.mark.it("Does not call Paho's disconnect() method if cause is None") def test_doesnt_call_disconnect_without_cause(self, mock_mqtt_client, transport): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_success_rc) assert mock_mqtt_client.disconnect.call_count == 0 @pytest.mark.it("Calls Paho's loop_stop() if cause is not None") def test_calls_loop_stop(self, mock_mqtt_client, transport): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_failed_rc) assert mock_mqtt_client.loop_stop.call_count == 1 @pytest.mark.it("Does not calls Paho's loop_stop() if cause is None") def test_does_not_call_loop_stop(self, mock_mqtt_client, transport): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_success_rc) assert mock_mqtt_client.loop_stop.call_count == 0 @pytest.mark.it( "Sets Paho's _thread to None if cause is not None while running in the Paho thread" ) def test_sets_thread_to_none_on_failure_in_paho_thread( self, mock_mqtt_client, transport, mock_paho_thread_current ): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_failed_rc) assert mock_mqtt_client._thread is None @pytest.mark.it( "Does not set Paho's _thread to None if cause is not None while running outside the paho thread" ) def test_sets_thread_to_none_on_failure_in_non_paho_thread( self, mock_mqtt_client, transport, mock_non_paho_thread_current ): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_failed_rc) assert mock_mqtt_client._thread is not None @pytest.mark.it( "Does not sets Paho's _thread to None if cause is None while running in the Paho thread" ) def test_does_not_set_thread_to_none_on_success_in_paho_thread( self, mock_mqtt_client, transport, mock_paho_thread_current ): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_success_rc) assert mock_mqtt_client._thread is not None @pytest.mark.it( "Does not sets Paho's _thread to None if cause is None while running outside the Paho thread" ) def test_does_not_set_thread_to_none_on_success_in_non_paho_thread( self, mock_mqtt_client, transport, mock_non_paho_thread_current ): mock_mqtt_client.on_disconnect(client=mock_mqtt_client, userdata=None, rc=fake_success_rc) assert mock_mqtt_client._thread is not None @pytest.mark.it("Allows any Exception raised by Paho's disconnect() to propagate") def test_disconnect_raises_exception( self, mock_mqtt_client, transport, mocker, arbitrary_exception ): mock_mqtt_client.disconnect = mocker.MagicMock(side_effect=arbitrary_exception) with pytest.raises(type(arbitrary_exception)) as e_info: mock_mqtt_client.on_disconnect( client=mock_mqtt_client, userdata=None, rc=fake_failed_rc ) assert e_info.value is arbitrary_exception @pytest.mark.it("Allows any BaseException raised by Paho's disconnect() to propagate") def test_disconnect_raises_base_exception( self, mock_mqtt_client, transport, mocker, arbitrary_base_exception ): mock_mqtt_client.disconnect = mocker.MagicMock(side_effect=arbitrary_base_exception) with pytest.raises(type(arbitrary_base_exception)) as e_info: mock_mqtt_client.on_disconnect( client=mock_mqtt_client, userdata=None, rc=fake_failed_rc ) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Allows any Exception raised by Paho's loop_stop() to propagate") def test_loop_stop_raises_exception( self, mock_mqtt_client, transport, mocker, arbitrary_exception ): mock_mqtt_client.loop_stop = mocker.MagicMock(side_effect=arbitrary_exception) with pytest.raises(type(arbitrary_exception)) as e_info: mock_mqtt_client.on_disconnect( client=mock_mqtt_client, userdata=None, rc=fake_failed_rc ) assert e_info.value is arbitrary_exception @pytest.mark.it("Allows any BaseException raised by Paho's loop_stop() to propagate") def test_loop_stop_raises_base_exception( self, mock_mqtt_client, transport, mocker, arbitrary_base_exception ): mock_mqtt_client.loop_stop = mocker.MagicMock(side_effect=arbitrary_base_exception) with pytest.raises(type(arbitrary_base_exception)) as e_info: mock_mqtt_client.on_disconnect( client=mock_mqtt_client, userdata=None, rc=fake_failed_rc ) assert e_info.value is arbitrary_base_exception @pytest.mark.it( "Does not raise any exceptions if the MQTTTransport object was garbage collected before the disconnect completed" ) def test_no_exception_after_gc( self, mock_mqtt_client, collected_transport_weakref, rc_success_or_failure ): assert mock_mqtt_client.on_disconnect mock_mqtt_client.on_disconnect(mock_mqtt_client, None, rc_success_or_failure) # lack of exception is success @pytest.mark.it( "Calls Paho's loop_stop() if the MQTTTransport object was garbage collected before the disconnect completed" ) def test_calls_loop_stop_after_gc( self, collected_transport_weakref, mock_mqtt_client, rc_success_or_failure, mocker ): assert mock_mqtt_client.loop_stop.call_count == 0 mock_mqtt_client.on_disconnect(mock_mqtt_client, None, rc_success_or_failure) assert mock_mqtt_client.loop_stop.call_count == 1 assert mock_mqtt_client.loop_stop.call_args == mocker.call() @pytest.mark.it( "Allows any Exception raised by Paho's loop_stop() to propagate if the MQTTTransport object was garbage collected before the disconnect completed" ) def test_raises_exception_after_gc( self, collected_transport_weakref, mock_mqtt_client, rc_success_or_failure, arbitrary_exception, ): mock_mqtt_client.loop_stop.side_effect = arbitrary_exception with pytest.raises(type(arbitrary_exception)): mock_mqtt_client.on_disconnect(mock_mqtt_client, None, rc_success_or_failure) @pytest.mark.it( "Allows any BaseException raised by Paho's loop_stop() to propagate if the MQTTTransport object was garbage collected before the disconnect completed" ) def test_raises_base_exception_after_gc( self, collected_transport_weakref, mock_mqtt_client, rc_success_or_failure, arbitrary_base_exception, ): mock_mqtt_client.loop_stop.side_effect = arbitrary_base_exception with pytest.raises(type(arbitrary_base_exception)): mock_mqtt_client.on_disconnect(mock_mqtt_client, None, rc_success_or_failure) @pytest.mark.describe("MQTTTransport - .subscribe()") class TestSubscribe(object): @pytest.mark.it("Subscribes with Paho") @pytest.mark.parametrize( "qos", [pytest.param(0, id="QoS 0"), pytest.param(1, id="QoS 1"), pytest.param(2, id="QoS 2")], ) def test_calls_paho_subscribe(self, mocker, mock_mqtt_client, transport, qos): transport.subscribe(fake_topic, qos=qos) assert mock_mqtt_client.subscribe.call_count == 1 assert mock_mqtt_client.subscribe.call_args == mocker.call(fake_topic, qos=qos) @pytest.mark.it("Raises ValueError on invalid QoS") @pytest.mark.parametrize("qos", [pytest.param(-1, id="QoS < 0"), pytest.param(3, id="QoS > 2")]) def test_raises_value_error_invalid_qos(self, qos): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(ValueError): transport.subscribe(fake_topic, qos=qos) @pytest.mark.it("Raises ValueError on invalid topic string") @pytest.mark.parametrize("topic", [pytest.param(None), pytest.param("", id="Empty string")]) def test_raises_value_error_invalid_topic(self, topic): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(ValueError): transport.subscribe(topic, qos=fake_qos) @pytest.mark.it("Triggers callback upon subscribe completion") def test_triggers_callback_upon_paho_on_subscribe_event( self, mocker, mock_mqtt_client, transport ): callback = mocker.MagicMock() mock_mqtt_client.subscribe.return_value = (fake_rc, fake_mid) # Initiate subscribe transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) # Check callback is not called yet assert callback.call_count == 0 # Manually trigger Paho on_subscribe event handler mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) # Check callback has now been called assert callback.call_count == 1 @pytest.mark.it( "Triggers callback upon subscribe completion when Paho event handler triggered early" ) def test_triggers_callback_when_paho_on_subscribe_event_called_early( self, mocker, mock_mqtt_client, transport ): callback = mocker.MagicMock() def trigger_early_on_subscribe(topic, qos): # Trigger on_subscribe before returning mid mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) # Check callback not yet called assert callback.call_count == 0 return (fake_rc, fake_mid) mock_mqtt_client.subscribe.side_effect = trigger_early_on_subscribe # Initiate subscribe transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) # Check callback has now been called assert callback.call_count == 1 @pytest.mark.it("Skips callback that is set to 'None' upon subscribe completion") def test_none_callback_upon_paho_on_subscribe_event(self, mocker, mock_mqtt_client, transport): callback = None mock_mqtt_client.subscribe.return_value = (fake_rc, fake_mid) # Initiate subscribe transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) # Manually trigger Paho on_subscribe event handler mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) # No assertions necessary - not raising an exception => success @pytest.mark.it( "Skips callback that is set to 'None' upon subscribe completion when Paho event handler triggered early" ) def test_none_callback_when_paho_on_subscribe_event_called_early( self, mocker, mock_mqtt_client, transport ): callback = None def trigger_early_on_subscribe(topic, qos): # Trigger on_subscribe before returning mid mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) return (fake_rc, fake_mid) mock_mqtt_client.subscribe.side_effect = trigger_early_on_subscribe # Initiate subscribe transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) # No assertions necessary - not raising an exception => success @pytest.mark.it( "Handles multiple callbacks from multiple subscribe operations that complete out of order" ) def test_multiple_callbacks(self, mocker, mock_mqtt_client, transport): callback1 = mocker.MagicMock() callback2 = mocker.MagicMock() callback3 = mocker.MagicMock() mid1 = 1 mid2 = 2 mid3 = 3 mock_mqtt_client.subscribe.side_effect = [(fake_rc, mid1), (fake_rc, mid2), (fake_rc, mid3)] # Initiate subscribe (1 -> 2 -> 3) transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback1) transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback2) transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback3) # Check callbacks have not yet been called assert callback1.call_count == 0 assert callback2.call_count == 0 assert callback3.call_count == 0 # Manually trigger Paho on_subscribe event handler (2 -> 3 -> 1) mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=mid2, granted_qos=fake_qos ) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 0 mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=mid3, granted_qos=fake_qos ) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 1 mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=mid1, granted_qos=fake_qos ) assert callback1.call_count == 1 assert callback2.call_count == 1 assert callback3.call_count == 1 @pytest.mark.it("Recovers from Exception in callback") def test_callback_raises_exception( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): callback = mocker.MagicMock(side_effect=arbitrary_exception) mock_mqtt_client.subscribe.return_value = (fake_rc, fake_mid) transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) # Callback was called, but exception did not propagate assert callback.call_count == 1 @pytest.mark.it("Allows any BaseExceptions raised in callback to propagate") def test_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): callback = mocker.MagicMock(side_effect=arbitrary_base_exception) mock_mqtt_client.subscribe.return_value = (fake_rc, fake_mid) transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Recovers from Exception in callback when Paho event handler triggered early") def test_callback_rasies_exception_when_paho_on_subscribe_triggered_early( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): callback = mocker.MagicMock(side_effect=arbitrary_exception) def trigger_early_on_subscribe(topic, qos): mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) # Should not have yet called callback assert callback.call_count == 0 return (fake_rc, fake_mid) mock_mqtt_client.subscribe.side_effect = trigger_early_on_subscribe # Initiate subscribe transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) # Callback was called, but exception did not propagate assert callback.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in callback when Paho event handler triggered early to propagate" ) def test_callback_raises_base_exception_when_paho_on_subscribe_triggered_early( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): callback = mocker.MagicMock(side_effect=arbitrary_base_exception) def trigger_early_on_subscribe(topic, qos): mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=fake_mid, granted_qos=fake_qos ) # Should not have yet called callback assert callback.call_count == 0 return (fake_rc, fake_mid) mock_mqtt_client.subscribe.side_effect = trigger_early_on_subscribe # Initiate subscribe with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.subscribe(topic=fake_topic, qos=fake_qos, callback=callback) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Raises a ProtocolClientError if Paho subscribe raises an unexpected Exception") def test_client_raises_unexpected_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): mock_mqtt_client.subscribe.side_effect = arbitrary_exception with pytest.raises(errors.ProtocolClientError) as e_info: transport.subscribe(topic=fake_topic, qos=fake_qos, callback=None) assert e_info.value.__cause__ is arbitrary_exception @pytest.mark.it("Allows any BaseExceptions raised in Paho subscribe to propagate") def test_client_raises_base_exception( self, mock_mqtt_client, transport, arbitrary_base_exception ): mock_mqtt_client.subscribe.side_effect = arbitrary_base_exception with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.subscribe(topic=fake_topic, qos=fake_qos, callback=None) assert e_info.value is arbitrary_base_exception # NOTE: this test tests for all possible return codes, even ones that shouldn't be # possible on a subscribe operation. @pytest.mark.it("Raises a custom Exception if Paho subscribe returns a failing rc code") @pytest.mark.parametrize( "error_params", operation_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in operation_return_codes], ) def test_client_returns_failing_rc_code( self, mocker, mock_mqtt_client, transport, error_params ): mock_mqtt_client.subscribe.return_value = (error_params["rc"], 0) with pytest.raises(error_params["error"]): transport.subscribe(topic=fake_topic, qos=fake_qos, callback=None) @pytest.mark.describe("MQTTTransport - .unsubscribe()") class TestUnsubscribe(object): @pytest.mark.it("Unsubscribes with Paho") def test_calls_paho_unsubscribe(self, mocker, mock_mqtt_client, transport): transport.unsubscribe(fake_topic) assert mock_mqtt_client.unsubscribe.call_count == 1 assert mock_mqtt_client.unsubscribe.call_args == mocker.call(fake_topic) @pytest.mark.it("Raises ValueError on invalid topic string") @pytest.mark.parametrize("topic", [pytest.param(None), pytest.param("", id="Empty string")]) def test_raises_value_error_invalid_topic(self, topic): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(ValueError): transport.unsubscribe(topic) @pytest.mark.it("Triggers callback upon unsubscribe completion") def test_triggers_callback_upon_paho_on_unsubscribe_event( self, mocker, mock_mqtt_client, transport ): callback = mocker.MagicMock() mock_mqtt_client.unsubscribe.return_value = (fake_rc, fake_mid) # Initiate unsubscribe transport.unsubscribe(topic=fake_topic, callback=callback) # Check callback not called assert callback.call_count == 0 # Manually trigger Paho on_unsubscribe event handler mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) # Check callback has now been called assert callback.call_count == 1 @pytest.mark.it( "Triggers callback upon unsubscribe completion when Paho event handler triggered early" ) def test_triggers_callback_when_paho_on_unsubscribe_event_called_early( self, mocker, mock_mqtt_client, transport ): callback = mocker.MagicMock() def trigger_early_on_unsubscribe(topic): # Trigger on_unsubscribe before returning mid mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) # Check callback not yet called assert callback.call_count == 0 return (fake_rc, fake_mid) mock_mqtt_client.unsubscribe.side_effect = trigger_early_on_unsubscribe # Initiate unsubscribe transport.unsubscribe(topic=fake_topic, callback=callback) # Check callback has now been called assert callback.call_count == 1 @pytest.mark.it("Skips callback that is set to 'None' upon unsubscribe completion") def test_none_callback_upon_paho_on_unsubscribe_event( self, mocker, mock_mqtt_client, transport ): callback = None mock_mqtt_client.unsubscribe.return_value = (fake_rc, fake_mid) # Initiate unsubscribe transport.unsubscribe(topic=fake_topic, callback=callback) # Manually trigger Paho on_unsubscribe event handler mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) # No assertions necessary - not raising an exception => success @pytest.mark.it( "Skips callback that is set to 'None' upon unsubscribe completion when Paho event handler triggered early" ) def test_none_callback_when_paho_on_unsubscribe_event_called_early( self, mocker, mock_mqtt_client, transport ): callback = None def trigger_early_on_unsubscribe(topic): # Trigger on_unsubscribe before returning mid mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) return (fake_rc, fake_mid) mock_mqtt_client.unsubscribe.side_effect = trigger_early_on_unsubscribe # Initiate unsubscribe transport.unsubscribe(topic=fake_topic, callback=callback) # No assertions necessary - not raising an exception => success @pytest.mark.it( "Handles multiple callbacks from multiple unsubscribe operations that complete out of order" ) def test_multiple_callbacks(self, mocker, mock_mqtt_client, transport): callback1 = mocker.MagicMock() callback2 = mocker.MagicMock() callback3 = mocker.MagicMock() mid1 = 1 mid2 = 2 mid3 = 3 mock_mqtt_client.unsubscribe.side_effect = [ (fake_rc, mid1), (fake_rc, mid2), (fake_rc, mid3), ] # Initiate unsubscribe (1 -> 2 -> 3) transport.unsubscribe(topic=fake_topic, callback=callback1) transport.unsubscribe(topic=fake_topic, callback=callback2) transport.unsubscribe(topic=fake_topic, callback=callback3) # Check callbacks have not yet been called assert callback1.call_count == 0 assert callback2.call_count == 0 assert callback3.call_count == 0 # Manually trigger Paho on_unsubscribe event handler (2 -> 3 -> 1) mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=mid2) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 0 mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=mid3) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 1 mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=mid1) assert callback1.call_count == 1 assert callback2.call_count == 1 assert callback3.call_count == 1 @pytest.mark.it("Recovers from Exception in callback") def test_callback_raises_exception( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): callback = mocker.MagicMock(side_effect=arbitrary_exception) mock_mqtt_client.unsubscribe.return_value = (fake_rc, fake_mid) transport.unsubscribe(topic=fake_topic, callback=callback) mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) # Callback was called, but exception did not propagate assert callback.call_count == 1 @pytest.mark.it("Allows any BaseExceptions raised in callback to propagate") def test_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): callback = mocker.MagicMock(side_effect=arbitrary_base_exception) mock_mqtt_client.unsubscribe.return_value = (fake_rc, fake_mid) transport.unsubscribe(topic=fake_topic, callback=callback) with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Recovers from Exception in callback when Paho event handler triggered early") def test_callback_rasies_exception_when_paho_on_unsubscribe_triggered_early( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): callback = mocker.MagicMock(side_effect=arbitrary_exception) def trigger_early_on_unsubscribe(topic): mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) # Should not have yet called callback assert callback.call_count == 0 return (fake_rc, fake_mid) mock_mqtt_client.unsubscribe.side_effect = trigger_early_on_unsubscribe # Initiate unsubscribe transport.unsubscribe(topic=fake_topic, callback=callback) # Callback was called, but exception did not propagate assert callback.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in callback when Paho event handler triggered early to propagate" ) def test_callback_rasies_base_exception_when_paho_on_unsubscribe_triggered_early( self, mocker, mock_mqtt_client, transport, arbitrary_base_exception ): callback = mocker.MagicMock(side_effect=arbitrary_base_exception) def trigger_early_on_unsubscribe(topic): mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=fake_mid) # Should not have yet called callback assert callback.call_count == 0 return (fake_rc, fake_mid) mock_mqtt_client.unsubscribe.side_effect = trigger_early_on_unsubscribe # Initiate unsubscribe with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.unsubscribe(topic=fake_topic, callback=callback) assert e_info.value is arbitrary_base_exception @pytest.mark.it( "Raises a ProtocolClientError if Paho unsubscribe raises an unexpected Exception" ) def test_client_raises_unexpected_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): mock_mqtt_client.unsubscribe.side_effect = arbitrary_exception with pytest.raises(errors.ProtocolClientError) as e_info: transport.unsubscribe(topic=fake_topic, callback=None) assert e_info.value.__cause__ is arbitrary_exception @pytest.mark.it("Allows any BaseExceptions raised in Paho unsubscribe to propagate") def test_client_raises_base_exception( self, mock_mqtt_client, transport, arbitrary_base_exception ): mock_mqtt_client.unsubscribe.side_effect = arbitrary_base_exception with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.unsubscribe(topic=fake_topic, callback=None) assert e_info.value is arbitrary_base_exception # NOTE: this test tests for all possible return codes, even ones that shouldn't be # possible on an unsubscribe operation. @pytest.mark.it("Raises a custom Exception if Paho unsubscribe returns a failing rc code") @pytest.mark.parametrize( "error_params", operation_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in operation_return_codes], ) def test_client_returns_failing_rc_code( self, mocker, mock_mqtt_client, transport, error_params ): mock_mqtt_client.unsubscribe.return_value = (error_params["rc"], 0) with pytest.raises(error_params["error"]): transport.unsubscribe(topic=fake_topic, callback=None) @pytest.mark.describe("MQTTTransport - .publish()") class TestPublish(object): @pytest.fixture def message_info(self, mocker): mi = mqtt.MQTTMessageInfo(fake_mid) mi.rc = fake_rc return mi @pytest.mark.it("Publishes with Paho") @pytest.mark.parametrize( "qos", [pytest.param(0, id="QoS 0"), pytest.param(1, id="QoS 1"), pytest.param(2, id="QoS 2")], ) def test_calls_paho_publish(self, mocker, mock_mqtt_client, transport, qos): transport.publish(topic=fake_topic, payload=fake_payload, qos=qos) assert mock_mqtt_client.publish.call_count == 1 assert mock_mqtt_client.publish.call_args == mocker.call( topic=fake_topic, payload=fake_payload, qos=qos ) @pytest.mark.it("Raises ValueError on invalid QoS") @pytest.mark.parametrize("qos", [pytest.param(-1, id="QoS < 0"), pytest.param(3, id="Qos > 2")]) def test_raises_value_error_invalid_qos(self, qos): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(ValueError): transport.publish(topic=fake_topic, payload=fake_payload, qos=qos) @pytest.mark.it("Raises ValueError on invalid topic string") @pytest.mark.parametrize( "topic", [ pytest.param(None), pytest.param("", id="Empty string"), pytest.param("+", id="Contains wildcard (+)"), ], ) def test_raises_value_error_invalid_topic(self, topic): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(ValueError): transport.publish(topic=topic, payload=fake_payload, qos=fake_qos) @pytest.mark.it("Raises ValueError on invalid payload value") @pytest.mark.parametrize("payload", [str(b"0" * 268435456)], ids=["Payload > 268435455 bytes"]) def test_raises_value_error_invalid_payload(self, payload): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(ValueError): transport.publish(topic=fake_topic, payload=payload, qos=fake_qos) @pytest.mark.it("Raises TypeError on invalid payload type") @pytest.mark.parametrize( "payload", [ pytest.param({"a": "b"}, id="Dictionary"), pytest.param([1, 2, 3], id="List"), pytest.param(object(), id="Object"), ], ) def test_raises_type_error_invalid_payload_type(self, payload): # Manually instantiate protocol wrapper, do NOT mock paho client (paho generates this error) transport = MQTTTransport( client_id=fake_device_id, hostname=fake_hostname, username=fake_username ) with pytest.raises(TypeError): transport.publish(topic=fake_topic, payload=payload, qos=fake_qos) @pytest.mark.it("Triggers callback upon publish completion") def test_triggers_callback_upon_paho_on_publish_event( self, mocker, mock_mqtt_client, transport, message_info ): callback = mocker.MagicMock() mock_mqtt_client.publish.return_value = message_info # Initiate publish transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) # Check callback is not called assert callback.call_count == 0 # Manually trigger Paho on_publish event handler mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=message_info.mid) # Check callback has now been called assert callback.call_count == 1 @pytest.mark.it( "Triggers callback upon publish completion when Paho event handler triggered early" ) def test_triggers_callback_when_paho_on_publish_event_called_early( self, mocker, mock_mqtt_client, transport, message_info ): callback = mocker.MagicMock() def trigger_early_on_publish(topic, payload, qos): # Trigger on_publish before returning message_info mock_mqtt_client.on_publish( client=mock_mqtt_client, userdata=None, mid=message_info.mid ) # Check callback not yet called assert callback.call_count == 0 return message_info mock_mqtt_client.publish.side_effect = trigger_early_on_publish # Initiate publish transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) # Check callback has now been called assert callback.call_count == 1 @pytest.mark.it("Skips callback that is set to 'None' upon publish completion") def test_none_callback_upon_paho_on_publish_event( self, mocker, mock_mqtt_client, transport, message_info ): mock_mqtt_client.publish.return_value = message_info callback = None # Initiate publish transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) # Manually trigger Paho on_publish event handler mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=message_info.mid) # No assertions necessary - not raising an exception => success @pytest.mark.it( "Skips callback that is set to 'None' upon publish completion when Paho event handler triggered early" ) def test_none_callback_when_paho_on_publish_event_called_early( self, mocker, mock_mqtt_client, transport, message_info ): callback = None def trigger_early_on_publish(topic, payload, qos): # Trigger on_publish before returning message_info mock_mqtt_client.on_publish( client=mock_mqtt_client, userdata=None, mid=message_info.mid ) return message_info mock_mqtt_client.publish.side_effect = trigger_early_on_publish # Initiate publish transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) # No assertions necessary - not raising an exception => success @pytest.mark.it( "Handles multiple callbacks from multiple publish operations that complete out of order" ) def test_multiple_callbacks(self, mocker, mock_mqtt_client, transport): callback1 = mocker.MagicMock() callback2 = mocker.MagicMock() callback3 = mocker.MagicMock() mid1 = 1 mid2 = 2 mid3 = 3 mock_mqtt_client.publish.side_effect = [ mqtt.MQTTMessageInfo(mid1), mqtt.MQTTMessageInfo(mid2), mqtt.MQTTMessageInfo(mid3), ] # Initiate publish (1 -> 2 -> 3) transport.publish(topic=fake_topic, payload=fake_payload, callback=callback1) transport.publish(topic=fake_topic, payload=fake_payload, callback=callback2) transport.publish(topic=fake_topic, payload=fake_payload, callback=callback3) # Check callbacks have not yet been called assert callback1.call_count == 0 assert callback2.call_count == 0 assert callback3.call_count == 0 # Manually trigger Paho on_publish event handler (2 -> 3 -> 1) mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=mid2) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 0 mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=mid3) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 1 mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=mid1) assert callback1.call_count == 1 assert callback2.call_count == 1 assert callback3.call_count == 1 @pytest.mark.it("Recovers from Exception in callback") def test_callback_raises_exception( self, mocker, mock_mqtt_client, transport, message_info, arbitrary_exception ): callback = mocker.MagicMock(side_effect=arbitrary_exception) mock_mqtt_client.publish.return_value = message_info transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=message_info.mid) # Callback was called, but exception did not propagate assert callback.call_count == 1 @pytest.mark.it("Allows any BaseExceptions raised in callback to propagate") def test_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, message_info, arbitrary_base_exception ): callback = mocker.MagicMock(side_effect=arbitrary_base_exception) mock_mqtt_client.publish.return_value = message_info transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_publish( client=mock_mqtt_client, userdata=None, mid=message_info.mid ) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Recovers from Exception in callback when Paho event handler triggered early") def test_callback_rasies_exception_when_paho_on_publish_triggered_early( self, mocker, mock_mqtt_client, transport, message_info, arbitrary_exception ): callback = mocker.MagicMock(side_effect=arbitrary_exception) def trigger_early_on_publish(topic, payload, qos): mock_mqtt_client.on_publish( client=mock_mqtt_client, userdata=None, mid=message_info.mid ) # Should not have yet called callback assert callback.call_count == 0 return message_info mock_mqtt_client.publish.side_effect = trigger_early_on_publish # Initiate publish transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) # Callback was called, but exception did not propagate assert callback.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in callback when Paho event handler triggered early to propagate" ) def test_callback_rasies_base_exception_when_paho_on_publish_triggered_early( self, mocker, mock_mqtt_client, transport, message_info, arbitrary_base_exception ): callback = mocker.MagicMock(side_effect=arbitrary_base_exception) def trigger_early_on_publish(topic, payload, qos): mock_mqtt_client.on_publish( client=mock_mqtt_client, userdata=None, mid=message_info.mid ) # Should not have yet called callback assert callback.call_count == 0 return message_info mock_mqtt_client.publish.side_effect = trigger_early_on_publish # Initiate publish with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.publish(topic=fake_topic, payload=fake_payload, callback=callback) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Raises a ProtocolClientError if Paho publish raises an unexpected Exception") def test_client_raises_unexpected_error( self, mocker, mock_mqtt_client, transport, arbitrary_exception ): mock_mqtt_client.publish.side_effect = arbitrary_exception with pytest.raises(errors.ProtocolClientError) as e_info: transport.publish(topic=fake_topic, payload=fake_payload, callback=None) assert e_info.value.__cause__ is arbitrary_exception @pytest.mark.it("Allows any BaseExceptions raised in Paho publish to propagate") def test_client_raises_base_exception( self, mock_mqtt_client, transport, arbitrary_base_exception ): mock_mqtt_client.publish.side_effect = arbitrary_base_exception with pytest.raises(arbitrary_base_exception.__class__) as e_info: transport.publish(topic=fake_topic, payload=fake_payload, callback=None) assert e_info.value is arbitrary_base_exception # NOTE: this test tests for all possible return codes, even ones that shouldn't be # possible on a publish operation. @pytest.mark.it("Raises a custom Exception if Paho publish returns a failing rc code") @pytest.mark.parametrize( "error_params", operation_return_codes, ids=["{}->{}".format(x["name"], x["error"].__name__) for x in operation_return_codes], ) def test_client_returns_failing_rc_code( self, mocker, mock_mqtt_client, transport, error_params ): mock_mqtt_client.publish.return_value = (error_params["rc"], 0) with pytest.raises(error_params["error"]): transport.publish(topic=fake_topic, payload=fake_payload, callback=None) @pytest.mark.describe("MQTTTransport - OCCURANCE: Message Received") class TestMessageReceived(object): @pytest.fixture() def message(self): message = mqtt.MQTTMessage(mid=fake_mid, topic=fake_topic.encode()) message.payload = fake_payload message.qos = fake_qos return message @pytest.mark.it( "Triggers on_mqtt_message_received_handler event handler upon receiving message" ) def test_calls_event_handler_callback(self, mocker, mock_mqtt_client, transport, message): callback = mocker.MagicMock() transport.on_mqtt_message_received_handler = callback # Manually trigger Paho on_message event_handler mock_mqtt_client.on_message(client=mock_mqtt_client, userdata=None, mqtt_message=message) # Verify transport.on_mqtt_message_received_handler was called assert callback.call_count == 1 assert callback.call_args == mocker.call(message.topic, message.payload) @pytest.mark.it( "Skips on_mqtt_message_received_handler event handler if set to 'None' upon receiving message" ) def test_skips_none_event_handler_callback(self, mocker, mock_mqtt_client, transport, message): assert transport.on_mqtt_message_received_handler is None # Manually trigger Paho on_message event_handler mock_mqtt_client.on_message(client=mock_mqtt_client, userdata=None, mqtt_message=message) # No further asserts required - this is a test to show that it skips a callback. # Not raising an exception == test passed @pytest.mark.it("Recovers from Exception in on_mqtt_message_received_handler event handler") def test_event_handler_callback_raises_exception( self, mocker, mock_mqtt_client, transport, message, arbitrary_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_exception) transport.on_mqtt_message_received_handler = event_cb mock_mqtt_client.on_message(client=mock_mqtt_client, userdata=None, mqtt_message=message) # Callback was called, but exception did not propagate assert event_cb.call_count == 1 @pytest.mark.it( "Allows any BaseExceptions raised in on_mqtt_message_received_handler event handler to propagate" ) def test_event_handler_callback_raises_base_exception( self, mocker, mock_mqtt_client, transport, message, arbitrary_base_exception ): event_cb = mocker.MagicMock(side_effect=arbitrary_base_exception) transport.on_mqtt_message_received_handler = event_cb with pytest.raises(arbitrary_base_exception.__class__) as e_info: mock_mqtt_client.on_message( client=mock_mqtt_client, userdata=None, mqtt_message=message ) assert e_info.value is arbitrary_base_exception @pytest.mark.describe("MQTTTransport - Misc.") class TestMisc(object): @pytest.mark.it( "Handles multiple callbacks from multiple different types of operations that complete out of order" ) def test_multiple_callbacks_multiple_ops(self, mocker, mock_mqtt_client, transport): callback1 = mocker.MagicMock() callback2 = mocker.MagicMock() callback3 = mocker.MagicMock() mid1 = 1 mid2 = 2 mid3 = 3 topic1 = "topic1" topic2 = "topic2" topic3 = "topic3" mock_mqtt_client.subscribe.return_value = (fake_rc, mid1) mock_mqtt_client.publish.return_value = mqtt.MQTTMessageInfo(mid2) mock_mqtt_client.unsubscribe.return_value = (fake_rc, mid3) # Initiate operations (1 -> 2 -> 3) transport.subscribe(topic=topic1, qos=fake_qos, callback=callback1) transport.publish(topic=topic2, payload="payload", qos=fake_qos, callback=callback2) transport.unsubscribe(topic=topic3, callback=callback3) # Check callbacks have not yet been called assert callback1.call_count == 0 assert callback2.call_count == 0 assert callback3.call_count == 0 # Manually trigger Paho on_unsubscribe event handler (2 -> 3 -> 1) mock_mqtt_client.on_publish(client=mock_mqtt_client, userdata=None, mid=mid2) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 0 mock_mqtt_client.on_unsubscribe(client=mock_mqtt_client, userdata=None, mid=mid3) assert callback1.call_count == 0 assert callback2.call_count == 1 assert callback3.call_count == 1 mock_mqtt_client.on_subscribe( client=mock_mqtt_client, userdata=None, mid=mid1, granted_qos=fake_qos ) assert callback1.call_count == 1 assert callback2.call_count == 1 assert callback3.call_count == 1 @pytest.mark.describe("OperationManager") class TestOperationManager(object): @pytest.mark.it("Instantiates with no operation tracking information") def test_instantiates_empty(self): manager = OperationManager() assert len(manager._pending_operation_callbacks) == 0 assert len(manager._unknown_operation_completions) == 0 @pytest.mark.describe("OperationManager - .establish_operation()") class TestOperationManagerEstablishOperation(object): @pytest.fixture(params=[True, False]) def optional_callback(self, mocker, request): if request.param: return mocker.MagicMock() else: return None @pytest.mark.it("Begins tracking a pending operation for a new MID") @pytest.mark.parametrize( "optional_callback", [pytest.param(True, id="With callback"), pytest.param(False, id="No callback")], indirect=True, ) def test_no_early_completion(self, optional_callback): manager = OperationManager() mid = 1 manager.establish_operation(mid, optional_callback) assert len(manager._pending_operation_callbacks) == 1 assert manager._pending_operation_callbacks[mid] is optional_callback @pytest.mark.it( "Resolves operation tracking when MID corresponds to a previous unknown completion" ) def test_early_completion(self): manager = OperationManager() mid = 1 # Cause early completion of an unknown operation manager.complete_operation(mid) assert len(manager._unknown_operation_completions) == 1 assert manager._unknown_operation_completions[mid] # Establish operation that was already completed manager.establish_operation(mid) assert len(manager._unknown_operation_completions) == 0 @pytest.mark.it( "Triggers the callback if provided when MID corresponds to a previous unknown completion" ) def test_early_completion_with_callback(self, mocker): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock() # Cause early completion of an unknown operation manager.complete_operation(mid) # Establish operation that was already completed manager.establish_operation(mid, cb_mock) assert cb_mock.call_count == 1 @pytest.mark.it("Recovers from Exception thrown in callback") def test_callback_raises_exception(self, mocker, arbitrary_exception): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock(side_effect=arbitrary_exception) # Cause early completion of an unknown operation manager.complete_operation(mid) # Establish operation that was already completed manager.establish_operation(mid, cb_mock) # Callback was called, but exception did not propagate assert cb_mock.call_count == 1 @pytest.mark.it("Allows any BaseExceptions raised in callback to propagate") def test_callback_raises_base_exception(self, mocker, arbitrary_base_exception): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock(side_effect=arbitrary_base_exception) # Cause early completion of an unknown operation manager.complete_operation(mid) # Establish operation that was already completed with pytest.raises(arbitrary_base_exception.__class__) as e_info: manager.establish_operation(mid, cb_mock) assert e_info.value is arbitrary_base_exception @pytest.mark.it("Does not trigger the callback until after thread lock has been released") def test_callback_called_after_lock_release(self, mocker): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock() # Cause early completion of an unknown operation manager.complete_operation(mid) # Set up mock tracking lock_spy = mocker.spy(manager, "_lock") mock_tracker = mocker.MagicMock() calls_during_lock = [] # When the lock enters, start recording calls to callback # When the lock exits, copy the list of calls. def track_mocks(): mock_tracker.attach_mock(cb_mock, "cb") def stop_tracking_mocks(*args): local_calls_during_lock = calls_during_lock # do this for python2 compat local_calls_during_lock += copy.copy(mock_tracker.mock_calls) mock_tracker.reset_mock() lock_spy.__enter__.side_effect = track_mocks lock_spy.__exit__.side_effect = stop_tracking_mocks # Establish operation that was already completed manager.establish_operation(mid, cb_mock) # Callback WAS called, but... assert cb_mock.call_count == 1 # Callback WAS NOT called while the lock was held assert mocker.call.cb() not in calls_during_lock @pytest.mark.describe("OperationManager - .complete_operation()") class TestOperationManagerCompleteOperation(object): @pytest.mark.it("Resolves a operation tracking when MID corresponds to a pending operation") def test_complete_pending_operation(self): manager = OperationManager() mid = 1 # Establish a pending operation manager.establish_operation(mid) assert len(manager._pending_operation_callbacks) == 1 # Complete pending operation manager.complete_operation(mid) assert len(manager._pending_operation_callbacks) == 0 @pytest.mark.it("Triggers callback for a pending operation when resolving") def test_complete_pending_operation_callback(self, mocker): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock() manager.establish_operation(mid, cb_mock) assert cb_mock.call_count == 0 manager.complete_operation(mid) assert cb_mock.call_count == 1 @pytest.mark.it("Recovers from Exception thrown in callback") def test_callback_raises_exception(self, mocker, arbitrary_exception): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock(side_effect=arbitrary_exception) manager.establish_operation(mid, cb_mock) assert cb_mock.call_count == 0 manager.complete_operation(mid) # Callback was called but exception did not propagate assert cb_mock.call_count == 1 @pytest.mark.it("Allows any BaseExceptions raised in callback to propagate") def test_callback_raises_base_exception(self, mocker, arbitrary_base_exception): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock(side_effect=arbitrary_base_exception) manager.establish_operation(mid, cb_mock) assert cb_mock.call_count == 0 with pytest.raises(arbitrary_base_exception.__class__) as e_info: manager.complete_operation(mid) assert e_info.value is arbitrary_base_exception @pytest.mark.it( "Begins tracking an unknown completion if MID does not correspond to a pending operation" ) def test_early_completion(self): manager = OperationManager() mid = 1 manager.complete_operation(mid) assert len(manager._unknown_operation_completions) == 1 assert manager._unknown_operation_completions[mid] @pytest.mark.it("Does not trigger the callback until after thread lock has been released") def test_callback_called_after_lock_release(self, mocker): manager = OperationManager() mid = 1 cb_mock = mocker.MagicMock() # Set up an operation and save the callback manager.establish_operation(mid, cb_mock) # Set up mock tracking lock_spy = mocker.spy(manager, "_lock") mock_tracker = mocker.MagicMock() calls_during_lock = [] # When the lock enters, start recording calls to callback # When the lock exits, copy the list of calls. def track_mocks(): mock_tracker.attach_mock(cb_mock, "cb") def stop_tracking_mocks(*args): local_calls_during_lock = calls_during_lock # do this for python2 compat local_calls_during_lock += copy.copy(mock_tracker.mock_calls) mock_tracker.reset_mock() lock_spy.__enter__.side_effect = track_mocks lock_spy.__exit__.side_effect = stop_tracking_mocks # Complete the operation manager.complete_operation(mid) # Callback WAS called, but... assert cb_mock.call_count == 1 # Callback WAS NOT called while the lock was held assert mocker.call.cb() not in calls_during_lock
import sys sys.path.append("../../") from appJar import gui def press(): pass app = gui() app.addFileEntry("fe1") app.addLabel("hello", "hello") app.setLabelBg('hello', 'red') app.setLabelHeight('hello', 17) app.setEntryAlign("fe1", 'right') app.setEntryAnchor("fe1", 'e') app.setEntryWidth("fe1", 40) app.setEntryHeight("fe1", 7) app.go()
/* * Copyright 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <WebRTC/RTCMacros.h> #import <WebRTC/RTCVideoRenderer.h> #import <WebRTC/RTCVideoViewShading.h> NS_ASSUME_NONNULL_BEGIN @class RTCEAGLVideoView; RTC_EXPORT @protocol RTCEAGLVideoViewDelegate<RTCVideoViewDelegate> @end /** * RTCEAGLVideoView is an RTCVideoRenderer which renders video frames in its * bounds using OpenGLES 2.0 or OpenGLES 3.0. */ RTC_EXPORT @interface RTCEAGLVideoView : UIView <RTCVideoRenderer> @property(nonatomic, weak) id<RTCVideoViewDelegate> delegate; - (instancetype)initWithFrame:(CGRect)frame shader:(id<RTCVideoViewShading>)shader NS_DESIGNATED_INITIALIZER; - (instancetype)initWithCoder:(NSCoder *)aDecoder shader:(id<RTCVideoViewShading>)shader NS_DESIGNATED_INITIALIZER; @end NS_ASSUME_NONNULL_END
import Sequelize from 'sequelize'; import User from '../app/models/User'; import Recipient from '../app/models/Recipient'; import File from '../app/models/File'; import Deliverer from '../app/models/Deliverer'; import Order from '../app/models/Order'; import DeliveryProblem from '../app/models/DeliveryProblem'; import dataBaseConfig from '../config/database'; const models = [User, Recipient, File, Deliverer, Order, DeliveryProblem]; class Database { constructor() { this.init(); } init() { this.connection = new Sequelize(dataBaseConfig); models .map(model => model.init(this.connection)) .map(model => model.associate && model.associate(this.connection.models)); } } export default new Database();
var IdleTimeout = function () { return { //main function to initiate the module init: function () { // cache a reference to the countdown element so we don't have to query the DOM for it on each ping. var $countdown; $('body').append('<div class="modal fade" id="idle-timeout-dialog" data-backdrop="static"><div class="modal-dialog modal-small"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Your session is about to expire.</h4></div><div class="modal-body"><p><i class="fa fa-warning"></i> You session will be locked in <span id="idle-timeout-counter"></span> seconds.</p><p>Do you want to continue your session?</p></div><div class="modal-footer"><button id="idle-timeout-dialog-logout" type="button" class="btn btn-default">No, Logout</button><button id="idle-timeout-dialog-keepalive" type="button" class="btn btn-primary" data-dismiss="modal">Yes, Keep Working</button></div></div></div></div>'); // start the idle timer plugin $.idleTimeout('#idle-timeout-dialog', '.modal-content button:last', { idleAfter: 5, // 5 seconds timeout: 30000, //30 seconds to timeout pollingInterval: 5, // 5 seconds keepAliveURL: 'demo/idletimeout_keepalive.php', serverResponseEquals: 'OK', onTimeout: function(){ window.location = "page_locked.html"; }, onIdle: function(){ $('#idle-timeout-dialog').modal('show'); $countdown = $('#idle-timeout-counter'); $('#idle-timeout-dialog-keepalive').on('click', function () { $('#idle-timeout-dialog').modal('hide'); }); $('#idle-timeout-dialog-logout').on('click', function () { $('#idle-timeout-dialog').modal('hide'); $.idleTimeout.options.onTimeout.call(this); }); }, onCountdown: function(counter){ $countdown.html(counter); // update the counter } }); } }; }();
var P = (function() { 'use strict'; var SCALE = window.devicePixelRatio || 1; var hasTouchEvents = 'ontouchstart' in document; var inherits = function(cla, sup) { cla.prototype = Object.create(sup.prototype); cla.parent = sup; cla.base = function(self, method /*, args... */) { return sup.prototype[method].call(self, [].slice.call(arguments, 2)); }; }; var addEvents = function(cla /*, events... */) { [].slice.call(arguments, 1).forEach(function(event) { addEvent(cla, event); }); }; var addEvent = function(cla, event) { var capital = event[0].toUpperCase() + event.substr(1); cla.prototype.addEventListener = cla.prototype.addEventListener || function(event, listener) { var listeners = this['$' + event] = this['$' + event] || []; listeners.push(listener); return this; }; cla.prototype.removeEventListener = cla.prototype.removeEventListener || function(event, listener) { var listeners = this['$' + event]; if (listeners) { var i = listeners.indexOf(listener); if (i !== -1) { listeners.splice(i, 1); } } return this; }; cla.prototype.dispatchEvent = cla.prototype.dispatchEvent || function(event, arg) { var listeners = this['$' + event]; if (listeners) { listeners.forEach(function(listener) { listener(arg); }); } var listener = this['on' + event]; if (listener) { listener(arg); } return this; }; cla.prototype['on' + capital] = function(listener) { this.addEventListener(event, listener); return this; }; cla.prototype['dispatch' + capital] = function(arg) { this.dispatchEvent(event, arg); return this; }; }; var Request = function() { this.loaded = 0; }; addEvents(Request, 'load', 'progress', 'error'); Request.prototype.progress = function(loaded, total, lengthComputable) { this.loaded = loaded; this.total = total; this.lengthComputable = lengthComputable; this.dispatchProgress({ loaded: loaded, total: total, lengthComputable: lengthComputable }); }; Request.prototype.load = function(result) { this.result = result; this.isDone = true; this.dispatchLoad(result); }; Request.prototype.error = function(error) { this.result = error; this.isError = true; this.isDone = true; this.dispatchError(error); }; var CompositeRequest = function() { this.requests = []; this.isDone = true; this.update = this.update.bind(this); this.error = this.error.bind(this); }; inherits(CompositeRequest, Request); CompositeRequest.prototype.add = function(request) { if (request instanceof CompositeRequest) { for (var i = 0; i < request.requests.length; i++) { this.add(request.requests[i]); } } else { this.requests.push(request); request.addEventListener('progress', this.update); request.addEventListener('load', this.update); request.addEventListener('error', this.error); this.update(); } }; CompositeRequest.prototype.update = function() { if (this.isError) return; var requests = this.requests; var i = requests.length; var total = 0; var loaded = 0; var lengthComputable = true; var uncomputable = 0; var done = 0; while (i--) { var r = requests[i]; loaded += r.loaded; if (r.isDone) { total += r.loaded; done += 1; } else if (r.lengthComputable) { total += r.total; } else { lengthComputable = false; uncomputable += 1; } } if (!lengthComputable && uncomputable !== requests.length) { var each = total / (requests.length - uncomputable) * uncomputable; i = requests.length; total = 0; loaded = 0; lengthComputable = true; while (i--) { var r = requests[i]; if (r.lengthComputable) { loaded += r.loaded; total += r.total; } else { total += each; if (r.isDone) loaded += each; } } } this.progress(loaded, total, lengthComputable); this.doneCount = done; this.isDone = done === requests.length; if (this.isDone && !this.defer) { this.load(this.getResult()); } }; CompositeRequest.prototype.getResult = function() { throw new Error('Users must implement getResult()'); }; var wavFiles = {AcousticGuitar_F3:'instruments/AcousticGuitar_F3_22k.wav',AcousticPiano_As3:'instruments/AcousticPiano(5)_A%233_22k.wav',AcousticPiano_C4:'instruments/AcousticPiano(5)_C4_22k.wav',AcousticPiano_G4:'instruments/AcousticPiano(5)_G4_22k.wav',AcousticPiano_F5:'instruments/AcousticPiano(5)_F5_22k.wav',AcousticPiano_C6:'instruments/AcousticPiano(5)_C6_22k.wav',AcousticPiano_Ds6:'instruments/AcousticPiano(5)_D%236_22k.wav',AcousticPiano_D7:'instruments/AcousticPiano(5)_D7_22k.wav',AltoSax_A3:'instruments/AltoSax_A3_22K.wav',AltoSax_C6:'instruments/AltoSax(3)_C6_22k.wav',Bassoon_C3:'instruments/Bassoon_C3_22k.wav',BassTrombone_A2_2:'instruments/BassTrombone_A2(2)_22k.wav',BassTrombone_A2_3:'instruments/BassTrombone_A2(3)_22k.wav',Cello_C2:'instruments/Cello(3b)_C2_22k.wav',Cello_As2:'instruments/Cello(3)_A%232_22k.wav',Choir_F3:'instruments/Choir(4)_F3_22k.wav',Choir_F4:'instruments/Choir(4)_F4_22k.wav',Choir_F5:'instruments/Choir(4)_F5_22k.wav',Clarinet_C4:'instruments/Clarinet_C4_22k.wav',ElectricBass_G1:'instruments/ElectricBass(2)_G1_22k.wav',ElectricGuitar_F3:'instruments/ElectricGuitar(2)_F3(1)_22k.wav',ElectricPiano_C2:'instruments/ElectricPiano_C2_22k.wav',ElectricPiano_C4:'instruments/ElectricPiano_C4_22k.wav',EnglishHorn_D4:'instruments/EnglishHorn(1)_D4_22k.wav',EnglishHorn_F3:'instruments/EnglishHorn(1)_F3_22k.wav',Flute_B5_1:'instruments/Flute(3)_B5(1)_22k.wav',Flute_B5_2:'instruments/Flute(3)_B5(2)_22k.wav',Marimba_C4:'instruments/Marimba_C4_22k.wav',MusicBox_C4:'instruments/MusicBox_C4_22k.wav',Organ_G2:'instruments/Organ(2)_G2_22k.wav',Pizz_A3:'instruments/Pizz(2)_A3_22k.wav',Pizz_E4:'instruments/Pizz(2)_E4_22k.wav',Pizz_G2:'instruments/Pizz(2)_G2_22k.wav',SteelDrum_D5:'instruments/SteelDrum_D5_22k.wav',SynthLead_C4:'instruments/SynthLead(6)_C4_22k.wav',SynthLead_C6:'instruments/SynthLead(6)_C6_22k.wav',SynthPad_A3:'instruments/SynthPad(2)_A3_22k.wav',SynthPad_C6:'instruments/SynthPad(2)_C6_22k.wav',TenorSax_C3:'instruments/TenorSax(1)_C3_22k.wav',Trombone_B3:'instruments/Trombone_B3_22k.wav',Trumpet_E5:'instruments/Trumpet_E5_22k.wav',Vibraphone_C3:'instruments/Vibraphone_C3_22k.wav',Violin_D4:'instruments/Violin(2)_D4_22K.wav',Violin_A4:'instruments/Violin(3)_A4_22k.wav',Violin_E5:'instruments/Violin(3b)_E5_22k.wav',WoodenFlute_C5:'instruments/WoodenFlute_C5_22k.wav',BassDrum:'drums/BassDrum(1b)_22k.wav',Bongo:'drums/Bongo_22k.wav',Cabasa:'drums/Cabasa(1)_22k.wav',Clap:'drums/Clap(1)_22k.wav',Claves:'drums/Claves(1)_22k.wav',Conga:'drums/Conga(1)_22k.wav',Cowbell:'drums/Cowbell(3)_22k.wav',Crash:'drums/Crash(2)_22k.wav',Cuica:'drums/Cuica(2)_22k.wav',GuiroLong:'drums/GuiroLong(1)_22k.wav',GuiroShort:'drums/GuiroShort(1)_22k.wav',HiHatClosed:'drums/HiHatClosed(1)_22k.wav',HiHatOpen:'drums/HiHatOpen(2)_22k.wav',HiHatPedal:'drums/HiHatPedal(1)_22k.wav',Maracas:'drums/Maracas(1)_22k.wav',SideStick:'drums/SideStick(1)_22k.wav',SnareDrum:'drums/SnareDrum(1)_22k.wav',Tambourine:'drums/Tambourine(3)_22k.wav',Tom:'drums/Tom(1)_22k.wav',Triangle:'drums/Triangle(1)_22k.wav',Vibraslap:'drums/Vibraslap(1)_22k.wav',WoodBlock:'drums/WoodBlock(1)_22k.wav'}; var IO = {}; IO.PROJECT_URL = 'http://projects.scratch.mit.edu/internalapi/project/'; IO.ASSET_URL = 'http://cdn.assets.scratch.mit.edu/internalapi/asset/'; IO.SOUNDBANK_URL = 'https://cdn.rawgit.com/LLK/scratch-flash/v429/src/soundbank/'; IO.FONTS = { '': 'Helvetica', Donegal: 'Donegal One', Gloria: 'Gloria Hallelujah', Marker: 'Permanent Marker', Mystery: 'Mystery Quest' }; IO.LINE_HEIGHTS = { Helvetica: 1.13, 'Donegal One': 1.25, 'Gloria Hallelujah': 1.97, 'Permanent Marker': 1.43, 'Mystery Quest': 1.37 }; IO.init = function(request) { IO.projectRequest = request; IO.zip = null; }; IO.parseJSONish = function(json) { if (!/^\s*\{/.test(json)) throw new SyntaxError('Bad JSON'); try { return JSON.parse(json); } catch (e) {} if (/[^,:{}\[\]0-9\.\-+EINaefilnr-uy \n\r\t]/.test(json.replace(/"(\\.|[^"\\])*"/g, ''))) { throw new SyntaxError('Bad JSON'); } return (1, eval)('(' + json + ')'); }; IO.load = function(url, callback, self, type) { var request = new Request; var xhr = new XMLHttpRequest; xhr.open('GET', url, true); xhr.onprogress = function(e) { request.progress(e.loaded, e.total, e.lengthComputable); }; xhr.onload = function() { if (xhr.status === 200) { request.load(xhr.response); } else { request.error(new Error('HTTP ' + xhr.status + ': ' + xhr.statusText)); } }; xhr.onerror = function() { request.error(new Error('XHR Error')); }; xhr.responseType = type || ''; setTimeout(xhr.send.bind(xhr)); if (callback) request.onLoad(callback.bind(self)); return request; }; IO.loadImage = function(url, callback, self) { var request = new Request; var image = new Image; image.crossOrigin = 'anonymous'; image.src = url; image.onload = function() { request.load(image); }; image.onerror = function() { request.error(new Error('Failed to load image: ' + url)); }; if (callback) request.onLoad(callback.bind(self)); return request; }; IO.loadScratchr2Project = function(id, callback, self) { var request = new CompositeRequest; IO.init(request); request.defer = true; var url = IO.PROJECT_URL + id + '/get/'; request.add(IO.load(url).onLoad(function(contents) { try { var json = IO.parseJSONish(contents); } catch (e) { request.add(IO.load(url, null, null, 'arraybuffer').onLoad(function(ab) { var request2 = new Request; request.add(request2); request.add(IO.loadSB2Project(ab, function(stage) { request.getResult = function() { return stage; }; request2.load(); })); request.defer = false; })); return; } try { IO.loadProject(json); if (callback) request.onLoad(callback.bind(self)); if (request.isDone) { request.load(new Stage().fromJSON(json)); } else { request.defer = false; request.getResult = function() { return new Stage().fromJSON(json); }; } } catch (e) { request.error(e); } })); return request; }; IO.loadScratchr2ProjectTitle = function(id, callback, self) { var request = new CompositeRequest; request.defer = true; request.add(P.IO.load('http://crossorigin.me/http://scratch.mit.edu/projects/' + id + '/').onLoad(function(data) { var m = /<title>\s*(.+?)(\s+on\s+Scratch)?\s*<\/title>/.exec(data); if (callback) request.onLoad(callback.bind(self)); if (m) { var d = document.createElement('div'); d.innerHTML = m[1]; request.load(d.innerText); } else { request.error(new Error('No title')); } })); return request; }; IO.loadJSONProject = function(json, callback, self) { var request = new CompositeRequest; IO.init(request); try { IO.loadProject(json); if (callback) request.onLoad(callback.bind(self)); if (request.isDone) { request.load(new Stage().fromJSON(json)); } else { request.defer = false; request.getResult = function() { return new Stage().fromJSON(json); }; } } catch (e) { request.error(e); } return request; }; IO.loadSB2Project = function(ab, callback, self) { var request = new CompositeRequest; IO.init(request); try { IO.zip = new JSZip(ab); var json = IO.parseJSONish(IO.zip.file('project.json').asText()); IO.loadProject(json); if (callback) request.onLoad(callback.bind(self)); if (request.isDone) { request.load(new Stage().fromJSON(json)); } else { request.defer = false; request.getResult = function() { return new Stage().fromJSON(json); }; } } catch (e) { request.error(e); } return request; }; IO.loadSB2File = function(f, callback, self) { var cr = new CompositeRequest; cr.defer = true; var request = new Request; cr.add(request); var reader = new FileReader; reader.onloadend = function() { cr.defer = true; cr.add(IO.loadSB2Project(reader.result, function(result) { cr.defer = false; cr.getResult = function() { return result; }; cr.update(); })); request.load(); }; reader.onprogress = function(e) { request.progress(e.loaded, e.total, e.lengthComputable); }; reader.readAsArrayBuffer(f); if (callback) cr.onLoad(callback.bind(self)); return cr; }; IO.loadProject = function(data) { IO.loadWavs(); IO.loadArray(data.children, IO.loadObject); IO.loadBase(data); }; IO.wavBuffers = Object.create(null); IO.loadWavs = function() { if (!audioContext) return; for (var name in wavFiles) { if (IO.wavBuffers[name]) { if (IO.wavBuffers[name] instanceof Request) { IO.projectRequest.add(IO.wavBuffers[name]); } } else { IO.projectRequest.add(IO.wavBuffers[name] = IO.loadWavBuffer(name)); } } }; IO.loadWavBuffer = function(name) { var request = new Request; IO.load(IO.SOUNDBANK_URL + wavFiles[name], function(ab) { IO.decodeAudio(ab, function(buffer) { IO.wavBuffers[name] = buffer; request.load(); }); }, null, 'arraybuffer').onError(function(err) { request.error(err); }); return request; }; IO.decodeAudio = function(ab, cb) { if (audioContext) { audioContext.decodeAudioData(ab, function(buffer) { cb(buffer); }, function(err) { console.warn('Failed to load audio'); cb(null); }); } else { setTimeout(cb); } }; IO.loadBase = function(data) { data.scripts = data.scripts || []; data.costumes = IO.loadArray(data.costumes, IO.loadCostume); data.sounds = IO.loadArray(data.sounds, IO.loadSound); data.variables = data.variables || []; data.lists = data.lists || []; }; IO.loadArray = function(data, process) { if (!data) return []; for (var i = 0; i < data.length; i++) { process(data[i]); } return data; }; IO.loadObject = function(data) { if (!data.cmd && !data.listName) { IO.loadBase(data); } }; IO.loadCostume = function(data) { IO.loadMD5(data.baseLayerMD5, data.baseLayerID, function(asset) { data.$image = asset; }); if (data.textLayerMD5) { IO.loadMD5(data.textLayerMD5, data.textLayerID, function(asset) { data.$text = asset; }); } }; IO.loadSound = function(data) { IO.loadMD5(data.md5, data.soundID, function(asset) { data.$buffer = asset; }, true); }; IO.fixSVG = function(svg, element) { if (element.nodeType !== 1) return; if (element.nodeName === 'text') { var font = element.getAttribute('font-family') || ''; font = IO.FONTS[font] || font; if (font) { element.setAttribute('font-family', font); if (font === 'Helvetica') element.style.fontWeight = 'bold'; } var size = +element.getAttribute('font-size'); if (!size) { element.setAttribute('font-size', size = 18); } var bb = element.getBBox(); var x = 4 - .6 * element.transform.baseVal.consolidate().matrix.a; var y = (element.getAttribute('y') - bb.y) * 1.1; element.setAttribute('x', x); element.setAttribute('y', y); var lines = element.textContent.split('\n'); if (lines.length > 1) { element.textContent = lines[0]; var lineHeight = IO.LINE_HEIGHTS[font] || 1; for (var i = 1, l = lines.length; i < l; i++) { var tspan = document.createElementNS(null, 'tspan'); tspan.textContent = lines[i]; tspan.setAttribute('x', x); tspan.setAttribute('y', y + size * i * lineHeight); element.appendChild(tspan); } } // svg.style.cssText = ''; // console.log(element.textContent, 'data:image/svg+xml;base64,' + btoa(svg.outerHTML)); } else if ((element.hasAttribute('x') || element.hasAttribute('y')) && element.hasAttribute('transform')) { element.setAttribute('x', 0); element.setAttribute('y', 0); } [].forEach.call(element.childNodes, IO.fixSVG.bind(null, svg)); }; IO.loadMD5 = function(md5, id, callback, isAudio) { if (IO.zip) { var f = isAudio ? IO.zip.file(id + '.wav') : IO.zip.file(id + '.gif') || IO.zip.file(id + '.png') || IO.zip.file(id + '.jpg') || IO.zip.file(id + '.svg'); md5 = f.name; } var ext = md5.split('.').pop(); if (ext === 'svg') { var cb = function(source) { var div = document.createElement('div'); div.innerHTML = source; var svg = div.getElementsByTagName('svg')[0]; svg.style.visibility = 'hidden'; svg.style.position = 'absolute'; svg.style.left = '-10000px'; svg.style.top = '-10000px'; document.body.appendChild(svg); var viewBox = svg.viewBox.baseVal; if (viewBox && (viewBox.x || viewBox.y)) { svg.width.baseVal.value = viewBox.width - viewBox.x; svg.height.baseVal.value = viewBox.height - viewBox.y; viewBox.x = 0; viewBox.y = 0; viewBox.width = 0; viewBox.height = 0; } IO.fixSVG(svg, svg); while (div.firstChild) div.removeChild(div.lastChild); div.appendChild(svg); svg.style.visibility = 'visible'; var canvas = document.createElement('canvas'); var image = new Image; callback(image); // svg.style.cssText = ''; // console.log(md5, 'data:image/svg+xml;base64,' + btoa(div.innerHTML.trim())); canvg(canvas, div.innerHTML.trim(), { ignoreMouse: true, ignoreAnimation: true, ignoreClear: true, renderCallback: function() { image.src = canvas.toDataURL(); } }); }; if (IO.zip) { cb(f.asText()); } else { IO.projectRequest.add(IO.load(IO.ASSET_URL + md5 + '/get/', cb)); } } else if (ext === 'wav') { var request = new Request; var cb = function(ab) { IO.decodeAudio(ab, function(buffer) { callback(buffer); request.load(buffer); }); } IO.projectRequest.add(request); if (IO.zip) { var audio = new Audio; var ab = f.asArrayBuffer(); cb(ab); } else { IO.projectRequest.add(IO.load(IO.ASSET_URL + md5 + '/get/', cb, null, 'arraybuffer')); } } else { if (IO.zip) { var request = new Request; var image = new Image; image.onload = function() { if (callback) callback(image); request.load(); }; image.src = 'data:image/' + (ext === 'jpg' ? 'jpeg' : ext) + ';base64,' + btoa(f.asBinary()); IO.projectRequest.add(request); } else { IO.projectRequest.add( IO.loadImage(IO.ASSET_URL + md5 + '/get/', function(result) { callback(result); })); } } }; var Base = function() { this.isClone = false; this.costumes = []; this.currentCostumeIndex = 0; this.objName = ''; this.instrument = 0; this.volume = 1; this.soundRefs = Object.create(null); this.sounds = []; this.vars = Object.create(null); this.watchers = Object.create(null); this.lists = Object.create(null); this.procedures = {}; this.listeners = { whenClicked: [], whenCloned: [], whenGreenFlag: [], whenIReceive: {}, whenKeyPressed: [], whenSceneStarts: [], whenSensorGreaterThan: [] }; for (var i = 0; i < 128; i++) { this.listeners.whenKeyPressed.push([]); } this.fns = []; this.scripts = []; this.filters = { color: 0, fisheye: 0, whirl: 0, pixelate: 0, mosaic: 0, brightness: 0, ghost: 0 }; }; Base.prototype.fromJSON = function(data) { this.objName = data.objName; this.scripts = data.scripts; this.currentCostumeIndex = data.currentCostumeIndex || 0; this.costumes = data.costumes.map(function(d, i) { return new Costume(d, i, this); }, this); this.addSounds(data.sounds); this.addLists(data.lists); this.addVariables(data.variables); return this; }; Base.prototype.addSounds = function(sounds) { for (var i = 0; i < sounds.length; i++) { var s = new Sound(sounds[i]); this.sounds.push(s); this.soundRefs[s.name] = s; } }; Base.prototype.addVariables = function(variables) { for (var i = 0; i < variables.length; i++) { if (variables[i].isPeristent) { throw new Error('Cloud variables are not supported'); } this.vars[variables[i].name] = variables[i].value; } }; Base.prototype.addLists = function(lists) { for (var i = 0; i < lists.length; i++) { if (lists[i].isPeristent) { throw new Error('Cloud lists are not supported'); } this.lists[lists[i].listName] = lists[i].contents; // TODO list watchers } }; Base.prototype.showVariable = function(name, visible) { var watcher = this.watchers[name]; var stage = this.stage; if (!watcher) { watcher = this.watchers[name] = new P.Watcher(stage); watcher.x = stage.defaultWatcherX; watcher.y = stage.defaultWatcherY; stage.defaultWatcherY += 26; if (stage.defaultWatcherY >= 450) { stage.defaultWatcherY = 10; stage.defaultWatcherX += 150; } watcher.target = this; watcher.label = (watcher.target === stage ? '' : watcher.target.objName + ': ') + name; watcher.param = name; stage.children.push(watcher); } else { var i = stage.children.indexOf(watcher); if (i !== stage.children.length - 1) { stage.children.splice(i, 1); stage.children.push(watcher); } } watcher.visible = visible; }; Base.prototype.showNextCostume = function() { this.currentCostumeIndex = (this.currentCostumeIndex + 1) % this.costumes.length; if (this.isStage) this.updateBackdrop(); if (this.saying) this.updateBubble(); }; Base.prototype.showPreviousCostume = function() { var length = this.costumes.length; this.currentCostumeIndex = (this.currentCostumeIndex + length - 1) % length; if (this.isStage) this.updateBackdrop(); if (this.saying) this.updateBubble(); }; Base.prototype.getCostumeName = function() { return this.costumes[this.currentCostumeIndex] ? this.costumes[this.currentCostumeIndex].costumeName : ''; }; Base.prototype.setCostume = function(costume) { if (typeof costume !== 'number') { costume = '' + costume; for (var i = 0; i < this.costumes.length; i++) { if (this.costumes[i].costumeName === costume) { this.currentCostumeIndex = i; if (this.isStage) this.updateBackdrop(); if (this.saying) this.updateBubble(); return; } } if (costume === (this.isSprite ? 'next costume' : 'next backdrop')) { this.showNextCostume(); return; } if (costume === (this.isSprite ? 'previous costume' : 'previous backdrop')) { this.showPreviousCostume(); return; } } var i = (Math.floor(costume) - 1 || 0) % this.costumes.length; if (i < 0) i += this.costumes.length; this.currentCostumeIndex = i; if (this.isStage) this.updateBackdrop(); if (this.saying) this.updateBubble(); }; Base.prototype.setFilter = function(name, value) { var min = 0; var max = 100; switch (name) { case 'whirl': case 'fisheye': case 'pixelate': // absolute value case 'mosaic': // absolute value min = -Infinity; max = Infinity; break; case 'color': value = value % 200; if (value < 0) value += 200; max = 200; break; } if (value < min) value = min; if (value > max) value = max; this.filters[name] = value; if (this.isStage) this.updateFilters(); }; Base.prototype.changeFilter = function(name, value) { this.setFilter(name, this.filters[name] + value); }; Base.prototype.resetFilters = function() { this.filters = { color: 0, fisheye: 0, whirl: 0, pixelate: 0, mosaic: 0, brightness: 0, ghost: 0 }; }; Base.prototype.getSound = function(name) { if (typeof name === 'string') { var s = this.soundRefs[name]; if (s) return s; name = +name; } var l = this.sounds.length; if (l && typeof name === 'number' && name === name) { var i = Math.round(name - 1) % l; if (i < 0) i += l; return this.sounds[i]; } }; Base.prototype.stopSounds = function() { if (this.node) { this.node.disconnect(); this.node = null; } for (var i = this.sounds.length; i--;) { var s = this.sounds[i]; if (s.node) { s.node.disconnect(); s.node = null; } } }; Base.prototype.ask = function(question) { var stage = this.stage; if (question) { if (this.isSprite && this.visible) { this.say(question); stage.promptTitle.style.display = 'none'; } else { stage.promptTitle.style.display = 'block'; stage.promptTitle.textContent = question; } } else { stage.promptTitle.style.display = 'none'; } stage.hidePrompt = false; stage.prompter.style.display = 'block'; stage.prompt.value = ''; stage.prompt.focus(); }; var Stage = function() { this.stage = this; Stage.parent.call(this); this.children = []; this.defaultWatcherX = 10; this.defaultWatcherY = 10; this.info = {}; this.answer = ''; this.promptId = 0; this.nextPromptId = 0; this.tempoBPM = 60; this.videoAlpha = 1; this.zoom = 1; this.maxZoom = SCALE; this.baseNow = 0; this.baseTime = 0; this.timerStart = 0; this.keys = [] this.keys[128] = 0; this.rawMouseX = 0; this.rawMouseY = 0; this.mouseX = 0; this.mouseY = 0; this.mousePressed = false; this.root = document.createElement('div'); this.root.style.position = 'absolute'; this.root.style.overflow = 'hidden'; this.root.style.width = '480px'; this.root.style.height = '360px'; this.root.style.fontSize = '1px'; this.root.style.background = '#fff'; this.root.style.WebkitUserSelect = this.root.style.MozUserSelect = this.root.style.MSUserSelect = this.root.style.WebkitUserSelect = 'none'; this.backdropCanvas = document.createElement('canvas'); this.root.appendChild(this.backdropCanvas); this.backdropCanvas.width = SCALE * 480; this.backdropCanvas.height = SCALE * 360; this.backdropContext = this.backdropCanvas.getContext('2d'); this.penCanvas = document.createElement('canvas'); this.root.appendChild(this.penCanvas); this.penCanvas.width = SCALE * 480; this.penCanvas.height = SCALE * 360; this.penContext = this.penCanvas.getContext('2d'); this.penContext.lineCap = 'round'; this.penContext.scale(SCALE, SCALE); this.canvas = document.createElement('canvas'); this.root.appendChild(this.canvas); this.canvas.width = SCALE * 480; this.canvas.height = SCALE * 360; this.context = this.canvas.getContext('2d'); this.canvas.tabIndex = 0; this.canvas.style.outline = 'none'; this.backdropCanvas.style.position = this.penCanvas.style.position = this.canvas.style.position = 'absolute'; this.backdropCanvas.style.width = this.penCanvas.style.width = this.canvas.style.width = '480px'; this.backdropCanvas.style.height = this.penCanvas.style.height = this.canvas.style.height = '360px'; // hardware acceleration this.root.style.WebkitTransform = 'translateZ(0)'; this.root.addEventListener('keydown', function(e) { if (e.ctrlKey || e.altKey || e.metaKey) { return; } if (!this.keys[e.keyCode]) this.keys[128]++ this.keys[e.keyCode] = true; e.stopPropagation(); if (e.target === this.canvas) { e.preventDefault(); this.trigger('whenKeyPressed', e.keyCode); } }.bind(this)); this.root.addEventListener('keyup', function(e) { if (this.keys[e.keyCode]) this.keys[128]-- this.keys[e.keyCode] = false; e.stopPropagation(); if (e.target === this.canvas) { e.preventDefault(); } }.bind(this)); if (hasTouchEvents) { document.addEventListener('touchstart', function(e) { this.mousePressed = true; for (var i = 0; i < e.changedTouches.length; i++) { this.updateMouse(e.changedTouches[i]); if (e.target === this.canvas) { this.clickMouse(); } } if (e.target === this.canvas) e.preventDefault(); }.bind(this)); document.addEventListener('touchmove', function(e) { this.updateMouse(e.changedTouches[0]); }.bind(this)); document.addEventListener('touchend', function(e) { this.releaseMouse(); }.bind(this)); } else { document.addEventListener('mousedown', function(e) { this.updateMouse(e); this.mousePressed = true; if (e.target === this.canvas) { this.clickMouse(); e.preventDefault(); this.canvas.focus(); } }.bind(this)); document.addEventListener('mousemove', function(e) { this.updateMouse(e); }.bind(this)); document.addEventListener('mouseup', function(e) { this.updateMouse(e); this.releaseMouse(); }.bind(this)); } this.prompter = document.createElement('div'); this.root.appendChild(this.prompter); this.prompter.style.position = 'absolute'; this.prompter.style.left = this.prompter.style.right = '14em'; this.prompter.style.bottom = '6em'; this.prompter.style.padding = '5em 30em 5em 5em'; this.prompter.style.border = '3em solid rgb(46, 174, 223)'; this.prompter.style.borderRadius = '8em'; this.prompter.style.background = '#fff'; this.prompter.style.display = 'none'; this.promptTitle = document.createElement('div'); this.prompter.appendChild(this.promptTitle); this.promptTitle.textContent = ''; this.promptTitle.style.cursor = 'default'; this.promptTitle.style.font = 'bold 13em sans-serif'; this.promptTitle.style.margin = '0 '+(-25/13)+'em '+(5/13)+'em 0'; this.promptTitle.style.whiteSpace = 'pre'; this.promptTitle.style.overflow = 'hidden'; this.promptTitle.style.textOverflow = 'ellipsis'; this.prompt = document.createElement('input'); this.prompter.appendChild(this.prompt); this.prompt.style.border = '0'; this.prompt.style.background = '#eee'; this.prompt.style.MozBoxSizing = this.prompt.style.boxSizing = 'border-box'; this.prompt.style.font = '13em sans-serif'; this.prompt.style.padding = '0 '+(3/13)+'em'; this.prompt.style.outline = '0'; this.prompt.style.margin = '0'; this.prompt.style.width = '100%'; this.prompt.style.height = ''+(20/13)+'em'; this.prompt.style.display = 'block'; this.prompt.style.WebkitBorderRadius = this.prompt.style.borderRadius = '0'; this.prompt.style.WebkitBoxShadow = this.prompt.style.boxShadow = 'inset '+(1/13)+'em '+(1/13)+'em '+(2/13)+'em rgba(0, 0, 0, .2), inset '+(-1/13)+'em '+(-1/13)+'em '+(1/13)+'em rgba(255, 255, 255, .2)'; this.prompt.style.WebkitAppearance = 'none'; this.promptButton = document.createElement('div'); this.prompter.appendChild(this.promptButton); this.promptButton.style.width = '22em'; this.promptButton.style.height = '22em'; this.promptButton.style.position = 'absolute'; this.promptButton.style.right = '4em'; this.promptButton.style.bottom = '4em'; this.promptButton.style.background = 'url(icons.svg) -165em -37em'; this.promptButton.style.backgroundSize = '320em 96em'; this.prompt.addEventListener('keydown', function(e) { if (e.keyCode === 13) { this.submitPrompt(); } }.bind(this)); this.promptButton.addEventListener(hasTouchEvents ? 'touchstart' : 'mousedown', this.submitPrompt.bind(this)); this.initRuntime(); }; inherits(Stage, Base); Stage.prototype.isStage = true; Stage.prototype.fromJSON = function(data) { Stage.parent.prototype.fromJSON.call(this, data); data.children.forEach(function(d) { if (d.listName) return; this.children.push(new (d.cmd ? Watcher : Sprite)(this).fromJSON(d)); }, this); this.children.forEach(function(child) { if (child.resolve) child.resolve(); }, this); P.compile(this); return this; }; Stage.prototype.focus = function() { if (this.promptId < this.nextPromptId) { this.prompt.focus(); } else { this.canvas.focus(); } }; Stage.prototype.updateMouse = function(e) { var bb = this.canvas.getBoundingClientRect(); var x = (e.clientX - bb.left) / this.zoom - 240; var y = 180 - (e.clientY - bb.top) / this.zoom; this.rawMouseX = x; this.rawMouseY = y; if (x < -240) x = -240; if (x > 240) x = 240; if (y < -180) y = -180; if (y > 180) y = 180; this.mouseX = x; this.mouseY = y; }; Stage.prototype.updateBackdrop = function() { this.backdropCanvas.width = this.zoom * SCALE * 480; this.backdropCanvas.height = this.zoom * SCALE * 360; var costume = this.costumes[this.currentCostumeIndex]; this.backdropContext.save(); var s = this.zoom * SCALE * costume.scale; this.backdropContext.scale(s, s); this.backdropContext.drawImage(costume.image, 0, 0); this.backdropContext.restore(); }; Stage.prototype.updateFilters = function() { this.backdropCanvas.style.opacity = Math.max(0, Math.min(1, 1 - this.filters.ghost / 100)); }; Stage.prototype.setZoom = function(zoom) { if (this.zoom === zoom) return; if (this.maxZoom < zoom * SCALE) { this.maxZoom = zoom * SCALE; var canvas = document.createElement('canvas'); canvas.width = this.penCanvas.width; canvas.height = this.penCanvas.height; canvas.getContext('2d').drawImage(this.penCanvas, 0, 0); this.penCanvas.width = 480 * zoom * SCALE; this.penCanvas.height = 360 * zoom * SCALE; this.penContext.drawImage(canvas, 0, 0, 480 * zoom * SCALE, 360 * zoom * SCALE); this.penContext.scale(this.maxZoom, this.maxZoom); this.penContext.lineCap = 'round'; } this.root.style.width = this.canvas.style.width = this.backdropCanvas.style.width = this.penCanvas.style.width = (480 * zoom | 0) + 'px'; this.root.style.height = this.canvas.style.height = this.backdropCanvas.style.height = this.penCanvas.style.height = (360 * zoom | 0) + 'px'; this.root.style.fontSize = zoom + 'px'; this.zoom = zoom; this.updateBackdrop(); }; Stage.prototype.clickMouse = function() { this.mouseSprite = undefined; for (var i = this.children.length; i--;) { var c = this.children[i]; if (c.isSprite && c.visible && c.filters.ghost < 100 && c.touching('_mouse_')) { if (c.isDraggable) { this.mouseSprite = c; c.mouseDown(); } else { this.triggerFor(c, 'whenClicked'); } return; } } this.triggerFor(this, 'whenClicked'); }; Stage.prototype.releaseMouse = function() { this.mousePressed = false; if (this.mouseSprite) { this.mouseSprite.mouseUp(); this.mouseSprite = undefined; } }; Stage.prototype.stopAllSounds = function() { for (var children = this.children, i = children.length; i--;) { if (children[i].isSprite) { children[i].stopSounds(); } } this.stopSounds(); }; Stage.prototype.removeAllClones = function() { var i = this.children.length; while (i--) { if (this.children[i].isClone) { this.children[i].remove(); this.children.splice(i, 1); } } }; Stage.prototype.getObject = function(name) { for (var i = 0; i < this.children.length; i++) { var c = this.children[i]; if (c.objName === name && !c.isClone) { return c; } } if (name === '_stage_' || name === this.objName) { return this; } }; Stage.prototype.getObjects = function(name) { var result = []; for (var i = 0; i < this.children.length; i++) { if (this.children[i].objName === name) { result.push(this.children[i]); } } return result; }; Stage.prototype.draw = function() { var context = this.context; this.canvas.width = 480 * this.zoom * SCALE; // clear this.canvas.height = 360 * this.zoom * SCALE; context.scale(this.zoom * SCALE, this.zoom * SCALE); this.drawOn(context); if (this.hidePrompt) { this.hidePrompt = false; this.prompter.style.display = 'none'; this.canvas.focus(); } }; Stage.prototype.drawOn = function(context, except) { for (var i = 0; i < this.children.length; i++) { if (this.children[i].visible && this.children[i] !== except) { this.children[i].draw(context); } } }; Stage.prototype.drawAllOn = function(context, except) { var costume = this.costumes[this.currentCostumeIndex]; context.save(); context.scale(costume.scale, costume.scale); context.globalAlpha = Math.max(0, Math.min(1, 1 - this.filters.ghost / 100)); context.drawImage(costume.image, 0, 0); context.restore(); context.save(); context.scale(1 / this.maxZoom, 1 / this.maxZoom); context.drawImage(this.penCanvas, 0, 0); context.restore(); this.drawOn(context, except); }; Stage.prototype.moveTo = function() {}; Stage.prototype.submitPrompt = function() { if (this.promptId < this.nextPromptId) { this.answer = this.prompt.value; this.promptId += 1; if (this.promptId >= this.nextPromptId) { this.hidePrompt = true; } } }; var KEY_CODES = { 'space': 32, 'left arrow': 37, 'up arrow': 38, 'right arrow': 39, 'down arrow': 40, 'any': 128 }; var getKeyCode = function(keyName) { return KEY_CODES[keyName.toLowerCase()] || keyName.toUpperCase().charCodeAt(0); }; var Sprite = function(stage) { this.stage = stage; Sprite.parent.call(this); this.direction = 90; this.indexInLibrary = -1; this.isDraggable = false; this.isDragging = false; this.rotationStyle = 'normal'; this.scale = 1; this.scratchX = 0; this.scratchY = 0; this.spriteInfo = {}; this.visible = true; this.penHue = 240; this.penSaturation = 100; this.penLightness = 50; this.penSize = 1; this.isPenDown = false; this.isSprite = true; this.bubble = null; this.saying = false; this.thinking = false; this.sayId = 0; }; inherits(Sprite, Base); Sprite.prototype.fromJSON = function(data) { Sprite.parent.prototype.fromJSON.call(this, data); this.direction = data.direction; this.indexInLibrary = data.indexInLibrary; this.isDraggable = data.isDraggable; this.rotationStyle = data.rotationStyle; this.scale = data.scale; this.scratchX = data.scratchX; this.scratchY = data.scratchY; this.spriteInfo = data.spriteInfo; this.visible = data.visible; return this; }; Sprite.prototype.clone = function() { var c = new Sprite(this.stage); c.isClone = true; c.costumes = this.costumes; c.currentCostumeIndex = this.currentCostumeIndex; c.objName = this.objName; c.soundRefs = this.soundRefs; c.sounds = this.sounds; var keys = Object.keys(this.vars); for (var i = keys.length; i--;) { var k = keys[i]; c.vars[k] = this.vars[k]; } var keys = Object.keys(this.lists); for (var i = keys.length; i--;) { var k = keys[i]; c.lists[k] = this.lists[k].slice(0); } c.procedures = this.procedures; c.listeners = this.listeners; c.fns = this.fns; c.scripts = this.scripts; c.filters = { color: this.filters.color, fisheye: this.filters.fisheye, whirl: this.filters.whirl, pixelate: this.filters.pixelate, mosaic: this.filters.mosaic, brightness: this.filters.brightness, ghost: this.filters.ghost }; c.direction = this.direction; c.indexInLibrary = this.indexInLibrary; c.isDraggable = this.isDraggable; c.rotationStyle = this.rotationStyle; c.scale = this.scale; c.volume = this.volume; c.scratchX = this.scratchX; c.scratchY = this.scratchY; c.visible = this.visible; c.penColor = this.penColor; c.penCSS = this.penCSS; c.penHue = this.penHue; c.penSaturation = this.penSaturation; c.penLightness = this.penLightness; c.penSize = this.penSize; c.isPenDown = this.isPenDown; return c; }; Sprite.prototype.mouseDown = function() { this.dragStartX = this.scratchX; this.dragStartY = this.scratchY; this.dragOffsetX = this.scratchX - this.stage.mouseX; this.dragOffsetY = this.scratchY - this.stage.mouseY; this.isDragging = true; }; Sprite.prototype.mouseUp = function() { if (this.isDragging && this.scratchX === this.dragStartX && this.scratchY === this.dragStartY) { this.stage.triggerFor(this, 'whenClicked'); } this.isDragging = false; }; Sprite.prototype.forward = function(steps) { var d = (90 - this.direction) * Math.PI / 180; this.moveTo(this.scratchX + steps * Math.cos(d), this.scratchY + steps * Math.sin(d)); }; Sprite.prototype.moveTo = function(x, y) { var ox = this.scratchX; var oy = this.scratchY; if (ox === x && oy === y && !this.isPenDown) return; this.scratchX = x; this.scratchY = y; if (this.isPenDown) { var context = this.stage.penContext; if (this.penSize % 2 > .5 && this.penSize % 2 < 1.5) { ox -= .5; oy -= .5; x -= .5; y -= .5; } context.strokeStyle = this.penCSS || 'hsl(' + this.penHue + ',' + this.penSaturation + '%,' + (this.penLightness > 100 ? 200 - this.penLightness : this.penLightness) + '%)'; context.lineWidth = this.penSize; context.beginPath(); context.moveTo(240 + ox, 180 - oy); context.lineTo(240 + x, 180 - y); context.stroke(); } if (this.saying) { this.updateBubble(); } }; Sprite.prototype.dotPen = function() { var context = this.stage.penContext; var x = this.scratchX; var y = this.scratchY; context.fillStyle = this.penCSS || 'hsl(' + this.penHue + ',' + this.penSaturation + '%,' + (this.penLightness > 100 ? 200 - this.penLightness : this.penLightness) + '%)'; context.beginPath(); context.arc(240 + x, 180 - y, this.penSize / 2, 0, 2 * Math.PI, false); context.fill(); }; Sprite.prototype.draw = function(context, noEffects) { var costume = this.costumes[this.currentCostumeIndex]; if (this.isDragging) { this.moveTo(this.dragOffsetX + this.stage.mouseX, this.dragOffsetY + this.stage.mouseY); } if (costume) { context.save(); var z = this.stage.zoom * SCALE; context.translate(((this.scratchX + 240) * z | 0) / z, ((180 - this.scratchY) * z | 0) / z); if (this.rotationStyle === 'normal') { context.rotate((this.direction - 90) * Math.PI / 180); } else if (this.rotationStyle === 'leftRight' && this.direction < 0) { context.scale(-1, 1); } context.scale(this.scale, this.scale); context.scale(costume.scale, costume.scale); context.translate(-costume.rotationCenterX, -costume.rotationCenterY); if (!noEffects) context.globalAlpha = Math.max(0, Math.min(1, 1 - this.filters.ghost / 100)); context.drawImage(costume.image, 0, 0); context.restore(); } }; Sprite.prototype.setDirection = function(degrees) { var d = degrees % 360; if (d > 180) d -= 360; if (d <= -180) d += 360; this.direction = d; if (this.saying) this.updateBubble(); }; var collisionCanvas = document.createElement('canvas'); var collisionContext = collisionCanvas.getContext('2d'); Sprite.prototype.touching = function(thing) { var costume = this.costumes[this.currentCostumeIndex]; if (thing === '_mouse_') { var bounds = this.rotatedBounds(); var x = this.stage.rawMouseX; var y = this.stage.rawMouseY; if (x < bounds.left || y < bounds.bottom || x > bounds.right || y > bounds.top) { return false; } var cx = (x - this.scratchX) / this.scale var cy = (this.scratchY - y) / this.scale if (this.rotationStyle === 'normal' && this.direction !== 90) { var d = (90 - this.direction) * Math.PI / 180 var ox = cx var s = Math.sin(d), c = Math.cos(d) cx = c * ox - s * cy cy = s * ox + c * cy } else if (this.rotationStyle === 'leftRight' && this.direction < 0) { cx = -cx } var d = costume.context.getImageData(cx * costume.bitmapResolution + costume.rotationCenterX, cy * costume.bitmapResolution + costume.rotationCenterY, 1, 1).data; return d[3] !== 0; } else if (thing === '_edge_') { var bounds = this.rotatedBounds(); return bounds.left <= -240 || bounds.right >= 240 || bounds.top >= 180 || bounds.bottom <= -180; } else { if (!this.visible) return false; var sprites = this.stage.getObjects(thing); for (var i = sprites.length; i--;) { var sprite = sprites[i]; if (!sprite.visible) continue; var mb = this.rotatedBounds(); var ob = sprite.rotatedBounds(); if (mb.bottom >= ob.top || ob.bottom >= mb.top || mb.left >= ob.right || ob.left >= mb.right) { continue; } var left = Math.max(mb.left, ob.left); var top = Math.min(mb.top, ob.top); var right = Math.min(mb.right, ob.right); var bottom = Math.max(mb.bottom, ob.bottom); collisionCanvas.width = right - left; collisionCanvas.height = top - bottom; collisionContext.save(); collisionContext.translate(-(left + 240), -(180 - top)); this.draw(collisionContext, true); collisionContext.globalCompositeOperation = 'source-in'; sprite.draw(collisionContext, true); collisionContext.restore(); var data = collisionContext.getImageData(0, 0, right - left, top - bottom).data; var length = (right - left) * (top - bottom) * 4; for (var j = 0; j < length; j += 4) { if (data[j + 3]) { return true; } } } return false; } }; Sprite.prototype.touchingColor = function(rgb) { var b = this.rotatedBounds(); collisionCanvas.width = b.right - b.left; collisionCanvas.height = b.top - b.bottom; collisionContext.save(); collisionContext.translate(-(240 + b.left), -(180 - b.top)); this.stage.drawAllOn(collisionContext, this); collisionContext.globalCompositeOperation = 'destination-in'; this.draw(collisionContext, true); collisionContext.restore(); var data = collisionContext.getImageData(0, 0, b.right - b.left, b.top - b.bottom).data; rgb = rgb & 0xffffff; var length = (b.right - b.left) * (b.top - b.bottom) * 4; for (var i = 0; i < length; i += 4) { if ((data[i] << 16 | data[i + 1] << 8 | data[i + 2]) === rgb && data[i + 3]) { return true; } } return false; }; Sprite.prototype.bounceOffEdge = function() { var b = this.rotatedBounds(); var dl = 240 + b.left; var dt = 180 - b.top; var dr = 240 - b.right; var db = 180 + b.bottom; var d = Math.min(dl, dt, dr, db); if (d > 0) return; var dir = this.direction * Math.PI / 180; var dx = Math.sin(dir); var dy = -Math.cos(dir); switch (d) { case dl: dx = Math.max(0.2, Math.abs(dx)); break; case dt: dy = Math.max(0.2, Math.abs(dy)); break; case dr: dx = -Math.max(0.2, Math.abs(dx)); break; case db: dy = -Math.max(0.2, Math.abs(dy)); break; } this.direction = Math.atan2(dy, dx) * 180 / Math.PI + 90; if (this.saying) this.updateBubble(); b = this.rotatedBounds(); var x = this.scratchX; var y = this.scratchY; if (b.left < -240) x += -240 - b.left; if (b.top > 180) y += 180 - b.top; if (b.right > 240) x += 240 - b.left; if (b.bottom < -180) y += -180 - b.top; }; Sprite.prototype.rotatedBounds = function() { var costume = this.costumes[this.currentCostumeIndex]; var s = costume.scale * this.scale; var left = -costume.rotationCenterX * s; var top = costume.rotationCenterY * s; var right = left + costume.image.width * s; var bottom = top - costume.image.height * s; if (this.rotationStyle !== 'normal') { if (this.rotationStyle === 'leftRight' && this.direction < 0) { right = -left; left = right - costume.image.width * costume.scale * this.scale; } return { left: this.scratchX + left, right: this.scratchX + right, top: this.scratchY + top, bottom: this.scratchY + bottom }; } var mSin = Math.sin(this.direction * Math.PI / 180); var mCos = Math.cos(this.direction * Math.PI / 180); var tlX = mSin * left - mCos * top; var tlY = mCos * left + mSin * top; var trX = mSin * right - mCos * top; var trY = mCos * right + mSin * top; var blX = mSin * left - mCos * bottom; var blY = mCos * left + mSin * bottom; var brX = mSin * right - mCos * bottom; var brY = mCos * right + mSin * bottom; return { left: this.scratchX + Math.min(tlX, trX, blX, brX), right: this.scratchX + Math.max(tlX, trX, blX, brX), top: this.scratchY + Math.max(tlY, trY, blY, brY), bottom: this.scratchY + Math.min(tlY, trY, blY, brY) }; }; Sprite.prototype.showRotatedBounds = function() { var bounds = this.rotatedBounds(); var div = document.createElement('div'); div.style.outline = '1px solid red'; div.style.position = 'absolute'; div.style.left = (240 + bounds.left) + 'px'; div.style.top = (180 - bounds.top) + 'px'; div.style.width = (bounds.right - bounds.left) + 'px'; div.style.height = (bounds.top - bounds.bottom) + 'px'; this.stage.canvas.parentNode.appendChild(div); }; Sprite.prototype.distanceTo = function(thing) { if (thing === '_mouse_') { var x = this.stage.mouseX; var y = this.stage.mouseY; } else { var sprite = this.stage.getObject(thing); if (!sprite) return 0; x = sprite.scratchX; y = sprite.scratchY; } return Math.sqrt((this.scratchX - x) * (this.scratchX - x) + (this.scratchY - y) * (this.scratchY - y)); }; Sprite.prototype.gotoObject = function(thing) { if (thing === '_mouse_') { this.moveTo(this.stage.mouseX, this.stage.mouseY); } else if (thing === '_random_') { var x = Math.round(480 * Math.random() - 240); var y = Math.round(360 * Math.random() - 180); this.moveTo(x, y); } else { var sprite = this.stage.getObject(thing); if (!sprite) return 0; this.moveTo(sprite.scratchX, sprite.scratchY); } }; Sprite.prototype.pointTowards = function(thing) { if (thing === '_mouse_') { var x = this.stage.mouseX; var y = this.stage.mouseY; } else { var sprite = this.stage.getObject(thing); if (!sprite) return 0; x = sprite.scratchX; y = sprite.scratchY; } var dx = x - this.scratchX; var dy = y - this.scratchY; this.direction = dx === 0 && dy === 0 ? 90 : Math.atan2(dx, dy) * 180 / Math.PI; if (this.saying) this.updateBubble(); }; Sprite.prototype.say = function(text, thinking) { text = '' + text; if (!text) { this.saying = false; if (!this.bubble) return; this.bubble.style.display = 'none'; return ++this.sayId; } this.saying = true; this.thinking = thinking; if (!this.bubble) { this.bubble = document.createElement('div'); this.bubble.style.maxWidth = ''+(127/14)+'em'; this.bubble.style.minWidth = ''+(48/14)+'em'; this.bubble.style.padding = ''+(8/14)+'em '+(10/14)+'em'; this.bubble.style.border = ''+(3/14)+'em solid rgb(160, 160, 160)'; this.bubble.style.borderRadius = ''+(10/14)+'em'; this.bubble.style.background = '#fff'; this.bubble.style.position = 'absolute'; this.bubble.style.font = 'bold 14em sans-serif'; this.bubble.style.whiteSpace = 'pre-wrap'; this.bubble.style.wordWrap = 'break-word'; this.bubble.style.textAlign = 'center'; this.bubble.style.cursor = 'default'; this.bubble.appendChild(this.bubbleText = document.createTextNode('')); this.bubble.appendChild(this.bubblePointer = document.createElement('div')); this.bubblePointer.style.position = 'absolute'; this.bubblePointer.style.height = ''+(21/14)+'em'; this.bubblePointer.style.width = ''+(44/14)+'em'; this.bubblePointer.style.background = 'url(icons.svg) '+(-195/14)+'em '+(-4/14)+'em'; this.bubblePointer.style.backgroundSize = ''+(320/14)+'em '+(96/14)+'em'; this.stage.root.appendChild(this.bubble); } this.bubblePointer.style.backgroundPositionX = ((thinking ? -259 : -195)/14)+'em'; this.bubble.style.display = 'block'; this.bubbleText.nodeValue = text; this.updateBubble(); return ++this.sayId; }; Sprite.prototype.updateBubble = function() { if (!this.visible || !this.saying) { this.bubble.style.display = 'none'; return; } var b = this.rotatedBounds(); var left = 240 + b.right; var bottom = 180 + b.top; var width = this.bubble.offsetWidth / this.stage.zoom; var height = this.bubble.offsetHeight / this.stage.zoom; this.bubblePointer.style.top = ((height - 6) / 14) + 'em'; if (left + width + 2 > 480) { this.bubble.style.right = ((240 - b.left) / 14) + 'em'; this.bubble.style.left = 'auto'; this.bubblePointer.style.right = (3/14)+'em'; this.bubblePointer.style.left = 'auto'; this.bubblePointer.style.backgroundPositionY = (-36/14)+'em'; } else { this.bubble.style.left = (left / 14) + 'em'; this.bubble.style.right = 'auto'; this.bubblePointer.style.left = (3/14)+'em'; this.bubblePointer.style.right = 'auto'; this.bubblePointer.style.backgroundPositionY = (-4/14)+'em'; } if (bottom + height + 2 > 360) { bottom = 360 - height - 2; } if (bottom < 19) { bottom = 19; } this.bubble.style.bottom = (bottom / 14) + 'em'; }; Sprite.prototype.remove = function() { if (this.bubble) { this.stage.root.removeChild(this.bubble); this.bubble = null; } if (this.node) { this.node.disconnect(); this.node = null; } }; var Costume = function(data, index, base) { this.index = index; this.base = base; this.baseLayerID = data.baseLayerID; this.baseLayerMD5 = data.baseLayerMD5; this.baseLayer = data.$image; this.bitmapResolution = data.bitmapResolution || 1; this.scale = 1 / this.bitmapResolution; this.costumeName = data.costumeName; this.rotationCenterX = data.rotationCenterX; this.rotationCenterY = data.rotationCenterY; this.textLayer = data.$text; this.image = document.createElement('canvas'); this.context = this.image.getContext('2d'); this.render(); this.baseLayer.onload = function() { this.render(); }.bind(this); if (this.textLayer) { this.textLayer.onload = this.baseLayer.onload; } }; addEvents(Costume, 'load'); Costume.prototype.render = function() { if (!this.baseLayer.width || this.textLayer && !this.textLayer.width) { return; } this.image.width = this.baseLayer.width; this.image.height = this.baseLayer.height; this.context.drawImage(this.baseLayer, 0, 0); if (this.textLayer) { this.context.drawImage(this.textLayer, 0, 0); } if (this.base.isStage && this.index == this.base.currentCostumeIndex) { setTimeout(function() { this.base.updateBackdrop(); }.bind(this)); } }; var Sound = function(data) { this.name = data.soundName; this.buffer = data.$buffer; this.duration = this.buffer ? this.buffer.duration : 0; }; var Watcher = function(stage) { this.stage = stage; this.cmd = 'getVar:'; this.color = '#ee7d16'; this.isDiscrete = true; this.label = 'watcher'; this.mode = 1; this.param = 'var'; this.sliderMax = 100; this.sliderMin = 0; this.target = undefined; this.visible = true; this.x = 0; this.y = 0; }; Watcher.prototype.fromJSON = function(data) { this.cmd = data.cmd || 'getVar:'; if (data.color) { var c = (data.color < 0 ? data.color + 0x1000000 : data.color).toString(16); this.color = '#000000'.slice(0, -c.length) + c; } this.isDiscrete = data.isDiscrete == null ? true : data.isDiscrete; this.label = data.label || ''; this.mode = data.mode || 1; this.param = data.param; this.sliderMax = data.sliderMax == null ? 100 : data.sliderMax; this.sliderMin = data.sliderMin || 0; this.targetName = data.target; this.visible = data.visible == null ? true : data.visible; this.x = data.x || 0; this.y = data.y || 0; return this; }; Watcher.prototype.resolve = function() { this.target = this.stage.getObject(this.targetName); if (this.target && this.cmd === 'getVar:') { this.target.watchers[this.param] = this; } if (!this.label) { this.label = this.getLabel(); if (this.target.isSprite) this.label = this.target.objName + ': ' + this.label; } }; var WATCHER_LABELS = { 'costumeIndex': 'costume #', 'xpos': 'x position', 'ypos': 'y position', 'heading': 'direction', 'scale': 'size', 'backgroundIndex': 'background #', 'sceneName': 'background name', 'tempo': 'tempo', 'volume': 'volume', 'answer': 'answer', 'timer': 'timer', 'soundLevel': 'loudness', 'isLoud': 'loud?', 'xScroll': 'x scroll', 'yScroll': 'y scroll' }; Watcher.prototype.getLabel = function() { switch (this.cmd) { case 'getVar:': return this.param; case 'sensor:': return this.param + ' sensor value'; case 'sensorPressed': return 'sensor ' + this.param + '?'; case 'timeAndDate': return this.param; case 'senseVideoMotion': return 'video ' + this.param; } return WATCHER_LABELS[this.cmd] || ''; }; Watcher.prototype.draw = function(context) { var value = 0; if (!this.target) return; switch (this.cmd) { case 'answer': value = this.stage.answer; break; case 'backgroundIndex': value = this.stage.currentCostumeIndex + 1; break; case 'costumeIndex': value = this.target.currentCostumeIndex + 1; break; case 'getVar:': value = this.target.vars[this.param]; if (this.mode === 3 && this.stage.mousePressed) { var x = this.stage.mouseX + 240 - this.x - 5; var y = 180 - this.stage.mouseY - this.y - 20; if (x >= 0 && y >= 0 && x <= this.width - 5 - 5 && y <= 9) { value = this.sliderMin + Math.max(0, Math.min(1, (x - 2.5) / (this.width - 5 - 5 - 5))) * (this.sliderMax - this.sliderMin); value = this.isDiscrete ? Math.round(value) : Math.round(value * 100) / 100; this.target.vars[this.param] = value; } } break; case 'heading': value = this.target.direction; break; case 'scale': value = this.target.scale * 100; break; case 'sceneName': value = this.stage.getCostumeName(); break; case 'senseVideoMotion': // TODO break; case 'soundLevel': // TODO break; case 'tempo': value = this.stage.tempoBPM; break; case 'timeAndDate': value = this.timeAndDate(this.param); break; case 'timer': value = Math.round((this.stage.now() - this.stage.timerStart) / 100) / 10; break; case 'volume': value = this.target.volume * 100; break; case 'xpos': value = this.target.scratchX; break; case 'ypos': value = this.target.scratchY; break; } if (typeof value === 'number' && (value < 0.001 || value > 0.001)) { value = Math.round(value * 1000) / 1000; } value = '' + value; if (this.labelWidth == null) { context.font = 'bold 11px sans-serif'; this.labelWidth = context.measureText(this.label).width; } context.save(); context.translate(this.x, this.y); if (this.mode === 1 || this.mode === 3) { context.font = 'bold 11px sans-serif'; var dw = Math.max(41, 5 + context.measureText(value).width + 5); var r = 5; var w = this.width = 5 + this.labelWidth + 5 + dw + 5; var h = this.mode === 1 ? 21 : 32; context.strokeStyle = 'rgb(148, 145, 145)'; context.fillStyle = 'rgb(193, 196, 199)'; context.lineWidth = 2; context.beginPath(); context.arc(r + 1, r + 1, r, Math.PI, Math.PI * 3/2, false); context.arc(w - r - 1, r + 1, r, Math.PI * 3/2, 0, false); context.arc(w - r - 1, h - r - 1, r, 0, Math.PI/2, false); context.arc(r + 1, h - r - 1, r, Math.PI/2, Math.PI, false); context.closePath(); context.stroke(); context.fill(); context.fillStyle = '#000'; context.fillText(this.label, 5, 14); var dh = 15; var dx = 5 + this.labelWidth + 5; var dy = 3; var dr = 4; context.save(); context.translate(dx, dy); context.strokeStyle = '#fff'; context.fillStyle = this.color; context.lineWidth = 2; context.beginPath(); context.arc(dr + 1, dr + 1, dr, Math.PI, Math.PI * 3/2, false); context.arc(dw - dr - 1, dr + 1, dr, Math.PI * 3/2, 0, false); context.arc(dw - dr - 1, dh - dr - 1, dr, 0, Math.PI/2, false); context.arc(dr + 1, dh - dr - 1, dr, Math.PI/2, Math.PI, false); context.closePath(); context.stroke(); context.fill(); context.fillStyle = '#fff'; context.textAlign = 'center'; context.fillText(value, dw / 2, dh - 4); context.restore(); if (this.mode === 3) { var sh = 5; var sw = w - 5 - 5; var sr = 1.5; var br = 4.5; context.save(); context.translate(5, 22); context.strokeStyle = 'rgb(148, 145, 145)'; context.fillStyle = 'rgb(213, 216, 219)'; context.lineWidth = 2; context.beginPath(); context.arc(sr + 1, sr + 1, sr, Math.PI, Math.PI * 3/2, false); context.arc(sw - sr - 1, sr + 1, sr, Math.PI * 3/2, 0, false); context.arc(sw - sr - 1, sh - sr - 1, sr, 0, Math.PI/2, false); context.arc(sr + 1, sh - sr - 1, sr, Math.PI/2, Math.PI, false); context.closePath(); context.stroke(); context.fill(); var x = (sw - sh) * Math.max(0, Math.min(1, ((+value || 0) - this.sliderMin) / (this.sliderMax - this.sliderMin))); context.strokeStyle = 'rgb(108, 105, 105)'; context.fillStyle = 'rgb(233, 236, 239)'; context.beginPath(); context.arc(x + sh / 2, sh / 2, br - 1, 0, Math.PI * 2, false); context.stroke(); context.fill(); context.restore(); } } else if (this.mode === 2) { context.font = 'bold 15px sans-serif'; dh = 21; dw = Math.max(41, 5 + context.measureText(value).width + 5); dr = 4; context.strokeStyle = '#fff'; context.fillStyle = this.color; context.lineWidth = 2; context.beginPath(); context.arc(dr + 1, dr + 1, dr, Math.PI, Math.PI * 3/2, false); context.arc(dw - dr - 1, dr + 1, dr, Math.PI * 3/2, 0, false); context.arc(dw - dr - 1, dh - dr - 1, dr, 0, Math.PI/2, false); context.arc(dr + 1, dh - dr - 1, dr, Math.PI/2, Math.PI, false); context.closePath(); context.stroke(); context.fill(); context.fillStyle = '#fff'; context.textAlign = 'center'; context.fillText(value, dw / 2, dh - 5); } context.restore(); }; var AudioContext = window.AudioContext || window.webkitAudioContext; var audioContext = AudioContext && new AudioContext; return { hasTouchEvents: hasTouchEvents, getKeyCode: getKeyCode, audioContext: audioContext, IO: IO, Base: Base, Stage: Stage, Sprite: Sprite, Watcher: Watcher }; }()); P.compile = (function() { 'use strict'; var LOG_PRIMITIVES; var DEBUG; // LOG_PRIMITIVES = true; // DEBUG = true; var EVENT_SELECTORS = [ 'procDef', 'whenClicked', 'whenCloned', 'whenGreenFlag', 'whenIReceive', 'whenKeyPressed', 'whenSceneStarts', 'whenSensorGreaterThan' // TODO ]; var compileScripts = function(object) { for (var i = 0; i < object.scripts.length; i++) { compileListener(object, object.scripts[i][2]); } }; var warnings; var warn = function(message) { warnings[message] = (warnings[message] || 0) + 1; }; var compileListener = function(object, script) { if (!script[0] || EVENT_SELECTORS.indexOf(script[0][0]) === -1) return; var nextLabel = function() { return object.fns.length + fns.length; }; var label = function() { var id = nextLabel(); fns.push(source.length); return id; }; var delay = function() { source += 'return;\n'; label(); }; var queue = function(id) { source += 'queue(' + id + ');\n'; source += 'return;\n'; }; var forceQueue = function(id) { source += 'forceQueue(' + id + ');\n'; source += 'return;\n'; }; var seq = function(script) { if (!script) return; for (var i = 0; i < script.length; i++) { compile(script[i]); } }; var varRef = function(name) { if (typeof name !== 'string') { return 'getVars(' + val(name) + ')[' + val(name) + ']'; } var o = object.stage.vars[name] !== undefined ? 'self' : 'S'; return o + '.vars[' + val(name) + ']'; }; var listRef = function(name) { if (typeof name !== 'string') { return 'getLists(' + val(name) + ')[' + val(name) + ']'; } var o = object.stage.lists[name] !== undefined ? 'self' : 'S'; if (o === 'S' && !object.lists[name]) { object.lists[name] = []; } return o + '.lists[' + val(name) + ']'; }; var param = function(name, usenum, usebool) { if (typeof name !== 'string') { throw new Error('Dynamic parameters are not supported'); } if (!inputs) return '0'; var i = inputs.indexOf(name); if (i === -1) { return '0'; } var t = types[i]; var kind = t === '%n' || t === '%d' || t === '%c' ? 'num' : t === '%b' ? 'bool' : ''; if (kind === 'num' && usenum) { return 'C.numargs[' + i + ']'; } if (kind === 'bool' && usebool) { return 'C.boolargs[' + i + ']'; } if (usenum) return '(+C.args[' + i + '] || 0)'; if (usebool) return 'bool(C.args[' + i + '])'; return 'C.args[' + i + ']'; }; var val = function(e, usenum, usebool) { var v; if (typeof e === 'number' || typeof e === 'boolean') { return '' + e; } else if (typeof e === 'string') { return '"' + e .replace(/\\/g, '\\\\') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/"/g, '\\"') .replace(/\{/g, '\\x7b') .replace(/\}/g, '\\x7d') + '"'; } else if (e[0] === 'getParam') { /* Data */ return param(e[1], usenum, usebool); } else if ((v = numval(e)) != null || (v = boolval(e)) != null) { return v; } else if (e[0] === 'costumeName') { return 'S.getCostumeName()'; } else if (e[0] === 'sceneName') { return 'self.getCostumeName()'; } else if (e[0] === 'readVariable') { return varRef(e[1]); } else if (e[0] === 'contentsOfList:') { return 'contentsOfList(' + listRef(e[1]) + ')'; } else if (e[0] === 'getLine:ofList:') { return 'getLineOfList(' + listRef(e[2]) + ', ' + val(e[1]) + ')'; } else if (e[0] === 'concatenate:with:') { return '("" + ' + val(e[1]) + ' + ' + val(e[2]) + ')'; } else if (e[0] === 'letter:of:') { return '(("" + ' + val(e[2]) + ')[(' + num(e[1]) + ' | 0) - 1] || "")'; } else if (e[0] === 'answer') { /* Sensing */ return 'self.answer'; } else if (e[0] === 'getAttribute:of:') { return 'attribute(' + val(e[1]) + ', ' + val(e[2]) + ')'; } else if (e[0] === 'getUserId') { return '0'; } else if (e[0] === 'getUserName') { return '""'; } else { warn('Undefined val: ' + e[0]); } }; var numval = function(e) { if (e[0] === 'xpos') { /* Motion */ return 'S.scratchX'; } else if (e[0] === 'ypos') { return 'S.scratchY'; } else if (e[0] === 'heading') { return 'S.direction'; } else if (e[0] === 'costumeIndex') { /* Looks */ return '(S.currentCostumeIndex + 1)'; } else if (e[0] === 'backgroundIndex') { return '(self.currentCostumeIndex + 1)'; } else if (e[0] === 'scale') { return '(S.scale * 100)'; } else if (e[0] === 'volume') { /* Sound */ return '(S.volume * 100)'; } else if (e[0] === 'tempo') { return 'self.tempoBPM'; } else if (e[0] === 'lineCountOfList:') { /* Data */ return listRef(e[1]) + '.length'; } else if (e[0] === '+') { /* Operators */ return '(' + num(e[1]) + ' + ' + num(e[2]) + ' || 0)'; } else if (e[0] === '-') { return '(' + num(e[1]) + ' - ' + num(e[2]) + ' || 0)'; } else if (e[0] === '*') { return '(' + num(e[1]) + ' * ' + num(e[2]) + ' || 0)'; } else if (e[0] === '/') { return '(' + num(e[1]) + ' / ' + num(e[2]) + ' || 0)'; } else if (e[0] === 'randomFrom:to:') { return 'random(' + num(e[1]) + ', ' + num(e[2]) + ')'; } else if (e[0] === 'abs') { return 'Math.abs(' + num(e[1]) + ')'; } else if (e[0] === 'sqrt') { return 'Math.sqrt(' + num(e[1]) + ')'; } else if (e[0] === 'stringLength:') { return '("" + ' + val(e[1]) + ').length'; } else if (e[0] === '%' || e[0] === '\\\\') { return 'mod(' + num(e[1]) + ', ' + num(e[2]) + ')'; } else if (e[0] === 'rounded') { return 'Math.round(' + num(e[1]) + ')'; } else if (e[0] === 'computeFunction:of:') { return 'mathFunc(' + val(e[1]) + ', ' + num(e[2]) + ')'; } else if (e[0] === 'mouseX') { /* Sensing */ return 'self.mouseX'; } else if (e[0] === 'mouseY') { return 'self.mouseY'; } else if (e[0] === 'timer') { return '((self.now() - self.timerStart) / 1000)'; } else if (e[0] === 'distanceTo:') { return 'S.distanceTo(' + val(e[1]) + ')'; // } else if (e[0] === 'soundLevel') { } else if (e[0] === 'timestamp') { return '((Date.now() - epoch) / 86400000)'; } else if (e[0] === 'timeAndDate') { return 'timeAndDate(' + val(e[1]) + ')'; // } else if (e[0] === 'sensor:') { } }; var DIGIT = /\d/; var boolval = function(e) { if (e[0] === 'list:contains:') { /* Data */ return 'listContains(' + listRef(e[1]) + ', ' + val(e[2]) + ')'; } else if (e[0] === '<' || e[0] === '>') { /* Operators */ if (typeof e[1] === 'string' && DIGIT.test(e[1]) || typeof e[1] === 'number') { var less = e[0] === '<'; var x = e[1]; var y = e[2]; } else if (typeof e[2] === 'string' && DIGIT.test(e[2]) || typeof e[2] === 'number') { var less = e[0] === '>'; var x = e[2]; var y = e[1]; } var nx = +x; if (x == null || nx !== nx) { return '(compare(' + val(e[1]) + ', ' + val(e[2]) + ') === ' + (e[0] === '<' ? -1 : 1) + ')'; } return (less ? 'numLess' : 'numGreater') + '(' + nx + ', ' + val(y) + ')'; } else if (e[0] === '=') { if (typeof e[1] === 'string' && DIGIT.test(e[1]) || typeof e[1] === 'number') { var x = e[1]; var y = e[2]; } else if (typeof e[2] === 'string' && DIGIT.test(e[2]) || typeof e[2] === 'number') { var x = e[2]; var y = e[1]; } var nx = +x; if (x == null || nx !== nx) { return '(equal(' + val(e[1]) + ', ' + val(e[2]) + '))'; } return '(numEqual(' + nx + ', ' + val(y) + '))'; } else if (e[0] === '&') { return '(' + bool(e[1]) + ' && ' + bool(e[2]) + ')'; } else if (e[0] === '|') { return '(' + bool(e[1]) + ' || ' + bool(e[2]) + ')'; } else if (e[0] === 'not') { return '!' + bool(e[1]) + ''; } else if (e[0] === 'mousePressed') { /* Sensing */ return 'self.mousePressed'; } else if (e[0] === 'touching:') { return 'S.touching(' + val(e[1]) + ')'; } else if (e[0] === 'touchingColor:') { return 'S.touchingColor(' + val(e[1]) + ')'; // } else if (e[0] === 'color:sees:') { } else if (e[0] === 'keyPressed:') { return '!!self.keys[P.getKeyCode(' + val(e[1]) + ')]'; // } else if (e[0] === 'isLoud') { // } else if (e[0] === 'sensorPressed:') { } }; var bool = function(e) { if (typeof e === 'boolean') { return e; } if (typeof e === 'number' || typeof e === 'string') { return +e !== 0 && e !== '' && e !== 'false' && e !== false; } var v = boolval(e); return v != null ? v : 'bool(' + val(e, false, true) + ')'; }; var num = function(e) { if (typeof e === 'number') { return e || 0; } if (typeof e === 'boolean' || typeof e === 'string') { return +e || 0; } var v = numval(e); return v != null ? v : '(+' + val(e, true) + ' || 0)'; }; var beatHead = function(dur) { source += 'save();\n'; source += 'R.start = self.now();\n'; source += 'R.duration = ' + num(dur) + ' * 60 / self.tempoBPM;\n'; source += 'R.first = true;\n'; }; var beatTail = function(dur) { var id = label(); source += 'if (self.now() - R.start < R.duration * 1000 || R.first) {\n'; source += ' R.first = false;\n'; forceQueue(id); source += '}\n'; source += 'restore();\n'; }; var wait = function(dur) { source += 'save();\n'; source += 'R.start = self.now();\n'; source += 'R.duration = ' + dur + ';\n'; source += 'R.first = true;\n'; var id = label(); source += 'if (self.now() - R.start < R.duration * 1000 || R.first) {\n'; source += ' R.first = false;\n'; forceQueue(id); source += '}\n'; source += 'restore();\n'; }; var noRGB = ''; noRGB += 'if (S.penCSS) {\n'; noRGB += ' var hsl = rgb2hsl(S.penColor & 0xffffff);\n'; noRGB += ' S.penHue = hsl[0];\n'; noRGB += ' S.penSaturation = hsl[1];\n'; noRGB += ' S.penLightness = hsl[2];\n'; noRGB += ' S.penCSS = null;'; noRGB += '}\n'; var compile = function(block) { if (LOG_PRIMITIVES) { source += 'console.log(' + val(block[0]) + ');\n'; } if (['turnRight:', 'turnLeft:', 'heading:', 'pointTowards:', 'setRotationStyle', 'lookLike:', 'nextCostume', 'say:duration:elapsed:from:', 'say:', 'think:duration:elapsed:from:', 'think:', 'changeGraphicEffect:by:', 'setGraphicEffect:to:', 'filterReset', 'changeSizeBy:', 'setSizeTo:', 'comeToFront', 'goBackByLayers:'].indexOf(block[0]) !== -1) { source += 'if (S.visible) VISUAL = true;\n'; } else if (['forward:', 'gotoX:y:', 'gotoSpriteOrMouse:', 'changeXposBy:', 'xpos:', 'changeYposBy:', 'ypos:', 'bounceOffEdge', 'glideSecs:toX:y:elapsed:from:'].indexOf(block[0]) !== -1) { source += 'if (S.visible || S.isPenDown) VISUAL = true;\n'; } else if (['showBackground:', 'startScene', 'nextBackground', 'nextScene', 'startSceneAndWait', 'show', 'hide', 'putPenDown', 'stampCostume', 'showVariable:', 'hideVariable:', 'doAsk', 'setVolumeTo:', 'changeVolumeBy:', 'setTempoTo:', 'changeTempoBy:'].indexOf(block[0]) !== -1) { source += 'VISUAL = true;\n'; } if (block[0] === 'forward:') { /* Motion */ source += 'S.forward(' + num(block[1]) + ');\n'; } else if (block[0] === 'turnRight:') { source += 'S.setDirection(S.direction + ' + num(block[1]) + ');\n'; } else if (block[0] === 'turnLeft:') { source += 'S.setDirection(S.direction - ' + num(block[1]) + ');\n'; } else if (block[0] === 'heading:') { source += 'S.setDirection(' + num(block[1]) + ');\n'; } else if (block[0] === 'pointTowards:') { source += 'S.pointTowards(' + val(block[1]) + ');\n'; } else if (block[0] === 'gotoX:y:') { source += 'S.moveTo(' + num(block[1]) + ', ' + num(block[2]) + ');\n'; } else if (block[0] === 'gotoSpriteOrMouse:') { source += 'S.gotoObject(' + val(block[1]) + ');\n'; } else if (block[0] === 'changeXposBy:') { source += 'S.moveTo(S.scratchX + ' + num(block[1]) + ', S.scratchY);\n'; } else if (block[0] === 'xpos:') { source += 'S.moveTo(' + num(block[1]) + ', S.scratchY);\n'; } else if (block[0] === 'changeYposBy:') { source += 'S.moveTo(S.scratchX, S.scratchY + ' + num(block[1]) + ');\n'; } else if (block[0] === 'ypos:') { source += 'S.moveTo(S.scratchX, ' + num(block[1]) + ');\n'; } else if (block[0] === 'bounceOffEdge') { source += 'S.bounceOffEdge();\n'; } else if (block[0] === 'setRotationStyle') { source += 'var style = ' + val(block[1]) + ';\n'; source += 'S.rotationStyle = style === "left-right" ? "leftRight" : style === "don\'t rotate" ? "none" : "normal";\n'; } else if (block[0] === 'lookLike:') { /* Looks */ source += 'S.setCostume(' + val(block[1]) + ');\n'; } else if (block[0] === 'nextCostume') { source += 'S.showNextCostume();\n'; } else if (block[0] === 'showBackground:' || block[0] === 'startScene') { source += 'self.setCostume(' + val(block[1]) + ');\n'; source += 'var threads = sceneChange();\n'; source += 'if (threads.indexOf(BASE) !== -1) return;\n'; } else if (block[0] === 'nextBackground' || block[0] === 'nextScene') { source += 'S.showNextCostume();\n'; source += 'var threads = sceneChange();\n'; source += 'if (threads.indexOf(BASE) !== -1) return;\n'; } else if (block[0] === 'startSceneAndWait') { source += 'save();\n'; source += 'self.setCostume(' + val(block[1]) + ');\n'; source += 'R.threads = sceneChange();\n'; source += 'if (R.threads.indexOf(BASE) !== -1) return;\n'; var id = label(); source += 'if (!running(R.threads)) {\n'; forceQueue(id); source += '}\n'; source += 'restore();\n'; } else if (block[0] === 'say:duration:elapsed:from:') { source += 'save();\n'; source += 'R.id = S.say(' + val(block[1]) + ', false);\n'; source += 'R.start = self.now();\n'; source += 'R.duration = ' + num(block[2]) + ';\n'; var id = label(); source += 'if (self.now() - R.start < R.duration * 1000) {\n'; forceQueue(id); source += '}\n'; source += 'if (S.sayId === R.id) {\n'; source += ' S.say("");\n'; source += '}\n'; source += 'restore();\n'; } else if (block[0] === 'say:') { source += 'S.say(' + val(block[1]) + ', false);\n'; } else if (block[0] === 'think:duration:elapsed:from:') { source += 'save();\n'; source += 'R.id = S.say(' + val(block[1]) + ', true);\n'; source += 'R.start = self.now();\n'; source += 'R.duration = ' + num(block[2]) + ';\n'; var id = label(); source += 'if (self.now() - R.start < R.duration * 1000) {\n'; forceQueue(id); source += '}\n'; source += 'if (S.sayId === R.id) {\n'; source += ' S.say("");\n'; source += '}\n'; source += 'restore();\n'; } else if (block[0] === 'think:') { source += 'S.say(' + val(block[1]) + ', true);\n'; } else if (block[0] === 'changeGraphicEffect:by:') { source += 'S.changeFilter(' + val(block[1]) + ', ' + num(block[2]) + ');\n'; } else if (block[0] === 'setGraphicEffect:to:') { source += 'S.setFilter(' + val(block[1]) + ', ' + num(block[2]) + ');\n'; } else if (block[0] === 'filterReset') { source += 'S.resetFilters();\n'; } else if (block[0] === 'changeSizeBy:') { source += 'S.scale += ' + num(block[1]) + ' / 100;\n'; } else if (block[0] === 'setSizeTo:') { source += 'S.scale = ' + num(block[1]) + ' / 100;\n'; } else if (block[0] === 'show') { source += 'S.visible = true;\n'; source += 'if (S.saying) S.updateBubble();\n'; } else if (block[0] === 'hide') { source += 'S.visible = false;\n'; source += 'if (S.saying) S.updateBubble();\n'; } else if (block[0] === 'comeToFront') { source += 'var i = self.children.indexOf(S);\n'; source += 'if (i !== -1) self.children.splice(i, 1);\n'; source += 'self.children.push(S);\n'; } else if (block[0] === 'goBackByLayers:') { source += 'var i = self.children.indexOf(S);\n'; source += 'if (i !== -1) {\n'; source += ' self.children.splice(i, 1);\n'; source += ' self.children.splice(Math.max(0, i - ' + num(block[1]) + '), 0, S);\n'; source += '}\n'; // } else if (block[0] === 'setVideoState') { // } else if (block[0] === 'setVideoTransparency') { } else if (block[0] === 'playSound:') { /* Sound */ if (P.audioContext) { source += 'var sound = S.getSound(' + val(block[1]) + ');\n'; source += 'if (sound) playSound(sound);\n'; } } else if (block[0] === 'doPlaySoundAndWait') { if (P.audioContext) { source += 'var sound = S.getSound(' + val(block[1]) + ');\n'; source += 'if (sound) {\n'; source += ' playSound(sound);\n'; wait('sound.duration'); source += '}\n'; } } else if (block[0] === 'stopAllSounds') { if (P.audioContext) { source += 'self.stopAllSounds();\n'; } // } else if (block[0] === 'drum:duration:elapsed:from:') { } else if (block[0] === 'playDrum') { beatHead(block[2]); if (P.audioContext) { source += 'playSpan(DRUMS[Math.round(' + num(block[1]) + ') - 1] || DRUMS[2], 60, 10);\n'; } beatTail(); } else if (block[0] === 'rest:elapsed:from:') { beatHead(block[1]); beatTail(); } else if (block[0] === 'noteOn:duration:elapsed:from:') { beatHead(block[2]); if (P.audioContext) { source += 'playNote(' + num(block[1]) + ', R.duration);\n'; } beatTail(); // } else if (block[0] === 'midiInstrument:') { } else if (block[0] === 'instrument:') { source += 'S.instrument = Math.max(0, Math.min(INSTRUMENTS.length - 1, ' + num(block[1]) + ' - 1)) | 0;'; } else if (block[0] === 'changeVolumeBy:' || block[0] === 'setVolumeTo:') { source += 'S.volume = Math.min(1, Math.max(0, ' + (block[0] === 'changeVolumeBy:' ? 'S.volume + ' : '') + num(block[1]) + ' / 100));\n'; source += 'if (S.node) S.node.gain.setValueAtTime(S.volume, audioContext.currentTime);\n'; source += 'for (var sounds = S.sounds, i = sounds.length; i--;) {\n'; source += ' var sound = sounds[i];\n'; source += ' if (sound.node && sound.target === S) {\n'; source += ' sound.node.gain.setValueAtTime(S.volume, audioContext.currentTime);\n'; source += ' }\n'; source += '}\n'; } else if (block[0] === 'changeTempoBy:') { source += 'self.tempoBPM += ' + num(block[1]) + ';\n'; } else if (block[0] === 'setTempoTo:') { source += 'self.tempoBPM = ' + num(block[1]) + ';\n'; } else if (block[0] === 'clearPenTrails') { /* Pen */ source += 'self.penCanvas.width = 480 * self.maxZoom;\n'; source += 'self.penContext.scale(self.maxZoom, self.maxZoom);\n'; source += 'self.penContext.lineCap = "round";\n' } else if (block[0] === 'putPenDown') { source += 'S.isPenDown = true;\n'; source += 'S.dotPen();\n'; } else if (block[0] === 'putPenUp') { source += 'S.isPenDown = false;\n'; source += 'S.penState = null;\n'; } else if (block[0] === 'penColor:') { source += 'var c = ' + num(block[1]) + ';\n'; source += 'S.penColor = c;\n'; source += 'var a = (c >> 24 & 0xff) / 0xff;\n'; source += 'S.penCSS = "rgba(" + (c >> 16 & 0xff) + "," + (c >> 8 & 0xff) + "," + (c & 0xff) + ", " + (a || 1) + ")";\n'; } else if (block[0] === 'setPenHueTo:') { source += noRGB; source += 'S.penHue = ' + num(block[1]) + ' * 360 / 200;\n'; source += 'S.penSaturation = 100;\n'; } else if (block[0] === 'changePenHueBy:') { source += noRGB; source += 'S.penHue += ' + num(block[1]) + ' * 360 / 200;\n'; source += 'S.penSaturation = 100;\n'; } else if (block[0] === 'setPenShadeTo:') { source += noRGB; source += 'S.penLightness = ' + num(block[1]) + ' % 200;\n'; source += 'if (S.penLightness < 0) S.penLightness += 200;\n'; source += 'S.penSaturation = 100;\n'; } else if (block[0] === 'changePenShadeBy:') { source += noRGB; source += 'S.penLightness = (S.penLightness + ' + num(block[1]) + ') % 200;\n'; source += 'if (S.penLightness < 0) S.penLightness += 200;\n'; source += 'S.penSaturation = 100;\n'; } else if (block[0] === 'penSize:') { source += 'var f = ' + num(block[1]) + ';\n'; source += 'S.penSize = f < 1 ? 1 : f;\n'; } else if (block[0] === 'changePenSizeBy:') { source += 'var f = S.penSize + ' + num(block[1]) + ';\n'; source += 'S.penSize = f < 1 ? 1 : f;\n'; } else if (block[0] === 'stampCostume') { source += 'S.draw(self.penContext);\n'; } else if (block[0] === 'setVar:to:') { /* Data */ source += varRef(block[1]) + ' = ' + val(block[2]) + ';\n'; } else if (block[0] === 'changeVar:by:') { var ref = varRef(block[1]); source += ref + ' = (+' + ref + ' || 0) + ' + num(block[2]) + ';\n'; } else if (block[0] === 'append:toList:') { source += 'appendToList(' + listRef(block[2]) + ', ' + val(block[1]) + ');\n'; } else if (block[0] === 'deleteLine:ofList:') { source += 'deleteLineOfList(' + listRef(block[2]) + ', ' + val(block[1]) + ');\n'; } else if (block[0] === 'insert:at:ofList:') { source += 'insertInList(' + listRef(block[3]) + ', ' + val(block[2]) + ', '+ val(block[1]) + ');\n'; } else if (block[0] === 'setLine:ofList:to:') { source += 'setLineOfList(' + listRef(block[2]) + ', ' + val(block[1]) + ', '+ val(block[3]) + ');\n'; } else if (block[0] === 'showVariable:' || block[0] === 'hideVariable:') { var isShow = block[0] === 'showVariable:'; if (typeof block[1] !== 'string') { throw new Error('Dynamic variables are not supported'); } var o = object.vars[block[1]] !== undefined ? 'S' : 'self'; source += o + '.showVariable(' + val(block[1]) + ', ' + isShow + ');\n'; // } else if (block[0] === 'showList:') { // } else if (block[0] === 'hideList:') { } else if (block[0] === 'broadcast:') { /* Control */ source += 'var threads = broadcast(' + val(block[1]) + ');\n'; source += 'if (threads.indexOf(BASE) !== -1) return;\n'; } else if (block[0] === 'call') { if (DEBUG && block[1] === 'phosphorus: debug') { source += 'debugger;\n'; } else { source += 'call(' + val(block[1]) + ', ' + nextLabel() + ', ['; for (var i = 2; i < block.length; i++) { if (i > 2) { source += ', '; } source += val(block[i]); } source += ']);\n'; delay(); } } else if (block[0] === 'doBroadcastAndWait') { source += 'save();\n'; source += 'R.threads = broadcast(' + val(block[1]) + ');\n'; source += 'if (R.threads.indexOf(BASE) !== -1) return;\n'; var id = label(); source += 'if (running(R.threads)) {\n'; forceQueue(id); source += '}\n'; source += 'restore();\n'; } else if (block[0] === 'doForever') { var id = label(); seq(block[1]); forceQueue(id); } else if (block[0] === 'doForeverIf') { var id = label(); source += 'if (' + bool(block[1]) + ') {\n'; seq(block[2]); source += '}\n'; forceQueue(id); // } else if (block[0] === 'doForLoop') { } else if (block[0] === 'doIf') { source += 'if (' + bool(block[1]) + ') {\n'; seq(block[2]); source += '}\n'; } else if (block[0] === 'doIfElse') { source += 'if (' + bool(block[1]) + ') {\n'; seq(block[2]); source += '} else {\n'; seq(block[3]); source += '}\n'; } else if (block[0] === 'doRepeat') { source += 'save();\n'; source += 'R.count = ' + num(block[1]) + ';\n'; var id = label(); source += 'if (R.count >= 0.5) {\n'; source += ' R.count -= 1;\n'; seq(block[2]); queue(id); source += '} else {\n'; source += ' restore();\n'; source += '}\n'; } else if (block[0] === 'doReturn') { source += 'endCall();\n'; source += 'return;\n'; } else if (block[0] === 'doUntil') { var id = label(); source += 'if (!' + bool(block[1]) + ') {\n'; seq(block[2]); queue(id); source += '}\n'; } else if (block[0] === 'doWhile') { var id = label(); source += 'if (' + bool(block[1]) + ') {\n'; seq(block[2]); queue(id); source += '}\n'; } else if (block[0] === 'doWaitUntil') { var id = label(); source += 'if (!' + bool(block[1]) + ') {\n'; queue(id); source += '}\n'; } else if (block[0] === 'glideSecs:toX:y:elapsed:from:') { source += 'save();\n'; source += 'R.start = self.now();\n'; source += 'R.duration = ' + num(block[1]) + ';\n'; source += 'R.baseX = S.scratchX;\n'; source += 'R.baseY = S.scratchY;\n'; source += 'R.deltaX = ' + num(block[2]) + ' - S.scratchX;\n'; source += 'R.deltaY = ' + num(block[3]) + ' - S.scratchY;\n'; var id = label(); source += 'var f = (self.now() - R.start) / (R.duration * 1000);\n'; source += 'if (f > 1) f = 1;\n'; source += 'S.moveTo(R.baseX + f * R.deltaX, R.baseY + f * R.deltaY);\n'; source += 'if (f < 1) {\n'; forceQueue(id); source += '}\n'; source += 'restore();\n'; } else if (block[0] === 'stopAll') { source += 'self.stopAll();\n'; source += 'return;\n'; } else if (block[0] === 'stopScripts') { source += 'switch (' + val(block[1]) + ') {\n'; source += ' case "all":\n'; source += ' self.stopAll();\n'; source += ' return;\n'; source += ' case "this script":\n'; source += ' endCall();\n'; source += ' return;\n'; source += ' case "other scripts in sprite":\n'; source += ' case "other scripts in stage":\n'; source += ' for (var i = 0; i < self.queue.length; i++) {\n'; source += ' if (i !== THREAD && self.queue[i] && self.queue[i].sprite === S) {\n'; source += ' self.queue[i] = undefined;\n'; source += ' }\n'; source += ' }\n'; source += ' break;\n'; source += '}\n'; } else if (block[0] === 'wait:elapsed:from:') { wait(num(block[1])); } else if (block[0] === 'warpSpeed') { source += 'WARP++;\n'; seq(block[1]); source += 'WARP--;\n'; } else if (block[0] === 'createCloneOf') { source += 'clone(' + val(block[1]) + ');\n'; } else if (block[0] === 'deleteClone') { source += 'if (S.isClone) {\n'; source += ' S.remove();\n'; source += ' var i = self.children.indexOf(S);\n'; source += ' if (i !== -1) self.children.splice(i, 1);\n'; source += ' for (var i = 0; i < self.queue.length; i++) {\n'; source += ' if (self.queue[i] && self.queue[i].sprite === S) {\n'; source += ' self.queue[i] = undefined;\n'; source += ' }\n'; source += ' }\n'; source += ' return;\n'; source += '}\n'; } else if (block[0] === 'doAsk') { /* Sensing */ source += 'R.id = self.nextPromptId++;\n'; var id = label(); source += 'if (self.promptId < R.id) {\n'; forceQueue(id); source += '}\n'; source += 'S.ask(' + val(block[1]) + ');\n'; var id = label(); source += 'if (self.promptId === R.id) {\n'; forceQueue(id); source += '}\n'; } else if (block[0] === 'timerReset') { source += 'self.timerStart = self.now();\n'; } else { warn('Undefined command: ' + block[0]); } }; var source = ''; var startfn = object.fns.length; var fns = [0]; if (script[0][0] === 'procDef') { var inputs = script[0][2]; var types = script[0][1].match(/%[snmdcb]/g) || []; for (var i = types.length; i--;) { var t = types[i]; if (t === '%d' || t === '%n' || t === '%c') { source += 'C.numargs[' + i + '] = +C.args[' + i + '] || 0;\n'; } else if (t === '%b') { source += 'C.boolargs[' + i + '] = bool(C.args[' + i + ']);\n'; } } } for (var i = 1; i < script.length; i++) { compile(script[i]); } if (script[0][0] === 'procDef') { source += 'endCall();\n'; source += 'return;\n'; } var createContinuation = function(source) { var result = '(function() {\n'; var brackets = 0; var delBrackets = 0; var shouldDelete = false; var here = 0; var length = source.length; while (here < length) { var i = source.indexOf('{', here); var j = source.indexOf('}', here); if (i === -1 && j === -1) { if (!shouldDelete) { result += source.slice(here); } break; } if (i === -1) i = length; if (j === -1) j = length; if (shouldDelete) { if (i < j) { delBrackets++; here = i + 1; } else { delBrackets--; if (!delBrackets) { shouldDelete = false; } here = j + 1; } } else { if (i < j) { result += source.slice(here, i + 1); brackets++; here = i + 1; } else { result += source.slice(here, j); here = j + 1; if (source.substr(j, 8) === '} else {') { if (brackets > 0) { result += '} else {'; here = j + 8; } else { shouldDelete = true; delBrackets = 0; } } else { if (brackets > 0) { result += '}'; brackets--; } } } } } result += '})'; return P.runtime.scopedEval(result); }; for (var i = 0; i < fns.length; i++) { object.fns.push(createContinuation(source.slice(fns[i]))); } var f = object.fns[startfn]; if (script[0][0] === 'whenClicked') { object.listeners.whenClicked.push(f); } else if (script[0][0] === 'whenGreenFlag') { object.listeners.whenGreenFlag.push(f); } else if (script[0][0] === 'whenCloned') { object.listeners.whenCloned.push(f); } else if (script[0][0] === 'whenIReceive') { var key = script[0][1].toLowerCase(); (object.listeners.whenIReceive[key] || (object.listeners.whenIReceive[key] = [])).push(f); } else if (script[0][0] === 'whenKeyPressed') { if (script[0][1] === 'any') { for (var i = 128; i--;) { object.listeners.whenKeyPressed[i].push(f); } } else { object.listeners.whenKeyPressed[P.getKeyCode(script[0][1])].push(f); } } else if (script[0][0] === 'whenSceneStarts') { var key = script[0][1].toLowerCase(); (object.listeners.whenSceneStarts[key] || (object.listeners.whenSceneStarts[key] = [])).push(f); } else if (script[0][0] === 'procDef') { object.procedures[script[0][1]] = { inputs: inputs, warp: script[0][4], fn: f }; } else { warn('Undefined event: ' + script[0][0]); } }; return function(stage) { warnings = Object.create(null); compileScripts(stage); for (var i = 0; i < stage.children.length; i++) { if (!stage.children[i].cmd) { compileScripts(stage.children[i]); } } for (var key in warnings) { console.warn(key + (warnings[key] > 1 ? ' (repeated ' + warnings[key] + ' times)' : '')); } }; }()); P.runtime = (function() { 'use strict'; var self, S, R, STACK, C, WARP, CALLS, BASE, THREAD, IMMEDIATE, VISUAL; var bool = function(v) { return +v !== 0 && v !== '' && v !== 'false' && v !== false; }; var DIGIT = /\d/; var compare = function(x, y) { if ((typeof x === 'number' || DIGIT.test(x)) && (typeof y === 'number' || DIGIT.test(y))) { var nx = +x; var ny = +y; if (nx === nx && ny === ny) { return nx < ny ? -1 : nx === ny ? 0 : 1; } } var xs = ('' + x).toLowerCase(); var ys = ('' + y).toLowerCase(); return xs < ys ? -1 : xs === ys ? 0 : 1; }; var numLess = function(nx, y) { if (typeof y === 'number' || DIGIT.test(y)) { var ny = +y; if (ny === ny) { return nx < ny; } } var ys = ('' + y).toLowerCase(); return '' + nx < ys; }; var numGreater = function(nx, y) { if (typeof y === 'number' || DIGIT.test(y)) { var ny = +y; if (ny === ny) { return nx > ny; } } var ys = ('' + y).toLowerCase(); return '' + nx > ys; }; var equal = function(x, y) { if ((typeof x === 'number' || DIGIT.test(x)) && (typeof y === 'number' || DIGIT.test(y))) { var nx = +x; var ny = +y; if (nx === nx && ny === ny) { return nx === ny; } } var xs = ('' + x).toLowerCase(); var ys = ('' + y).toLowerCase(); return xs === ys; }; var numEqual = function(nx, y) { if (typeof y === 'number' || DIGIT.test(y)) { var ny = +y; return ny === ny && nx === ny; } return false; }; var mod = function(x, y) { var r = x % y; if (r / y < 0) { r += y; } return r; }; var random = function(x, y) { x = +x || 0; y = +y || 0; if (x > y) { var tmp = y; y = x; x = tmp; } if (x % 1 === 0 && y % 1 === 0) { return Math.floor(Math.random() * (y - x + 1)) + x; } return Math.random() * (y - x) + x; }; var rgb2hsl = function(rgb) { var r = (rgb >> 16 & 0xff) / 0xff; var g = (rgb >> 8 & 0xff) / 0xff; var b = (rgb & 0xff) / 0xff; var min = Math.min(r, g, b); var max = Math.max(r, g, b); if (min === max) { return [0, 0, r * 100]; } var c = max - min; var l = (min + max) / 2; var s = c / (1 - Math.abs(2 * l - 1)); var h; switch (max) { case r: h = ((g - b) / c + 6) % 6; break; case g: h = (b - r) / c + 2; break; case b: h = (r - g) / c + 4; break; } h *= 60; return [h, s * 100, l * 100]; }; var clone = function(name) { var parent = name === '_myself_' ? S : self.getObject(name); var c = parent.clone(); self.children.splice(self.children.indexOf(parent), 0, c); self.triggerFor(c, 'whenCloned'); }; var epoch = Date.UTC(2000, 0, 1); var timeAndDate = P.Watcher.prototype.timeAndDate = function(format) { switch (format) { case 'year': return new Date().getFullYear(); case 'month': return new Date().getMonth() + 1; case 'date': return new Date().getDate(); case 'day of week': return new Date().getDay() + 1; case 'hour': return new Date().getHours(); case 'minute': return new Date().getMinutes(); case 'second': return new Date().getSeconds(); } return 0; }; var getVars = function(name) { return self.vars[name] !== undefined ? self.vars : S.vars; }; var getLists = function(name) { if (self.lists[name] !== undefined) return self.lists; if (S.lists[name] === undefined) { S.lists[name] = []; } return S.lists; }; var listIndex = function(list, index, length) { var i = index | 0; if (i === index) return i > 0 && i <= length ? i - 1 : -1; if (index === 'random' || index === 'any') { return Math.random() * length | 0; } if (index === 'last') { return length - 1; } return i > 0 && i <= length ? i - 1 : -1; }; var contentsOfList = function(list) { var isSingle = true; for (var i = list.length; i--;) { if (list[i].length !== 1) { isSingle = false; break; } } return list.join(isSingle ? '' : ' '); }; var getLineOfList = function(list, index) { var i = listIndex(list, index, list.length); return i !== -1 ? list[i] : ''; }; var listContains = function(list, value) { for (var i = list.length; i--;) { if (equal(list[i], value)) return true; } return false; }; var appendToList = function(list, value) { list.push(value); }; var deleteLineOfList = function(list, index) { if (index === 'all') { list.length = 0; } else { var i = listIndex(list, index, list.length); if (i === list.length - 1) { list.pop(); } else if (i !== -1) { list.splice(i, 1); } } }; var insertInList = function(list, index, value) { var i = listIndex(list, index, list.length + 1); if (i === list.length) { list.push(value); } else if (i !== -1) { list.splice(i, 0, value); } }; var setLineOfList = function(list, index, value) { var i = listIndex(list, index, list.length); if (i !== -1) { list[i] = value; } }; var mathFunc = function(f, x) { switch (f) { case 'abs': return Math.abs(x); case 'floor': return Math.floor(x); case 'sqrt': return Math.sqrt(x); case 'ceiling': return Math.ceil(x); case 'cos': return Math.cos(x * Math.PI / 180); case 'sin': return Math.sin(x * Math.PI / 180); case 'tan': return Math.tan(x * Math.PI / 180); case 'asin': return Math.asin(x) * 180 / Math.PI; case 'acos': return Math.acos(x) * 180 / Math.PI; case 'atan': return Math.atan(x) * 180 / Math.PI; case 'ln': return Math.log(x); case 'log': return Math.log(x) / Math.LN10; case 'e ^': return Math.exp(x); case '10 ^': return Math.exp(x * Math.LN10); } return 0; }; var attribute = function(attr, objName) { var o = self.getObject(objName); if (!o) return 0; if (o.isSprite) { switch (attr) { case 'x position': return o.scratchX; case 'y position': return o.scratchY; case 'direction': return o.direction; case 'costume #': return o.currentCostumeIndex + 1; case 'costume name': return o.costumes[o.currentCostumeIndex].costumeName; case 'size': return o.scale * 100; case 'volume': return 0; // TODO } } else { switch (attr) { case 'background #': case 'backdrop #': return o.currentCostumeIndex + 1; case 'backdrop name': return o.costumes[o.currentCostumeIndex].costumeName; case 'volume': return 0; // TODO } } var value = o.vars[attr]; if (value !== undefined) { return value; } return 0; }; var VOLUME = 0.3; var audioContext = P.audioContext; if (audioContext) { var wavBuffers = P.IO.wavBuffers; var volumeNode = audioContext.createGain(); volumeNode.gain.value = VOLUME; volumeNode.connect(audioContext.destination); var playNote = function(id, duration) { var spans = INSTRUMENTS[S.instrument]; for (var i = 0, l = spans.length; i < l; i++) { var span = spans[i]; if (span.top >= id || span.top === 128) break; } playSpan(span, Math.max(0, Math.min(127, id)), duration); }; var playSpan = function(span, id, duration) { if (!S.node) { S.node = audioContext.createGain(); S.node.gain.value = S.volume; S.node.connect(volumeNode); } var source = audioContext.createBufferSource(); var note = audioContext.createGain(); var buffer = wavBuffers[span.name]; if (!buffer) return; source.buffer = buffer; if (source.loop = span.loop) { source.loopStart = span.loopStart; source.loopEnd = span.loopEnd; } source.connect(note); note.connect(S.node); var time = audioContext.currentTime; source.playbackRate.value = Math.pow(2, (id - 69) / 12) / span.baseRatio; var gain = note.gain; gain.value = 0; gain.setValueAtTime(0, time); if (span.attackEnd < duration) { gain.linearRampToValueAtTime(1, time + span.attackEnd); if (span.decayTime > 0 && span.holdEnd < duration) { gain.linearRampToValueAtTime(1, time + span.holdEnd); if (span.decayEnd < duration) { gain.linearRampToValueAtTime(0, time + span.decayEnd); } else { gain.linearRampToValueAtTime(1 - (duration - holdEnd) / span.decayTime, time + duration); } } else { gain.linearRampToValueAtTime(1, time + duration); } } else { gain.linearRampToValueAtTime(1, time + duration); } gain.linearRampToValueAtTime(0, time + duration + 0.02267573696); source.start(time); source.stop(time + duration + 0.02267573696); }; var playSound = function(sound) { if (!sound.buffer) return; if (!sound.node) { sound.node = audioContext.createGain(); sound.node.gain.value = S.volume; sound.node.connect(volumeNode); } sound.target = S; sound.node.gain.setValueAtTime(S.volume, audioContext.currentTime); if (sound.source) { sound.source.disconnect(); } sound.source = audioContext.createBufferSource(); sound.source.buffer = sound.buffer; sound.source.connect(sound.node); sound.source.start(audioContext.currentTime); }; } var save = function() { STACK.push(R); R = {}; }; var restore = function() { R = STACK.pop(); }; // var lastCalls = []; var call = function(spec, id, values) { // lastCalls.push(spec); // if (lastCalls.length > 10000) lastCalls.shift(); var procedure = S.procedures[spec]; if (procedure) { STACK.push(R); CALLS.push(C); C = { base: procedure.fn, fn: S.fns[id], args: values, numargs: [], boolargs: [], stack: STACK = [], warp: procedure.warp }; R = {}; if (C.warp || WARP) { WARP++; IMMEDIATE = procedure.fn; } else { for (var i = CALLS.length, j = 5; i-- && j--;) { if (CALLS[i].base === procedure.fn) { var recursive = true; break; } } if (recursive) { self.queue[THREAD] = { sprite: S, base: BASE, fn: procedure.fn, calls: CALLS }; } else { IMMEDIATE = procedure.fn; } } } else { IMMEDIATE = S.fns[id]; } }; var endCall = function() { if (CALLS.length) { if (WARP) WARP--; IMMEDIATE = C.fn; C = CALLS.pop(); STACK = C.stack; R = STACK.pop(); } }; var sceneChange = function() { return self.trigger('whenSceneStarts', self.costumes[self.currentCostumeIndex].costumeName); }; var broadcast = function(name) { return self.trigger('whenIReceive', name); }; var running = function(bases) { for (var j = 0; j < self.queue.length; j++) { if (self.queue[j] && bases.indexOf(self.queue[j].base) !== -1) return true; } return false; }; var queue = function(id) { if (WARP) { IMMEDIATE = S.fns[id]; } else { forceQueue(id); } }; var forceQueue = function(id) { self.queue[THREAD] = { sprite: S, base: BASE, fn: S.fns[id], calls: CALLS }; }; // Internal definition (function() { 'use strict'; P.Stage.prototype.framerate = 30; P.Stage.prototype.initRuntime = function() { this.queue = []; this.onError = this.onError.bind(this); }; P.Stage.prototype.startThread = function(sprite, base) { var thread = { sprite: sprite, base: base, fn: base, calls: [{args: [], stack: [{}]}] }; for (var i = 0; i < this.queue.length; i++) { var q = this.queue[i]; if (q && q.sprite === sprite && q.base === base) { this.queue[i] = thread; return; } } this.queue.push(thread); }; P.Stage.prototype.triggerFor = function(sprite, event, arg) { var threads; if (event === 'whenClicked') { threads = sprite.listeners.whenClicked; } else if (event === 'whenCloned') { threads = sprite.listeners.whenCloned; } else if (event === 'whenGreenFlag') { threads = sprite.listeners.whenGreenFlag; } else if (event === 'whenIReceive') { threads = sprite.listeners.whenIReceive[('' + arg).toLowerCase()]; } else if (event === 'whenKeyPressed') { threads = sprite.listeners.whenKeyPressed[arg]; } else if (event === 'whenSceneStarts') { threads = sprite.listeners.whenSceneStarts[('' + arg).toLowerCase()]; } if (threads) { for (var i = 0; i < threads.length; i++) { this.startThread(sprite, threads[i]); } } return threads || []; }; P.Stage.prototype.trigger = function(event, arg) { var threads = []; for (var i = this.children.length; i--;) { if (this.children[i].isSprite) { threads = threads.concat(this.triggerFor(this.children[i], event, arg)); } } return threads.concat(this.triggerFor(this, event, arg)); }; P.Stage.prototype.triggerGreenFlag = function() { this.timerStart = this.now(); this.trigger('whenGreenFlag'); }; P.Stage.prototype.start = function() { this.isRunning = true; if (this.interval) return; addEventListener('error', this.onError); this.baseTime = Date.now(); this.interval = setInterval(this.step.bind(this), 1000 / this.framerate); }; P.Stage.prototype.pause = function() { if (this.interval) { this.baseNow = this.now(); clearInterval(this.interval); delete this.interval; removeEventListener('error', this.onError); } this.isRunning = false; }; P.Stage.prototype.stopAll = function() { this.hidePrompt = false; this.prompter.style.display = 'none'; this.promptId = this.nextPromptId = 0; this.queue.length = 0; this.resetFilters(); this.stopSounds(); for (var i = 0; i < this.children.length; i++) { var c = this.children[i]; if (c.isClone) { c.remove(); this.children.splice(i, 1); i -= 1; } else if (c.isSprite) { c.resetFilters(); if (c.saying) c.say(''); c.stopSounds(); } } }; P.Stage.prototype.now = function() { return this.baseNow + Date.now() - this.baseTime; }; P.Stage.prototype.step = function() { self = this; VISUAL = false; var start = Date.now(); do { var queue = this.queue; for (THREAD = 0; THREAD < queue.length; THREAD++) { if (queue[THREAD]) { S = queue[THREAD].sprite; IMMEDIATE = queue[THREAD].fn; BASE = queue[THREAD].base; CALLS = queue[THREAD].calls; C = CALLS.pop(); STACK = C.stack; R = STACK.pop(); queue[THREAD] = undefined; WARP = 0; while (IMMEDIATE) { var fn = IMMEDIATE; IMMEDIATE = null; fn(); } STACK.push(R); CALLS.push(C); } } for (var i = queue.length; i--;) { if (!queue[i]) queue.splice(i, 1); } } while ((self.isTurbo || !VISUAL) && Date.now() - start < 1000 / this.framerate && queue.length); this.draw(); S = null; }; P.Stage.prototype.onError = function(e) { this.handleError(e.error); clearInterval(this.interval); }; P.Stage.prototype.handleError = function(e) { console.error(e.stack); }; }()); /* copy(JSON.stringify(instruments.map(function(g) { return g.map(function(r) { var attackTime = r[5] ? r[5][0] * 0.001 : 0; var holdTime = r[5] ? r[5][1] * 0.001 : 0; var decayTime = r[5] ? r[5][2] : 0; var baseRatio = Math.pow(2, (r[2] - 69) / 12); if (r[3] !== -1) { var length = r[4] - r[3]; baseRatio = 22050 * Math.round(length * 440 * baseRatio / 22050) / length / 440; } return { top: r[0], name: r[1], baseRatio: baseRatio, loop: r[3] !== -1, loopStart: r[3] / 22050, loopEnd: r[4] / 22050, attackEnd: attackTime, holdEnd: attackTime + holdTime, decayEnd: attackTime + holdTime + decayTime } }) })).replace(/"(\w+)":/g,'$1:').replace(/"/g, '\'')); */ var INSTRUMENTS = [[{top:38,name:'AcousticPiano_As3',baseRatio:0.5316313272700484,loop:true,loopStart:0.465578231292517,loopEnd:0.7733786848072562,attackEnd:0,holdEnd:0.1,decayEnd:22.1},{top:44,name:'AcousticPiano_C4',baseRatio:0.5905141892259927,loop:true,loopStart:0.6334693877551021,loopEnd:0.8605442176870748,attackEnd:0,holdEnd:0.1,decayEnd:20.1},{top:51,name:'AcousticPiano_G4',baseRatio:0.8843582887700535,loop:true,loopStart:0.5532879818594104,loopEnd:0.5609977324263039,attackEnd:0,holdEnd:0.08,decayEnd:18.08},{top:62,name:'AcousticPiano_C6',baseRatio:2.3557692307692304,loop:true,loopStart:0.5914739229024943,loopEnd:0.6020861678004535,attackEnd:0,holdEnd:0.08,decayEnd:16.08},{top:70,name:'AcousticPiano_F5',baseRatio:1.5776515151515151,loop:true,loopStart:0.5634920634920635,loopEnd:0.5879818594104308,attackEnd:0,holdEnd:0.04,decayEnd:14.04},{top:77,name:'AcousticPiano_Ds6',baseRatio:2.800762112139358,loop:true,loopStart:0.560907029478458,loopEnd:0.5836281179138322,attackEnd:0,holdEnd:0.02,decayEnd:10.02},{top:85,name:'AcousticPiano_Ds6',baseRatio:2.800762112139358,loop:true,loopStart:0.560907029478458,loopEnd:0.5836281179138322,attackEnd:0,holdEnd:0,decayEnd:8},{top:90,name:'AcousticPiano_Ds6',baseRatio:2.800762112139358,loop:true,loopStart:0.560907029478458,loopEnd:0.5836281179138322,attackEnd:0,holdEnd:0,decayEnd:6},{top:96,name:'AcousticPiano_D7',baseRatio:5.275119617224881,loop:true,loopStart:0.3380498866213152,loopEnd:0.34494331065759637,attackEnd:0,holdEnd:0,decayEnd:3},{top:128,name:'AcousticPiano_D7',baseRatio:5.275119617224881,loop:true,loopStart:0.3380498866213152,loopEnd:0.34494331065759637,attackEnd:0,holdEnd:0,decayEnd:2}],[{top:48,name:'ElectricPiano_C2',baseRatio:0.14870515241435123,loop:true,loopStart:0.6956009070294784,loopEnd:0.7873015873015873,attackEnd:0,holdEnd:0.08,decayEnd:10.08},{top:74,name:'ElectricPiano_C4',baseRatio:0.5945685670261941,loop:true,loopStart:0.5181859410430839,loopEnd:0.5449433106575964,attackEnd:0,holdEnd:0.04,decayEnd:8.04},{top:128,name:'ElectricPiano_C4',baseRatio:0.5945685670261941,loop:true,loopStart:0.5181859410430839,loopEnd:0.5449433106575964,attackEnd:0,holdEnd:0,decayEnd:6}],[{top:128,name:'Organ_G2',baseRatio:0.22283731584620914,loop:true,loopStart:0.05922902494331066,loopEnd:0.1510204081632653,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:40,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:15},{top:56,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:13.5},{top:60,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:12},{top:67,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:8.5},{top:72,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:7},{top:83,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:5.5},{top:128,name:'AcousticGuitar_F3',baseRatio:0.3977272727272727,loop:true,loopStart:1.6628117913832199,loopEnd:1.6685260770975057,attackEnd:0,holdEnd:0,decayEnd:4.5}],[{top:40,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:15},{top:56,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:13.5},{top:60,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:12},{top:67,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:8.5},{top:72,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:7},{top:83,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:5.5},{top:128,name:'ElectricGuitar_F3',baseRatio:0.39615522817103843,loop:true,loopStart:1.5733333333333333,loopEnd:1.5848072562358277,attackEnd:0,holdEnd:0,decayEnd:4.5}],[{top:34,name:'ElectricBass_G1',baseRatio:0.11111671034065712,loop:true,loopStart:1.9007709750566892,loopEnd:1.9212244897959183,attackEnd:0,holdEnd:0,decayEnd:17},{top:48,name:'ElectricBass_G1',baseRatio:0.11111671034065712,loop:true,loopStart:1.9007709750566892,loopEnd:1.9212244897959183,attackEnd:0,holdEnd:0,decayEnd:14},{top:64,name:'ElectricBass_G1',baseRatio:0.11111671034065712,loop:true,loopStart:1.9007709750566892,loopEnd:1.9212244897959183,attackEnd:0,holdEnd:0,decayEnd:12},{top:128,name:'ElectricBass_G1',baseRatio:0.11111671034065712,loop:true,loopStart:1.9007709750566892,loopEnd:1.9212244897959183,attackEnd:0,holdEnd:0,decayEnd:10}],[{top:38,name:'Pizz_G2',baseRatio:0.21979665071770335,loop:true,loopStart:0.3879365079365079,loopEnd:0.3982766439909297,attackEnd:0,holdEnd:0,decayEnd:5},{top:45,name:'Pizz_G2',baseRatio:0.21979665071770335,loop:true,loopStart:0.3879365079365079,loopEnd:0.3982766439909297,attackEnd:0,holdEnd:0.012,decayEnd:4.012},{top:56,name:'Pizz_A3',baseRatio:0.503654636820466,loop:true,loopStart:0.5197278911564626,loopEnd:0.5287528344671202,attackEnd:0,holdEnd:0,decayEnd:4},{top:64,name:'Pizz_A3',baseRatio:0.503654636820466,loop:true,loopStart:0.5197278911564626,loopEnd:0.5287528344671202,attackEnd:0,holdEnd:0,decayEnd:3.2},{top:72,name:'Pizz_E4',baseRatio:0.7479647218453188,loop:true,loopStart:0.7947845804988662,loopEnd:0.7978231292517007,attackEnd:0,holdEnd:0,decayEnd:2.8},{top:80,name:'Pizz_E4',baseRatio:0.7479647218453188,loop:true,loopStart:0.7947845804988662,loopEnd:0.7978231292517007,attackEnd:0,holdEnd:0,decayEnd:2.2},{top:128,name:'Pizz_E4',baseRatio:0.7479647218453188,loop:true,loopStart:0.7947845804988662,loopEnd:0.7978231292517007,attackEnd:0,holdEnd:0,decayEnd:1.5}],[{top:41,name:'Cello_C2',baseRatio:0.14870515241435123,loop:true,loopStart:0.3876643990929705,loopEnd:0.40294784580498866,attackEnd:0,holdEnd:0,decayEnd:0},{top:52,name:'Cello_As2',baseRatio:0.263755980861244,loop:true,loopStart:0.3385487528344671,loopEnd:0.35578231292517004,attackEnd:0,holdEnd:0,decayEnd:0},{top:62,name:'Violin_D4',baseRatio:0.6664047388781432,loop:true,loopStart:0.48108843537414964,loopEnd:0.5151927437641723,attackEnd:0,holdEnd:0,decayEnd:0},{top:75,name:'Violin_A4',baseRatio:0.987460815047022,loop:true,loopStart:0.14108843537414967,loopEnd:0.15029478458049886,attackEnd:0.07,holdEnd:0.07,decayEnd:0.07},{top:128,name:'Violin_E5',baseRatio:1.4885238523852387,loop:true,loopStart:0.10807256235827664,loopEnd:0.1126530612244898,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:30,name:'BassTrombone_A2_3',baseRatio:0.24981872564125807,loop:true,loopStart:0.061541950113378686,loopEnd:0.10702947845804989,attackEnd:0,holdEnd:0,decayEnd:0},{top:40,name:'BassTrombone_A2_2',baseRatio:0.24981872564125807,loop:true,loopStart:0.08585034013605441,loopEnd:0.13133786848072562,attackEnd:0,holdEnd:0,decayEnd:0},{top:55,name:'Trombone_B3',baseRatio:0.5608240680183126,loop:true,loopStart:0.12,loopEnd:0.17673469387755103,attackEnd:0,holdEnd:0,decayEnd:0},{top:88,name:'Trombone_B3',baseRatio:0.5608240680183126,loop:true,loopStart:0.12,loopEnd:0.17673469387755103,attackEnd:0.05,holdEnd:0.05,decayEnd:0.05},{top:128,name:'Trumpet_E5',baseRatio:1.4959294436906376,loop:true,loopStart:0.1307936507936508,loopEnd:0.14294784580498865,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:128,name:'Clarinet_C4',baseRatio:0.5940193965517241,loop:true,loopStart:0.6594104308390023,loopEnd:0.7014965986394558,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:40,name:'TenorSax_C3',baseRatio:0.2971698113207547,loop:true,loopStart:0.4053968253968254,loopEnd:0.4895238095238095,attackEnd:0,holdEnd:0,decayEnd:0},{top:50,name:'TenorSax_C3',baseRatio:0.2971698113207547,loop:true,loopStart:0.4053968253968254,loopEnd:0.4895238095238095,attackEnd:0.02,holdEnd:0.02,decayEnd:0.02},{top:59,name:'TenorSax_C3',baseRatio:0.2971698113207547,loop:true,loopStart:0.4053968253968254,loopEnd:0.4895238095238095,attackEnd:0.04,holdEnd:0.04,decayEnd:0.04},{top:67,name:'AltoSax_A3',baseRatio:0.49814747876378096,loop:true,loopStart:0.3875736961451247,loopEnd:0.4103854875283447,attackEnd:0,holdEnd:0,decayEnd:0},{top:75,name:'AltoSax_A3',baseRatio:0.49814747876378096,loop:true,loopStart:0.3875736961451247,loopEnd:0.4103854875283447,attackEnd:0.02,holdEnd:0.02,decayEnd:0.02},{top:80,name:'AltoSax_A3',baseRatio:0.49814747876378096,loop:true,loopStart:0.3875736961451247,loopEnd:0.4103854875283447,attackEnd:0.02,holdEnd:0.02,decayEnd:0.02},{top:128,name:'AltoSax_C6',baseRatio:2.3782742681047764,loop:true,loopStart:0.05705215419501134,loopEnd:0.0838095238095238,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:61,name:'Flute_B5_2',baseRatio:2.255113636363636,loop:true,loopStart:0.08430839002267573,loopEnd:0.10244897959183673,attackEnd:0,holdEnd:0,decayEnd:0},{top:128,name:'Flute_B5_1',baseRatio:2.255113636363636,loop:true,loopStart:0.10965986394557824,loopEnd:0.12780045351473923,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:128,name:'WoodenFlute_C5',baseRatio:1.1892952324548416,loop:true,loopStart:0.5181859410430839,loopEnd:0.7131065759637188,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:57,name:'Bassoon_C3',baseRatio:0.29700969827586204,loop:true,loopStart:0.11011337868480725,loopEnd:0.19428571428571428,attackEnd:0,holdEnd:0,decayEnd:0},{top:67,name:'Bassoon_C3',baseRatio:0.29700969827586204,loop:true,loopStart:0.11011337868480725,loopEnd:0.19428571428571428,attackEnd:0.04,holdEnd:0.04,decayEnd:0.04},{top:76,name:'Bassoon_C3',baseRatio:0.29700969827586204,loop:true,loopStart:0.11011337868480725,loopEnd:0.19428571428571428,attackEnd:0.08,holdEnd:0.08,decayEnd:0.08},{top:84,name:'EnglishHorn_F3',baseRatio:0.39601293103448276,loop:true,loopStart:0.341859410430839,loopEnd:0.4049886621315193,attackEnd:0.04,holdEnd:0.04,decayEnd:0.04},{top:128,name:'EnglishHorn_D4',baseRatio:0.6699684005833739,loop:true,loopStart:0.22027210884353743,loopEnd:0.23723356009070296,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:39,name:'Choir_F3',baseRatio:0.3968814788643197,loop:true,loopStart:0.6352380952380953,loopEnd:1.8721541950113378,attackEnd:0,holdEnd:0,decayEnd:0},{top:50,name:'Choir_F3',baseRatio:0.3968814788643197,loop:true,loopStart:0.6352380952380953,loopEnd:1.8721541950113378,attackEnd:0.04,holdEnd:0.04,decayEnd:0.04},{top:61,name:'Choir_F3',baseRatio:0.3968814788643197,loop:true,loopStart:0.6352380952380953,loopEnd:1.8721541950113378,attackEnd:0.06,holdEnd:0.06,decayEnd:0.06},{top:72,name:'Choir_F4',baseRatio:0.7928898424161845,loop:true,loopStart:0.7415419501133786,loopEnd:2.1059410430839,attackEnd:0,holdEnd:0,decayEnd:0},{top:128,name:'Choir_F5',baseRatio:1.5879576065654504,loop:true,loopStart:0.836281179138322,loopEnd:2.0585487528344673,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:38,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0.1,decayEnd:8.1},{top:48,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0.1,decayEnd:7.6},{top:59,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0.06,decayEnd:7.06},{top:70,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0.04,decayEnd:6.04},{top:78,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0.02,decayEnd:5.02},{top:86,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0,decayEnd:4},{top:128,name:'Vibraphone_C3',baseRatio:0.29829545454545453,loop:true,loopStart:0.2812698412698413,loopEnd:0.28888888888888886,attackEnd:0,holdEnd:0,decayEnd:3}],[{top:128,name:'MusicBox_C4',baseRatio:0.5937634640241276,loop:true,loopStart:0.6475283446712018,loopEnd:0.6666666666666666,attackEnd:0,holdEnd:0,decayEnd:2}],[{top:128,name:'SteelDrum_D5',baseRatio:1.3660402567543959,loop:false,loopStart:-0.000045351473922902495,loopEnd:-0.000045351473922902495,attackEnd:0,holdEnd:0,decayEnd:2}],[{top:128,name:'Marimba_C4',baseRatio:0.5946035575013605,loop:false,loopStart:-0.000045351473922902495,loopEnd:-0.000045351473922902495,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:80,name:'SynthLead_C4',baseRatio:0.5942328422565577,loop:true,loopStart:0.006122448979591836,loopEnd:0.06349206349206349,attackEnd:0,holdEnd:0,decayEnd:0},{top:128,name:'SynthLead_C6',baseRatio:2.3760775862068964,loop:true,loopStart:0.005623582766439909,loopEnd:0.01614512471655329,attackEnd:0,holdEnd:0,decayEnd:0}],[{top:38,name:'SynthPad_A3',baseRatio:0.4999105065330231,loop:true,loopStart:0.1910204081632653,loopEnd:3.9917006802721087,attackEnd:0.05,holdEnd:0.05,decayEnd:0.05},{top:50,name:'SynthPad_A3',baseRatio:0.4999105065330231,loop:true,loopStart:0.1910204081632653,loopEnd:3.9917006802721087,attackEnd:0.08,holdEnd:0.08,decayEnd:0.08},{top:62,name:'SynthPad_A3',baseRatio:0.4999105065330231,loop:true,loopStart:0.1910204081632653,loopEnd:3.9917006802721087,attackEnd:0.11,holdEnd:0.11,decayEnd:0.11},{top:74,name:'SynthPad_A3',baseRatio:0.4999105065330231,loop:true,loopStart:0.1910204081632653,loopEnd:3.9917006802721087,attackEnd:0.15,holdEnd:0.15,decayEnd:0.15},{top:86,name:'SynthPad_A3',baseRatio:0.4999105065330231,loop:true,loopStart:0.1910204081632653,loopEnd:3.9917006802721087,attackEnd:0.2,holdEnd:0.2,decayEnd:0.2},{top:128,name:'SynthPad_C6',baseRatio:2.3820424708835755,loop:true,loopStart:0.11678004535147392,loopEnd:0.41732426303854875,attackEnd:0,holdEnd:0,decayEnd:0}]]; /* copy(JSON.stringify(drums.map(function(d) { var decayTime = d[4] || 0; var baseRatio = Math.pow(2, (60 - d[1] - 69) / 12); if (d[2]) { var length = d[3] - d[2]; baseRatio = 22050 * Math.round(length * 440 * baseRatio / 22050) / length / 440; } return { name: d[0], baseRatio: baseRatio, loop: !!d[2], loopStart: d[2] / 22050, loopEnd: d[3] / 22050, attackEnd: 0, holdEnd: 0, decayEnd: decayTime } })).replace(/"(\w+)":/g,'$1:').replace(/"/g, '\'')); */ var DRUMS = [{name:'SnareDrum',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Tom',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'SideStick',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Crash',baseRatio:0.8908987181403393,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'HiHatOpen',baseRatio:0.9438743126816935,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'HiHatClosed',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Tambourine',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Clap',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Claves',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'WoodBlock',baseRatio:0.7491535384383408,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Cowbell',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Triangle',baseRatio:0.8514452780229479,loop:true,loopStart:0.7638548752834468,loopEnd:0.7825396825396825,attackEnd:0,holdEnd:0,decayEnd:2},{name:'Bongo',baseRatio:0.5297315471796477,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Conga',baseRatio:0.7954545454545454,loop:true,loopStart:0.1926077097505669,loopEnd:0.20403628117913833,attackEnd:0,holdEnd:0,decayEnd:2},{name:'Cabasa',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'GuiroLong',baseRatio:0.5946035575013605,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Vibraslap',baseRatio:0.8408964152537145,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0},{name:'Cuica',baseRatio:0.7937005259840998,loop:false,loopStart:null,loopEnd:null,attackEnd:0,holdEnd:0,decayEnd:0}]; return { scopedEval: function(source) { return eval(source); } }; }());
var fs = require('fs'), path = require('path'); exports.homepage = function(req, res, next) { try { res.render("index"); } catch(err) { var html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><div style="text-align: center;font-size: 30px;">Welcome to use aptl-route!</div></body></html>'; res.writeHead(200, {'Content-type' : 'text/html'}); res.write(html); res.end(); } }; exports.sendJson = function(req, res, next) { 'use strict'; var jsonDir = req.params[0], jsonName = req.params[1]; res.set('Content-type', 'application/json'); res.sendfile(path.join(__dirname, req.path)); }; exports.getHtml = function (req, res, next) { 'use strict'; var recursive = function (typeIdx) { var shownTypes = ['html', 'shtml', 'php', 'ejs', 'jade', 'htm']; var filename = req.params[1] ? req.params[0] + req.params[1] : req.params[0] + '.' + shownTypes[typeIdx], filepath = path.join('.', 'views', filename); if (typeIdx < shownTypes.length) { fs.exists(filepath, function (exists) { if (exists) { res.render(filename, { title: req.params[0] }); } else { recursive(typeIdx + 1); } }); } else { next(); } }; recursive(0); };
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_PLATFORM_STR_UTIL_H_ #define TENSORFLOW_CORE_PLATFORM_STR_UTIL_H_ #include <string> #include <vector> #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "tensorflow/core/platform/stringpiece.h" #include "tensorflow/core/platform/types.h" // Basic string utility routines namespace tensorflow { namespace str_util { // Returns a version of 'src' where unprintable characters have been // escaped using C-style escape sequences. string CEscape(StringPiece src); // Copies "source" to "dest", rewriting C-style escape sequences -- // '\n', '\r', '\\', '\ooo', etc -- to their ASCII equivalents. // // Errors: Sets the description of the first encountered error in // 'error'. To disable error reporting, set 'error' to NULL. // // NOTE: Does not support \u or \U! bool CUnescape(StringPiece source, string* dest, string* error); // Removes any trailing whitespace from "*s". void StripTrailingWhitespace(string* s); // Removes leading ascii_isspace() characters. // Returns number of characters removed. size_t RemoveLeadingWhitespace(StringPiece* text); // Removes trailing ascii_isspace() characters. // Returns number of characters removed. size_t RemoveTrailingWhitespace(StringPiece* text); // Removes leading and trailing ascii_isspace() chars. // Returns number of chars removed. size_t RemoveWhitespaceContext(StringPiece* text); // Consume a leading positive integer value. If any digits were // found, store the value of the leading unsigned number in "*val", // advance "*s" past the consumed number, and return true. If // overflow occurred, returns false. Otherwise, returns false. bool ConsumeLeadingDigits(StringPiece* s, uint64* val); // Consume a leading token composed of non-whitespace characters only. // If *s starts with a non-zero number of non-whitespace characters, store // them in *val, advance *s past them, and return true. Else return false. bool ConsumeNonWhitespace(StringPiece* s, StringPiece* val); // If "*s" starts with "expected", consume it and return true. // Otherwise, return false. bool ConsumePrefix(StringPiece* s, StringPiece expected); // If "*s" ends with "expected", remove it and return true. // Otherwise, return false. bool ConsumeSuffix(StringPiece* s, StringPiece expected); // Return lower-cased version of s. string Lowercase(StringPiece s); // Return upper-cased version of s. string Uppercase(StringPiece s); // Capitalize first character of each word in "*s". "delimiters" is a // set of characters that can be used as word boundaries. void TitlecaseString(string* s, StringPiece delimiters); // Replaces the first occurrence (if replace_all is false) or all occurrences // (if replace_all is true) of oldsub in s with newsub. string StringReplace(StringPiece s, StringPiece oldsub, StringPiece newsub, bool replace_all); // Join functionality template <typename T> string Join(const T& s, const char* sep) { return absl::StrJoin(s, sep); } // A variant of Join where for each element of "s", f(&dest_string, elem) // is invoked (f is often constructed with a lambda of the form: // [](string* result, ElemType elem) template <typename T, typename Formatter> string Join(const T& s, const char* sep, Formatter f) { return absl::StrJoin(s, sep, f); } struct AllowEmpty { bool operator()(StringPiece sp) const { return true; } }; struct SkipEmpty { bool operator()(StringPiece sp) const { return !sp.empty(); } }; struct SkipWhitespace { bool operator()(StringPiece sp) const { return !absl::StripTrailingAsciiWhitespace(sp).empty(); } }; // Split strings using any of the supplied delimiters. For example: // Split("a,b.c,d", ".,") would return {"a", "b", "c", "d"}. inline std::vector<string> Split(StringPiece text, StringPiece delims) { return text.empty() ? std::vector<string>() : absl::StrSplit(text, absl::ByAnyChar(delims)); } template <typename Predicate> std::vector<string> Split(StringPiece text, StringPiece delims, Predicate p) { return text.empty() ? std::vector<string>() : absl::StrSplit(text, absl::ByAnyChar(delims), p); } inline std::vector<string> Split(StringPiece text, char delim) { return text.empty() ? std::vector<string>() : absl::StrSplit(text, delim); } template <typename Predicate> std::vector<string> Split(StringPiece text, char delim, Predicate p) { return text.empty() ? std::vector<string>() : absl::StrSplit(text, delim, p); } // StartsWith() // // Returns whether a given string `text` begins with `prefix`. bool StartsWith(StringPiece text, StringPiece prefix); // EndsWith() // // Returns whether a given string `text` ends with `suffix`. bool EndsWith(StringPiece text, StringPiece suffix); // StrContains() // // Returns whether a given string `haystack` contains the substring `needle`. bool StrContains(StringPiece haystack, StringPiece needle); // Returns the length of the given null-terminated byte string 'str'. // Returns 'string_max_len' if the null character was not found in the first // 'string_max_len' bytes of 'str'. size_t Strnlen(const char* str, const size_t string_max_len); // ----- NON STANDARD, TF SPECIFIC METHOD ----- // Converts "^2ILoveYou!" to "i_love_you_". More specifically: // - converts all non-alphanumeric characters to underscores // - replaces each occurrence of a capital letter (except the very // first character and if there is already an '_' before it) with '_' // followed by this letter in lower case // - Skips leading non-alpha characters // This method is useful for producing strings matching "[a-z][a-z0-9_]*" // as required by OpDef.ArgDef.name. The resulting string is either empty or // matches this regex. string ArgDefCase(StringPiece s); } // namespace str_util } // namespace tensorflow #endif // TENSORFLOW_CORE_PLATFORM_STR_UTIL_H_
(window.webpackJsonp=window.webpackJsonp||[]).push([[1],[function(e,t,n){"use strict";e.exports=n(116)},function(e,t,n){n(43),n(62),n(97),n(63);var r=n(101),o=n(2).publicLoader,i=o.getResourcesForPathname,a=o.getResourcesForPathnameSync,l=o.getResourceURLsForPathname;t.apiRunner=function(e,t,n,o){void 0===t&&(t={}),window.Cypress&&(window.___apiHandler?window.___apiHandler(e):window.___resolvedAPIs?window.___resolvedAPIs.push(e):window.___resolvedAPIs=[e]);var u=r.map(function(n){if(n.plugin[e]){t.getResourcesForPathnameSync=a,t.getResourcesForPathname=i,t.getResourceURLsForPathname=l;var r=n.plugin[e](t,n.options);return r&&o&&(t=o({args:t,result:r,plugin:n})),r}});return(u=u.filter(function(e){return void 0!==e})).length>0?u:n?[n]:[]},t.apiRunnerAsync=function(e,t,n){return r.reduce(function(n,r){return r.plugin[e]?n.then(function(){return r.plugin[e](t,r.options)}):n},Promise.resolve())}},function(e,t,n){"use strict";n.r(t);n(64),n(108),n(68),n(32),n(110),n(111),n(112),n(63),n(43),n(113),n(114);var r=n(24),o=function(e,t){return void 0===t&&(t=""),e.substr(0,t.length)===t?e.slice(t.length):e},i={},a=n(8),l=function(e){if("undefined"==typeof document)return!1;var t=document.createElement("link");try{if(t.relList&&"function"==typeof t.relList.supports)return t.relList.supports(e)}catch(e){return!1}}("prefetch")?function(e){if("undefined"!=typeof document){var t=document.createElement("link");t.setAttribute("rel","prefetch"),t.setAttribute("href",e),(document.getElementsByTagName("head")[0]||document.getElementsByName("script")[0].parentNode).appendChild(t)}}:function(e){var t=new XMLHttpRequest;t.open("GET",e,!0),t.withCredentials=!0,t.send(null)},u={},c=function(e){u[e]||(u[e]=!0,l(e))};n.d(t,"setApiRunnerForLoader",function(){return L}),n.d(t,"publicLoader",function(){return M});var s,f=function(e){return e&&e.default||e},d=!0,p=Object.create(null),h={},m={},v=[],g=null,y=!1,b={},w={},_={};var x,k=function(){return g||(g=new Promise(function(e){h.data().then(function(t){var n=t.pages,r=t.dataPaths;window.___dataPaths=r,N.addPagesArray(n),N.addDataPaths(r),e(y=!0)})})),g},S=function(e){return"/static/d/"+e+".json"},T=function(e){return window.___chunkMapping[e].map(function(e){return""+e})},E=function(e){if("component---"===e.slice(0,12))T(e).forEach(function(e){return c(e)});else{var t=S(m[e]);c(t)}},P=function(e){return function(e){var t;return t="component---"===e.slice(0,12)?h.components[e]:e in _?function(){return _[e]}:function(){var t=new Promise(function(t,n){var r=S(m[e]),o=new XMLHttpRequest;o.open("GET",r,!0),o.withCredentials=!0,o.onreadystatechange=function(){4==o.readyState&&(200===o.status?t(JSON.parse(o.responseText)):n())},o.send(null)});return _[e]=t,t},p[e]=!0,new Promise(function(n){var r=t(),o=!1;return r.catch(function(){o=!0}).then(function(t){v.push({resource:e,succeeded:!o}),w[e]||(w[e]=o),v=v.slice(-5),n(t)})})}(e).then(f)},C=function(e,t){var n;b[e]||(b[e]=t),("boolean"==typeof(n=navigator.onLine)?n:v.find(function(e){return e.succeeded}))&&window.location.pathname.replace(/\/$/g,"")!==e.replace(/\/$/g,"")&&(window.location.pathname=e)},O=(Object.create(null),{}),R={},j=!1,N={addPagesArray:function(e){var t,n;t=e,void 0===(n="")&&(n=""),x=function(e){var a,l=decodeURIComponent(e),u=o(l,n);return u.split("#").length>1&&(u=u.split("#").slice(0,-1).join("")),u.split("?").length>1&&(u=u.split("?").slice(0,-1).join("")),i[u]?i[u]:(t.some(function(e){var t=e.matchPath?e.matchPath:e.path;return Object(r.match)(t,u)?(a=e,i[u]=e,!0):!!Object(r.match)(e.path+"index.html",u)&&(a=e,i[u]=e,!0)}),a)}},addDevRequires:function(e){e},addProdRequires:function(e){h=e},addDataPaths:function(e){m=e},hovering:function(e){var t=o(e,"");N.getResourcesForPathname(t)},enqueue:function(e){var t=o(e,"");if(s||console.error("Run setApiRunnerForLoader() before enqueing paths"),R[t]||(s("onPrefetchPathname",{pathname:t}),R[t]=!0),j.some(function(e){return e}))return!1;var n=x(t);return n||y?!!n&&(E(n.jsonName),E(n.componentChunkName),!0):k().then(function(){return N.enqueue(e)})},getPage:function(e){return x(e)},getResourceURLsForPathname:function(e){var t=x(e);return t?T(t.componentChunkName).concat([S(m[t.jsonName])]):null},getResourcesForPathnameSync:function(e){var t=x(e);return t?O[t.path]:"/404.html"!==e?N.getResourcesForPathnameSync("/404.html"):null},getResourcesForPathname:function(e){return new Promise(function(t,n){var r=d;if(d=!1,b[e])return C(e,'Previously detected load failure for "'+e+'"'),n();var o=x(e);return o||y?o?(e=o.path,O[e]?(a.a.emit("onPostLoadPageResources",{page:o,pageResources:O[e]}),t(O[e])):(a.a.emit("onPreLoadPageResources",{path:e}),void Promise.all([P(o.componentChunkName),P(o.jsonName)]).then(function(n){var i=n[0],l=n[1];if(i&&l){var u={component:i,json:l,page:o};u.page.jsonURL=S(m[o.jsonName]),O[e]=u,t(u),a.a.emit("onPostLoadPageResources",{page:o,pageResources:u}),r&&k()}else t(null)}))):(console.log("A page wasn't found for \""+e+'"'),"/404.html"!==e?t(N.getResourcesForPathname("/404.html")):t()):k().then(function(){return t(N.getResourcesForPathname(e))})})}},L=function(e){j=(s=e)("disableCorePrefetching")},M={getResourcesForPathname:N.getResourcesForPathname,getResourceURLsForPathname:N.getResourceURLsForPathname,getResourcesForPathnameSync:N.getResourcesForPathnameSync};t.default=N},function(e,t,n){var r=n(54)("wks"),o=n(37),i=n(5).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t,n){e.exports=n(120)()},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(5),o=n(19),i=n(10),a=n(18),l=n(20),u=function(e,t,n){var c,s,f,d,p=e&u.F,h=e&u.G,m=e&u.S,v=e&u.P,g=e&u.B,y=h?r:m?r[t]||(r[t]={}):(r[t]||{}).prototype,b=h?o:o[t]||(o[t]={}),w=b.prototype||(b.prototype={});for(c in h&&(n=t),n)f=((s=!p&&y&&void 0!==y[c])?y:n)[c],d=g&&s?l(f,r):v&&"function"==typeof f?l(Function.call,f):f,y&&a(y,c,f,e&u.U),b[c]!=f&&i(b,c,d),v&&w[c]!=f&&(w[c]=f)};r.core=o,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},function(e,t){e.exports=function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}},function(e,t,n){"use strict";var r=function(e){return e=e||Object.create(null),{on:function(t,n){(e[t]||(e[t]=[])).push(n)},off:function(t,n){e[t]&&e[t].splice(e[t].indexOf(n)>>>0,1)},emit:function(t,n){(e[t]||[]).slice().map(function(e){e(n)}),(e["*"]||[]).slice().map(function(e){e(t,n)})}}}();t.a=r},function(e,t,n){"use strict";e.exports=function(e,t,n,r,o,i,a,l){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,l],s=0;(u=new Error(t.replace(/%s/g,function(){return c[s++]}))).name="Invariant Violation"}throw u.framesToPop=1,u}}},function(e,t,n){var r=n(26),o=n(53);e.exports=n(16)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(12);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){"use strict";var r=n(17);e.exports=function(e,t){return!!e&&r(function(){t?e.call(null,function(){},1):e.call(null)})}},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n.n(r),i=(n(69),n(4),n(9)),a=n.n(i),l=o.a.createContext,u=n(71),c=function(e,t){return e.substr(0,t.length)===t},s=function(e,t){for(var n=void 0,r=void 0,o=t.split("?")[0],i=g(o),l=""===i[0],u=v(e),c=0,s=u.length;c<s;c++){var f=!1,d=u[c].route;if(d.default)r={route:d,params:{},uri:t};else{for(var h=g(d.path),m={},y=Math.max(i.length,h.length),w=0;w<y;w++){var _=h[w],x=i[w];if("*"===_){m["*"]=i.slice(w).map(decodeURIComponent).join("/");break}if(void 0===x){f=!0;break}var k=p.exec(_);if(k&&!l){-1===b.indexOf(k[1])||a()(!1);var S=decodeURIComponent(x);m[k[1]]=S}else if(_!==x){f=!0;break}}if(!f){n={route:d,params:m,uri:"/"+i.slice(0,w).join("/")};break}}}return n||r||null},f=function(e,t){if(c(e,"/"))return e;var n=e.split("?"),r=n[0],o=n[1],i=t.split("?")[0],a=g(r),l=g(i);if(""===a[0])return y(i,o);if(!c(a[0],".")){var u=l.concat(a).join("/");return y(("/"===i?"":"/")+u,o)}for(var s=l.concat(a),f=[],d=0,p=s.length;d<p;d++){var h=s[d];".."===h?f.pop():"."!==h&&f.push(h)}return y("/"+f.join("/"),o)},d=function(e,t){return"/"+g(e).map(function(e){var n=p.exec(e);return n?t[n[1]]:e}).join("/")},p=/^:(.+)/,h=function(e){return p.test(e)},m=function(e,t){return{route:e,score:e.default?0:g(e.path).reduce(function(e,t){return e+=4,!function(e){return""===e}(t)?h(t)?e+=2:!function(e){return"*"===e}(t)?e+=3:e-=5:e+=1,e},0),index:t}},v=function(e){return e.map(m).sort(function(e,t){return e.score<t.score?1:e.score>t.score?-1:e.index-t.index})},g=function(e){return e.replace(/(^\/+|\/+$)/g,"").split("/")},y=function(e,t){return e+(t?"?"+t:"")},b=["uri","path"],w=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},_=function(e){return w({},e.location,{state:e.history.state,key:e.history.state&&e.history.state.key||"initial"})},x=function(e,t){var n=[],r=_(e),o=!1,i=function(){};return{get location(){return r},get transitioning(){return o},_onTransitionComplete:function(){o=!1,i()},listen:function(t){n.push(t);var o=function(){r=_(e),t({location:r,action:"POP"})};return e.addEventListener("popstate",o),function(){e.removeEventListener("popstate",o),n=n.filter(function(e){return e!==t})}},navigate:function(t){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},l=a.state,u=a.replace,c=void 0!==u&&u;l=w({},l,{key:Date.now()+""});try{o||c?e.history.replaceState(l,null,t):e.history.pushState(l,null,t)}catch(n){e.location[c?"replace":"assign"](t)}r=_(e),o=!0;var s=new Promise(function(e){return i=e});return n.forEach(function(e){return e({location:r,action:"PUSH"})}),s}}},k=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",t=0,n=[{pathname:e,search:""}],r=[];return{get location(){return n[t]},addEventListener:function(e,t){},removeEventListener:function(e,t){},history:{get entries(){return n},get index(){return t},get state(){return r[t]},pushState:function(e,o,i){var a=i.split("?"),l=a[0],u=a[1],c=void 0===u?"":u;t++,n.push({pathname:l,search:c}),r.push(e)},replaceState:function(e,o,i){var a=i.split("?"),l=a[0],u=a[1],c=void 0===u?"":u;n[t]={pathname:l,search:c},r[t]=e}}}},S=!("undefined"==typeof window||!window.document||!window.document.createElement),T=x(S?window:k()),E=T.navigate;n.d(t,"Link",function(){return K}),n.d(t,"Location",function(){return M}),n.d(t,"LocationProvider",function(){return F}),n.d(t,"Match",function(){return Z}),n.d(t,"Redirect",function(){return J}),n.d(t,"Router",function(){return D}),n.d(t,"ServerLocation",function(){return U}),n.d(t,"isRedirect",function(){return G}),n.d(t,"redirectTo",function(){return Q}),n.d(t,"createHistory",function(){return x}),n.d(t,"createMemorySource",function(){return k}),n.d(t,"navigate",function(){return E}),n.d(t,"globalHistory",function(){return T});var P=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};function C(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function O(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function R(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function j(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var N=function(e,t){var n=l(t);return n.Consumer.displayName=e+".Consumer",n.Provider.displayName=e+".Provider",n},L=N("Location"),M=function(e){var t=e.children;return o.a.createElement(L.Consumer,null,function(e){return e?t(e):o.a.createElement(F,null,t)})},F=function(e){function t(){var n,r;O(this,t);for(var o=arguments.length,i=Array(o),a=0;a<o;a++)i[a]=arguments[a];return n=r=R(this,e.call.apply(e,[this].concat(i))),r.state={context:r.getContext(),refs:{unlisten:null}},R(r,n)}return j(t,e),t.prototype.getContext=function(){var e=this.props.history;return{navigate:e.navigate,location:e.location}},t.prototype.componentDidCatch=function(e,t){if(!G(e))throw e;(0,this.props.history.navigate)(e.uri,{replace:!0})},t.prototype.componentDidUpdate=function(e,t){t.context.location!==this.state.context.location&&this.props.history._onTransitionComplete()},t.prototype.componentDidMount=function(){var e=this,t=this.state.refs,n=this.props.history;t.unlisten=n.listen(function(){Promise.resolve().then(function(){requestAnimationFrame(function(){e.unmounted||e.setState(function(){return{context:e.getContext()}})})})})},t.prototype.componentWillUnmount=function(){var e=this.state.refs;this.unmounted=!0,e.unlisten()},t.prototype.render=function(){var e=this.state.context,t=this.props.children;return o.a.createElement(L.Provider,{value:e},"function"==typeof t?t(e):t||null)},t}(o.a.Component);F.defaultProps={history:T};var U=function(e){var t=e.url,n=e.children;return o.a.createElement(L.Provider,{value:{location:{pathname:t,search:"",hash:""},navigate:function(){throw new Error("You can't call navigate on the server.")}}},n)},A=N("Base",{baseuri:"/",basepath:"/"}),D=function(e){return o.a.createElement(A.Consumer,null,function(t){return o.a.createElement(M,null,function(n){return o.a.createElement(I,P({},t,n,e))})})},I=function(e){function t(){return O(this,t),R(this,e.apply(this,arguments))}return j(t,e),t.prototype.render=function(){var e=this.props,t=e.location,n=e.navigate,r=e.basepath,i=e.primary,a=e.children,l=(e.baseuri,e.component),u=void 0===l?"div":l,c=C(e,["location","navigate","basepath","primary","children","baseuri","component"]),d=o.a.Children.map(a,te(r)),p=t.pathname,h=s(d,p);if(h){var m=h.params,v=h.uri,g=h.route,y=h.route.value;r=g.default?r:g.path.replace(/\*$/,"");var b=P({},m,{uri:v,location:t,navigate:function(e,t){return n(f(e,v),t)}}),w=o.a.cloneElement(y,b,y.props.children?o.a.createElement(D,{primary:i},y.props.children):void 0),_=i?z:u,x=i?P({uri:v,location:t,component:u},c):c;return o.a.createElement(A.Provider,{value:{baseuri:v,basepath:r}},o.a.createElement(_,x,w))}return null},t}(o.a.PureComponent);I.defaultProps={primary:!0};var W=N("Focus"),z=function(e){var t=e.uri,n=e.location,r=e.component,i=C(e,["uri","location","component"]);return o.a.createElement(W.Consumer,null,function(e){return o.a.createElement(V,P({},i,{component:r,requestFocus:e,uri:t,location:n}))})},B=!0,H=0,V=function(e){function t(){var n,r;O(this,t);for(var o=arguments.length,i=Array(o),a=0;a<o;a++)i[a]=arguments[a];return n=r=R(this,e.call.apply(e,[this].concat(i))),r.state={},r.requestFocus=function(e){r.state.shouldFocus||e.focus()},R(r,n)}return j(t,e),t.getDerivedStateFromProps=function(e,t){if(null==t.uri)return P({shouldFocus:!0},e);var n=e.uri!==t.uri,r=t.location.pathname!==e.location.pathname&&e.location.pathname===e.uri;return P({shouldFocus:n||r},e)},t.prototype.componentDidMount=function(){H++,this.focus()},t.prototype.componentWillUnmount=function(){0===--H&&(B=!0)},t.prototype.componentDidUpdate=function(e,t){e.location!==this.props.location&&this.state.shouldFocus&&this.focus()},t.prototype.focus=function(){var e=this.props.requestFocus;e?e(this.node):B?B=!1:this.node.contains(document.activeElement)||this.node.focus()},t.prototype.render=function(){var e=this,t=this.props,n=(t.children,t.style),r=(t.requestFocus,t.role),i=void 0===r?"group":r,a=t.component,l=void 0===a?"div":a,u=(t.uri,t.location,C(t,["children","style","requestFocus","role","component","uri","location"]));return o.a.createElement(l,P({style:P({outline:"none"},n),tabIndex:"-1",role:i,ref:function(t){return e.node=t}},u),o.a.createElement(W.Provider,{value:this.requestFocus},this.props.children))},t}(o.a.Component);Object(u.polyfill)(V);var $=function(){},q=o.a.forwardRef;void 0===q&&(q=function(e){return e});var K=q(function(e,t){var n=e.innerRef,r=C(e,["innerRef"]);return o.a.createElement(A.Consumer,null,function(e){e.basepath;var i=e.baseuri;return o.a.createElement(M,null,function(e){var a=e.location,l=e.navigate,u=r.to,s=r.state,d=r.replace,p=r.getProps,h=void 0===p?$:p,m=C(r,["to","state","replace","getProps"]),v=f(u,i),g=a.pathname===v,y=c(a.pathname,v);return o.a.createElement("a",P({ref:t||n,"aria-current":g?"page":void 0},m,h({isCurrent:g,isPartiallyCurrent:y,href:v,location:a}),{href:v,onClick:function(e){m.onClick&&m.onClick(e),ne(e)&&(e.preventDefault(),l(v,{state:s,replace:d}))}}))})})});function Y(e){this.uri=e}var G=function(e){return e instanceof Y},Q=function(e){throw new Y(e)},X=function(e){function t(){return O(this,t),R(this,e.apply(this,arguments))}return j(t,e),t.prototype.componentDidMount=function(){var e=this.props,t=e.navigate,n=e.to,r=(e.from,e.replace),o=void 0===r||r,i=e.state,a=(e.noThrow,C(e,["navigate","to","from","replace","state","noThrow"]));Promise.resolve().then(function(){t(d(n,a),{replace:o,state:i})})},t.prototype.render=function(){var e=this.props,t=(e.navigate,e.to),n=(e.from,e.replace,e.state,e.noThrow),r=C(e,["navigate","to","from","replace","state","noThrow"]);return n||Q(d(t,r)),null},t}(o.a.Component),J=function(e){return o.a.createElement(M,null,function(t){return o.a.createElement(X,P({},t,e))})},Z=function(e){var t=e.path,n=e.children;return o.a.createElement(A.Consumer,null,function(e){var r=e.baseuri;return o.a.createElement(M,null,function(e){var o=e.navigate,i=e.location,a=function(e,t){return s([{path:e}],t)}(f(t,r),i.pathname);return n({navigate:o,location:i,match:a?P({},a.params,{uri:a.uri,path:t}):null})})})},ee=function(e){return e.replace(/(^\/+|\/+$)/g,"")},te=function(e){return function(t){if(!t)return null;var n,r,o;if(t.props.path||t.props.default||t.type===J||a()(!1),t.type!==J||t.props.from&&t.props.to||a()(!1),t.type===J&&(n=t.props.from,r=t.props.to,o=function(e){return h(e)},g(n).filter(o).sort().join("/")!==g(r).filter(o).sort().join("/"))&&a()(!1),t.props.default)return{value:t,default:!0};var i=t.type===J?t.props.from:t.props.path,l="/"===i?e:ee(e)+"/"+ee(i);return{value:t,default:t.props.default,path:t.props.children?ee(l)+"/*":l}}},ne=function(e){return!e.defaultPrevented&&0===e.button&&!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}},function(e,t,n){e.exports=!n(17)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){var r=n(5),o=n(10),i=n(27),a=n(37)("src"),l=Function.toString,u=(""+l).split("toString");n(19).inspectSource=function(e){return l.call(e)},(e.exports=function(e,t,n,l){var c="function"==typeof n;c&&(i(n,"name")||o(n,"name",t)),e[t]!==n&&(c&&(i(n,a)||o(n,a,e[t]?""+e[t]:u.join(String(t)))),e===r?e[t]=n:l?e[t]?e[t]=n:o(e,t,n):(delete e[t],o(e,t,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[a]||l.call(this)})},function(e,t){var n=e.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(21);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){e.exports={}},function(e,t,n){var r=n(20),o=n(29),i=n(31),a=n(30),l=n(98);e.exports=function(e,t){var n=1==e,u=2==e,c=3==e,s=4==e,f=6==e,d=5==e||f,p=t||l;return function(t,l,h){for(var m,v,g=i(t),y=o(g),b=r(l,h,3),w=a(y.length),_=0,x=n?p(t,w):u?p(t,0):void 0;w>_;_++)if((d||_ in y)&&(v=b(m=y[_],_,g),e))if(n)x[_]=v;else if(v)switch(e){case 3:return!0;case 5:return m;case 6:return _;case 2:x.push(m)}else if(s)return!1;return f?-1:c||s?s:x}}},function(e,t,n){"use strict";t.__esModule=!0,t.validateRedirect=t.insertParams=t.resolve=t.match=t.pick=t.startsWith=void 0;var r,o=n(9),i=(r=o)&&r.__esModule?r:{default:r};var a=function(e,t){return e.substr(0,t.length)===t},l=function(e,t){for(var n=void 0,r=void 0,o=t.split("?")[0],a=d(o),l=""===a[0],c=f(e),s=0,p=c.length;s<p;s++){var m=!1,v=c[s].route;if(v.default)r={route:v,params:{},uri:t};else{for(var g=d(v.path),y={},b=Math.max(a.length,g.length),w=0;w<b;w++){var _=g[w],x=a[w];if("*"===_){y["*"]=a.slice(w).map(decodeURIComponent).join("/");break}if(void 0===x){m=!0;break}var k=u.exec(_);if(k&&!l){-1===h.indexOf(k[1])||(0,i.default)(!1);var S=decodeURIComponent(x);y[k[1]]=S}else if(_!==x){m=!0;break}}if(!m){n={route:v,params:y,uri:"/"+a.slice(0,w).join("/")};break}}}return n||r||null},u=/^:(.+)/,c=function(e){return u.test(e)},s=function(e,t){return{route:e,score:e.default?0:d(e.path).reduce(function(e,t){return e+=4,!function(e){return""===e}(t)?c(t)?e+=2:!function(e){return"*"===e}(t)?e+=3:e-=5:e+=1,e},0),index:t}},f=function(e){return e.map(s).sort(function(e,t){return e.score<t.score?1:e.score>t.score?-1:e.index-t.index})},d=function(e){return e.replace(/(^\/+|\/+$)/g,"").split("/")},p=function(e,t){return e+(t?"?"+t:"")},h=["uri","path"];t.startsWith=a,t.pick=l,t.match=function(e,t){return l([{path:e}],t)},t.resolve=function(e,t){if(a(e,"/"))return e;var n=e.split("?"),r=n[0],o=n[1],i=t.split("?")[0],l=d(r),u=d(i);if(""===l[0])return p(i,o);if(!a(l[0],".")){var c=u.concat(l).join("/");return p(("/"===i?"":"/")+c,o)}for(var s=u.concat(l),f=[],h=0,m=s.length;h<m;h++){var v=s[h];".."===v?f.pop():"."!==v&&f.push(v)}return p("/"+f.join("/"),o)},t.insertParams=function(e,t){return"/"+d(e).map(function(e){var n=u.exec(e);return n?t[n[1]]:e}).join("/")},t.validateRedirect=function(e,t){var n=function(e){return c(e)};return d(e).filter(n).sort().join("/")===d(t).filter(n).sort().join("/")}},function(e,t,n){"use strict";var r=n(10),o=n(18),i=n(17),a=n(28),l=n(3);e.exports=function(e,t,n){var u=l(e),c=n(a,u,""[e]),s=c[0],f=c[1];i(function(){var t={};return t[u]=function(){return 7},7!=""[e](t)})&&(o(String.prototype,e,s),r(RegExp.prototype,u,2==t?function(e,t){return f.call(e,this,t)}:function(e){return f.call(e,this)}))}},function(e,t,n){var r=n(11),o=n(75),i=n(76),a=Object.defineProperty;t.f=n(16)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t){e.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(13);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){var r=n(41),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(28);e.exports=function(e){return Object(r(e))}},function(e,t,n){n(25)("replace",2,function(e,t,n){return[function(r,o){"use strict";var i=e(this),a=null==r?void 0:r[t];return void 0!==a?a.call(r,i,o):n.call(String(i),r,o)},n]})},function(e,t,n){"use strict";n.d(t,"a",function(){return r});n(133);function r(e){var t=e||"/",n="",r="",o=t.indexOf("#");-1!==o&&(r=t.substr(o),t=t.substr(0,o));var i=t.indexOf("?");return-1!==i&&(n=t.substr(i),t=t.substr(0,i)),{pathname:t,search:"?"===n?"":n,hash:"#"===r?"":r}}},function(e,t,n){var r=n(6);r(r.S+r.F,"Object",{assign:n(77)})},function(e,t){e.exports=function(e){return e&&e.__esModule?e:{default:e}}},function(e,t,n){var r=n(12),o=n(5).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){e.exports=!1},function(e,t,n){var r=n(78),o=n(57);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){var r=n(29),o=n(28);e.exports=function(e){return r(o(e))}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(54)("keys"),o=n(37);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){"use strict";var r,o,i,a,l=n(38),u=n(5),c=n(20),s=n(58),f=n(6),d=n(12),p=n(21),h=n(82),m=n(83),v=n(87),g=n(59).set,y=n(89)(),b=n(61),w=n(90),_=n(91),x=n(92),k=u.TypeError,S=u.process,T=S&&S.versions,E=T&&T.v8||"",P=u.Promise,C="process"==s(S),O=function(){},R=o=b.f,j=!!function(){try{var e=P.resolve(1),t=(e.constructor={})[n(3)("species")]=function(e){e(O,O)};return(C||"function"==typeof PromiseRejectionEvent)&&e.then(O)instanceof t&&0!==E.indexOf("6.6")&&-1===_.indexOf("Chrome/66")}catch(e){}}(),N=function(e){var t;return!(!d(e)||"function"!=typeof(t=e.then))&&t},L=function(e,t){if(!e._n){e._n=!0;var n=e._c;y(function(){for(var r=e._v,o=1==e._s,i=0,a=function(t){var n,i,a,l=o?t.ok:t.fail,u=t.resolve,c=t.reject,s=t.domain;try{l?(o||(2==e._h&&U(e),e._h=1),!0===l?n=r:(s&&s.enter(),n=l(r),s&&(s.exit(),a=!0)),n===t.promise?c(k("Promise-chain cycle")):(i=N(n))?i.call(n,u,c):u(n)):c(r)}catch(e){s&&!a&&s.exit(),c(e)}};n.length>i;)a(n[i++]);e._c=[],e._n=!1,t&&!e._h&&M(e)})}},M=function(e){g.call(u,function(){var t,n,r,o=e._v,i=F(e);if(i&&(t=w(function(){C?S.emit("unhandledRejection",o,e):(n=u.onunhandledrejection)?n({promise:e,reason:o}):(r=u.console)&&r.error&&r.error("Unhandled promise rejection",o)}),e._h=C||F(e)?2:1),e._a=void 0,i&&t.e)throw t.v})},F=function(e){return 1!==e._h&&0===(e._a||e._c).length},U=function(e){g.call(u,function(){var t;C?S.emit("rejectionHandled",e):(t=u.onrejectionhandled)&&t({promise:e,reason:e._v})})},A=function(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),L(t,!0))},D=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw k("Promise can't be resolved itself");(t=N(e))?y(function(){var r={_w:n,_d:!1};try{t.call(e,c(D,r,1),c(A,r,1))}catch(e){A.call(r,e)}}):(n._v=e,n._s=1,L(n,!1))}catch(e){A.call({_w:n,_d:!1},e)}}};j||(P=function(e){h(this,P,"Promise","_h"),p(e),r.call(this);try{e(c(D,this,1),c(A,this,1))}catch(e){A.call(this,e)}},(r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=n(93)(P.prototype,{then:function(e,t){var n=R(v(this,P));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=C?S.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&L(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),i=function(){var e=new r;this.promise=e,this.resolve=c(D,e,1),this.reject=c(A,e,1)},b.f=R=function(e){return e===P||e===a?new i(e):o(e)}),f(f.G+f.W+f.F*!j,{Promise:P}),n(44)(P,"Promise"),n(94)("Promise"),a=n(19).Promise,f(f.S+f.F*!j,"Promise",{reject:function(e){var t=R(this);return(0,t.reject)(e),t.promise}}),f(f.S+f.F*(l||!j),"Promise",{resolve:function(e){return x(l&&this===a?P:this,e)}}),f(f.S+f.F*!(j&&n(95)(function(e){P.all(e).catch(O)})),"Promise",{all:function(e){var t=this,n=R(t),r=n.resolve,o=n.reject,i=w(function(){var n=[],i=0,a=1;m(e,!1,function(e){var l=i++,u=!1;n.push(void 0),a++,t.resolve(e).then(function(e){u||(u=!0,n[l]=e,--a||r(n))},o)}),--a||r(n)});return i.e&&o(i.v),n.promise},race:function(e){var t=this,n=R(t),r=n.reject,o=w(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return o.e&&r(o.v),n.promise}})},function(e,t,n){var r=n(26).f,o=n(27),i=n(3)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=!("undefined"==typeof window||!window.document||!window.document.createElement),e.exports=t.default},function(e,t,n){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=n(117)},function(e,t,n){t.components={"component---node-modules-gatsby-plugin-offline-app-shell-js":function(){return n.e(2).then(n.t.bind(null,136,7))},"component---src-pages-404-js":function(){return Promise.all([n.e(0),n.e(3)]).then(n.bind(null,137))},"component---src-pages-about-js":function(){return Promise.all([n.e(0),n.e(4)]).then(n.bind(null,138))},"component---src-pages-contact-js":function(){return n.e(5).then(n.t.bind(null,139,7))},"component---src-pages-index-js":function(){return Promise.all([n.e(0),n.e(6)]).then(n.bind(null,140))},"component---src-pages-page-2-js":function(){return Promise.all([n.e(0),n.e(7)]).then(n.bind(null,141))}},t.data=function(){return n.e(8).then(n.t.bind(null,142,3))}},function(e,t,n){"use strict";n(34);var r=n(7),o=n.n(r),i=n(0),a=n.n(i),l=n(4),u=n.n(l),c=n(2),s=n(1),f=function(e){function t(){return e.apply(this,arguments)||this}return o()(t,e),t.prototype.render=function(){var e=Object.assign({},this.props,{pathContext:this.props.pageContext}),t=Object(s.apiRunner)("replaceComponentRenderer",{props:this.props,loader:c.publicLoader})[0]||Object(i.createElement)(this.props.pageResources.component,Object.assign({},e,{key:this.props.location.pathname}));return Object(s.apiRunner)("wrapPageElement",{element:t,props:e},t,function(t){return{element:t.result,props:e}}).pop()},t}(a.a.Component);f.propTypes={location:u.a.object.isRequired,pageResources:u.a.object.isRequired,data:u.a.object,pageContext:u.a.object.isRequired},t.a=f},function(e,t,n){"use strict"; /* object-assign (c) Sindre Sorhus @license MIT */var r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,a,l=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u<arguments.length;u++){for(var c in n=Object(arguments[u]))o.call(n,c)&&(l[c]=n[c]);if(r){a=r(n);for(var s=0;s<a.length;s++)i.call(n,a[s])&&(l[a[s]]=n[a[s]])}}return l}},function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}},function(e,t){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){n(25)("search",1,function(e,t,n){return[function(n){"use strict";var r=e(this),o=null==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(19),o=n(5),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(38)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(e,t,n){n(25)("match",1,function(e,t,n){return[function(n){"use strict";var r=e(this),o=null==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){var r=n(40),o=n(30),i=n(79);e.exports=function(e){return function(t,n,a){var l,u=r(t),c=o(u.length),s=i(a,c);if(e&&n!=n){for(;c>s;)if((l=u[s++])!=l)return!0}else for(;c>s;s++)if((e||s in u)&&u[s]===n)return e||s||0;return!e&&-1}}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(13),o=n(3)("toStringTag"),i="Arguments"==r(function(){return arguments}());e.exports=function(e){var t,n,a;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),o))?n:i?r(t):"Object"==(a=r(t))&&"function"==typeof t.callee?"Arguments":a}},function(e,t,n){var r,o,i,a=n(20),l=n(88),u=n(60),c=n(36),s=n(5),f=s.process,d=s.setImmediate,p=s.clearImmediate,h=s.MessageChannel,m=s.Dispatch,v=0,g={},y=function(){var e=+this;if(g.hasOwnProperty(e)){var t=g[e];delete g[e],t()}},b=function(e){y.call(e.data)};d&&p||(d=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return g[++v]=function(){l("function"==typeof e?e:Function(e),t)},r(v),v},p=function(e){delete g[e]},"process"==n(13)(f)?r=function(e){f.nextTick(a(y,e,1))}:m&&m.now?r=function(e){m.now(a(y,e,1))}:h?(i=(o=new h).port2,o.port1.onmessage=b,r=a(i.postMessage,i,1)):s.addEventListener&&"function"==typeof postMessage&&!s.importScripts?(r=function(e){s.postMessage(e+"","*")},s.addEventListener("message",b,!1)):r="onreadystatechange"in c("script")?function(e){u.appendChild(c("script")).onreadystatechange=function(){u.removeChild(this),y.call(e)}}:function(e){setTimeout(a(y,e,1),0)}),e.exports={set:d,clear:p}},function(e,t,n){var r=n(5).document;e.exports=r&&r.documentElement},function(e,t,n){"use strict";var r=n(21);function o(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw TypeError("Bad Promise constructor");t=e,n=r}),this.resolve=r(t),this.reject=r(n)}e.exports.f=function(e){return new o(e)}},function(e,t,n){"use strict";var r=n(6),o=n(96);r(r.P+r.F*!n(14)([].reduce,!0),"Array",{reduce:function(e){return o(this,e,arguments.length,arguments[1],!1)}})},function(e,t,n){"use strict";var r=n(6),o=n(23)(1);r(r.P+r.F*!n(14)([].map,!0),"Array",{map:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(65),o=n(104),i=n(22),a=n(40);e.exports=n(66)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):o(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){var r=n(3)("unscopables"),o=Array.prototype;null==o[r]&&n(10)(o,r,{}),e.exports=function(e){o[r][e]=!0}},function(e,t,n){"use strict";var r=n(38),o=n(6),i=n(18),a=n(10),l=n(22),u=n(105),c=n(44),s=n(107),f=n(3)("iterator"),d=!([].keys&&"next"in[].keys()),p=function(){return this};e.exports=function(e,t,n,h,m,v,g){u(n,t,h);var y,b,w,_=function(e){if(!d&&e in T)return T[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},x=t+" Iterator",k="values"==m,S=!1,T=e.prototype,E=T[f]||T["@@iterator"]||m&&T[m],P=E||_(m),C=m?k?_("entries"):P:void 0,O="Array"==t&&T.entries||E;if(O&&(w=s(O.call(new e)))!==Object.prototype&&w.next&&(c(w,x,!0),r||"function"==typeof w[f]||a(w,f,p)),k&&E&&"values"!==E.name&&(S=!0,P=function(){return E.call(this)}),r&&!g||!d&&!S&&T[f]||a(T,f,P),l[t]=P,l[x]=p,m)if(y={values:k?P:_("values"),keys:v?P:_("keys"),entries:C},g)for(b in y)b in T||i(T,b,y[b]);else o(o.P+o.F*(d||S),t,y);return y}},function(e,t,n){var r=n(11),o=n(106),i=n(57),a=n(42)("IE_PROTO"),l=function(){},u=function(){var e,t=n(36)("iframe"),r=i.length;for(t.style.display="none",n(60).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),u=e.F;r--;)delete u.prototype[i[r]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(l.prototype=r(e),n=new l,l.prototype=null,n[a]=e):n=u(),void 0===t?n:o(n,t)}},function(e,t,n){"use strict";var r=n(6),o=n(23)(3);r(r.P+r.F*!n(14)([].some,!0),"Array",{some:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";e.exports=function(){}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e===e.window?e:9===e.nodeType&&(e.defaultView||e.parentWindow)},e.exports=t.default},function(e,t){t.polyfill=function(e){return e}},function(e,t,n){"use strict";var r=n(35),o=r(n(122)),i=r(n(132));t.ScrollContainer=i.default,t.ScrollContext=o.default},function(e,t,n){var r,o,i,a,l;e.exports=(o=[],i=document,a=i.documentElement.doScroll,(l=(a?/^loaded|^c/:/^loaded|^i|^c/).test(i.readyState))||i.addEventListener("DOMContentLoaded",r=function(){for(i.removeEventListener("DOMContentLoaded",r),l=1;r=o.shift();)r()}),function(e){l?setTimeout(e,0):o.push(e)})},function(e){e.exports=[]},function(e,t,n){e.exports=!n(16)&&!n(17)(function(){return 7!=Object.defineProperty(n(36)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(12);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){"use strict";var r=n(39),o=n(80),i=n(81),a=n(31),l=n(29),u=Object.assign;e.exports=!u||n(17)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=a(e),u=arguments.length,c=1,s=o.f,f=i.f;u>c;)for(var d,p=l(arguments[c++]),h=s?r(p).concat(s(p)):r(p),m=h.length,v=0;m>v;)f.call(p,d=h[v++])&&(n[d]=p[d]);return n}:u},function(e,t,n){var r=n(27),o=n(40),i=n(56)(!1),a=n(42)("IE_PROTO");e.exports=function(e,t){var n,l=o(e),u=0,c=[];for(n in l)n!=a&&r(l,n)&&c.push(n);for(;t.length>u;)r(l,n=t[u++])&&(~i(c,n)||c.push(n));return c}},function(e,t,n){var r=n(41),o=Math.max,i=Math.min;e.exports=function(e,t){return(e=r(e))<0?o(e+t,0):i(e,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},function(e,t,n){var r=n(20),o=n(84),i=n(85),a=n(11),l=n(30),u=n(86),c={},s={};(t=e.exports=function(e,t,n,f,d){var p,h,m,v,g=d?function(){return e}:u(e),y=r(n,f,t?2:1),b=0;if("function"!=typeof g)throw TypeError(e+" is not iterable!");if(i(g)){for(p=l(e.length);p>b;b++)if((v=t?y(a(h=e[b])[0],h[1]):y(e[b]))===c||v===s)return v}else for(m=g.call(e);!(h=m.next()).done;)if((v=o(m,y,h.value,t))===c||v===s)return v}).BREAK=c,t.RETURN=s},function(e,t,n){var r=n(11);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t}}},function(e,t,n){var r=n(22),o=n(3)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(58),o=n(3)("iterator"),i=n(22);e.exports=n(19).getIteratorMethod=function(e){if(null!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){var r=n(11),o=n(21),i=n(3)("species");e.exports=function(e,t){var n,a=r(e).constructor;return void 0===a||null==(n=r(a)[i])?t:o(n)}},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){var r=n(5),o=n(59).set,i=r.MutationObserver||r.WebKitMutationObserver,a=r.process,l=r.Promise,u="process"==n(13)(a);e.exports=function(){var e,t,n,c=function(){var r,o;for(u&&(r=a.domain)&&r.exit();e;){o=e.fn,e=e.next;try{o()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(u)n=function(){a.nextTick(c)};else if(!i||r.navigator&&r.navigator.standalone)if(l&&l.resolve){var s=l.resolve(void 0);n=function(){s.then(c)}}else n=function(){o.call(r,c)};else{var f=!0,d=document.createTextNode("");new i(c).observe(d,{characterData:!0}),n=function(){d.data=f=!f}}return function(r){var o={fn:r,next:void 0};t&&(t.next=o),e||(e=o,n()),t=o}}},function(e,t){e.exports=function(e){try{return{e:!1,v:e()}}catch(e){return{e:!0,v:e}}}},function(e,t,n){var r=n(5).navigator;e.exports=r&&r.userAgent||""},function(e,t,n){var r=n(11),o=n(12),i=n(61);e.exports=function(e,t){if(r(e),o(t)&&t.constructor===e)return t;var n=i.f(e);return(0,n.resolve)(t),n.promise}},function(e,t,n){var r=n(18);e.exports=function(e,t,n){for(var o in t)r(e,o,t[o],n);return e}},function(e,t,n){"use strict";var r=n(5),o=n(26),i=n(16),a=n(3)("species");e.exports=function(e){var t=r[e];i&&t&&!t[a]&&o.f(t,a,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(3)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){var r=n(21),o=n(31),i=n(29),a=n(30);e.exports=function(e,t,n,l,u){r(t);var c=o(e),s=i(c),f=a(c.length),d=u?f-1:0,p=u?-1:1;if(n<2)for(;;){if(d in s){l=s[d],d+=p;break}if(d+=p,u?d<0:f<=d)throw TypeError("Reduce of empty array with no initial value")}for(;u?d>=0:f>d;d+=p)d in s&&(l=t(l,s[d],d,c));return l}},function(e,t,n){"use strict";var r=n(6),o=n(23)(2);r(r.P+r.F*!n(14)([].filter,!0),"Array",{filter:function(e){return o(this,e,arguments[1])}})},function(e,t,n){var r=n(99);e.exports=function(e,t){return new(r(e))(t)}},function(e,t,n){var r=n(12),o=n(100),i=n(3)("species");e.exports=function(e){var t;return o(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!o(t.prototype)||(t=void 0),r(t)&&null===(t=t[i])&&(t=void 0)),void 0===t?Array:t}},function(e,t,n){var r=n(13);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){e.exports=[{plugin:n(102),options:{plugins:[]}},{plugin:n(103),options:{plugins:[]}}]},function(e,t,n){"use strict";t.registerServiceWorker=function(){return!0};var r=!0,o=[];t.onPrefetchPathname=function(e){var t=e.pathname;r&&"serviceWorker"in navigator&&o.push(t)},t.onServiceWorkerActive=function(e){var t=e.getResourceURLsForPathname,n=e.serviceWorker;r=!1;var i=document.querySelectorAll("\n head > script[src],\n head > link[as=script],\n head > link[rel=stylesheet],\n head > style[data-href]\n "),a=[].slice.call(i).map(function(e){return e.src||e.href||e.getAttribute("data-href")}),l=[];o.forEach(function(e){return t(e).forEach(function(e){return l.push(e)})}),n.active.postMessage({api:"gatsby-runtime-cache",resources:a.concat(l)})}},function(e,t){},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){"use strict";var r=n(67),o=n(53),i=n(44),a={};n(10)(a,n(3)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(26),o=n(11),i=n(39);e.exports=n(16)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),l=a.length,u=0;l>u;)r.f(e,n=a[u++],t[n]);return e}},function(e,t,n){var r=n(27),o=n(31),i=n(42)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){"use strict";var r=n(109)(!0);n(66)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var r=n(41),o=n(28);e.exports=function(e){return function(t,n){var i,a,l=String(o(t)),u=r(n),c=l.length;return u<0||u>=c?e?"":void 0:(i=l.charCodeAt(u))<55296||i>56319||u+1===c||(a=l.charCodeAt(u+1))<56320||a>57343?e?l.charAt(u):i:e?l.slice(u,u+2):a-56320+(i-55296<<10)+65536}}},function(e,t,n){"use strict";var r=n(6),o=n(23)(5),i=!0;"find"in[]&&Array(1).find(function(){i=!1}),r(r.P+r.F*i,"Array",{find:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(65)("find")},function(e,t,n){for(var r=n(64),o=n(39),i=n(18),a=n(5),l=n(10),u=n(22),c=n(3),s=c("iterator"),f=c("toStringTag"),d=u.Array,p={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},h=o(p),m=0;m<h.length;m++){var v,g=h[m],y=p[g],b=a[g],w=b&&b.prototype;if(w&&(w[s]||l(w,s,d),w[f]||l(w,f,g),u[g]=d,y))for(v in r)w[v]||i(w,v,r[v],!0)}},function(e,t,n){"use strict";var r=n(6),o=n(23)(0),i=n(14)([].forEach,!0);r(r.P+r.F*!i,"Array",{forEach:function(e){return o(this,e,arguments[1])}})},function(e,t,n){var r=n(6);r(r.S,"Object",{create:n(67)})},function(e,t,n){n(25)("split",2,function(e,t,r){"use strict";var o=n(115),i=r,a=[].push;if("c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length){var l=void 0===/()??/.exec("")[1];r=function(e,t){var n=String(this);if(void 0===e&&0===t)return[];if(!o(e))return i.call(n,e,t);var r,u,c,s,f,d=[],p=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),h=0,m=void 0===t?4294967295:t>>>0,v=new RegExp(e.source,p+"g");for(l||(r=new RegExp("^"+v.source+"$(?!\\s)",p));(u=v.exec(n))&&!((c=u.index+u[0].length)>h&&(d.push(n.slice(h,u.index)),!l&&u.length>1&&u[0].replace(r,function(){for(f=1;f<arguments.length-2;f++)void 0===arguments[f]&&(u[f]=void 0)}),u.length>1&&u.index<n.length&&a.apply(d,u.slice(1)),s=u[0].length,h=c,d.length>=m));)v.lastIndex===u.index&&v.lastIndex++;return h===n.length?!s&&v.test("")||d.push(""):d.push(n.slice(h)),d.length>m?d.slice(0,m):d}}else"0".split(void 0,0).length&&(r=function(e,t){return void 0===e&&0===t?[]:i.call(this,e,t)});return[function(n,o){var i=e(this),a=null==n?void 0:n[t];return void 0!==a?a.call(n,i,o):r.call(String(i),n,o)},r]})},function(e,t,n){var r=n(12),o=n(13),i=n(3)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[i])?!!t:"RegExp"==o(e))}},function(e,t,n){"use strict"; /** @license React v16.5.2 * react.production.min.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. */var r=n(49),o="function"==typeof Symbol&&Symbol.for,i=o?Symbol.for("react.element"):60103,a=o?Symbol.for("react.portal"):60106,l=o?Symbol.for("react.fragment"):60107,u=o?Symbol.for("react.strict_mode"):60108,c=o?Symbol.for("react.profiler"):60114,s=o?Symbol.for("react.provider"):60109,f=o?Symbol.for("react.context"):60110,d=o?Symbol.for("react.async_mode"):60111,p=o?Symbol.for("react.forward_ref"):60112;o&&Symbol.for("react.placeholder");var h="function"==typeof Symbol&&Symbol.iterator;function m(e){for(var t=arguments.length-1,n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);!function(e,t,n,r,o,i,a,l){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,o,i,a,l],c=0;(e=Error(t.replace(/%s/g,function(){return u[c++]}))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",n)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g={};function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||v}function b(){}function w(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||v}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&m("85"),this.updater.enqueueSetState(this,e,t,"setState")},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},b.prototype=y.prototype;var _=w.prototype=new b;_.constructor=w,r(_,y.prototype),_.isPureReactComponent=!0;var x={current:null,currentDispatcher:null},k=Object.prototype.hasOwnProperty,S={key:!0,ref:!0,__self:!0,__source:!0};function T(e,t,n){var r=void 0,o={},a=null,l=null;if(null!=t)for(r in void 0!==t.ref&&(l=t.ref),void 0!==t.key&&(a=""+t.key),t)k.call(t,r)&&!S.hasOwnProperty(r)&&(o[r]=t[r]);var u=arguments.length-2;if(1===u)o.children=n;else if(1<u){for(var c=Array(u),s=0;s<u;s++)c[s]=arguments[s+2];o.children=c}if(e&&e.defaultProps)for(r in u=e.defaultProps)void 0===o[r]&&(o[r]=u[r]);return{$$typeof:i,type:e,key:a,ref:l,props:o,_owner:x.current}}function E(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}var P=/\/+/g,C=[];function O(e,t,n,r){if(C.length){var o=C.pop();return o.result=e,o.keyPrefix=t,o.func=n,o.context=r,o.count=0,o}return{result:e,keyPrefix:t,func:n,context:r,count:0}}function R(e){e.result=null,e.keyPrefix=null,e.func=null,e.context=null,e.count=0,10>C.length&&C.push(e)}function j(e,t,n){return null==e?0:function e(t,n,r,o){var l=typeof t;"undefined"!==l&&"boolean"!==l||(t=null);var u=!1;if(null===t)u=!0;else switch(l){case"string":case"number":u=!0;break;case"object":switch(t.$$typeof){case i:case a:u=!0}}if(u)return r(o,t,""===n?"."+N(t,0):n),1;if(u=0,n=""===n?".":n+":",Array.isArray(t))for(var c=0;c<t.length;c++){var s=n+N(l=t[c],c);u+=e(l,s,r,o)}else if(s=null===t||"object"!=typeof t?null:"function"==typeof(s=h&&t[h]||t["@@iterator"])?s:null,"function"==typeof s)for(t=s.call(t),c=0;!(l=t.next()).done;)u+=e(l=l.value,s=n+N(l,c++),r,o);else"object"===l&&m("31","[object Object]"==(r=""+t)?"object with keys {"+Object.keys(t).join(", ")+"}":r,"");return u}(e,"",t,n)}function N(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,function(e){return t[e]})}(e.key):t.toString(36)}function L(e,t){e.func.call(e.context,t,e.count++)}function M(e,t,n){var r=e.result,o=e.keyPrefix;e=e.func.call(e.context,t,e.count++),Array.isArray(e)?F(e,r,n,function(e){return e}):null!=e&&(E(e)&&(e=function(e,t){return{$$typeof:i,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(e,o+(!e.key||t&&t.key===e.key?"":(""+e.key).replace(P,"$&/")+"/")+n)),r.push(e))}function F(e,t,n,r,o){var i="";null!=n&&(i=(""+n).replace(P,"$&/")+"/"),j(e,M,t=O(t,i,r,o)),R(t)}var U={Children:{map:function(e,t,n){if(null==e)return e;var r=[];return F(e,r,null,t,n),r},forEach:function(e,t,n){if(null==e)return e;j(e,L,t=O(null,null,t,n)),R(t)},count:function(e){return j(e,function(){return null},null)},toArray:function(e){var t=[];return F(e,t,null,function(e){return e}),t},only:function(e){return E(e)||m("143"),e}},createRef:function(){return{current:null}},Component:y,PureComponent:w,createContext:function(e,t){return void 0===t&&(t=null),(e={$$typeof:f,_calculateChangedBits:t,_currentValue:e,_currentValue2:e,Provider:null,Consumer:null,unstable_read:null}).Provider={$$typeof:s,_context:e},e.Consumer=e,e.unstable_read=function(e,t){var n=x.currentDispatcher;return null===n&&m("277"),n.readContext(e,t)}.bind(null,e),e},forwardRef:function(e){return{$$typeof:p,render:e}},Fragment:l,StrictMode:u,unstable_AsyncMode:d,unstable_Profiler:c,createElement:T,cloneElement:function(e,t,n){null==e&&m("267",e);var o=void 0,a=r({},e.props),l=e.key,u=e.ref,c=e._owner;if(null!=t){void 0!==t.ref&&(u=t.ref,c=x.current),void 0!==t.key&&(l=""+t.key);var s=void 0;for(o in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)k.call(t,o)&&!S.hasOwnProperty(o)&&(a[o]=void 0===t[o]&&void 0!==s?s[o]:t[o])}if(1===(o=arguments.length-2))a.children=n;else if(1<o){s=Array(o);for(var f=0;f<o;f++)s[f]=arguments[f+2];a.children=s}return{$$typeof:i,type:e.type,key:l,ref:u,props:a,_owner:c}},createFactory:function(e){var t=T.bind(null,e);return t.type=e,t},isValidElement:E,version:"16.5.2",__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentOwner:x,assign:r}},A={default:U},D=A&&U||A;e.exports=D.default||D},function(e,t,n){"use strict"; /** @license React v16.5.2 * react-dom.production.min.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. */var r=n(0),o=n(49),i=n(118);function a(e){for(var t=arguments.length-1,n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);!function(e,t,n,r,o,i,a,l){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,o,i,a,l],c=0;(e=Error(t.replace(/%s/g,function(){return u[c++]}))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",n)}r||a("227");var l=!1,u=null,c=!1,s=null,f={onError:function(e){l=!0,u=e}};function d(e,t,n,r,o,i,a,c,s){l=!1,u=null,function(e,t,n,r,o,i,a,l,u){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(e){this.onError(e)}}.apply(f,arguments)}var p=null,h={};function m(){if(p)for(var e in h){var t=h[e],n=p.indexOf(e);if(-1<n||a("96",e),!g[n])for(var r in t.extractEvents||a("97",e),g[n]=t,n=t.eventTypes){var o=void 0,i=n[r],l=t,u=r;y.hasOwnProperty(u)&&a("99",u),y[u]=i;var c=i.phasedRegistrationNames;if(c){for(o in c)c.hasOwnProperty(o)&&v(c[o],l,u);o=!0}else i.registrationName?(v(i.registrationName,l,u),o=!0):o=!1;o||a("98",r,e)}}}function v(e,t,n){b[e]&&a("100",e),b[e]=t,w[e]=t.eventTypes[n].dependencies}var g=[],y={},b={},w={},_=null,x=null,k=null;function S(e,t,n,r){t=e.type||"unknown-event",e.currentTarget=k(r),function(e,t,n,r,o,i,f,p,h){if(d.apply(this,arguments),l){if(l){var m=u;l=!1,u=null}else a("198"),m=void 0;c||(c=!0,s=m)}}(t,n,void 0,e),e.currentTarget=null}function T(e,t){return null==t&&a("30"),null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}function E(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}var P=null;function C(e,t){if(e){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)S(e,t,n[o],r[o]);else n&&S(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null,e.isPersistent()||e.constructor.release(e)}}function O(e){return C(e,!0)}function R(e){return C(e,!1)}var j={injectEventPluginOrder:function(e){p&&a("101"),p=Array.prototype.slice.call(e),m()},injectEventPluginsByName:function(e){var t,n=!1;for(t in e)if(e.hasOwnProperty(t)){var r=e[t];h.hasOwnProperty(t)&&h[t]===r||(h[t]&&a("102",t),h[t]=r,n=!0)}n&&m()}};function N(e,t){var n=e.stateNode;if(!n)return null;var r=_(n);if(!r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}return e?null:(n&&"function"!=typeof n&&a("231",t,typeof n),n)}function L(e,t){if(null!==e&&(P=T(P,e)),e=P,P=null,e&&(E(e,t?O:R),P&&a("95"),c))throw t=s,c=!1,s=null,t}var M=Math.random().toString(36).slice(2),F="__reactInternalInstance$"+M,U="__reactEventHandlers$"+M;function A(e){if(e[F])return e[F];for(;!e[F];){if(!e.parentNode)return null;e=e.parentNode}return 7===(e=e[F]).tag||8===e.tag?e:null}function D(e){return!(e=e[F])||7!==e.tag&&8!==e.tag?null:e}function I(e){if(7===e.tag||8===e.tag)return e.stateNode;a("33")}function W(e){return e[U]||null}function z(e){do{e=e.return}while(e&&7!==e.tag);return e||null}function B(e,t,n){(t=N(e,n.dispatchConfig.phasedRegistrationNames[t]))&&(n._dispatchListeners=T(n._dispatchListeners,t),n._dispatchInstances=T(n._dispatchInstances,e))}function H(e){if(e&&e.dispatchConfig.phasedRegistrationNames){for(var t=e._targetInst,n=[];t;)n.push(t),t=z(t);for(t=n.length;0<t--;)B(n[t],"captured",e);for(t=0;t<n.length;t++)B(n[t],"bubbled",e)}}function V(e,t,n){e&&n&&n.dispatchConfig.registrationName&&(t=N(e,n.dispatchConfig.registrationName))&&(n._dispatchListeners=T(n._dispatchListeners,t),n._dispatchInstances=T(n._dispatchInstances,e))}function $(e){e&&e.dispatchConfig.registrationName&&V(e._targetInst,null,e)}function q(e){E(e,H)}var K=!("undefined"==typeof window||!window.document||!window.document.createElement);function Y(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var G={animationend:Y("Animation","AnimationEnd"),animationiteration:Y("Animation","AnimationIteration"),animationstart:Y("Animation","AnimationStart"),transitionend:Y("Transition","TransitionEnd")},Q={},X={};function J(e){if(Q[e])return Q[e];if(!G[e])return e;var t,n=G[e];for(t in n)if(n.hasOwnProperty(t)&&t in X)return Q[e]=n[t];return e}K&&(X=document.createElement("div").style,"AnimationEvent"in window||(delete G.animationend.animation,delete G.animationiteration.animation,delete G.animationstart.animation),"TransitionEvent"in window||delete G.transitionend.transition);var Z=J("animationend"),ee=J("animationiteration"),te=J("animationstart"),ne=J("transitionend"),re="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),oe=null,ie=null,ae=null;function le(){if(ae)return ae;var e,t,n=ie,r=n.length,o="value"in oe?oe.value:oe.textContent,i=o.length;for(e=0;e<r&&n[e]===o[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===o[i-t];t++);return ae=o.slice(e,1<t?1-t:void 0)}function ue(){return!0}function ce(){return!1}function se(e,t,n,r){for(var o in this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n,e=this.constructor.Interface)e.hasOwnProperty(o)&&((t=e[o])?this[o]=t(n):"target"===o?this.target=r:this[o]=n[o]);return this.isDefaultPrevented=(null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue)?ue:ce,this.isPropagationStopped=ce,this}function fe(e,t,n,r){if(this.eventPool.length){var o=this.eventPool.pop();return this.call(o,e,t,n,r),o}return new this(e,t,n,r)}function de(e){e instanceof this||a("279"),e.destructor(),10>this.eventPool.length&&this.eventPool.push(e)}function pe(e){e.eventPool=[],e.getPooled=fe,e.release=de}o(se.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ue)},persist:function(){this.isPersistent=ue},isPersistent:ce,destructor:function(){var e,t=this.constructor.Interface;for(e in t)this[e]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null,this.isPropagationStopped=this.isDefaultPrevented=ce,this._dispatchInstances=this._dispatchListeners=null}}),se.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null},se.extend=function(e){function t(){}function n(){return r.apply(this,arguments)}var r=this;t.prototype=r.prototype;var i=new t;return o(i,n.prototype),n.prototype=i,n.prototype.constructor=n,n.Interface=o({},r.Interface,e),n.extend=r.extend,pe(n),n},pe(se);var he=se.extend({data:null}),me=se.extend({data:null}),ve=[9,13,27,32],ge=K&&"CompositionEvent"in window,ye=null;K&&"documentMode"in document&&(ye=document.documentMode);var be=K&&"TextEvent"in window&&!ye,we=K&&(!ge||ye&&8<ye&&11>=ye),_e=String.fromCharCode(32),xe={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},ke=!1;function Se(e,t){switch(e){case"keyup":return-1!==ve.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"blur":return!0;default:return!1}}function Te(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var Ee=!1;var Pe={eventTypes:xe,extractEvents:function(e,t,n,r){var o=void 0,i=void 0;if(ge)e:{switch(e){case"compositionstart":o=xe.compositionStart;break e;case"compositionend":o=xe.compositionEnd;break e;case"compositionupdate":o=xe.compositionUpdate;break e}o=void 0}else Ee?Se(e,n)&&(o=xe.compositionEnd):"keydown"===e&&229===n.keyCode&&(o=xe.compositionStart);return o?(we&&"ko"!==n.locale&&(Ee||o!==xe.compositionStart?o===xe.compositionEnd&&Ee&&(i=le()):(ie="value"in(oe=r)?oe.value:oe.textContent,Ee=!0)),o=he.getPooled(o,t,n,r),i?o.data=i:null!==(i=Te(n))&&(o.data=i),q(o),i=o):i=null,(e=be?function(e,t){switch(e){case"compositionend":return Te(t);case"keypress":return 32!==t.which?null:(ke=!0,_e);case"textInput":return(e=t.data)===_e&&ke?null:e;default:return null}}(e,n):function(e,t){if(Ee)return"compositionend"===e||!ge&&Se(e,t)?(e=le(),ae=ie=oe=null,Ee=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return we&&"ko"!==t.locale?null:t.data;default:return null}}(e,n))?((t=me.getPooled(xe.beforeInput,t,n,r)).data=e,q(t)):t=null,null===i?t:null===t?i:[i,t]}},Ce=null,Oe=null,Re=null;function je(e){if(e=x(e)){"function"!=typeof Ce&&a("280");var t=_(e.stateNode);Ce(e.stateNode,e.type,t)}}function Ne(e){Oe?Re?Re.push(e):Re=[e]:Oe=e}function Le(){if(Oe){var e=Oe,t=Re;if(Re=Oe=null,je(e),t)for(e=0;e<t.length;e++)je(t[e])}}function Me(e,t){return e(t)}function Fe(e,t,n){return e(t,n)}function Ue(){}var Ae=!1;function De(e,t){if(Ae)return e(t);Ae=!0;try{return Me(e,t)}finally{Ae=!1,(null!==Oe||null!==Re)&&(Ue(),Le())}}var Ie={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function We(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Ie[e.type]:"textarea"===t}function ze(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}function Be(e){if(!K)return!1;var t=(e="on"+e)in document;return t||((t=document.createElement("div")).setAttribute(e,"return;"),t="function"==typeof t[e]),t}function He(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function Ve(e){e._valueTracker||(e._valueTracker=function(e){var t=He(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==n&&"function"==typeof n.get&&"function"==typeof n.set){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(e){r=""+e,i.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function $e(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=He(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}var qe=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Ke=/^(.*)[\\\/]/,Ye="function"==typeof Symbol&&Symbol.for,Ge=Ye?Symbol.for("react.element"):60103,Qe=Ye?Symbol.for("react.portal"):60106,Xe=Ye?Symbol.for("react.fragment"):60107,Je=Ye?Symbol.for("react.strict_mode"):60108,Ze=Ye?Symbol.for("react.profiler"):60114,et=Ye?Symbol.for("react.provider"):60109,tt=Ye?Symbol.for("react.context"):60110,nt=Ye?Symbol.for("react.async_mode"):60111,rt=Ye?Symbol.for("react.forward_ref"):60112,ot=Ye?Symbol.for("react.placeholder"):60113,it="function"==typeof Symbol&&Symbol.iterator;function at(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=it&&e[it]||e["@@iterator"])?e:null}function lt(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case nt:return"AsyncMode";case Xe:return"Fragment";case Qe:return"Portal";case Ze:return"Profiler";case Je:return"StrictMode";case ot:return"Placeholder"}if("object"==typeof e){switch(e.$$typeof){case tt:return"Context.Consumer";case et:return"Context.Provider";case rt:var t=e.render;return t=t.displayName||t.name||"",e.displayName||(""!==t?"ForwardRef("+t+")":"ForwardRef")}if("function"==typeof e.then&&(e=1===e._reactStatus?e._reactResult:null))return lt(e)}return null}function ut(e){var t="";do{e:switch(e.tag){case 4:case 0:case 1:case 2:case 3:case 7:case 10:var n=e._debugOwner,r=e._debugSource,o=lt(e.type),i=null;n&&(i=lt(n.type)),n=o,o="",r?o=" (at "+r.fileName.replace(Ke,"")+":"+r.lineNumber+")":i&&(o=" (created by "+i+")"),i="\n in "+(n||"Unknown")+o;break e;default:i=""}t+=i,e=e.return}while(e);return t}var ct=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,st=Object.prototype.hasOwnProperty,ft={},dt={};function pt(e,t,n,r,o){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t}var ht={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ht[e]=new pt(e,0,!1,e,null)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ht[t]=new pt(t,1,!1,e[1],null)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){ht[e]=new pt(e,2,!1,e.toLowerCase(),null)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ht[e]=new pt(e,2,!1,e,null)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ht[e]=new pt(e,3,!1,e.toLowerCase(),null)}),["checked","multiple","muted","selected"].forEach(function(e){ht[e]=new pt(e,3,!0,e,null)}),["capture","download"].forEach(function(e){ht[e]=new pt(e,4,!1,e,null)}),["cols","rows","size","span"].forEach(function(e){ht[e]=new pt(e,6,!1,e,null)}),["rowSpan","start"].forEach(function(e){ht[e]=new pt(e,5,!1,e.toLowerCase(),null)});var mt=/[\-:]([a-z])/g;function vt(e){return e[1].toUpperCase()}function gt(e,t,n,r){var o=ht.hasOwnProperty(t)?ht[t]:null;(null!==o?0===o.type:!r&&(2<t.length&&("o"===t[0]||"O"===t[0])&&("n"===t[1]||"N"===t[1])))||(function(e,t,n,r){if(null==t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,n,o,r)&&(n=null),r||null===o?function(e){return!!st.call(dt,e)||!st.call(ft,e)&&(ct.test(e)?dt[e]=!0:(ft[e]=!0,!1))}(t)&&(null===n?e.removeAttribute(t):e.setAttribute(t,""+n)):o.mustUseProperty?e[o.propertyName]=null===n?3!==o.type&&"":n:(t=o.attributeName,r=o.attributeNamespace,null===n?e.removeAttribute(t):(n=3===(o=o.type)||4===o&&!0===n?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}function yt(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}function bt(e,t){var n=t.checked;return o({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=n?n:e._wrapperState.initialChecked})}function wt(e,t){var n=null==t.defaultValue?"":t.defaultValue,r=null!=t.checked?t.checked:t.defaultChecked;n=yt(null!=t.value?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function _t(e,t){null!=(t=t.checked)&&gt(e,"checked",t,!1)}function xt(e,t){_t(e,t);var n=yt(t.value),r=t.type;if(null!=n)"number"===r?(0===n&&""===e.value||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");t.hasOwnProperty("value")?St(e,t.type,n):t.hasOwnProperty("defaultValue")&&St(e,t.type,yt(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function kt(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!("submit"!==r&&"reset"!==r||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}""!==(n=e.name)&&(e.name=""),e.defaultChecked=!e.defaultChecked,e.defaultChecked=!!e._wrapperState.initialChecked,""!==n&&(e.name=n)}function St(e,t,n){"number"===t&&e.ownerDocument.activeElement===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(mt,vt);ht[t]=new pt(t,1,!1,e,null)}),"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(mt,vt);ht[t]=new pt(t,1,!1,e,"http://www.w3.org/1999/xlink")}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(mt,vt);ht[t]=new pt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace")}),ht.tabIndex=new pt("tabIndex",1,!1,"tabindex",null);var Tt={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function Et(e,t,n){return(e=se.getPooled(Tt.change,e,t,n)).type="change",Ne(n),q(e),e}var Pt=null,Ct=null;function Ot(e){L(e,!1)}function Rt(e){if($e(I(e)))return e}function jt(e,t){if("change"===e)return t}var Nt=!1;function Lt(){Pt&&(Pt.detachEvent("onpropertychange",Mt),Ct=Pt=null)}function Mt(e){"value"===e.propertyName&&Rt(Ct)&&De(Ot,e=Et(Ct,e,ze(e)))}function Ft(e,t,n){"focus"===e?(Lt(),Ct=n,(Pt=t).attachEvent("onpropertychange",Mt)):"blur"===e&&Lt()}function Ut(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Rt(Ct)}function At(e,t){if("click"===e)return Rt(t)}function Dt(e,t){if("input"===e||"change"===e)return Rt(t)}K&&(Nt=Be("input")&&(!document.documentMode||9<document.documentMode));var It={eventTypes:Tt,_isInputEventSupported:Nt,extractEvents:function(e,t,n,r){var o=t?I(t):window,i=void 0,a=void 0,l=o.nodeName&&o.nodeName.toLowerCase();if("select"===l||"input"===l&&"file"===o.type?i=jt:We(o)?Nt?i=Dt:(i=Ut,a=Ft):(l=o.nodeName)&&"input"===l.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(i=At),i&&(i=i(e,t)))return Et(i,n,r);a&&a(e,o,t),"blur"===e&&(e=o._wrapperState)&&e.controlled&&"number"===o.type&&St(o,"number",o.value)}},Wt=se.extend({view:null,detail:null}),zt={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Bt(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=zt[e])&&!!t[e]}function Ht(){return Bt}var Vt=0,$t=0,qt=!1,Kt=!1,Yt=Wt.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Ht,button:null,buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},movementX:function(e){if("movementX"in e)return e.movementX;var t=Vt;return Vt=e.screenX,qt?"mousemove"===e.type?e.screenX-t:0:(qt=!0,0)},movementY:function(e){if("movementY"in e)return e.movementY;var t=$t;return $t=e.screenY,Kt?"mousemove"===e.type?e.screenY-t:0:(Kt=!0,0)}}),Gt=Yt.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),Qt={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout","pointerover"]}},Xt={eventTypes:Qt,extractEvents:function(e,t,n,r){var o="mouseover"===e||"pointerover"===e,i="mouseout"===e||"pointerout"===e;if(o&&(n.relatedTarget||n.fromElement)||!i&&!o)return null;if(o=r.window===r?r:(o=r.ownerDocument)?o.defaultView||o.parentWindow:window,i?(i=t,t=(t=n.relatedTarget||n.toElement)?A(t):null):i=null,i===t)return null;var a=void 0,l=void 0,u=void 0,c=void 0;"mouseout"===e||"mouseover"===e?(a=Yt,l=Qt.mouseLeave,u=Qt.mouseEnter,c="mouse"):"pointerout"!==e&&"pointerover"!==e||(a=Gt,l=Qt.pointerLeave,u=Qt.pointerEnter,c="pointer");var s=null==i?o:I(i);if(o=null==t?o:I(t),(e=a.getPooled(l,i,n,r)).type=c+"leave",e.target=s,e.relatedTarget=o,(n=a.getPooled(u,t,n,r)).type=c+"enter",n.target=o,n.relatedTarget=s,r=t,i&&r)e:{for(o=r,c=0,a=t=i;a;a=z(a))c++;for(a=0,u=o;u;u=z(u))a++;for(;0<c-a;)t=z(t),c--;for(;0<a-c;)o=z(o),a--;for(;c--;){if(t===o||t===o.alternate)break e;t=z(t),o=z(o)}t=null}else t=null;for(o=t,t=[];i&&i!==o&&(null===(c=i.alternate)||c!==o);)t.push(i),i=z(i);for(i=[];r&&r!==o&&(null===(c=r.alternate)||c!==o);)i.push(r),r=z(r);for(r=0;r<t.length;r++)V(t[r],"bubbled",e);for(r=i.length;0<r--;)V(i[r],"captured",n);return[e,n]}},Jt=Object.prototype.hasOwnProperty;function Zt(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}function en(e,t){if(Zt(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++)if(!Jt.call(t,n[r])||!Zt(e[n[r]],t[n[r]]))return!1;return!0}function tn(e){var t=e;if(e.alternate)for(;t.return;)t=t.return;else{if(0!=(2&t.effectTag))return 1;for(;t.return;)if(0!=(2&(t=t.return).effectTag))return 1}return 5===t.tag?2:3}function nn(e){2!==tn(e)&&a("188")}function rn(e){if(!(e=function(e){var t=e.alternate;if(!t)return 3===(t=tn(e))&&a("188"),1===t?null:e;for(var n=e,r=t;;){var o=n.return,i=o?o.alternate:null;if(!o||!i)break;if(o.child===i.child){for(var l=o.child;l;){if(l===n)return nn(o),e;if(l===r)return nn(o),t;l=l.sibling}a("188")}if(n.return!==r.return)n=o,r=i;else{l=!1;for(var u=o.child;u;){if(u===n){l=!0,n=o,r=i;break}if(u===r){l=!0,r=o,n=i;break}u=u.sibling}if(!l){for(u=i.child;u;){if(u===n){l=!0,n=i,r=o;break}if(u===r){l=!0,r=i,n=o;break}u=u.sibling}l||a("189")}}n.alternate!==r&&a("190")}return 5!==n.tag&&a("188"),n.stateNode.current===n?e:t}(e)))return null;for(var t=e;;){if(7===t.tag||8===t.tag)return t;if(t.child)t.child.return=t,t=t.child;else{if(t===e)break;for(;!t.sibling;){if(!t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}}return null}var on=se.extend({animationName:null,elapsedTime:null,pseudoElement:null}),an=se.extend({clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),ln=Wt.extend({relatedTarget:null});function un(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}var cn={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},sn={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fn=Wt.extend({key:function(e){if(e.key){var t=cn[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=un(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?sn[e.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Ht,charCode:function(e){return"keypress"===e.type?un(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?un(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),dn=Yt.extend({dataTransfer:null}),pn=Wt.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Ht}),hn=se.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),mn=Yt.extend({deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null}),vn=[["abort","abort"],[Z,"animationEnd"],[ee,"animationIteration"],[te,"animationStart"],["canplay","canPlay"],["canplaythrough","canPlayThrough"],["drag","drag"],["dragenter","dragEnter"],["dragexit","dragExit"],["dragleave","dragLeave"],["dragover","dragOver"],["durationchange","durationChange"],["emptied","emptied"],["encrypted","encrypted"],["ended","ended"],["error","error"],["gotpointercapture","gotPointerCapture"],["load","load"],["loadeddata","loadedData"],["loadedmetadata","loadedMetadata"],["loadstart","loadStart"],["lostpointercapture","lostPointerCapture"],["mousemove","mouseMove"],["mouseout","mouseOut"],["mouseover","mouseOver"],["playing","playing"],["pointermove","pointerMove"],["pointerout","pointerOut"],["pointerover","pointerOver"],["progress","progress"],["scroll","scroll"],["seeking","seeking"],["stalled","stalled"],["suspend","suspend"],["timeupdate","timeUpdate"],["toggle","toggle"],["touchmove","touchMove"],[ne,"transitionEnd"],["waiting","waiting"],["wheel","wheel"]],gn={},yn={};function bn(e,t){var n=e[0],r="on"+((e=e[1])[0].toUpperCase()+e.slice(1));t={phasedRegistrationNames:{bubbled:r,captured:r+"Capture"},dependencies:[n],isInteractive:t},gn[e]=t,yn[n]=t}[["blur","blur"],["cancel","cancel"],["click","click"],["close","close"],["contextmenu","contextMenu"],["copy","copy"],["cut","cut"],["auxclick","auxClick"],["dblclick","doubleClick"],["dragend","dragEnd"],["dragstart","dragStart"],["drop","drop"],["focus","focus"],["input","input"],["invalid","invalid"],["keydown","keyDown"],["keypress","keyPress"],["keyup","keyUp"],["mousedown","mouseDown"],["mouseup","mouseUp"],["paste","paste"],["pause","pause"],["play","play"],["pointercancel","pointerCancel"],["pointerdown","pointerDown"],["pointerup","pointerUp"],["ratechange","rateChange"],["reset","reset"],["seeked","seeked"],["submit","submit"],["touchcancel","touchCancel"],["touchend","touchEnd"],["touchstart","touchStart"],["volumechange","volumeChange"]].forEach(function(e){bn(e,!0)}),vn.forEach(function(e){bn(e,!1)});var wn={eventTypes:gn,isInteractiveTopLevelEventType:function(e){return void 0!==(e=yn[e])&&!0===e.isInteractive},extractEvents:function(e,t,n,r){var o=yn[e];if(!o)return null;switch(e){case"keypress":if(0===un(n))return null;case"keydown":case"keyup":e=fn;break;case"blur":case"focus":e=ln;break;case"click":if(2===n.button)return null;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":e=Yt;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":e=dn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":e=pn;break;case Z:case ee:case te:e=on;break;case ne:e=hn;break;case"scroll":e=Wt;break;case"wheel":e=mn;break;case"copy":case"cut":case"paste":e=an;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":e=Gt;break;default:e=se}return q(t=e.getPooled(o,t,n,r)),t}},_n=wn.isInteractiveTopLevelEventType,xn=[];function kn(e){var t=e.targetInst,n=t;do{if(!n){e.ancestors.push(n);break}var r;for(r=n;r.return;)r=r.return;if(!(r=5!==r.tag?null:r.stateNode.containerInfo))break;e.ancestors.push(n),n=A(r)}while(n);for(n=0;n<e.ancestors.length;n++){t=e.ancestors[n];var o=ze(e.nativeEvent);r=e.topLevelType;for(var i=e.nativeEvent,a=null,l=0;l<g.length;l++){var u=g[l];u&&(u=u.extractEvents(r,t,i,o))&&(a=T(a,u))}L(a,!1)}}var Sn=!0;function Tn(e,t){if(!t)return null;var n=(_n(e)?Pn:Cn).bind(null,e);t.addEventListener(e,n,!1)}function En(e,t){if(!t)return null;var n=(_n(e)?Pn:Cn).bind(null,e);t.addEventListener(e,n,!0)}function Pn(e,t){Fe(Cn,e,t)}function Cn(e,t){if(Sn){var n=ze(t);if(null===(n=A(n))||"number"!=typeof n.tag||2===tn(n)||(n=null),xn.length){var r=xn.pop();r.topLevelType=e,r.nativeEvent=t,r.targetInst=n,e=r}else e={topLevelType:e,nativeEvent:t,targetInst:n,ancestors:[]};try{De(kn,e)}finally{e.topLevelType=null,e.nativeEvent=null,e.targetInst=null,e.ancestors.length=0,10>xn.length&&xn.push(e)}}}var On={},Rn=0,jn="_reactListenersID"+(""+Math.random()).slice(2);function Nn(e){return Object.prototype.hasOwnProperty.call(e,jn)||(e[jn]=Rn++,On[e[jn]]={}),On[e[jn]]}function Ln(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function Mn(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Fn(e,t){var n,r=Mn(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Mn(r)}}function Un(){for(var e=window,t=Ln();t instanceof e.HTMLIFrameElement;){try{e=t.contentDocument.defaultView}catch(e){break}t=Ln(e.document)}return t}function An(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var Dn=K&&"documentMode"in document&&11>=document.documentMode,In={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Wn=null,zn=null,Bn=null,Hn=!1;function Vn(e,t){var n=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;return Hn||null==Wn||Wn!==Ln(n)?null:("selectionStart"in(n=Wn)&&An(n)?n={start:n.selectionStart,end:n.selectionEnd}:n={anchorNode:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset},Bn&&en(Bn,n)?null:(Bn=n,(e=se.getPooled(In.select,zn,e,t)).type="select",e.target=Wn,q(e),e))}var $n={eventTypes:In,extractEvents:function(e,t,n,r){var o,i=r.window===r?r.document:9===r.nodeType?r:r.ownerDocument;if(!(o=!i)){e:{i=Nn(i),o=w.onSelect;for(var a=0;a<o.length;a++){var l=o[a];if(!i.hasOwnProperty(l)||!i[l]){i=!1;break e}}i=!0}o=!i}if(o)return null;switch(i=t?I(t):window,e){case"focus":(We(i)||"true"===i.contentEditable)&&(Wn=i,zn=t,Bn=null);break;case"blur":Bn=zn=Wn=null;break;case"mousedown":Hn=!0;break;case"contextmenu":case"mouseup":case"dragend":return Hn=!1,Vn(n,r);case"selectionchange":if(Dn)break;case"keydown":case"keyup":return Vn(n,r)}return null}};function qn(e,t){return e=o({children:void 0},t),(t=function(e){var t="";return r.Children.forEach(e,function(e){null!=e&&(t+=e)}),t}(t.children))&&(e.children=t),e}function Kn(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o<n.length;o++)t["$"+n[o]]=!0;for(n=0;n<e.length;n++)o=t.hasOwnProperty("$"+e[n].value),e[n].selected!==o&&(e[n].selected=o),o&&r&&(e[n].defaultSelected=!0)}else{for(n=""+yt(n),t=null,o=0;o<e.length;o++){if(e[o].value===n)return e[o].selected=!0,void(r&&(e[o].defaultSelected=!0));null!==t||e[o].disabled||(t=e[o])}null!==t&&(t.selected=!0)}}function Yn(e,t){return null!=t.dangerouslySetInnerHTML&&a("91"),o({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Gn(e,t){var n=t.value;null==n&&(n=t.defaultValue,null!=(t=t.children)&&(null!=n&&a("92"),Array.isArray(t)&&(1>=t.length||a("93"),t=t[0]),n=t),null==n&&(n="")),e._wrapperState={initialValue:yt(n)}}function Qn(e,t){var n=yt(t.value),r=yt(t.defaultValue);null!=n&&((n=""+n)!==e.value&&(e.value=n),null==t.defaultValue&&e.defaultValue!==n&&(e.defaultValue=n)),null!=r&&(e.defaultValue=""+r)}function Xn(e){var t=e.textContent;t===e._wrapperState.initialValue&&(e.value=t)}j.injectEventPluginOrder("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" ")),_=W,x=D,k=I,j.injectEventPluginsByName({SimpleEventPlugin:wn,EnterLeaveEventPlugin:Xt,ChangeEventPlugin:It,SelectEventPlugin:$n,BeforeInputEventPlugin:Pe});var Jn={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function Zn(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function er(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?Zn(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var tr,nr=void 0,rr=(tr=function(e,t){if(e.namespaceURI!==Jn.svg||"innerHTML"in e)e.innerHTML=t;else{for((nr=nr||document.createElement("div")).innerHTML="<svg>"+t+"</svg>",t=nr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,n,r){MSApp.execUnsafeLocalFunction(function(){return tr(e,t)})}:tr);function or(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t}var ir={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ar=["Webkit","ms","Moz","O"];function lr(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=0===n.indexOf("--"),o=n,i=t[n];o=null==i||"boolean"==typeof i||""===i?"":r||"number"!=typeof i||0===i||ir.hasOwnProperty(o)&&ir[o]?(""+i).trim():i+"px","float"===n&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}Object.keys(ir).forEach(function(e){ar.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ir[t]=ir[e]})});var ur=o({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function cr(e,t){t&&(ur[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&a("137",e,""),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&a("60"),"object"==typeof t.dangerouslySetInnerHTML&&"__html"in t.dangerouslySetInnerHTML||a("61")),null!=t.style&&"object"!=typeof t.style&&a("62",""))}function sr(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function fr(e,t){var n=Nn(e=9===e.nodeType||11===e.nodeType?e:e.ownerDocument);t=w[t];for(var r=0;r<t.length;r++){var o=t[r];if(!n.hasOwnProperty(o)||!n[o]){switch(o){case"scroll":En("scroll",e);break;case"focus":case"blur":En("focus",e),En("blur",e),n.blur=!0,n.focus=!0;break;case"cancel":case"close":Be(o)&&En(o,e);break;case"invalid":case"submit":case"reset":break;default:-1===re.indexOf(o)&&Tn(o,e)}n[o]=!0}}}function dr(){}var pr=null,hr=null;function mr(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function vr(e,t){return"textarea"===e||"option"===e||"noscript"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}function gr(e){for(e=e.nextSibling;e&&1!==e.nodeType&&3!==e.nodeType;)e=e.nextSibling;return e}function yr(e){for(e=e.firstChild;e&&1!==e.nodeType&&3!==e.nodeType;)e=e.nextSibling;return e}new Set;var br=[],wr=-1;function _r(e){0>wr||(e.current=br[wr],br[wr]=null,wr--)}function xr(e,t){br[++wr]=e.current,e.current=t}var kr={},Sr={current:kr},Tr={current:!1},Er=kr;function Pr(e,t){var n=e.type.contextTypes;if(!n)return kr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o,i={};for(o in n)i[o]=t[o];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Cr(e){return null!=(e=e.childContextTypes)}function Or(e){_r(Tr),_r(Sr)}function Rr(e){_r(Tr),_r(Sr)}function jr(e,t,n){Sr.current!==kr&&a("168"),xr(Sr,t),xr(Tr,n)}function Nr(e,t,n){var r=e.stateNode;if(e=t.childContextTypes,"function"!=typeof r.getChildContext)return n;for(var i in r=r.getChildContext())i in e||a("108",lt(t)||"Unknown",i);return o({},n,r)}function Lr(e){var t=e.stateNode;return t=t&&t.__reactInternalMemoizedMergedChildContext||kr,Er=Sr.current,xr(Sr,t),xr(Tr,Tr.current),!0}function Mr(e,t,n){var r=e.stateNode;r||a("169"),n?(t=Nr(e,t,Er),r.__reactInternalMemoizedMergedChildContext=t,_r(Tr),_r(Sr),xr(Sr,t)):_r(Tr),xr(Tr,n)}var Fr=null,Ur=null;function Ar(e){return function(t){try{return e(t)}catch(e){}}}function Dr(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=null,this.index=0,this.ref=null,this.pendingProps=t,this.firstContextDependency=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.effectTag=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childExpirationTime=this.expirationTime=0,this.alternate=null}function Ir(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Wr(e,t,n){var r=e.alternate;return null===r?((r=new Dr(e.tag,t,e.key,e.mode)).type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.effectTag=0,r.nextEffect=null,r.firstEffect=null,r.lastEffect=null),r.childExpirationTime=e.childExpirationTime,r.expirationTime=t!==e.pendingProps?n:e.expirationTime,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,r.firstContextDependency=e.firstContextDependency,r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function zr(e,t,n){var r=e.type,o=e.key;e=e.props;var i=void 0;if("function"==typeof r)i=Ir(r)?2:4;else if("string"==typeof r)i=7;else e:switch(r){case Xe:return Br(e.children,t,n,o);case nt:i=10,t|=3;break;case Je:i=10,t|=2;break;case Ze:return(r=new Dr(15,e,o,4|t)).type=Ze,r.expirationTime=n,r;case ot:i=16;break;default:if("object"==typeof r&&null!==r)switch(r.$$typeof){case et:i=12;break e;case tt:i=11;break e;case rt:i=13;break e;default:if("function"==typeof r.then){i=4;break e}}a("130",null==r?r:typeof r,"")}return(t=new Dr(i,e,o,t)).type=r,t.expirationTime=n,t}function Br(e,t,n,r){return(e=new Dr(9,e,r,t)).expirationTime=n,e}function Hr(e,t,n){return(e=new Dr(8,e,null,t)).expirationTime=n,e}function Vr(e,t,n){return(t=new Dr(6,null!==e.children?e.children:[],e.key,t)).expirationTime=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function $r(e,t){e.didError=!1;var n=e.earliestPendingTime;0===n?e.earliestPendingTime=e.latestPendingTime=t:n>t?e.earliestPendingTime=t:e.latestPendingTime<t&&(e.latestPendingTime=t),qr(t,e)}function qr(e,t){var n=t.earliestSuspendedTime,r=t.latestSuspendedTime,o=t.earliestPendingTime,i=t.latestPingedTime;0===(o=0!==o?o:i)&&(0===e||r>e)&&(o=r),0!==(e=o)&&0!==n&&n<e&&(e=n),t.nextExpirationTimeToWorkOn=o,t.expirationTime=e}var Kr=!1;function Yr(e){return{baseState:e,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Gr(e){return{baseState:e.baseState,firstUpdate:e.firstUpdate,lastUpdate:e.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Qr(e){return{expirationTime:e,tag:0,payload:null,callback:null,next:null,nextEffect:null}}function Xr(e,t){null===e.lastUpdate?e.firstUpdate=e.lastUpdate=t:(e.lastUpdate.next=t,e.lastUpdate=t)}function Jr(e,t){var n=e.alternate;if(null===n){var r=e.updateQueue,o=null;null===r&&(r=e.updateQueue=Yr(e.memoizedState))}else r=e.updateQueue,o=n.updateQueue,null===r?null===o?(r=e.updateQueue=Yr(e.memoizedState),o=n.updateQueue=Yr(n.memoizedState)):r=e.updateQueue=Gr(o):null===o&&(o=n.updateQueue=Gr(r));null===o||r===o?Xr(r,t):null===r.lastUpdate||null===o.lastUpdate?(Xr(r,t),Xr(o,t)):(Xr(r,t),o.lastUpdate=t)}function Zr(e,t){var n=e.updateQueue;null===(n=null===n?e.updateQueue=Yr(e.memoizedState):eo(e,n)).lastCapturedUpdate?n.firstCapturedUpdate=n.lastCapturedUpdate=t:(n.lastCapturedUpdate.next=t,n.lastCapturedUpdate=t)}function eo(e,t){var n=e.alternate;return null!==n&&t===n.updateQueue&&(t=e.updateQueue=Gr(t)),t}function to(e,t,n,r,i,a){switch(n.tag){case 1:return"function"==typeof(e=n.payload)?e.call(a,r,i):e;case 3:e.effectTag=-1025&e.effectTag|64;case 0:if(null==(i="function"==typeof(e=n.payload)?e.call(a,r,i):e))break;return o({},r,i);case 2:Kr=!0}return r}function no(e,t,n,r,o){Kr=!1;for(var i=(t=eo(e,t)).baseState,a=null,l=0,u=t.firstUpdate,c=i;null!==u;){var s=u.expirationTime;s>o?(null===a&&(a=u,i=c),(0===l||l>s)&&(l=s)):(c=to(e,0,u,c,n,r),null!==u.callback&&(e.effectTag|=32,u.nextEffect=null,null===t.lastEffect?t.firstEffect=t.lastEffect=u:(t.lastEffect.nextEffect=u,t.lastEffect=u))),u=u.next}for(s=null,u=t.firstCapturedUpdate;null!==u;){var f=u.expirationTime;f>o?(null===s&&(s=u,null===a&&(i=c)),(0===l||l>f)&&(l=f)):(c=to(e,0,u,c,n,r),null!==u.callback&&(e.effectTag|=32,u.nextEffect=null,null===t.lastCapturedEffect?t.firstCapturedEffect=t.lastCapturedEffect=u:(t.lastCapturedEffect.nextEffect=u,t.lastCapturedEffect=u))),u=u.next}null===a&&(t.lastUpdate=null),null===s?t.lastCapturedUpdate=null:e.effectTag|=32,null===a&&null===s&&(i=c),t.baseState=i,t.firstUpdate=a,t.firstCapturedUpdate=s,e.expirationTime=l,e.memoizedState=c}function ro(e,t,n){null!==t.firstCapturedUpdate&&(null!==t.lastUpdate&&(t.lastUpdate.next=t.firstCapturedUpdate,t.lastUpdate=t.lastCapturedUpdate),t.firstCapturedUpdate=t.lastCapturedUpdate=null),oo(t.firstEffect,n),t.firstEffect=t.lastEffect=null,oo(t.firstCapturedEffect,n),t.firstCapturedEffect=t.lastCapturedEffect=null}function oo(e,t){for(;null!==e;){var n=e.callback;if(null!==n){e.callback=null;var r=t;"function"!=typeof n&&a("191",n),n.call(r)}e=e.nextEffect}}function io(e,t){return{value:e,source:t,stack:ut(t)}}var ao={current:null},lo=null,uo=null,co=null;function so(e,t){var n=e.type._context;xr(ao,n._currentValue),n._currentValue=t}function fo(e){var t=ao.current;_r(ao),e.type._context._currentValue=t}function po(e){lo=e,co=uo=null,e.firstContextDependency=null}function ho(e,t){return co!==e&&!1!==t&&0!==t&&("number"==typeof t&&1073741823!==t||(co=e,t=1073741823),t={context:e,observedBits:t,next:null},null===uo?(null===lo&&a("277"),lo.firstContextDependency=uo=t):uo=uo.next=t),e._currentValue}var mo={},vo={current:mo},go={current:mo},yo={current:mo};function bo(e){return e===mo&&a("174"),e}function wo(e,t){xr(yo,t),xr(go,e),xr(vo,mo);var n=t.nodeType;switch(n){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:er(null,"");break;default:t=er(t=(n=8===n?t.parentNode:t).namespaceURI||null,n=n.tagName)}_r(vo),xr(vo,t)}function _o(e){_r(vo),_r(go),_r(yo)}function xo(e){bo(yo.current);var t=bo(vo.current),n=er(t,e.type);t!==n&&(xr(go,e),xr(vo,n))}function ko(e){go.current===e&&(_r(vo),_r(go))}var So=(new r.Component).refs;function To(e,t,n,r){n=null==(n=n(r,t=e.memoizedState))?t:o({},t,n),e.memoizedState=n,null!==(r=e.updateQueue)&&0===e.expirationTime&&(r.baseState=n)}var Eo={isMounted:function(e){return!!(e=e._reactInternalFiber)&&2===tn(e)},enqueueSetState:function(e,t,n){e=e._reactInternalFiber;var r=la(),o=Qr(r=Li(r,e));o.payload=t,null!=n&&(o.callback=n),Jr(e,o),Mi(e,r)},enqueueReplaceState:function(e,t,n){e=e._reactInternalFiber;var r=la(),o=Qr(r=Li(r,e));o.tag=1,o.payload=t,null!=n&&(o.callback=n),Jr(e,o),Mi(e,r)},enqueueForceUpdate:function(e,t){e=e._reactInternalFiber;var n=la(),r=Qr(n=Li(n,e));r.tag=2,null!=t&&(r.callback=t),Jr(e,r),Mi(e,n)}};function Po(e,t,n,r,o,i,a){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,i,a):!t.prototype||!t.prototype.isPureReactComponent||(!en(n,r)||!en(o,i))}function Co(e,t,n,r){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&Eo.enqueueReplaceState(t,t.state,null)}function Oo(e,t,n,r){var o=e.stateNode,i=Cr(t)?Er:Sr.current;o.props=n,o.state=e.memoizedState,o.refs=So,o.context=Pr(e,i),null!==(i=e.updateQueue)&&(no(e,i,n,o,r),o.state=e.memoizedState),"function"==typeof(i=t.getDerivedStateFromProps)&&(To(e,t,i,n),o.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof o.getSnapshotBeforeUpdate||"function"!=typeof o.UNSAFE_componentWillMount&&"function"!=typeof o.componentWillMount||(t=o.state,"function"==typeof o.componentWillMount&&o.componentWillMount(),"function"==typeof o.UNSAFE_componentWillMount&&o.UNSAFE_componentWillMount(),t!==o.state&&Eo.enqueueReplaceState(o,o.state,null),null!==(i=e.updateQueue)&&(no(e,i,n,o,r),o.state=e.memoizedState)),"function"==typeof o.componentDidMount&&(e.effectTag|=4)}var Ro=Array.isArray;function jo(e,t,n){if(null!==(e=n.ref)&&"function"!=typeof e&&"object"!=typeof e){if(n._owner){n=n._owner;var r=void 0;n&&(2!==n.tag&&3!==n.tag&&a("110"),r=n.stateNode),r||a("147",e);var o=""+e;return null!==t&&null!==t.ref&&"function"==typeof t.ref&&t.ref._stringRef===o?t.ref:((t=function(e){var t=r.refs;t===So&&(t=r.refs={}),null===e?delete t[o]:t[o]=e})._stringRef=o,t)}"string"!=typeof e&&a("284"),n._owner||a("254",e)}return e}function No(e,t){"textarea"!==e.type&&a("31","[object Object]"===Object.prototype.toString.call(t)?"object with keys {"+Object.keys(t).join(", ")+"}":t,"")}function Lo(e){function t(t,n){if(e){var r=t.lastEffect;null!==r?(r.nextEffect=n,t.lastEffect=n):t.firstEffect=t.lastEffect=n,n.nextEffect=null,n.effectTag=8}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function o(e,t,n){return(e=Wr(e,t,n)).index=0,e.sibling=null,e}function i(t,n,r){return t.index=r,e?null!==(r=t.alternate)?(r=r.index)<n?(t.effectTag=2,n):r:(t.effectTag=2,n):n}function l(t){return e&&null===t.alternate&&(t.effectTag=2),t}function u(e,t,n,r){return null===t||8!==t.tag?((t=Hr(n,e.mode,r)).return=e,t):((t=o(t,n,r)).return=e,t)}function c(e,t,n,r){return null!==t&&t.type===n.type?((r=o(t,n.props,r)).ref=jo(e,t,n),r.return=e,r):((r=zr(n,e.mode,r)).ref=jo(e,t,n),r.return=e,r)}function s(e,t,n,r){return null===t||6!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=Vr(n,e.mode,r)).return=e,t):((t=o(t,n.children||[],r)).return=e,t)}function f(e,t,n,r,i){return null===t||9!==t.tag?((t=Br(n,e.mode,r,i)).return=e,t):((t=o(t,n,r)).return=e,t)}function d(e,t,n){if("string"==typeof t||"number"==typeof t)return(t=Hr(""+t,e.mode,n)).return=e,t;if("object"==typeof t&&null!==t){switch(t.$$typeof){case Ge:return(n=zr(t,e.mode,n)).ref=jo(e,null,t),n.return=e,n;case Qe:return(t=Vr(t,e.mode,n)).return=e,t}if(Ro(t)||at(t))return(t=Br(t,e.mode,n,null)).return=e,t;No(e,t)}return null}function p(e,t,n,r){var o=null!==t?t.key:null;if("string"==typeof n||"number"==typeof n)return null!==o?null:u(e,t,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case Ge:return n.key===o?n.type===Xe?f(e,t,n.props.children,r,o):c(e,t,n,r):null;case Qe:return n.key===o?s(e,t,n,r):null}if(Ro(n)||at(n))return null!==o?null:f(e,t,n,r,null);No(e,n)}return null}function h(e,t,n,r,o){if("string"==typeof r||"number"==typeof r)return u(t,e=e.get(n)||null,""+r,o);if("object"==typeof r&&null!==r){switch(r.$$typeof){case Ge:return e=e.get(null===r.key?n:r.key)||null,r.type===Xe?f(t,e,r.props.children,o,r.key):c(t,e,r,o);case Qe:return s(t,e=e.get(null===r.key?n:r.key)||null,r,o)}if(Ro(r)||at(r))return f(t,e=e.get(n)||null,r,o,null);No(t,r)}return null}function m(o,a,l,u){for(var c=null,s=null,f=a,m=a=0,v=null;null!==f&&m<l.length;m++){f.index>m?(v=f,f=null):v=f.sibling;var g=p(o,f,l[m],u);if(null===g){null===f&&(f=v);break}e&&f&&null===g.alternate&&t(o,f),a=i(g,a,m),null===s?c=g:s.sibling=g,s=g,f=v}if(m===l.length)return n(o,f),c;if(null===f){for(;m<l.length;m++)(f=d(o,l[m],u))&&(a=i(f,a,m),null===s?c=f:s.sibling=f,s=f);return c}for(f=r(o,f);m<l.length;m++)(v=h(f,o,m,l[m],u))&&(e&&null!==v.alternate&&f.delete(null===v.key?m:v.key),a=i(v,a,m),null===s?c=v:s.sibling=v,s=v);return e&&f.forEach(function(e){return t(o,e)}),c}function v(o,l,u,c){var s=at(u);"function"!=typeof s&&a("150"),null==(u=s.call(u))&&a("151");for(var f=s=null,m=l,v=l=0,g=null,y=u.next();null!==m&&!y.done;v++,y=u.next()){m.index>v?(g=m,m=null):g=m.sibling;var b=p(o,m,y.value,c);if(null===b){m||(m=g);break}e&&m&&null===b.alternate&&t(o,m),l=i(b,l,v),null===f?s=b:f.sibling=b,f=b,m=g}if(y.done)return n(o,m),s;if(null===m){for(;!y.done;v++,y=u.next())null!==(y=d(o,y.value,c))&&(l=i(y,l,v),null===f?s=y:f.sibling=y,f=y);return s}for(m=r(o,m);!y.done;v++,y=u.next())null!==(y=h(m,o,v,y.value,c))&&(e&&null!==y.alternate&&m.delete(null===y.key?v:y.key),l=i(y,l,v),null===f?s=y:f.sibling=y,f=y);return e&&m.forEach(function(e){return t(o,e)}),s}return function(e,r,i,u){var c="object"==typeof i&&null!==i&&i.type===Xe&&null===i.key;c&&(i=i.props.children);var s="object"==typeof i&&null!==i;if(s)switch(i.$$typeof){case Ge:e:{for(s=i.key,c=r;null!==c;){if(c.key===s){if(9===c.tag?i.type===Xe:c.type===i.type){n(e,c.sibling),(r=o(c,i.type===Xe?i.props.children:i.props,u)).ref=jo(e,c,i),r.return=e,e=r;break e}n(e,c);break}t(e,c),c=c.sibling}i.type===Xe?((r=Br(i.props.children,e.mode,u,i.key)).return=e,e=r):((u=zr(i,e.mode,u)).ref=jo(e,r,i),u.return=e,e=u)}return l(e);case Qe:e:{for(c=i.key;null!==r;){if(r.key===c){if(6===r.tag&&r.stateNode.containerInfo===i.containerInfo&&r.stateNode.implementation===i.implementation){n(e,r.sibling),(r=o(r,i.children||[],u)).return=e,e=r;break e}n(e,r);break}t(e,r),r=r.sibling}(r=Vr(i,e.mode,u)).return=e,e=r}return l(e)}if("string"==typeof i||"number"==typeof i)return i=""+i,null!==r&&8===r.tag?(n(e,r.sibling),(r=o(r,i,u)).return=e,e=r):(n(e,r),(r=Hr(i,e.mode,u)).return=e,e=r),l(e);if(Ro(i))return m(e,r,i,u);if(at(i))return v(e,r,i,u);if(s&&No(e,i),void 0===i&&!c)switch(e.tag){case 2:case 3:case 0:a("152",(u=e.type).displayName||u.name||"Component")}return n(e,r)}}var Mo=Lo(!0),Fo=Lo(!1),Uo=null,Ao=null,Do=!1;function Io(e,t){var n=new Dr(7,null,null,0);n.type="DELETED",n.stateNode=t,n.return=e,n.effectTag=8,null!==e.lastEffect?(e.lastEffect.nextEffect=n,e.lastEffect=n):e.firstEffect=e.lastEffect=n}function Wo(e,t){switch(e.tag){case 7:var n=e.type;return null!==(t=1!==t.nodeType||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,!0);case 8:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,!0);default:return!1}}function zo(e){if(Do){var t=Ao;if(t){var n=t;if(!Wo(e,t)){if(!(t=gr(n))||!Wo(e,t))return e.effectTag|=2,Do=!1,void(Uo=e);Io(Uo,n)}Uo=e,Ao=yr(t)}else e.effectTag|=2,Do=!1,Uo=e}}function Bo(e){for(e=e.return;null!==e&&7!==e.tag&&5!==e.tag;)e=e.return;Uo=e}function Ho(e){if(e!==Uo)return!1;if(!Do)return Bo(e),Do=!0,!1;var t=e.type;if(7!==e.tag||"head"!==t&&"body"!==t&&!vr(t,e.memoizedProps))for(t=Ao;t;)Io(e,t),t=gr(t);return Bo(e),Ao=Uo?gr(e.stateNode):null,!0}function Vo(){Ao=Uo=null,Do=!1}var $o=qe.ReactCurrentOwner;function qo(e,t,n,r){t.child=null===e?Fo(t,null,n,r):Mo(t,e.child,n,r)}function Ko(e,t,n,r,o){n=n.render;var i=t.ref;return Tr.current||t.memoizedProps!==r||i!==(null!==e?e.ref:null)?(qo(e,t,n=n(r,i),o),t.memoizedProps=r,t.child):ei(e,t,o)}function Yo(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.effectTag|=128)}function Go(e,t,n,r,o){var i=Cr(n)?Er:Sr.current;return i=Pr(t,i),po(t),n=n(r,i),t.effectTag|=1,qo(e,t,n,o),t.memoizedProps=r,t.child}function Qo(e,t,n,r,o){if(Cr(n)){var i=!0;Lr(t)}else i=!1;if(po(t),null===e)if(null===t.stateNode){var a=Cr(n)?Er:Sr.current,l=n.contextTypes,u=null!=l,c=new n(r,l=u?Pr(t,a):kr);t.memoizedState=null!==c.state&&void 0!==c.state?c.state:null,c.updater=Eo,t.stateNode=c,c._reactInternalFiber=t,u&&((u=t.stateNode).__reactInternalMemoizedUnmaskedChildContext=a,u.__reactInternalMemoizedMaskedChildContext=l),Oo(t,n,r,o),r=!0}else{a=t.stateNode,l=t.memoizedProps,a.props=l;var s=a.context;u=Pr(t,u=Cr(n)?Er:Sr.current);var f=n.getDerivedStateFromProps;(c="function"==typeof f||"function"==typeof a.getSnapshotBeforeUpdate)||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(l!==r||s!==u)&&Co(t,a,r,u),Kr=!1;var d=t.memoizedState;s=a.state=d;var p=t.updateQueue;null!==p&&(no(t,p,r,a,o),s=t.memoizedState),l!==r||d!==s||Tr.current||Kr?("function"==typeof f&&(To(t,n,f,r),s=t.memoizedState),(l=Kr||Po(t,n,l,r,d,s,u))?(c||"function"!=typeof a.UNSAFE_componentWillMount&&"function"!=typeof a.componentWillMount||("function"==typeof a.componentWillMount&&a.componentWillMount(),"function"==typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount()),"function"==typeof a.componentDidMount&&(t.effectTag|=4)):("function"==typeof a.componentDidMount&&(t.effectTag|=4),t.memoizedProps=r,t.memoizedState=s),a.props=r,a.state=s,a.context=u,r=l):("function"==typeof a.componentDidMount&&(t.effectTag|=4),r=!1)}else a=t.stateNode,l=t.memoizedProps,a.props=l,s=a.context,u=Pr(t,u=Cr(n)?Er:Sr.current),(c="function"==typeof(f=n.getDerivedStateFromProps)||"function"==typeof a.getSnapshotBeforeUpdate)||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(l!==r||s!==u)&&Co(t,a,r,u),Kr=!1,s=t.memoizedState,d=a.state=s,null!==(p=t.updateQueue)&&(no(t,p,r,a,o),d=t.memoizedState),l!==r||s!==d||Tr.current||Kr?("function"==typeof f&&(To(t,n,f,r),d=t.memoizedState),(f=Kr||Po(t,n,l,r,s,d,u))?(c||"function"!=typeof a.UNSAFE_componentWillUpdate&&"function"!=typeof a.componentWillUpdate||("function"==typeof a.componentWillUpdate&&a.componentWillUpdate(r,d,u),"function"==typeof a.UNSAFE_componentWillUpdate&&a.UNSAFE_componentWillUpdate(r,d,u)),"function"==typeof a.componentDidUpdate&&(t.effectTag|=4),"function"==typeof a.getSnapshotBeforeUpdate&&(t.effectTag|=256)):("function"!=typeof a.componentDidUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=4),"function"!=typeof a.getSnapshotBeforeUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=256),t.memoizedProps=r,t.memoizedState=d),a.props=r,a.state=d,a.context=u,r=f):("function"!=typeof a.componentDidUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=4),"function"!=typeof a.getSnapshotBeforeUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=256),r=!1);return Xo(e,t,n,r,i,o)}function Xo(e,t,n,r,o,i){Yo(e,t);var a=0!=(64&t.effectTag);if(!r&&!a)return o&&Mr(t,n,!1),ei(e,t,i);r=t.stateNode,$o.current=t;var l=a?null:r.render();return t.effectTag|=1,null!==e&&a&&(qo(e,t,null,i),t.child=null),qo(e,t,l,i),t.memoizedState=r.state,t.memoizedProps=r.props,o&&Mr(t,n,!0),t.child}function Jo(e){var t=e.stateNode;t.pendingContext?jr(0,t.pendingContext,t.pendingContext!==t.context):t.context&&jr(0,t.context,!1),wo(e,t.containerInfo)}function Zo(e,t){if(e&&e.defaultProps)for(var n in t=o({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}function ei(e,t,n){null!==e&&(t.firstContextDependency=e.firstContextDependency);var r=t.childExpirationTime;if(0===r||r>n)return null;if(null!==e&&t.child!==e.child&&a("153"),null!==t.child){for(n=Wr(e=t.child,e.pendingProps,e.expirationTime),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=Wr(e,e.pendingProps,e.expirationTime)).return=t;n.sibling=null}return t.child}function ti(e,t,n){var r=t.expirationTime;if(!Tr.current&&(0===r||r>n)){switch(t.tag){case 5:Jo(t),Vo();break;case 7:xo(t);break;case 2:Cr(t.type)&&Lr(t);break;case 3:Cr(t.type._reactResult)&&Lr(t);break;case 6:wo(t,t.stateNode.containerInfo);break;case 12:so(t,t.memoizedProps.value)}return ei(e,t,n)}switch(t.expirationTime=0,t.tag){case 4:return function(e,t,n,r){null!==e&&a("155");var o=t.pendingProps;if("object"==typeof n&&null!==n&&"function"==typeof n.then){var i=n=function(e){switch(e._reactStatus){case 1:return e._reactResult;case 2:throw e._reactResult;case 0:throw e;default:throw e._reactStatus=0,e.then(function(t){if(0===e._reactStatus){if(e._reactStatus=1,"object"==typeof t&&null!==t){var n=t.default;t=null!=n?n:t}e._reactResult=t}},function(t){0===e._reactStatus&&(e._reactStatus=2,e._reactResult=t)}),e}}(n);i="function"==typeof i?Ir(i)?3:1:null!=i&&i.$$typeof?14:4,i=t.tag=i;var l=Zo(n,o);switch(i){case 1:return Go(e,t,n,l,r);case 3:return Qo(e,t,n,l,r);case 14:return Ko(e,t,n,l,r);default:a("283",n)}}if(i=Pr(t,Sr.current),po(t),i=n(o,i),t.effectTag|=1,"object"==typeof i&&null!==i&&"function"==typeof i.render&&void 0===i.$$typeof){t.tag=2,Cr(n)?(l=!0,Lr(t)):l=!1,t.memoizedState=null!==i.state&&void 0!==i.state?i.state:null;var u=n.getDerivedStateFromProps;return"function"==typeof u&&To(t,n,u,o),i.updater=Eo,t.stateNode=i,i._reactInternalFiber=t,Oo(t,n,o,r),Xo(e,t,n,!0,l,r)}return t.tag=0,qo(e,t,i,r),t.memoizedProps=o,t.child}(e,t,t.type,n);case 0:return Go(e,t,t.type,t.pendingProps,n);case 1:var o=t.type._reactResult;return e=Go(e,t,o,Zo(o,r=t.pendingProps),n),t.memoizedProps=r,e;case 2:return Qo(e,t,t.type,t.pendingProps,n);case 3:return e=Qo(e,t,o=t.type._reactResult,Zo(o,r=t.pendingProps),n),t.memoizedProps=r,e;case 5:return Jo(t),null===(r=t.updateQueue)&&a("282"),o=null!==(o=t.memoizedState)?o.element:null,no(t,r,t.pendingProps,null,n),(r=t.memoizedState.element)===o?(Vo(),t=ei(e,t,n)):(o=t.stateNode,(o=(null===e||null===e.child)&&o.hydrate)&&(Ao=yr(t.stateNode.containerInfo),Uo=t,o=Do=!0),o?(t.effectTag|=2,t.child=Fo(t,null,r,n)):(qo(e,t,r,n),Vo()),t=t.child),t;case 7:xo(t),null===e&&zo(t),r=t.type,o=t.pendingProps;var i=null!==e?e.memoizedProps:null,l=o.children;return vr(r,o)?l=null:null!==i&&vr(r,i)&&(t.effectTag|=16),Yo(e,t),1073741823!==n&&1&t.mode&&o.hidden?(t.expirationTime=1073741823,t.memoizedProps=o,t=null):(qo(e,t,l,n),t.memoizedProps=o,t=t.child),t;case 8:return null===e&&zo(t),t.memoizedProps=t.pendingProps,null;case 16:return null;case 6:return wo(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=Mo(t,null,r,n):qo(e,t,r,n),t.memoizedProps=r,t.child;case 13:return Ko(e,t,t.type,t.pendingProps,n);case 14:return e=Ko(e,t,o=t.type._reactResult,Zo(o,r=t.pendingProps),n),t.memoizedProps=r,e;case 9:return qo(e,t,r=t.pendingProps,n),t.memoizedProps=r,t.child;case 10:return qo(e,t,r=t.pendingProps.children,n),t.memoizedProps=r,t.child;case 15:return qo(e,t,(r=t.pendingProps).children,n),t.memoizedProps=r,t.child;case 12:e:{if(r=t.type._context,o=t.pendingProps,l=t.memoizedProps,i=o.value,t.memoizedProps=o,so(t,i),null!==l){var u=l.value;if(0===(i=u===i&&(0!==u||1/u==1/i)||u!=u&&i!=i?0:0|("function"==typeof r._calculateChangedBits?r._calculateChangedBits(u,i):1073741823))){if(l.children===o.children&&!Tr.current){t=ei(e,t,n);break e}}else for(null!==(l=t.child)&&(l.return=t);null!==l;){if(null!==(u=l.firstContextDependency))do{if(u.context===r&&0!=(u.observedBits&i)){if(2===l.tag||3===l.tag){var c=Qr(n);c.tag=2,Jr(l,c)}(0===l.expirationTime||l.expirationTime>n)&&(l.expirationTime=n),null!==(c=l.alternate)&&(0===c.expirationTime||c.expirationTime>n)&&(c.expirationTime=n);for(var s=l.return;null!==s;){if(c=s.alternate,0===s.childExpirationTime||s.childExpirationTime>n)s.childExpirationTime=n,null!==c&&(0===c.childExpirationTime||c.childExpirationTime>n)&&(c.childExpirationTime=n);else{if(null===c||!(0===c.childExpirationTime||c.childExpirationTime>n))break;c.childExpirationTime=n}s=s.return}}c=l.child,u=u.next}while(null!==u);else c=12===l.tag&&l.type===t.type?null:l.child;if(null!==c)c.return=l;else for(c=l;null!==c;){if(c===t){c=null;break}if(null!==(l=c.sibling)){l.return=c.return,c=l;break}c=c.return}l=c}}qo(e,t,o.children,n),t=t.child}return t;case 11:return i=t.type,o=(r=t.pendingProps).children,po(t),o=o(i=ho(i,r.unstable_observedBits)),t.effectTag|=1,qo(e,t,o,n),t.memoizedProps=r,t.child;default:a("156")}}function ni(e){e.effectTag|=4}var ri=void 0,oi=void 0,ii=void 0;function ai(e,t){var n=t.source,r=t.stack;null===r&&null!==n&&(r=ut(n)),null!==n&&lt(n.type),t=t.value,null!==e&&2===e.tag&&lt(e.type);try{console.error(t)}catch(e){setTimeout(function(){throw e})}}function li(e){var t=e.ref;if(null!==t)if("function"==typeof t)try{t(null)}catch(t){Ni(e,t)}else t.current=null}function ui(e){switch("function"==typeof Ur&&Ur(e),e.tag){case 2:case 3:li(e);var t=e.stateNode;if("function"==typeof t.componentWillUnmount)try{t.props=e.memoizedProps,t.state=e.memoizedState,t.componentWillUnmount()}catch(t){Ni(e,t)}break;case 7:li(e);break;case 6:fi(e)}}function ci(e){return 7===e.tag||5===e.tag||6===e.tag}function si(e){e:{for(var t=e.return;null!==t;){if(ci(t)){var n=t;break e}t=t.return}a("160"),n=void 0}var r=t=void 0;switch(n.tag){case 7:t=n.stateNode,r=!1;break;case 5:case 6:t=n.stateNode.containerInfo,r=!0;break;default:a("161")}16&n.effectTag&&(or(t,""),n.effectTag&=-17);e:t:for(n=e;;){for(;null===n.sibling;){if(null===n.return||ci(n.return)){n=null;break e}n=n.return}for(n.sibling.return=n.return,n=n.sibling;7!==n.tag&&8!==n.tag;){if(2&n.effectTag)continue t;if(null===n.child||6===n.tag)continue t;n.child.return=n,n=n.child}if(!(2&n.effectTag)){n=n.stateNode;break e}}for(var o=e;;){if(7===o.tag||8===o.tag)if(n)if(r){var i=t,l=o.stateNode,u=n;8===i.nodeType?i.parentNode.insertBefore(l,u):i.insertBefore(l,u)}else t.insertBefore(o.stateNode,n);else r?(i=t,l=o.stateNode,8===i.nodeType?(u=i.parentNode).insertBefore(l,i):(u=i).appendChild(l),null===u.onclick&&(u.onclick=dr)):t.appendChild(o.stateNode);else if(6!==o.tag&&null!==o.child){o.child.return=o,o=o.child;continue}if(o===e)break;for(;null===o.sibling;){if(null===o.return||o.return===e)return;o=o.return}o.sibling.return=o.return,o=o.sibling}}function fi(e){for(var t=e,n=!1,r=void 0,o=void 0;;){if(!n){n=t.return;e:for(;;){switch(null===n&&a("160"),n.tag){case 7:r=n.stateNode,o=!1;break e;case 5:case 6:r=n.stateNode.containerInfo,o=!0;break e}n=n.return}n=!0}if(7===t.tag||8===t.tag){e:for(var i=t,l=i;;)if(ui(l),null!==l.child&&6!==l.tag)l.child.return=l,l=l.child;else{if(l===i)break;for(;null===l.sibling;){if(null===l.return||l.return===i)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}o?(i=r,l=t.stateNode,8===i.nodeType?i.parentNode.removeChild(l):i.removeChild(l)):r.removeChild(t.stateNode)}else if(6===t.tag?(r=t.stateNode.containerInfo,o=!0):ui(t),null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return;6===(t=t.return).tag&&(n=!1)}t.sibling.return=t.return,t=t.sibling}}function di(e,t){switch(t.tag){case 2:case 3:break;case 7:var n=t.stateNode;if(null!=n){var r=t.memoizedProps,o=null!==e?e.memoizedProps:r;e=t.type;var i=t.updateQueue;if(t.updateQueue=null,null!==i){for(n[U]=r,"input"===e&&"radio"===r.type&&null!=r.name&&_t(n,r),sr(e,o),t=sr(e,r),o=0;o<i.length;o+=2){var l=i[o],u=i[o+1];"style"===l?lr(n,u):"dangerouslySetInnerHTML"===l?rr(n,u):"children"===l?or(n,u):gt(n,l,u,t)}switch(e){case"input":xt(n,r);break;case"textarea":Qn(n,r);break;case"select":e=n._wrapperState.wasMultiple,n._wrapperState.wasMultiple=!!r.multiple,null!=(i=r.value)?Kn(n,!!r.multiple,i,!1):e!==!!r.multiple&&(null!=r.defaultValue?Kn(n,!!r.multiple,r.defaultValue,!0):Kn(n,!!r.multiple,r.multiple?[]:"",!1))}}}break;case 8:null===t.stateNode&&a("162"),t.stateNode.nodeValue=t.memoizedProps;break;case 5:case 15:case 16:break;default:a("163")}}function pi(e,t,n){(n=Qr(n)).tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){ha(r),ai(e,t)},n}function hi(e,t,n){(n=Qr(n)).tag=3;var r=e.stateNode;return null!==r&&"function"==typeof r.componentDidCatch&&(n.callback=function(){null===Pi?Pi=new Set([this]):Pi.add(this);var n=t.value,r=t.stack;ai(e,t),this.componentDidCatch(n,{componentStack:null!==r?r:""})}),n}function mi(e){switch(e.tag){case 2:Cr(e.type)&&Or();var t=e.effectTag;return 1024&t?(e.effectTag=-1025&t|64,e):null;case 3:return Cr(e.type._reactResult)&&Or(),1024&(t=e.effectTag)?(e.effectTag=-1025&t|64,e):null;case 5:return _o(),Rr(),0!=(64&(t=e.effectTag))&&a("285"),e.effectTag=-1025&t|64,e;case 7:return ko(e),null;case 16:return 1024&(t=e.effectTag)?(e.effectTag=-1025&t|64,e):null;case 6:return _o(),null;case 12:return fo(e),null;default:return null}}ri=function(){},oi=function(e,t,n,r,i){var a=e.memoizedProps;if(a!==r){var l=t.stateNode;switch(bo(vo.current),e=null,n){case"input":a=bt(l,a),r=bt(l,r),e=[];break;case"option":a=qn(l,a),r=qn(l,r),e=[];break;case"select":a=o({},a,{value:void 0}),r=o({},r,{value:void 0}),e=[];break;case"textarea":a=Yn(l,a),r=Yn(l,r),e=[];break;default:"function"!=typeof a.onClick&&"function"==typeof r.onClick&&(l.onclick=dr)}cr(n,r),l=n=void 0;var u=null;for(n in a)if(!r.hasOwnProperty(n)&&a.hasOwnProperty(n)&&null!=a[n])if("style"===n){var c=a[n];for(l in c)c.hasOwnProperty(l)&&(u||(u={}),u[l]="")}else"dangerouslySetInnerHTML"!==n&&"children"!==n&&"suppressContentEditableWarning"!==n&&"suppressHydrationWarning"!==n&&"autoFocus"!==n&&(b.hasOwnProperty(n)?e||(e=[]):(e=e||[]).push(n,null));for(n in r){var s=r[n];if(c=null!=a?a[n]:void 0,r.hasOwnProperty(n)&&s!==c&&(null!=s||null!=c))if("style"===n)if(c){for(l in c)!c.hasOwnProperty(l)||s&&s.hasOwnProperty(l)||(u||(u={}),u[l]="");for(l in s)s.hasOwnProperty(l)&&c[l]!==s[l]&&(u||(u={}),u[l]=s[l])}else u||(e||(e=[]),e.push(n,u)),u=s;else"dangerouslySetInnerHTML"===n?(s=s?s.__html:void 0,c=c?c.__html:void 0,null!=s&&c!==s&&(e=e||[]).push(n,""+s)):"children"===n?c===s||"string"!=typeof s&&"number"!=typeof s||(e=e||[]).push(n,""+s):"suppressContentEditableWarning"!==n&&"suppressHydrationWarning"!==n&&(b.hasOwnProperty(n)?(null!=s&&fr(i,n),e||c===s||(e=[])):(e=e||[]).push(n,s))}u&&(e=e||[]).push("style",u),i=e,(t.updateQueue=i)&&ni(t)}},ii=function(e,t,n,r){n!==r&&ni(t)};var vi={readContext:ho},gi=qe.ReactCurrentOwner,yi=0,bi=0,wi=!1,_i=null,xi=null,ki=0,Si=!1,Ti=null,Ei=!1,Pi=null;function Ci(){if(null!==_i)for(var e=_i.return;null!==e;){var t=e;switch(t.tag){case 2:var n=t.type.childContextTypes;null!=n&&Or();break;case 3:null!=(n=t.type._reactResult.childContextTypes)&&Or();break;case 5:_o(),Rr();break;case 7:ko(t);break;case 6:_o();break;case 12:fo(t)}e=e.return}xi=null,ki=0,Si=!1,_i=null}function Oi(e){for(;;){var t=e.alternate,n=e.return,r=e.sibling;if(0==(512&e.effectTag)){var i=t,l=(t=e).pendingProps;switch(t.tag){case 0:case 1:break;case 2:Cr(t.type)&&Or();break;case 3:Cr(t.type._reactResult)&&Or();break;case 5:_o(),Rr(),(l=t.stateNode).pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),null!==i&&null!==i.child||(Ho(t),t.effectTag&=-3),ri(t);break;case 7:ko(t);var u=bo(yo.current),c=t.type;if(null!==i&&null!=t.stateNode)oi(i,t,c,l,u),i.ref!==t.ref&&(t.effectTag|=128);else if(l){var s=bo(vo.current);if(Ho(t)){i=(l=t).stateNode;var f=l.type,d=l.memoizedProps,p=u;switch(i[F]=l,i[U]=d,c=void 0,u=f){case"iframe":case"object":Tn("load",i);break;case"video":case"audio":for(f=0;f<re.length;f++)Tn(re[f],i);break;case"source":Tn("error",i);break;case"img":case"image":case"link":Tn("error",i),Tn("load",i);break;case"form":Tn("reset",i),Tn("submit",i);break;case"details":Tn("toggle",i);break;case"input":wt(i,d),Tn("invalid",i),fr(p,"onChange");break;case"select":i._wrapperState={wasMultiple:!!d.multiple},Tn("invalid",i),fr(p,"onChange");break;case"textarea":Gn(i,d),Tn("invalid",i),fr(p,"onChange")}for(c in cr(u,d),f=null,d)d.hasOwnProperty(c)&&(s=d[c],"children"===c?"string"==typeof s?i.textContent!==s&&(f=["children",s]):"number"==typeof s&&i.textContent!==""+s&&(f=["children",""+s]):b.hasOwnProperty(c)&&null!=s&&fr(p,c));switch(u){case"input":Ve(i),kt(i,d,!0);break;case"textarea":Ve(i),Xn(i);break;case"select":case"option":break;default:"function"==typeof d.onClick&&(i.onclick=dr)}c=f,l.updateQueue=c,(l=null!==c)&&ni(t)}else{d=t,i=c,p=l,f=9===u.nodeType?u:u.ownerDocument,s===Jn.html&&(s=Zn(i)),s===Jn.html?"script"===i?((i=f.createElement("div")).innerHTML="<script><\/script>",f=i.removeChild(i.firstChild)):"string"==typeof p.is?f=f.createElement(i,{is:p.is}):(f=f.createElement(i),"select"===i&&p.multiple&&(f.multiple=!0)):f=f.createElementNS(s,i),(i=f)[F]=d,i[U]=l;e:for(d=i,p=t,f=p.child;null!==f;){if(7===f.tag||8===f.tag)d.appendChild(f.stateNode);else if(6!==f.tag&&null!==f.child){f.child.return=f,f=f.child;continue}if(f===p)break;for(;null===f.sibling;){if(null===f.return||f.return===p)break e;f=f.return}f.sibling.return=f.return,f=f.sibling}p=i;var h=u,m=sr(f=c,d=l);switch(f){case"iframe":case"object":Tn("load",p),u=d;break;case"video":case"audio":for(u=0;u<re.length;u++)Tn(re[u],p);u=d;break;case"source":Tn("error",p),u=d;break;case"img":case"image":case"link":Tn("error",p),Tn("load",p),u=d;break;case"form":Tn("reset",p),Tn("submit",p),u=d;break;case"details":Tn("toggle",p),u=d;break;case"input":wt(p,d),u=bt(p,d),Tn("invalid",p),fr(h,"onChange");break;case"option":u=qn(p,d);break;case"select":p._wrapperState={wasMultiple:!!d.multiple},u=o({},d,{value:void 0}),Tn("invalid",p),fr(h,"onChange");break;case"textarea":Gn(p,d),u=Yn(p,d),Tn("invalid",p),fr(h,"onChange");break;default:u=d}cr(f,u),s=void 0;var v=f,g=p,y=u;for(s in y)if(y.hasOwnProperty(s)){var w=y[s];"style"===s?lr(g,w):"dangerouslySetInnerHTML"===s?null!=(w=w?w.__html:void 0)&&rr(g,w):"children"===s?"string"==typeof w?("textarea"!==v||""!==w)&&or(g,w):"number"==typeof w&&or(g,""+w):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(b.hasOwnProperty(s)?null!=w&&fr(h,s):null!=w&&gt(g,s,w,m))}switch(f){case"input":Ve(p),kt(p,d,!1);break;case"textarea":Ve(p),Xn(p);break;case"option":null!=d.value&&p.setAttribute("value",""+yt(d.value));break;case"select":(u=p).multiple=!!d.multiple,null!=(p=d.value)?Kn(u,!!d.multiple,p,!1):null!=d.defaultValue&&Kn(u,!!d.multiple,d.defaultValue,!0);break;default:"function"==typeof u.onClick&&(p.onclick=dr)}(l=mr(c,l))&&ni(t),t.stateNode=i}null!==t.ref&&(t.effectTag|=128)}else null===t.stateNode&&a("166");break;case 8:i&&null!=t.stateNode?ii(i,t,i.memoizedProps,l):("string"!=typeof l&&(null===t.stateNode&&a("166")),i=bo(yo.current),bo(vo.current),Ho(t)?(c=(l=t).stateNode,i=l.memoizedProps,c[F]=l,(l=c.nodeValue!==i)&&ni(t)):(c=t,(l=(9===i.nodeType?i:i.ownerDocument).createTextNode(l))[F]=c,t.stateNode=l));break;case 13:case 14:case 16:case 9:case 10:case 15:break;case 6:_o(),ri(t);break;case 12:fo(t);break;case 11:break;case 4:a("167");default:a("156")}if(t=_i=null,l=e,1073741823===ki||1073741823!==l.childExpirationTime){for(c=0,i=l.child;null!==i;)u=i.expirationTime,d=i.childExpirationTime,(0===c||0!==u&&u<c)&&(c=u),(0===c||0!==d&&d<c)&&(c=d),i=i.sibling;l.childExpirationTime=c}if(null!==t)return t;null!==n&&0==(512&n.effectTag)&&(null===n.firstEffect&&(n.firstEffect=e.firstEffect),null!==e.lastEffect&&(null!==n.lastEffect&&(n.lastEffect.nextEffect=e.firstEffect),n.lastEffect=e.lastEffect),1<e.effectTag&&(null!==n.lastEffect?n.lastEffect.nextEffect=e:n.firstEffect=e,n.lastEffect=e))}else{if(null!==(e=mi(e)))return e.effectTag&=511,e;null!==n&&(n.firstEffect=n.lastEffect=null,n.effectTag|=512)}if(null!==r)return r;if(null===n)break;e=n}return null}function Ri(e){var t=ti(e.alternate,e,ki);return null===t&&(t=Oi(e)),gi.current=null,t}function ji(e,t,n){wi&&a("243"),wi=!0,gi.currentDispatcher=vi;var r=e.nextExpirationTimeToWorkOn;r===ki&&e===xi&&null!==_i||(Ci(),ki=r,_i=Wr((xi=e).current,null,ki),e.pendingCommitExpirationTime=0);for(var o=!1;;){try{if(t)for(;null!==_i&&!pa();)_i=Ri(_i);else for(;null!==_i;)_i=Ri(_i)}catch(e){if(null===_i)o=!0,ha(e);else{null===_i&&a("271");var i=_i,l=i.return;if(null!==l){e:{var u=l,c=i,s=e;l=ki,c.effectTag|=512,c.firstEffect=c.lastEffect=null,Si=!0,s=io(s,c);do{switch(u.tag){case 5:u.effectTag|=1024,u.expirationTime=l,Zr(u,l=pi(u,s,l));break e;case 2:case 3:c=s;var f=u.stateNode;if(0==(64&u.effectTag)&&null!==f&&"function"==typeof f.componentDidCatch&&(null===Pi||!Pi.has(f))){u.effectTag|=1024,u.expirationTime=l,Zr(u,l=hi(u,c,l));break e}}u=u.return}while(null!==u)}_i=Oi(i);continue}o=!0,ha(e)}}break}if(wi=!1,co=uo=lo=gi.currentDispatcher=null,o)xi=null,e.finishedWork=null;else if(null!==_i)e.finishedWork=null;else{if(null===(t=e.current.alternate)&&a("281"),xi=null,Si){if(o=e.latestPendingTime,i=e.latestSuspendedTime,l=e.latestPingedTime,0!==o&&o>r||0!==i&&i>r||0!==l&&l>r)return e.didError=!1,0!==(n=e.latestPingedTime)&&n<=r&&(e.latestPingedTime=0),n=e.earliestPendingTime,t=e.latestPendingTime,n===r?e.earliestPendingTime=t===r?e.latestPendingTime=0:t:t===r&&(e.latestPendingTime=n),n=e.earliestSuspendedTime,t=e.latestSuspendedTime,0===n?e.earliestSuspendedTime=e.latestSuspendedTime=r:n>r?e.earliestSuspendedTime=r:t<r&&(e.latestSuspendedTime=r),qr(r,e),void(e.expirationTime=e.expirationTime);if(!e.didError&&!n)return e.didError=!0,e.nextExpirationTimeToWorkOn=r,r=e.expirationTime=1,void(e.expirationTime=r)}e.pendingCommitExpirationTime=r,e.finishedWork=t}}function Ni(e,t){var n;e:{for(wi&&!Ei&&a("263"),n=e.return;null!==n;){switch(n.tag){case 2:case 3:var r=n.stateNode;if("function"==typeof n.type.getDerivedStateFromCatch||"function"==typeof r.componentDidCatch&&(null===Pi||!Pi.has(r))){Jr(n,e=hi(n,e=io(t,e),1)),Mi(n,1),n=void 0;break e}break;case 5:Jr(n,e=pi(n,e=io(t,e),1)),Mi(n,1),n=void 0;break e}n=n.return}5===e.tag&&(Jr(e,n=pi(e,n=io(t,e),1)),Mi(e,1)),n=void 0}return n}function Li(e,t){return 0!==bi?e=bi:wi?e=Ei?1:ki:1&t.mode?(e=Qi?2+10*(1+((e-2+15)/10|0)):2+25*(1+((e-2+500)/25|0)),null!==xi&&e===ki&&(e+=1)):e=1,Qi&&(0===Hi||e>Hi)&&(Hi=e),e}function Mi(e,t){e:{(0===e.expirationTime||e.expirationTime>t)&&(e.expirationTime=t);var n=e.alternate;null!==n&&(0===n.expirationTime||n.expirationTime>t)&&(n.expirationTime=t);var r=e.return;if(null===r&&5===e.tag)e=e.stateNode;else{for(;null!==r;){if(n=r.alternate,(0===r.childExpirationTime||r.childExpirationTime>t)&&(r.childExpirationTime=t),null!==n&&(0===n.childExpirationTime||n.childExpirationTime>t)&&(n.childExpirationTime=t),null===r.return&&5===r.tag){e=r.stateNode;break e}r=r.return}e=null}}null!==e&&(!wi&&0!==ki&&t<ki&&Ci(),$r(e,t),wi&&!Ei&&xi===e||(t=e,e=e.expirationTime,null===t.nextScheduledRoot?(t.expirationTime=e,null===Ai?(Ui=Ai=t,t.nextScheduledRoot=t):(Ai=Ai.nextScheduledRoot=t).nextScheduledRoot=Ui):(0===(n=t.expirationTime)||e<n)&&(t.expirationTime=e),Wi||(Yi?Gi&&(zi=t,Bi=1,fa(t,1,!0)):1===e?sa(1,null):aa(t,e))),na>ta&&(na=0,a("185")))}function Fi(e,t,n,r,o){var i=bi;bi=1;try{return e(t,n,r,o)}finally{bi=i}}var Ui=null,Ai=null,Di=0,Ii=void 0,Wi=!1,zi=null,Bi=0,Hi=0,Vi=!1,$i=!1,qi=null,Ki=null,Yi=!1,Gi=!1,Qi=!1,Xi=null,Ji=i.unstable_now(),Zi=2+(Ji/10|0),ea=Zi,ta=50,na=0,ra=null,oa=1;function ia(){Zi=2+((i.unstable_now()-Ji)/10|0)}function aa(e,t){if(0!==Di){if(t>Di)return;null!==Ii&&i.unstable_cancelScheduledWork(Ii)}Di=t,e=i.unstable_now()-Ji,Ii=i.unstable_scheduleWork(ca,{timeout:10*(t-2)-e})}function la(){return Wi?ea:(ua(),0!==Bi&&1073741823!==Bi||(ia(),ea=Zi),ea)}function ua(){var e=0,t=null;if(null!==Ai)for(var n=Ai,r=Ui;null!==r;){var o=r.expirationTime;if(0===o){if((null===n||null===Ai)&&a("244"),r===r.nextScheduledRoot){Ui=Ai=r.nextScheduledRoot=null;break}if(r===Ui)Ui=o=r.nextScheduledRoot,Ai.nextScheduledRoot=o,r.nextScheduledRoot=null;else{if(r===Ai){(Ai=n).nextScheduledRoot=Ui,r.nextScheduledRoot=null;break}n.nextScheduledRoot=r.nextScheduledRoot,r.nextScheduledRoot=null}r=n.nextScheduledRoot}else{if((0===e||o<e)&&(e=o,t=r),r===Ai)break;if(1===e)break;n=r,r=r.nextScheduledRoot}}zi=t,Bi=e}function ca(e){if(e.didTimeout&&null!==Ui){ia();var t=Ui;do{var n=t.expirationTime;0!==n&&Zi>=n&&(t.nextExpirationTimeToWorkOn=Zi),t=t.nextScheduledRoot}while(t!==Ui)}sa(0,e)}function sa(e,t){if(Ki=t,ua(),null!==Ki)for(ia(),ea=Zi;null!==zi&&0!==Bi&&(0===e||e>=Bi)&&(!Vi||Zi>=Bi);)fa(zi,Bi,Zi>=Bi),ua(),ia(),ea=Zi;else for(;null!==zi&&0!==Bi&&(0===e||e>=Bi);)fa(zi,Bi,!0),ua();if(null!==Ki&&(Di=0,Ii=null),0!==Bi&&aa(zi,Bi),Ki=null,Vi=!1,na=0,ra=null,null!==Xi)for(e=Xi,Xi=null,t=0;t<e.length;t++){var n=e[t];try{n._onComplete()}catch(e){$i||($i=!0,qi=e)}}if($i)throw e=qi,qi=null,$i=!1,e}function fa(e,t,n){if(Wi&&a("245"),Wi=!0,null===Ki||n){var r=e.finishedWork;null!==r?da(e,r,t):(e.finishedWork=null,ji(e,!1,n),null!==(r=e.finishedWork)&&da(e,r,t))}else null!==(r=e.finishedWork)?da(e,r,t):(e.finishedWork=null,ji(e,!0,n),null!==(r=e.finishedWork)&&(pa()?e.finishedWork=r:da(e,r,t)));Wi=!1}function da(e,t,n){var r=e.firstBatch;if(null!==r&&r._expirationTime<=n&&(null===Xi?Xi=[r]:Xi.push(r),r._defer))return e.finishedWork=t,void(e.expirationTime=0);e.finishedWork=null,e===ra?na++:(ra=e,na=0),Ei=wi=!0,e.current===t&&a("177"),0===(n=e.pendingCommitExpirationTime)&&a("261"),e.pendingCommitExpirationTime=0,r=t.expirationTime;var o=t.childExpirationTime;if(r=0===r||0!==o&&o<r?o:r,e.didError=!1,0===r?(e.earliestPendingTime=0,e.latestPendingTime=0,e.earliestSuspendedTime=0,e.latestSuspendedTime=0,e.latestPingedTime=0):(0!==(o=e.latestPendingTime)&&(o<r?e.earliestPendingTime=e.latestPendingTime=0:e.earliestPendingTime<r&&(e.earliestPendingTime=e.latestPendingTime)),0===(o=e.earliestSuspendedTime)?$r(e,r):r>e.latestSuspendedTime?(e.earliestSuspendedTime=0,e.latestSuspendedTime=0,e.latestPingedTime=0,$r(e,r)):r<o&&$r(e,r)),qr(0,e),gi.current=null,1<t.effectTag?null!==t.lastEffect?(t.lastEffect.nextEffect=t,r=t.firstEffect):r=t:r=t.firstEffect,pr=Sn,An(o=Un())){if("selectionStart"in o)var i={start:o.selectionStart,end:o.selectionEnd};else e:{var l=(i=(i=o.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(l&&0!==l.rangeCount){i=l.anchorNode;var u=l.anchorOffset,c=l.focusNode;l=l.focusOffset;try{i.nodeType,c.nodeType}catch(e){i=null;break e}var s=0,f=-1,d=-1,p=0,h=0,m=o,v=null;t:for(;;){for(var g;m!==i||0!==u&&3!==m.nodeType||(f=s+u),m!==c||0!==l&&3!==m.nodeType||(d=s+l),3===m.nodeType&&(s+=m.nodeValue.length),null!==(g=m.firstChild);)v=m,m=g;for(;;){if(m===o)break t;if(v===i&&++p===u&&(f=s),v===c&&++h===l&&(d=s),null!==(g=m.nextSibling))break;v=(m=v).parentNode}m=g}i=-1===f||-1===d?null:{start:f,end:d}}else i=null}i=i||{start:0,end:0}}else i=null;for(hr={focusedElem:o,selectionRange:i},Sn=!1,Ti=r;null!==Ti;){o=!1,i=void 0;try{for(;null!==Ti;){if(256&Ti.effectTag){var y=Ti.alternate;e:switch(u=Ti,u.tag){case 2:case 3:if(256&u.effectTag&&null!==y){var b=y.memoizedProps,w=y.memoizedState,_=u.stateNode;_.props=u.memoizedProps,_.state=u.memoizedState;var x=_.getSnapshotBeforeUpdate(b,w);_.__reactInternalSnapshotBeforeUpdate=x}break e;case 5:case 7:case 8:case 6:break e;default:a("163")}}Ti=Ti.nextEffect}}catch(e){o=!0,i=e}o&&(null===Ti&&a("178"),Ni(Ti,i),null!==Ti&&(Ti=Ti.nextEffect))}for(Ti=r;null!==Ti;){y=!1,b=void 0;try{for(;null!==Ti;){var k=Ti.effectTag;if(16&k&&or(Ti.stateNode,""),128&k){var S=Ti.alternate;if(null!==S){var T=S.ref;null!==T&&("function"==typeof T?T(null):T.current=null)}}switch(14&k){case 2:si(Ti),Ti.effectTag&=-3;break;case 6:si(Ti),Ti.effectTag&=-3,di(Ti.alternate,Ti);break;case 4:di(Ti.alternate,Ti);break;case 8:fi(w=Ti),w.return=null,w.child=null,w.alternate&&(w.alternate.child=null,w.alternate.return=null)}Ti=Ti.nextEffect}}catch(e){y=!0,b=e}y&&(null===Ti&&a("178"),Ni(Ti,b),null!==Ti&&(Ti=Ti.nextEffect))}if(T=hr,S=Un(),k=T.focusedElem,b=T.selectionRange,S!==k&&k&&k.ownerDocument&&function e(t,n){return!(!t||!n)&&(t===n||(!t||3!==t.nodeType)&&(n&&3===n.nodeType?e(t,n.parentNode):"contains"in t?t.contains(n):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(n))))}(k.ownerDocument.documentElement,k)){null!==b&&An(k)&&(S=b.start,void 0===(T=b.end)&&(T=S),"selectionStart"in k?(k.selectionStart=S,k.selectionEnd=Math.min(T,k.value.length)):(S=((y=k.ownerDocument||document)&&y.defaultView||window).getSelection(),w=k.textContent.length,T=Math.min(b.start,w),b=void 0===b.end?T:Math.min(b.end,w),!S.extend&&T>b&&(w=b,b=T,T=w),w=Fn(k,T),_=Fn(k,b),w&&_&&(1!==S.rangeCount||S.anchorNode!==w.node||S.anchorOffset!==w.offset||S.focusNode!==_.node||S.focusOffset!==_.offset)&&((y=y.createRange()).setStart(w.node,w.offset),S.removeAllRanges(),T>b?(S.addRange(y),S.extend(_.node,_.offset)):(y.setEnd(_.node,_.offset),S.addRange(y))))),S=[];for(T=k;T=T.parentNode;)1===T.nodeType&&S.push({element:T,left:T.scrollLeft,top:T.scrollTop});for("function"==typeof k.focus&&k.focus(),k=0;k<S.length;k++)(T=S[k]).element.scrollLeft=T.left,T.element.scrollTop=T.top}for(hr=null,Sn=!!pr,pr=null,e.current=t,Ti=r;null!==Ti;){r=!1,k=void 0;try{for(S=n;null!==Ti;){var E=Ti.effectTag;if(36&E){var P=Ti.alternate;switch(y=S,(T=Ti).tag){case 2:case 3:var C=T.stateNode;if(4&T.effectTag)if(null===P)C.props=T.memoizedProps,C.state=T.memoizedState,C.componentDidMount();else{var O=P.memoizedProps,R=P.memoizedState;C.props=T.memoizedProps,C.state=T.memoizedState,C.componentDidUpdate(O,R,C.__reactInternalSnapshotBeforeUpdate)}var j=T.updateQueue;null!==j&&(C.props=T.memoizedProps,C.state=T.memoizedState,ro(0,j,C));break;case 5:var N=T.updateQueue;if(null!==N){if(b=null,null!==T.child)switch(T.child.tag){case 7:b=T.child.stateNode;break;case 2:case 3:b=T.child.stateNode}ro(0,N,b)}break;case 7:var L=T.stateNode;null===P&&4&T.effectTag&&mr(T.type,T.memoizedProps)&&L.focus();break;case 8:case 6:case 15:case 16:break;default:a("163")}}if(128&E){var M=Ti.ref;if(null!==M){var F=Ti.stateNode;switch(Ti.tag){case 7:var U=F;break;default:U=F}"function"==typeof M?M(U):M.current=U}}var A=Ti.nextEffect;Ti.nextEffect=null,Ti=A}}catch(e){r=!0,k=e}r&&(null===Ti&&a("178"),Ni(Ti,k),null!==Ti&&(Ti=Ti.nextEffect))}wi=Ei=!1,"function"==typeof Fr&&Fr(t.stateNode),E=t.expirationTime,t=t.childExpirationTime,0===(t=0===E||0!==t&&t<E?t:E)&&(Pi=null),e.expirationTime=t,e.finishedWork=null}function pa(){return!!Vi||!(null===Ki||Ki.timeRemaining()>oa)&&(Vi=!0)}function ha(e){null===zi&&a("246"),zi.expirationTime=0,$i||($i=!0,qi=e)}function ma(e,t){var n=Yi;Yi=!0;try{return e(t)}finally{(Yi=n)||Wi||sa(1,null)}}function va(e,t){if(Yi&&!Gi){Gi=!0;try{return e(t)}finally{Gi=!1}}return e(t)}function ga(e,t,n){if(Qi)return e(t,n);Yi||Wi||0===Hi||(sa(Hi,null),Hi=0);var r=Qi,o=Yi;Yi=Qi=!0;try{return e(t,n)}finally{Qi=r,(Yi=o)||Wi||sa(1,null)}}function ya(e,t,n,r,o){var i=t.current;return n=function(e){if(!e)return kr;e:{(2!==tn(e=e._reactInternalFiber)||2!==e.tag&&3!==e.tag)&&a("170");var t=e;do{switch(t.tag){case 5:t=t.stateNode.context;break e;case 2:if(Cr(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}break;case 3:if(Cr(t.type._reactResult)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);a("171"),t=void 0}if(2===e.tag){var n=e.type;if(Cr(n))return Nr(e,n,t)}else if(3===e.tag&&Cr(n=e.type._reactResult))return Nr(e,n,t);return t}(n),null===t.context?t.context=n:t.pendingContext=n,t=o,(o=Qr(r)).payload={element:e},null!==(t=void 0===t?null:t)&&(o.callback=t),Jr(i,o),Mi(i,r),r}function ba(e,t,n,r){var o=t.current;return ya(e,t,n,o=Li(la(),o),r)}function wa(e){if(!(e=e.current).child)return null;switch(e.child.tag){case 7:default:return e.child.stateNode}}function _a(e){var t=2+25*(1+((la()-2+500)/25|0));t<=yi&&(t=yi+1),this._expirationTime=yi=t,this._root=e,this._callbacks=this._next=null,this._hasChildren=this._didComplete=!1,this._children=null,this._defer=!0}function xa(){this._callbacks=null,this._didCommit=!1,this._onCommit=this._onCommit.bind(this)}function ka(e,t,n){e={current:t=new Dr(5,null,null,t?3:0),containerInfo:e,pendingChildren:null,earliestPendingTime:0,latestPendingTime:0,earliestSuspendedTime:0,latestSuspendedTime:0,latestPingedTime:0,didError:!1,pendingCommitExpirationTime:0,finishedWork:null,timeoutHandle:-1,context:null,pendingContext:null,hydrate:n,nextExpirationTimeToWorkOn:0,expirationTime:0,firstBatch:null,nextScheduledRoot:null},this._internalRoot=t.stateNode=e}function Sa(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Ta(e,t,n,r,o){Sa(n)||a("200");var i=n._reactRootContainer;if(i){if("function"==typeof o){var l=o;o=function(){var e=wa(i._internalRoot);l.call(e)}}null!=e?i.legacy_renderSubtreeIntoContainer(e,t,o):i.render(t,o)}else{if(i=n._reactRootContainer=function(e,t){if(t||(t=!(!(t=e?9===e.nodeType?e.documentElement:e.firstChild:null)||1!==t.nodeType||!t.hasAttribute("data-reactroot"))),!t)for(var n;n=e.lastChild;)e.removeChild(n);return new ka(e,!1,t)}(n,r),"function"==typeof o){var u=o;o=function(){var e=wa(i._internalRoot);u.call(e)}}va(function(){null!=e?i.legacy_renderSubtreeIntoContainer(e,t,o):i.render(t,o)})}return wa(i._internalRoot)}function Ea(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;return Sa(t)||a("200"),function(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Qe,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}(e,t,null,n)}Ce=function(e,t,n){switch(t){case"input":if(xt(e,n),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var o=W(r);o||a("90"),$e(r),xt(r,o)}}}break;case"textarea":Qn(e,n);break;case"select":null!=(t=n.value)&&Kn(e,!!n.multiple,t,!1)}},_a.prototype.render=function(e){this._defer||a("250"),this._hasChildren=!0,this._children=e;var t=this._root._internalRoot,n=this._expirationTime,r=new xa;return ya(e,t,null,n,r._onCommit),r},_a.prototype.then=function(e){if(this._didComplete)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},_a.prototype.commit=function(){var e=this._root._internalRoot,t=e.firstBatch;if(this._defer&&null!==t||a("251"),this._hasChildren){var n=this._expirationTime;if(t!==this){this._hasChildren&&(n=this._expirationTime=t._expirationTime,this.render(this._children));for(var r=null,o=t;o!==this;)r=o,o=o._next;null===r&&a("251"),r._next=o._next,this._next=t,e.firstBatch=this}this._defer=!1,t=n,Wi&&a("253"),zi=e,Bi=t,fa(e,t,!0),sa(1,null),t=this._next,this._next=null,null!==(t=e.firstBatch=t)&&t._hasChildren&&t.render(t._children)}else this._next=null,this._defer=!1},_a.prototype._onComplete=function(){if(!this._didComplete){this._didComplete=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++)(0,e[t])()}},xa.prototype.then=function(e){if(this._didCommit)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},xa.prototype._onCommit=function(){if(!this._didCommit){this._didCommit=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++){var n=e[t];"function"!=typeof n&&a("191",n),n()}}},ka.prototype.render=function(e,t){var n=this._internalRoot,r=new xa;return null!==(t=void 0===t?null:t)&&r.then(t),ba(e,n,null,r._onCommit),r},ka.prototype.unmount=function(e){var t=this._internalRoot,n=new xa;return null!==(e=void 0===e?null:e)&&n.then(e),ba(null,t,null,n._onCommit),n},ka.prototype.legacy_renderSubtreeIntoContainer=function(e,t,n){var r=this._internalRoot,o=new xa;return null!==(n=void 0===n?null:n)&&o.then(n),ba(t,r,e,o._onCommit),o},ka.prototype.createBatch=function(){var e=new _a(this),t=e._expirationTime,n=this._internalRoot,r=n.firstBatch;if(null===r)n.firstBatch=e,e._next=null;else{for(n=null;null!==r&&r._expirationTime<=t;)n=r,r=r._next;e._next=r,null!==n&&(n._next=e)}return e},Me=ma,Fe=ga,Ue=function(){Wi||0===Hi||(sa(Hi,null),Hi=0)};var Pa={createPortal:Ea,findDOMNode:function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternalFiber;return void 0===t&&("function"==typeof e.render?a("188"):a("268",Object.keys(e))),e=null===(e=rn(t))?null:e.stateNode},hydrate:function(e,t,n){return Ta(null,e,t,!0,n)},render:function(e,t,n){return Ta(null,e,t,!1,n)},unstable_renderSubtreeIntoContainer:function(e,t,n,r){return(null==e||void 0===e._reactInternalFiber)&&a("38"),Ta(e,t,n,!1,r)},unmountComponentAtNode:function(e){return Sa(e)||a("40"),!!e._reactRootContainer&&(va(function(){Ta(null,null,e,!1,function(){e._reactRootContainer=null})}),!0)},unstable_createPortal:function(){return Ea.apply(void 0,arguments)},unstable_batchedUpdates:ma,unstable_interactiveUpdates:ga,flushSync:function(e,t){Wi&&a("187");var n=Yi;Yi=!0;try{return Fi(e,t)}finally{Yi=n,sa(1,null)}},unstable_flushControlled:function(e){var t=Yi;Yi=!0;try{Fi(e)}finally{(Yi=t)||Wi||sa(1,null)}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[D,I,W,j.injectEventPluginsByName,y,q,function(e){E(e,$)},Ne,Le,Cn,L]},unstable_createRoot:function(e,t){return Sa(e)||a("278"),new ka(e,!0,null!=t&&!0===t.hydrate)}};!function(e){var t=e.findFiberByHostInstance;(function(e){if("undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var t=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t.isDisabled||!t.supportsFiber)return!0;try{var n=t.inject(e);Fr=Ar(function(e){return t.onCommitFiberRoot(n,e)}),Ur=Ar(function(e){return t.onCommitFiberUnmount(n,e)})}catch(e){}})(o({},e,{findHostInstanceByFiber:function(e){return null===(e=rn(e))?null:e.stateNode},findFiberByHostInstance:function(e){return t?t(e):null}}))}({findFiberByHostInstance:A,bundleType:0,version:"16.5.2",rendererPackageName:"react-dom"});var Ca={default:Pa},Oa=Ca&&Pa||Ca;e.exports=Oa.default||Oa},function(e,t,n){"use strict";e.exports=n(119)},function(e,t,n){"use strict"; /** @license React v16.5.2 * schedule.production.min.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. */Object.defineProperty(t,"__esModule",{value:!0});var r=null,o=!1,i=!1,a="object"==typeof performance&&"function"==typeof performance.now,l={timeRemaining:a?function(){var e=m()-performance.now();return 0<e?e:0}:function(){var e=m()-Date.now();return 0<e?e:0},didTimeout:!1};function u(){if(!o){var e=r.timesOutAt;i?h():i=!0,p(s,e)}}function c(){var e=r,t=r.next;if(r===t)r=null;else{var n=r.previous;r=n.next=t,t.previous=n}e.next=e.previous=null,(e=e.callback)(l)}function s(e){o=!0,l.didTimeout=e;try{if(e)for(;null!==r;){var n=t.unstable_now();if(!(r.timesOutAt<=n))break;do{c()}while(null!==r&&r.timesOutAt<=n)}else if(null!==r)do{c()}while(null!==r&&0<m()-t.unstable_now())}finally{o=!1,null!==r?u():i=!1}}var f,d,p,h,m,v=Date,g="function"==typeof setTimeout?setTimeout:void 0,y="function"==typeof clearTimeout?clearTimeout:void 0,b="function"==typeof requestAnimationFrame?requestAnimationFrame:void 0,w="function"==typeof cancelAnimationFrame?cancelAnimationFrame:void 0;function _(e){f=b(function(t){y(d),e(t)}),d=g(function(){w(f),e(t.unstable_now())},100)}if(a){var x=performance;t.unstable_now=function(){return x.now()}}else t.unstable_now=function(){return v.now()};if("undefined"==typeof window){var k=-1;p=function(e){k=setTimeout(e,0,!0)},h=function(){clearTimeout(k)},m=function(){return 0}}else if(window._schedMock){var S=window._schedMock;p=S[0],h=S[1],m=S[2]}else{"undefined"!=typeof console&&("function"!=typeof b&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"function"!=typeof w&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"));var T=null,E=!1,P=-1,C=!1,O=!1,R=0,j=33,N=33;m=function(){return R};var L="__reactIdleCallback$"+Math.random().toString(36).slice(2);window.addEventListener("message",function(e){if(e.source===window&&e.data===L){E=!1;var n=t.unstable_now();if(e=!1,0>=R-n){if(!(-1!==P&&P<=n))return void(C||(C=!0,_(M)));e=!0}if(P=-1,n=T,T=null,null!==n){O=!0;try{n(e)}finally{O=!1}}}},!1);var M=function(e){C=!1;var t=e-R+N;t<N&&j<N?(8>t&&(t=8),N=t<j?j:t):j=t,R=e+N,E||(E=!0,window.postMessage(L,"*"))};p=function(e,t){T=e,P=t,O?window.postMessage(L,"*"):C||(C=!0,_(M))},h=function(){T=null,E=!1,P=-1}}t.unstable_scheduleWork=function(e,n){var o=t.unstable_now();if(e={callback:e,timesOutAt:n=null!=n&&null!==n.timeout&&void 0!==n.timeout?o+n.timeout:o+5e3,next:null,previous:null},null===r)r=e.next=e.previous=e,u();else{o=null;var i=r;do{if(i.timesOutAt>n){o=i;break}i=i.next}while(i!==r);null===o?o=r:o===r&&(r=e,u()),(n=o.previous).next=o.previous=e,e.next=o,e.previous=n}return e},t.unstable_cancelScheduledWork=function(e){var t=e.next;if(null!==t){if(t===e)r=null;else{e===r&&(r=t);var n=e.previous;n.next=t,t.previous=n}e.next=e.previous=null}}},function(e,t,n){"use strict";var r=n(121);function o(){}e.exports=function(){function e(e,t,n,o,i,a){if(a!==r){var l=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw l.name="Invariant Violation",l}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=o,n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";var r=n(35);t.__esModule=!0,t.default=void 0;var o=r(n(7)),i=r(n(50)),a=r(n(51)),l=r(n(0)),u=r(n(123)),c=r(n(4)),s=n(130),f=r(n(131)),d={shouldUpdateScroll:c.default.func,children:c.default.element.isRequired,location:c.default.object.isRequired},p={scrollBehavior:c.default.object.isRequired},h=function(e){function t(t,n){var r;return r=e.call(this,t,n)||this,(0,a.default)((0,i.default)((0,i.default)(r)),"shouldUpdateScroll",function(e,t){var n=r.props.shouldUpdateScroll;return!n||n.call(r.scrollBehavior,e,t)}),(0,a.default)((0,i.default)((0,i.default)(r)),"registerElement",function(e,t,n){r.scrollBehavior.registerElement(e,t,n,r.getRouterProps())}),(0,a.default)((0,i.default)((0,i.default)(r)),"unregisterElement",function(e){r.scrollBehavior.unregisterElement(e)}),r.scrollBehavior=new u.default({addTransitionHook:s.globalHistory.listen,stateStorage:new f.default,getCurrentLocation:function(){return r.props.location},shouldUpdateScroll:r.shouldUpdateScroll}),r.scrollBehavior.updateScroll(null,r.getRouterProps()),r}(0,o.default)(t,e);var n=t.prototype;return n.getChildContext=function(){return{scrollBehavior:this}},n.componentDidUpdate=function(e){var t=this.props.location;if(t!==e.location){var n={location:e.location};window.__navigatingToLink?t.action="PUSH":t.action="POP",this.scrollBehavior.updateScroll(n,{history:s.globalHistory,location:t})}},n.componentWillUnmount=function(){this.scrollBehavior.stop()},n.getRouterProps=function(){return{location:this.props.location,history:s.globalHistory}},n.render=function(){return l.default.Children.only(this.props.children)},t}(l.default.Component);h.propTypes=d,h.childContextTypes=p;var m=h;t.default=m},function(e,t,n){"use strict";t.__esModule=!0;var r=s(n(124)),o=s(n(125)),i=s(n(126)),a=s(n(127)),l=s(n(128)),u=s(n(9)),c=n(129);function s(e){return e&&e.__esModule?e:{default:e}}var f=2,d=function(){function e(t){var n=this,r=t.addTransitionHook,u=t.stateStorage,s=t.getCurrentLocation,d=t.shouldUpdateScroll;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._onWindowScroll=function(){if(n._saveWindowPositionHandle||(n._saveWindowPositionHandle=(0,l.default)(n._saveWindowPosition)),n._windowScrollTarget){var e=n._windowScrollTarget,t=e[0],r=e[1],o=(0,i.default)(window),u=(0,a.default)(window);o===t&&u===r&&(n._windowScrollTarget=null,n._cancelCheckWindowScroll())}},this._saveWindowPosition=function(){n._saveWindowPositionHandle=null,n._savePosition(null,window)},this._checkWindowScrollPosition=function(){n._checkWindowScrollHandle=null,n._windowScrollTarget&&(n.scrollToTarget(window,n._windowScrollTarget),++n._numWindowScrollAttempts,n._numWindowScrollAttempts>=f?n._windowScrollTarget=null:n._checkWindowScrollHandle=(0,l.default)(n._checkWindowScrollPosition))},this._stateStorage=u,this._getCurrentLocation=s,this._shouldUpdateScroll=d,"scrollRestoration"in window.history&&!(0,c.isMobileSafari)()){this._oldScrollRestoration=window.history.scrollRestoration;try{window.history.scrollRestoration="manual"}catch(e){this._oldScrollRestoration=null}}else this._oldScrollRestoration=null;this._saveWindowPositionHandle=null,this._checkWindowScrollHandle=null,this._windowScrollTarget=null,this._numWindowScrollAttempts=0,this._scrollElements={},(0,o.default)(window,"scroll",this._onWindowScroll),this._removeTransitionHook=r(function(){l.default.cancel(n._saveWindowPositionHandle),n._saveWindowPositionHandle=null,Object.keys(n._scrollElements).forEach(function(e){var t=n._scrollElements[e];l.default.cancel(t.savePositionHandle),t.savePositionHandle=null,n._saveElementPosition(e)})})}return e.prototype.registerElement=function(e,t,n,r){var i=this;this._scrollElements[e]&&(0,u.default)(!1);var a=function(){i._saveElementPosition(e)},c={element:t,shouldUpdateScroll:n,savePositionHandle:null,onScroll:function(){c.savePositionHandle||(c.savePositionHandle=(0,l.default)(a))}};this._scrollElements[e]=c,(0,o.default)(t,"scroll",c.onScroll),this._updateElementScroll(e,null,r)},e.prototype.unregisterElement=function(e){this._scrollElements[e]||(0,u.default)(!1);var t=this._scrollElements[e],n=t.element,o=t.onScroll,i=t.savePositionHandle;(0,r.default)(n,"scroll",o),l.default.cancel(i),delete this._scrollElements[e]},e.prototype.updateScroll=function(e,t){var n=this;this._updateWindowScroll(e,t),Object.keys(this._scrollElements).forEach(function(r){n._updateElementScroll(r,e,t)})},e.prototype.stop=function(){if(this._oldScrollRestoration)try{window.history.scrollRestoration=this._oldScrollRestoration}catch(e){}(0,r.default)(window,"scroll",this._onWindowScroll),this._cancelCheckWindowScroll(),this._removeTransitionHook()},e.prototype._cancelCheckWindowScroll=function(){l.default.cancel(this._checkWindowScrollHandle),this._checkWindowScrollHandle=null},e.prototype._saveElementPosition=function(e){var t=this._scrollElements[e];t.savePositionHandle=null,this._savePosition(e,t.element)},e.prototype._savePosition=function(e,t){this._stateStorage.save(this._getCurrentLocation(),e,[(0,i.default)(t),(0,a.default)(t)])},e.prototype._updateWindowScroll=function(e,t){this._cancelCheckWindowScroll(),this._windowScrollTarget=this._getScrollTarget(null,this._shouldUpdateScroll,e,t),this._numWindowScrollAttempts=0,this._checkWindowScrollPosition()},e.prototype._updateElementScroll=function(e,t,n){var r=this._scrollElements[e],o=r.element,i=r.shouldUpdateScroll,a=this._getScrollTarget(e,i,t,n);a&&this.scrollToTarget(o,a)},e.prototype._getDefaultScrollTarget=function(e){var t=e.hash;return t&&"#"!==t?"#"===t.charAt(0)?t.slice(1):t:[0,0]},e.prototype._getScrollTarget=function(e,t,n,r){var o=!t||t.call(this,n,r);if(!o||Array.isArray(o)||"string"==typeof o)return o;var i=this._getCurrentLocation();return this._getSavedScrollTarget(e,i)||this._getDefaultScrollTarget(i)},e.prototype._getSavedScrollTarget=function(e,t){return"PUSH"===t.action?null:this._stateStorage.read(t,e)},e.prototype.scrollToTarget=function(e,t){if("string"==typeof t){var n=document.getElementById(t)||document.getElementsByName(t)[0];if(n)return void n.scrollIntoView();t=[0,0]}var r=t,o=r[0],l=r[1];(0,i.default)(e,o),(0,a.default)(e,l)},e}();t.default=d,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,o=n(45);var i=function(){};((r=o)&&r.__esModule?r:{default:r}).default&&(i=document.addEventListener?function(e,t,n,r){return e.removeEventListener(t,n,r||!1)}:document.attachEvent?function(e,t,n){return e.detachEvent("on"+t,n)}:void 0),t.default=i,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,o=n(45);var i=function(){};((r=o)&&r.__esModule?r:{default:r}).default&&(i=document.addEventListener?function(e,t,n,r){return e.addEventListener(t,n,r||!1)}:document.attachEvent?function(e,t,n){return e.attachEvent("on"+t,function(t){(t=t||window.event).target=t.target||t.srcElement,t.currentTarget=e,n.call(e,t)})}:void 0),t.default=i,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var n=(0,i.default)(e);if(void 0===t)return n?"pageXOffset"in n?n.pageXOffset:n.document.documentElement.scrollLeft:e.scrollLeft;n?n.scrollTo(t,"pageYOffset"in n?n.pageYOffset:n.document.documentElement.scrollTop):e.scrollLeft=t};var r,o=n(70),i=(r=o)&&r.__esModule?r:{default:r};e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var n=(0,i.default)(e);if(void 0===t)return n?"pageYOffset"in n?n.pageYOffset:n.document.documentElement.scrollTop:e.scrollTop;n?n.scrollTo("pageXOffset"in n?n.pageXOffset:n.document.documentElement.scrollLeft,t):e.scrollTop=t};var r,o=n(70),i=(r=o)&&r.__esModule?r:{default:r};e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,o=n(45),i=(r=o)&&r.__esModule?r:{default:r};var a,l="clearTimeout",u=function(e){var t=(new Date).getTime(),n=Math.max(0,16-(t-s)),r=setTimeout(e,n);return s=t,r},c=function(e,t){return e+(e?t[0].toUpperCase()+t.substr(1):t)+"AnimationFrame"};i.default&&["","webkit","moz","o","ms"].some(function(e){var t=c(e,"request");if(t in window)return l=c(e,"cancel"),u=function(e){return window[t](e)}});var s=(new Date).getTime();(a=function(e){return u(e)}).cancel=function(e){window[l]&&"function"==typeof window[l]&&window[l](e)},t.default=a,e.exports=t.default},function(e,t,n){"use strict";t.__esModule=!0,t.isMobileSafari=function(){return/iPad|iPhone|iPod/.test(window.navigator.platform)&&/^((?!CriOS).)*Safari/.test(window.navigator.userAgent)}},function(e,t,n){"use strict";t.__esModule=!0;var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=function(e){return r({},e.location,{state:e.history.state,key:e.history.state&&e.history.state.key||"initial"})},i=function(e,t){var n=[],i=o(e),a=!1,l=function(){};return{get location(){return i},get transitioning(){return a},_onTransitionComplete:function(){a=!1,l()},listen:function(t){n.push(t);var r=function(){i=o(e),t({location:i,action:"POP"})};return e.addEventListener("popstate",r),function(){e.removeEventListener("popstate",r),n=n.filter(function(e){return e!==t})}},navigate:function(t){var u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},c=u.state,s=u.replace,f=void 0!==s&&s;c=r({},c,{key:Date.now()+""});try{a||f?e.history.replaceState(c,null,t):e.history.pushState(c,null,t)}catch(n){e.location[f?"replace":"assign"](t)}i=o(e),a=!0;var d=new Promise(function(e){return l=e});return n.forEach(function(e){return e({location:i,action:"PUSH"})}),d}}},a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",t=0,n=[{pathname:e,search:""}],r=[];return{get location(){return n[t]},addEventListener:function(e,t){},removeEventListener:function(e,t){},history:{get entries(){return n},get index(){return t},get state(){return r[t]},pushState:function(e,o,i){var a=i.split("?"),l=a[0],u=a[1],c=void 0===u?"":u;t++,n.push({pathname:l,search:c}),r.push(e)},replaceState:function(e,o,i){var a=i.split("?"),l=a[0],u=a[1],c=void 0===u?"":u;n[t]={pathname:l,search:c},r[t]=e}}}},l=i(!("undefined"==typeof window||!window.document||!window.document.createElement)?window:a()),u=l.navigate;t.globalHistory=l,t.navigate=u,t.createHistory=i,t.createMemorySource=a},function(e,t,n){"use strict";t.__esModule=!0,t.default=void 0;var r=function(){function e(){}var t=e.prototype;return t.read=function(e,t){var n=this.getStateKey(e,t);try{var r=window.sessionStorage.getItem(n);return JSON.parse(r)}catch(e){return console.warn("[gatsby-react-router-scroll] Unable to access sessionStorage; sessionStorage is not available."),window&&window.___GATSBY_REACT_ROUTER_SCROLL&&window.___GATSBY_REACT_ROUTER_SCROLL[n]?window.___GATSBY_REACT_ROUTER_SCROLL[n]:{}}},t.save=function(e,t,n){var r=this.getStateKey(e,t),o=JSON.stringify(n);try{window.sessionStorage.setItem(r,o)}catch(e){window&&window.___GATSBY_REACT_ROUTER_SCROLL?window.___GATSBY_REACT_ROUTER_SCROLL[r]=JSON.parse(o):(window.___GATSBY_REACT_ROUTER_SCROLL={},window.___GATSBY_REACT_ROUTER_SCROLL[r]=JSON.parse(o)),console.warn("[gatsby-react-router-scroll] Unable to save state in sessionStorage; sessionStorage is not available.")}},t.getStateKey=function(e,t){var n="@@scroll|"+e.pathname;return null==t?n:n+"|"+t},e}();t.default=r},function(e,t,n){"use strict";var r=n(35);t.__esModule=!0,t.default=void 0;var o=r(n(7)),i=r(n(50)),a=r(n(51)),l=r(n(0)),u=r(n(46)),c=(r(n(69)),r(n(4))),s={scrollKey:c.default.string.isRequired,shouldUpdateScroll:c.default.func,children:c.default.element.isRequired},f={scrollBehavior:c.default.object},d=function(e){function t(t,n){var r;return r=e.call(this,t,n)||this,(0,a.default)((0,i.default)((0,i.default)(r)),"shouldUpdateScroll",function(e,t){var n=r.props.shouldUpdateScroll;return!n||n.call(r.context.scrollBehavior.scrollBehavior,e,t)}),r.scrollKey=t.scrollKey,r}(0,o.default)(t,e);var n=t.prototype;return n.componentDidMount=function(){this.context.scrollBehavior.registerElement(this.props.scrollKey,u.default.findDOMNode(this),this.shouldUpdateScroll)},n.componentDidUpdate=function(e){},n.componentWillUnmount=function(){this.context.scrollBehavior.unregisterElement(this.scrollKey)},n.render=function(){return this.props.children},t}(l.default.Component);d.propTypes=s,d.contextTypes=f;var p=d;t.default=p},function(e,t,n){"use strict";var r=n(6),o=n(56)(!1),i=[].indexOf,a=!!i&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(a||!n(14)(i)),"Array",{indexOf:function(e){return a?i.apply(this,arguments)||0:o(this,e,arguments[1])}})},function(e,t,n){"use strict";n.r(t);var r=n(1);"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(function(e){e.addEventListener("updatefound",function(){Object(r.apiRunner)("onServiceWorkerUpdateFound",{serviceWorker:e});var t=e.installing;console.log("installingWorker",t),t.addEventListener("statechange",function(){switch(t.state){case"installed":navigator.serviceWorker.controller?window.GATSBY_SW_UPDATED=!0:(console.log("Content is now available offline!"),Object(r.apiRunner)("onServiceWorkerInstalled",{serviceWorker:e}));break;case"redundant":console.error("The installing service worker became redundant."),Object(r.apiRunner)("onServiceWorkerRedundant",{serviceWorker:e});break;case"activated":Object(r.apiRunner)("onServiceWorkerActive",{serviceWorker:e})}})})}).catch(function(e){console.error("Error during service worker registration:",e)})},function(e,t,n){"use strict";n.r(t);n(52),n(55),n(34);var r=n(7),o=n.n(r),i=n(1),a=n(0),l=n.n(a),u=n(46),c=n.n(u),s=n(15),f=n(24),d=n(72),p=n(73),h=n.n(p),m=(n(32),n(62),n(4)),v=n.n(m),g=n(2),y=n(74),b=n(8),w=n(33);n(43);function _(e){var t=new URL(e,window.location.origin);return t.search.match(/\?(.*&)?no-cache=1(&|$)/)?(console.log("Found no-cache=1 while attempting to load a page directly; this is likely due to a bug in Gatsby, or a misconfiguration in your project."),!1):(t.search?t.search+="&no-cache=1":t.search="?no-cache=1",t)}var x=function(e,t,n){return void 0===n&&(n=!1),new Promise(function(r,o){var i=_(t);if(!i)return o(i);e?fetch(i.href).then(function(e){404!==e.status?n?window.location.replace(i):window.location=i:r()}).catch(function(){window.location=i}):window.location=i})},k=y.reduce(function(e,t){return e[t.fromPath]=t,e},{});function S(e){var t=k[e];return null!=t&&(window.___replace(t.toPath),!0)}var T=function(e){S(e.pathname)||Object(i.apiRunner)("onPreRouteUpdate",{location:e})},E=function(e){S(e.pathname)||(Object(i.apiRunner)("onRouteUpdate",{location:e}),window.__navigatingToLink=!1)},P=function(e,t){void 0===t&&(t={}),t.replace||(window.__navigatingToLink=!0);var n=Object(w.a)(e).pathname,r=k[n];if(r&&(e=r.toPath,n=Object(w.a)(e).pathname),window.GATSBY_SW_UPDATED)window.location=n;else{var o=setTimeout(function(){b.a.emit("onDelayedLoadPageResources",{pathname:n}),Object(i.apiRunner)("onRouteUpdateDelayed",{location:window.location})},1e3);g.default.getResourcesForPathname(n).then(function(n){n&&"/404.html"!==n.page.path?(Object(s.navigate)(e,t),clearTimeout(o)):(clearTimeout(o),x(n,e).then(function(){return Object(s.navigate)(e,t)}))})}};function C(e,t){var n=this,r=t.location,o=r.pathname,a=r.hash,l=Object(i.apiRunner)("shouldUpdateScroll",{prevRouterProps:e,pathname:o,routerProps:{location:r},getSavedScrollPosition:function(e){return n._stateStorage.read(e)}});if(l.length>0)return l[0];if(e&&e.location.pathname===o)return a?a.slice(1):[0,0];return!0}var O=function(e){function t(t){var n;return n=e.call(this,t)||this,T(t.location),n}o()(t,e);var n=t.prototype;return n.componentDidMount=function(){E(this.props.location)},n.componentDidUpdate=function(e,t,n){n&&E(this.props.location)},n.getSnapshotBeforeUpdate=function(e){return this.props.location.pathname!==e.location.pathname&&(T(this.props.location),!0)},n.render=function(){return this.props.children},t}(l.a.Component);O.propTypes={location:v.a.object.isRequired};var R=n(48),j=n(47),N=n.n(j);function L(e,t){for(var n in e)if(!(n in t))return!0;for(var r in t)if(e[r]!==t[r])return!0;return!1}var M=function(e){function t(t){var n;n=e.call(this)||this;var r=t.location;return n.state={location:Object.assign({},r),pageResources:g.default.getResourcesForPathnameSync(r.pathname)},n}o()(t,e),t.getDerivedStateFromProps=function(e,t){e.pageResources;var n=e.location;if(t.location!==n){var r=g.default.getResourcesForPathnameSync(n.pathname);if(r)return{pageResources:r,location:Object.assign({},n)}}return null};var n=t.prototype;return n.componentDidUpdate=function(e){var t=this;if(e!==this.props){var n=this.props.location.pathname;g.default.getResourcesForPathnameSync(n)||g.default.getResourcesForPathname(n).then(function(e){t.props.location.pathname===location.pathname&&t.setState({location:Object.assign({},location),pageResources:e})})}},n.shouldComponentUpdate=function(e,t){return!t.pageResources||(!(this.state.pageResources||!t.pageResources)||(this.state.pageResources.component!==t.pageResources.component||(this.state.pageResources.json!==t.pageResources.json||(!(this.state.location.key===t.location.key||!t.pageResources.page||!t.pageResources.page.matchPath&&!t.pageResources.page.path)||function(e,t,n){return L(e.props,t)||L(e.state,n)}(this,e,t)))))},n.render=function(){if(!this.state.pageResources||!this.state.pageResources.json){var e=_(this.state.location.href);return e&&window.location.replace(e),null}return this.props.children(this.state)},t}(l.a.Component);M.propTypes={location:v.a.object.isRequired,pageResources:v.a.object};var F,U=M;window.___emitter=b.a,window.asyncRequires=N.a,window.___emitter=b.a,window.___loader=g.default,g.default.addPagesArray([window.page]),g.default.addDataPaths(((F={})[window.page.jsonName]=window.dataPath,F)),g.default.addProdRequires(N.a),window.__navigatingToLink=!1,Object(g.setApiRunnerForLoader)(i.apiRunner),window.___loader=g.default,window.___push=function(e){return P(e,{replace:!1})},window.___replace=function(e){return P(e,{replace:!0})},window.___navigate=function(e,t){return P(e,t)},S(window.location.pathname),Object(i.apiRunnerAsync)("onClientEntry").then(function(){Object(i.apiRunner)("registerServiceWorker").length>0&&n(134);var e=function(e){function t(){return e.apply(this,arguments)||this}return o()(t,e),t.prototype.render=function(){var e=this,t=this.props.location;return l.a.createElement(U,{location:t},function(t){var n=t.pageResources,r=t.location;return l.a.createElement(O,{location:r},l.a.createElement(d.ScrollContext,{location:r,shouldUpdateScroll:C},l.a.createElement(R.a,Object.assign({},e.props,{location:r,pageResources:n},n.json))))})},t}(l.a.Component),t=window,r=t.page,u=t.location;!r||"/404.html"===r.path||""+r.path===u.pathname||r.path.match(/^\/offline-plugin-app-shell-fallback\/?$/)||r.matchPath&&Object(f.match)(""+r.matchPath,u.pathname)||Object(s.navigate)(""+r.path+u.search+u.hash,{replace:!0}),g.default.getResourcesForPathname(u.pathname).then(function(e){return e&&"/404.html"!==e.page.path?null:x(e,u.pathname+u.search+u.hash,!0)}).then(function(){var t=function(){return Object(a.createElement)(s.Router,{basepath:""},Object(a.createElement)(e,{path:"/*"}))},n=Object(i.apiRunner)("wrapRootElement",{element:l.a.createElement(t,null)},l.a.createElement(t,null),function(e){return{element:e.result}}).pop(),r=function(){return n},o=Object(i.apiRunner)("replaceHydrateFunction",void 0,c.a.hydrate)[0];h()(function(){o(l.a.createElement(r,null),"undefined"!=typeof window?document.getElementById("___gatsby"):void 0,function(){Object(i.apiRunner)("onInitialClientRender")})})})})}],[[135,9]]]); //# sourceMappingURL=app-ad614d89d07617869c6d.js.map
/* * Copyright (C) 2008 Karel Zak <[email protected]> * * Inspired by libvolume_id by * Kay Sievers <[email protected]> * * This file may be redistributed under the terms of the * GNU Lesser General Public License. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include "superblocks.h" struct adaptec_metadata { uint32_t b0idcode; uint8_t lunsave[8]; uint16_t sdtype; uint16_t ssavecyl; uint8_t ssavehed; uint8_t ssavesec; uint8_t sb0flags; uint8_t jbodEnable; uint8_t lundsave; uint8_t svpdirty; uint16_t biosInfo; uint16_t svwbskip; uint16_t svwbcln; uint16_t svwbmax; uint16_t res3; uint16_t svwbmin; uint16_t res4; uint16_t svrcacth; uint16_t svwcacth; uint16_t svwbdly; uint8_t svsdtime; uint8_t res5; uint16_t firmval; uint16_t firmbln; uint32_t firmblk; uint32_t fstrsvrb; uint16_t svBlockStorageTid; uint16_t svtid; uint8_t svseccfl; uint8_t res6; uint8_t svhbanum; uint8_t resver; uint32_t drivemagic; uint8_t reserved[20]; uint8_t testnum; uint8_t testflags; uint16_t maxErrorCount; uint32_t count; uint32_t startTime; uint32_t interval; uint8_t tstxt0; uint8_t tstxt1; uint8_t serNum[32]; uint8_t res8[102]; uint32_t fwTestMagic; uint32_t fwTestSeqNum; uint8_t fwTestRes[8]; uint32_t smagic; uint32_t raidtbl; uint16_t raidline; uint8_t res9[0xF6]; } __attribute__((packed)); #define AD_SIGNATURE 0x4450544D /* "DPTM" */ #define AD_MAGIC 0x37FC4D1E static int probe_adraid(blkid_probe pr, const struct blkid_idmag *mag __attribute__((__unused__))) { uint64_t off; struct adaptec_metadata *ad; if (pr->size < 0x10000) return BLKID_PROBE_NONE; if (!S_ISREG(pr->mode) && !blkid_probe_is_wholedisk(pr)) return BLKID_PROBE_NONE; off = ((pr->size / 0x200)-1) * 0x200; ad = (struct adaptec_metadata *) blkid_probe_get_buffer(pr, off, sizeof(struct adaptec_metadata)); if (!ad) return errno ? -errno : BLKID_PROBE_NONE;; if (ad->smagic != be32_to_cpu(AD_SIGNATURE)) return BLKID_PROBE_NONE; if (ad->b0idcode != be32_to_cpu(AD_MAGIC)) return BLKID_PROBE_NONE; if (blkid_probe_sprintf_version(pr, "%u", ad->resver) != 0) return BLKID_PROBE_NONE; if (blkid_probe_set_magic(pr, off, sizeof(ad->b0idcode), (unsigned char *) &ad->b0idcode)) return BLKID_PROBE_NONE; return BLKID_PROBE_OK; } const struct blkid_idinfo adraid_idinfo = { .name = "adaptec_raid_member", .usage = BLKID_USAGE_RAID, .probefunc = probe_adraid, .magics = BLKID_NONE_MAGIC };
class TestEndpointsHandlerWithAuth(AsyncHTTPTestCase): @classmethod def setUpClass(cls): cls.patcher = patch("tabpy.tabpy_server.app.app.TabPyApp._parse_cli_arguments", return_value=Namespace(config=None)) cls.patcher.start() prefix = "__TestEndpointsHandlerWithAuth_" cls.pwd_file = tempfile.NamedTemporaryFile(mode="w+t", prefix=prefix, suffix=".txt", delete=False) username = "username" password = "password" cls.pwd_file.write(f"{username} {hash_password(username, password)}") cls.pwd_file.close() cls.state_dir = tempfile.mkdtemp(prefix=prefix) cls.state_file = open(os.path.join(cls.state_dir, "state.ini"), "w+") cls.state_file.write("[Service Info]\n" "Name = TabPy Serve\n" "Description = \n" "Creation Time = 0\n" "Access-Control-Allow-Origin = \n" "Access-Control-Allow-Headers = \n" "Access-Control-Allow-Methods = \n" "\n" "[Query Objects Service Versions]\n" "\n" "[Query Objects Docstrings]\n" "\n" "[Meta]\n" "Revision Number = 1\n") cls.state_file.close() cls.config_file = tempfile.NamedTemporaryFile(mode="w+t", prefix=prefix, suffix=".conf", delete=False) cls.config_file.write("[TabPy]\n" f"TABPY_PWD_FILE = {cls.pwd_file.name}\n" f"TABPY_STATE_PATH = {cls.state_dir}") cls.config_file.close() @classmethod def tearDownClass(cls): cls.patcher.stop() os.remove(cls.pwd_file.name) os.remove(cls.state_file.name) os.remove(cls.config_file.name) os.rmdir(cls.state_dir) def get_app(self): self.app = TabPyApp(self.config_file.name) return self.app._create_tornado_web_app() def test_no_creds_required_auth_fails(self): response = self.fetch("/endpoints") self.assertEqual(401, response.code) def test_invalid_creds_fails(self): response = self.fetch("/endpoints", method="GET", headers={"Authorization": "Basic {}".format(base64.b64encode("user:wrong_password".encode("utf-8")).decode("utf-8"))}) self.assertEqual(401, response.code) def test_valid_creds_pass(self): response = self.fetch("/endpoints", method="GET", headers={"Authorization": "Basic {}".format(base64.b64encode("username:password".encode("utf-8")).decode("utf-8"))}) self.assertEqual(200, response.code)
from musictaxonomy.auth import service as auth_service from musictaxonomy.handlers import BaseAPIHandler from musictaxonomy.spotify import service as spotify_service class LoginHandler(BaseAPIHandler): async def get(self): """ Before using Music Taxonomy, a user must authenticate with Spotify's Oauth. This endpoint is the first step in that authentication flow. We redirect to Spotify's login page, passing query parameters to identify our application and specify which scopes the application requires. We also pass a redirect URL parameter, which Spotify will use once the user logs in successfully. For more information, see: https://developer.spotify.com/documentation/general/guides/authorization-guide """ access_token = self.get_access_token() is_access_token_valid = await auth_service.is_access_token_valid(access_token) # User is already logged in, so redirect them to the core application. if is_access_token_valid: return self.redirect("/", permanent=False) redirect_base_url = "{protocol}://{host}".format( protocol=self.request.protocol, host=self.request.host ) spotify_authorize_url = auth_service.generate_spotify_authorize_url( redirect_base_url ) return self.redirect(spotify_authorize_url, permanent=False) class OauthCallbackHandler(BaseAPIHandler): async def get(self): """ This endpoint is the second and final step of the authentication flow. At this point the user has logged in successfully to Spotify, and the user has been redirected back to Music Taxonomy with an authorization code. We exchange this authorization code for an access token by making a request to Spotify, passing our application's credentials. Once we receive the access token, we redirect to the IndexHandler so the user can start using the application. For more information, see: https://developer.spotify.com/documentation/general/guides/authorization-guide """ authorization_code = self.get_argument("code") # Exchange the authorization code for an access token from Spotify. redirect_base_url = "{protocol}://{host}".format( protocol=self.request.protocol, host=self.request.host ) access_token = await auth_service.get_spotify_access_token( authorization_code, redirect_base_url ) # Set the access token as a cookie. self.set_secure_cookie("AccessToken", access_token) # Create a new User in the database if one does not already exist. spotify_user = await spotify_service.get_spotify_user(access_token) await auth_service.create_new_user_if_necessary(spotify_user) # Redirect the user to the core application. return self.redirect("/", permanent=False)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) The James Hutton Institute 2016-2019 # (c) University of Strathclyde 2019-2020 # Author: Leighton Pritchard # # Contact: # [email protected] # # Leighton Pritchard, # Strathclyde Institute for Pharmacy and Biomedical Sciences, # 161 Cathedral Street, # Glasgow, # G4 0RE # Scotland, # UK # # The MIT License # # Copyright (c) 2016-2019 The James Hutton Institute # Copyright (c) 2019-2020 University of Strathclyde # # 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. """Test legacy scripts. The test suite is intended to be run from the repository root using: pytest -v The two legacy scripts download genomes, then carry out ANI analysis. The pytest ordering plug-in is used to guarantee that the download script tests are conducted first. """ import copy from argparse import Namespace from pathlib import Path import pytest from pyani.pyani_config import ( BLASTALL_DEFAULT, BLASTN_DEFAULT, FILTER_DEFAULT, FORMATDB_DEFAULT, MAKEBLASTDB_DEFAULT, NUCMER_DEFAULT, ) from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon from tools import modify_namespace @pytest.fixture def legacy_ani_namespace(path_fixtures_base, tmp_path): """Base namespace for legacy average_nucleotide_identity.py tests.""" return Namespace( outdirname=tmp_path, indirname=path_fixtures_base / "legacy" / "ANI_input", verbose=False, debug=False, force=True, fragsize=1020, logfile=Path("test_ANIm.log"), skip_nucmer=False, skip_blastn=False, noclobber=False, nocompress=False, graphics=True, gformat="pdf,png", gmethod="seaborn", labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt", classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt", method="ANIm", scheduler="multiprocessing", workers=None, sgeargs=None, sgegroupsize=10000, maxmatch=False, nucmer_exe=NUCMER_DEFAULT, filter_exe=FILTER_DEFAULT, blastn_exe=BLASTN_DEFAULT, blastall_exe=BLASTALL_DEFAULT, makeblastdb_exe=MAKEBLASTDB_DEFAULT, formatdb_exe=FORMATDB_DEFAULT, write_excel=False, rerender=False, subsample=None, seed=None, jobprefix="ANI", ) @pytest.fixture def legacy_anib_sns_namespace(tmp_path, legacy_ani_namespace): """Namespace for legacy ANIm script tests. Uses the base namespace to run ANIm with seaborn output """ return modify_namespace(legacy_ani_namespace, method="ANIb") @pytest.fixture def legacy_anib_mpl_namespace(tmp_path, legacy_ani_namespace): """Namespace for legacy ANIm script tests. Runs ANIm with matplotlib output """ return modify_namespace(legacy_ani_namespace, gmethod="mpl", method="ANIb") @pytest.fixture def legacy_anim_sns_namespace(tmp_path, legacy_ani_namespace): """Namespace for legacy ANIm script tests. Uses the base namespace to run ANIm with seaborn output """ return legacy_ani_namespace @pytest.fixture def legacy_anim_mpl_namespace(tmp_path, legacy_ani_namespace): """Namespace for legacy ANIm script tests. Runs ANIm with matplotlib output """ return modify_namespace(legacy_ani_namespace, gmethod="mpl") @pytest.fixture def legacy_download_namespace(tmp_path): """Namespace for legacy download script tests.""" return Namespace( outdirname=tmp_path, taxon="203804", verbose=False, force=True, noclobber=False, logfile=None, format="fasta", email="[email protected]", retries=20, batchsize=10000, timeout=10, debug=False, ) @pytest.fixture def legacy_tetra_sns_namespace(tmp_path, legacy_ani_namespace): """Namespace for legacy ANIm script tests. Uses the base namespace to run ANIm with seaborn output """ return modify_namespace(legacy_ani_namespace, method="TETRA") @pytest.fixture def legacy_tetra_mpl_namespace(tmp_path, legacy_ani_namespace): """Namespace for legacy ANIm script tests. Uses the base namespace to run ANIm with mpl output """ return modify_namespace(legacy_ani_namespace, method="TETRA", gmethod="mpl") @pytest.mark.skip_if_exe_missing("nucmer") def test_legacy_anim_sns(legacy_anim_sns_namespace): r"""Use legacy script to run ANIm (seaborn output). average_nucleotide_identity.py \ -l test_ANIm.log \ -i tests/fixtures/legacy/ANI_input \ -o tests/test_output/legacy_scripts/ANIm_seaborn \ -g --gmethod seaborn --gformat pdf,png \ -f --jobprefix ANI """ average_nucleotide_identity.run_main(legacy_anim_sns_namespace) @pytest.mark.skip_if_exe_missing("nucmer") def test_legacy_anim_mpl(legacy_anim_mpl_namespace): r"""Use legacy script to run ANIm (mpl output). average_nucleotide_identity.py \ -l test_ANIm.log \ -i tests/fixtures/legacy/ANI_input \ -o tests/test_output/legacy_scripts/ANIm_mpl \ -g --gmethod mpl --gformat pdf,png \ -f --jobprefix ANI """ average_nucleotide_identity.run_main(legacy_anim_mpl_namespace) @pytest.mark.skip_if_exe_missing("blastn") def test_legacy_anib_sns(legacy_anib_sns_namespace): r"""Use legacy script to run ANIb (seaborn output). average_nucleotide_identity.py \ -l test_ANIb.log \ -i tests/test_output/legacy_scripts/C_blochmannia \ -o tests/test_output/legacy_scripts/ANIb_seaborn \ -g --gmethod seaborn --gformat pdf,png \ -f --jobprefix ANI """ average_nucleotide_identity.run_main(legacy_anib_sns_namespace) @pytest.mark.skip_if_exe_missing("blastn") def test_legacy_anib_mpl(legacy_anib_mpl_namespace): r"""Use legacy script to run ANIb (mpl output). average_nucleotide_identity.py \ -l test_ANIb.log \ -i tests/test_output/legacy_scripts/C_blochmannia \ -o tests/test_output/legacy_scripts/ANIb_mpl \ -g --gmethod mpl --gformat pdf,png \ -f --jobprefix ANI """ average_nucleotide_identity.run_main(legacy_anib_mpl_namespace) def test_legacy_tetra_sns(legacy_tetra_sns_namespace): r"""Use legacy script to run TETRA (seaborn output).""" average_nucleotide_identity.run_main(legacy_tetra_sns_namespace) def test_legacy_tetra_mpl(legacy_tetra_mpl_namespace): r"""Use legacy script to run TETRA (mpl output).""" average_nucleotide_identity.run_main(legacy_tetra_mpl_namespace) def test_legacy_genome_downloads( legacy_download_namespace, mock_legacy_single_genome_dl ): r"""Use legacy script to download genomes; mocks file downloading. Otherwise emulates a command such as: genbank_get_genomes_by_taxon.py \ -o tests/fixtures/legacy/ANI_input \ --email [email protected] \ -t 203804 -f """ genbank_get_genomes_by_taxon.run_main(legacy_download_namespace)
""" @author: Leon Elaiza @license: MIT license @contact: [email protected] @file: map_streetview_spider.py @time: 2020/9/10 3:50 下午 @desc: An spider for acquiring streetview images """ from typing import List, Dict import os import requests from requests import Response from urllib.request import urlretrieve from urllib.parse import urlencode import logging import json BMAP_STREETVIEW_API = 'http://api.map.baidu.com/panorama/v2' def __check_json(content: str): """ Check the response :param content: :return bool: """ try: json.loads(content) return True except Exception: return False class BmapStreetViewSpider(object): """ Baidu Map Streetview API SPider """ api_key: str width: float height: float locations: List[str] coord_type: str heading: int pitch: int urls: List[str] = [] def __init__(self, api_key: str, locations: List[str], width: float = 400, height: float = 300, coord_type: str = 'wgs84ll', heading: int = 0, pitch: int = 0, fov: int = 90): self.api_key = api_key self.locations = locations self.width = width self.height = height self.coord_type = coord_type self.heading = heading self.pitch = pitch self.fov = fov def search_streeview_images(self): """ get streetview url :return self: """ for location in self.locations: params: Dict = { 'ak': self.api_key, 'width': self.width, 'height': self.height, 'location': location, 'coordtype': self.coord_type, 'heading': self.heading, 'pitch': self.pitch, 'fov': self.fov } try: response: Response = requests.get(BMAP_STREETVIEW_API, params=params) if __check_json(response.text): logging.error('JSON parse failed.') break except Exception as e: logging.error('Parse Error - ', e) self.urls.append('{0}?{1}'.format(BMAP_STREETVIEW_API, urlencode(params))) return self def download(self, path: str = None): """ Download images :param path: :return: """ for i in range(len(self.locations)): lng, lat = self.locations[i].split(',') img_name = 'sv_{0}_{1}.png'.format(lng, lat) try: if path: if not os.path.exists(path): os.makedirs(path) save_path = path else: save_path = '{0}/{1}'.format(os.path.abspath(os.curdir), 'streetview_imgs') if not os.path.exists(save_path): os.makedirs(save_path) filename = '{0}/{1}'.format(save_path, img_name) urlretrieve(self.urls[i], filename=filename) except IOError as e: logging.error('file operation failed! ', e) except Exception as e: logging.error('exception!! ', e)
from django.contrib.auth import get_user_model from django.db.models import Q def search_users(region, query): """ Searches for all users that match the given `query`. If region is None, all users are searched. :param region: The current region :type region: ~integreat_cms.cms.models.regions.region.Region :param query: The query string used for filtering the regions :type query: str :return: A query for all matching objects :rtype: ~django.db.models.QuerySet """ filter_query = ( Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query) ) if region: objects = region.users else: objects = get_user_model().objects return objects.filter(filter_query)
class ValidationError(Exception): pass class CaptchaError(Exception): pass
import styles from 'styles/Share.module.css' export default function Share() { const params = new URLSearchParams({ url: 'https://covid-vacuna-chile.vercel.app', text: '¡Sigue aquí el estado y progreso de vacunación contra el COVID19 en Chile! 👩‍⚕️💉' }) const url = `https://twitter.com/share?${params}` const TwitterLogo = () => ( <svg viewBox='0 0 612 612' width='24'> <path d='M612 116.258a250.714 250.714.0 01-72.088 19.772c25.929-15.527 45.777-40.155 55.184-69.411-24.322 14.379-51.169 24.82-79.775 30.48-22.907-24.437-55.49-39.658-91.63-39.658-69.334.0-125.551 56.217-125.551 125.513.0 9.828 1.109 19.427 3.251 28.606-104.326-5.24-196.835-55.223-258.75-131.174-10.823 18.51-16.98 40.078-16.98 63.101.0 43.559 22.181 81.993 55.835 104.479a125.556 125.556.0 01-56.867-15.756v1.568c0 60.806 43.291 111.554 100.693 123.104-10.517 2.83-21.607 4.398-33.08 4.398-8.107.0-15.947-.803-23.634-2.333 15.985 49.907 62.336 86.199 117.253 87.194-42.947 33.654-97.099 53.655-155.916 53.655-10.134.0-20.116-.612-29.944-1.721 55.567 35.681 121.536 56.485 192.438 56.485 230.948.0 357.188-191.291 357.188-357.188l-.421-16.253c24.666-17.593 46.005-39.697 62.794-64.861z' fill='#1da1f2' /> </svg> ) return ( <div className={styles.share}> <a target='_blank' rel='nofollow noopener noreferrer' href={url} title='Estado y progreso de vacunación contra el COVID-19 en Chile' > <span>¡Compártelo!</span> <TwitterLogo /> </a> </div> ) }
import pickle, copy, os, datetime, subprocess, json from collections import defaultdict import numpy as np import pandas as pd from scipy.stats import entropy import time from io import StringIO import dash import dash_core_components as dcc import dash_html_components as html import dash_table_experiments as dt from dash.dependencies import Input, Output, State import plotly.graph_objs as go import flask import plotly from flask_caching import Cache import inDelphi import generalStats import lib, header import boto3, botocore import os s3 = boto3.resource('s3', aws_access_key_id = os.environ['S3_KEY'], aws_secret_access_key = os.environ['S3_SECRET']) from indelphi_app import app # init if not os.path.isdir('local-s3/'): os.mkdir('local-s3/') else: subprocess.check_output('rm -rf local-s3/*', shell = True) # Set up flask caching CACHE_CONFIG = { 'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': os.environ.get('REDIS_URL', '') } cache = Cache() cache.init_app(app.server, config = CACHE_CONFIG) cache_timeout = 120 # Remove these plotly modebar buttons to limit interactivity modebarbuttons_2d = ['zoom2d', 'pan2d', 'select2d', 'lasso2d', 'zoomIn2d', 'zoomOut2d', 'autoScale2d', 'resetScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian', 'toggleSpikelines'] ## Parameters ################################################################### ################################################################### ## # App layout ## layout = html.Div([ ################################################### # Hidden divs for light data storage ################################################### html.Div( [ html.Div( id = 'G_hidden-pred-df-stats-signal', children = 'init' ), html.Div( id = 'G_table-stats-signal', children = 'init' ), html.Div( id = 'G_hidden-selected-genome', children = 'init' ), html.Div( id = 'G_hidden-selected-gene', children = 'init' ), html.Div( id = 'G_hidden-cache-submit-button', children = '%s' % (time.time()) ), html.Div( id = 'G_hidden-sort-module-interaction', children = '%s' % (time.time()) ), html.Div( id = 'G_hidden-clickData', children = '%s init' % (time.time()) ), html.Div( id = 'G_hidden-selected-id', children = '' ), # Datatable dt.DataTable( id = 'G_table-stats', rows = [{}], # init rows selected_row_indices = [], ), dcc.Location( id = 'G_url', refresh = False, ), ], style = dict( display = 'none', ), ), ################################################### # Header ################################################### html.Div( [ ################################################### # Upper header ################################################### header.get_navigation_header('gene'), ################################################### # Genome choice ################################################### html.Div( [ html.Div( [ # Left html.Div( [ html.Span('Genome: '), ], style = dict( display = 'table-cell', textAlign = 'right', width = '50%', transform = 'translateX(-10px)', ), ), # Middle html.Div( [ dcc.RadioItems( id = 'G_genome-radio', options = [ {'label': 'Human (hg38)', 'value': 'hg38'}, {'label': 'Mouse (mm10)', 'value': 'mm10'}, ], value = 'hg38' ) ], style = dict( display = 'table-cell', width = '30%', ), ), # Right html.Div( [], style = dict( display = 'table-cell', textAlign = 'left', width = '20%', transform = 'translateX(10px)', ), ), ], style = dict( display = 'table-row', ), ), ], style = dict( display = 'table', width = '100%', marginBottom = 10, ), ), ################################################### # Gene dropdown ################################################### html.Div( [ html.Div( [ # Left html.Div( [ html.Span('Gene: '), ], style = dict( display = 'table-cell', textAlign = 'right', width = '50%', transform = 'translateX(-10px)', ), ), # Middle html.Div( [ dcc.Dropdown( id = 'G_gene-dropdown', placeholder = 'Type to search for a gene', ), ], style = dict( display = 'table-cell', width = '25%', ), ), # Right html.Div( [], style = dict( display = 'table-cell', textAlign = 'left', width = '25%', transform = 'translateX(10px)', ), ), ], style = dict( display = 'table-row', ), ), ], style = dict( display = 'table', width = '100%', marginBottom = 10, ), ), ################################################### # Cell type ################################################### html.Div( [ html.Div( [ # Left html.Div( [ html.Span('Cell type: '), ], style = dict( display = 'table-cell', textAlign = 'right', width = '50%', transform = 'translateX(-10px)', ), ), # Middle html.Div( [ dcc.Dropdown( options = [ {'label': 'mESC', 'value': 'mESC'}, {'label': 'U2OS', 'value': 'U2OS'}, {'label': 'HCT116', 'value': 'HCT116'}, {'label': 'HEK293', 'value': 'HEK293'}, {'label': 'K562', 'value': 'K562'}, ], id = 'G_celltype_dropdown', searchable = False, clearable = False, value = 'mESC', ), ], style = dict( display = 'table-cell', width = '10%', ), ), # Right html.Div( [ html.Div( [ html.Img( src = '/staticfiles/tooltip_logo', className = 'tooltiprightlogo', ), html.Span( 'Choose a cell type specific version of inDelphi. If your cell type of interest is not listed here, we recommend using mESC if your cell type has no expected defects in DNA repair. Contradicting the genome choice is not a problem: for example, human embryonic stem cells are likely to have more similar DNA repair outcomes to mESC than human cancer cell lines.', className = 'tooltiprighttext', style = dict(width = '200px',) ), ], className = 'tooltipright', ), ], style = dict( display = 'table-cell', textAlign = 'left', width = '40%', transform = 'translateX(10px)', ), ), ], style = dict( display = 'table-row', ), ), ], style = dict( display = 'table', width = '100%', marginBottom = 10, ), ), ################################################### # Submit button ################################################### # Submit button html.Div([ html.Button( 'SUBMIT', id = 'G_submit_button', style = dict( boxShadow = '1px 3px 6px 0 rgba(0, 0, 0, 0.2)', ), )], style = dict( textAlign = 'center', marginBottom = 15, ), ), ], style = dict( backgroundColor = 'white', width = '1010px', position = 'relative', left = '50%', transform = 'translate(-50%, 0px)', borderBottom = '3px solid #777777', marginBottom = '50px', ), ), ################################################### # Post-computation settings module + Histograms (sticky) ################################################### html.Div( [ # Module html.Div([ # Header html.Div([ html.Div([ html.Strong('', id = 'G_postcomp_module_header', )], className = 'module_header_text'), ], className = 'module_header' ), # Module body html.Div( [ # Row: Display kgIDs... html.Div( [ html.Strong( 'Display kgIDs:', style = dict( textAlign = 'right', marginRight = '5px', height = '36px', # height of one dropdown line lineHeight = '36px', # centers vertically ), className = 'three columns', ), # Multi drop down to select columns dcc.Dropdown( id = 'G_dropdown-kgid', multi = True, searchable = False, clearable = False, className = 'nine columns', ), ], style = dict( # width = '1050px', marginBottom = '5px', marginTop = '10px', ), className = 'row', id = 'G_row_dropdown-kgid', ), # Row: Display columns... html.Div( [ html.Strong( 'Display columns:', style = dict( textAlign = 'right', marginRight = '5px', height = '36px', # height of one dropdown line lineHeight = '36px', # centers vertically ), className = 'three columns', ), # Multi drop down to select columns dcc.Dropdown( id = 'G_dropdown-columns', options = [ {'label': 'Exon number', 'value': 'Exon number'}, {'label': 'Distance to 5\' exon boundary', 'value': 'Dist. to 5\' end'}, {'label': 'Distance to 3\' exon boundary', 'value': 'Dist. to 3\' end'}, {'label': 'Precision', 'value': 'Precision'}, {'label': 'Frameshift (%)', 'value': 'Frameshift (%)'}, {'label': 'Frame +0 (%)', 'value': 'Frame +0 (%)'}, {'label': 'Frame +1 (%)', 'value': 'Frame +1 (%)'}, {'label': 'Frame +2 (%)', 'value': 'Frame +2 (%)'}, {'label': 'Microhomology strength', 'value': 'MH strength'}, {'label': 'Most frequent genotype (%)', 'value': 'M.F. gt (%)'}, {'label': 'Most frequent deletion (%)', 'value': 'M.F. del (%)'}, {'label': 'Most frequent insertion (%)', 'value': 'M.F. ins (%)'}, {'label': 'Expected indel length', 'value': 'Exp. indel len'}, ], multi = True, searchable = False, clearable = False, value = ['Exon number', 'Dist. to 5\' end', 'Dist. to 3\' end', 'Precision', 'Frameshift (%)', 'Frame +0 (%)'], className = 'nine columns', ), ], style = dict( # width = '1050px', marginBottom = '5px', marginTop = '10px', ), className = 'row', id = 'G_row_dropdown-columns', ), # Row: Sort by... html.Div( [ html.Strong( 'Sort by: ', className = 'three columns', style = dict( textAlign = 'right', marginRight = '5px', height = '36px', lineHeight = '36px', ), ), # Sorting columns dcc.Dropdown( id = 'G_dropdown-sortcol', options = [], searchable = False, clearable = False, className = 'three columns', ), # Sort direction dcc.RadioItems( id = 'G_sortdirection', options = [ {'label': 'Ascending', 'value': 'Ascending'}, {'label': 'Descending', 'value': 'Descending'}, ], value = 'Descending', labelStyle = {'display': 'inline-block'}, className = 'six columns', style = dict( marginLeft = 5, height = '36px', lineHeight = '36px', ), ), ], style = dict( marginBottom = '10px', ), className = 'row', id = 'G_row_dropdown-sortcol', ), # Links html.Div([ html.Div( # Sharable link html.A( '🔗 Shareable link to page before computation', id = 'G_page-link' ) ), html.Div( # Download link: summary statistics html.A( '📑 Download table of predictions', id = 'G_download-link' ) ), html.Div([ html.Span( 'Note: Online visualization is limited to 1000 gRNAs.', ) ]) ], style = dict( textAlign = 'center', height = 90, ) ), ], ), ## ], style = dict( transform = 'translateX(240px)', width = '970px', boxShadow = '1px 3px 6px 0 rgba(0, 0, 0, 0.2)', marginBottom = '50px', position = 'relative', zIndex = 10, ), ), # Hists html.Div( dcc.Graph( id = 'G_hist-stats', config = dict( modeBarButtonsToRemove = modebarbuttons_2d, displaylogo = False, displayModeBar = False, ), ), id = 'G_hist-stats-div', style = dict( display = 'none', position = 'relative', zIndex = 1, ) ), ], # body style id = 'G_postcomputation_settings', className = 'batch_postcomputation_sticky', style = dict( display = 'none', ), ), ################################################### # Plots ################################################### html.Div( [ # Plots html.Div( dcc.Graph( id = 'G_plot-stats', config = dict( modeBarButtonsToRemove = modebarbuttons_2d, displaylogo = False, displayModeBar = False, ), ), id = 'G_plot-stats-div', style = dict( display = 'none', ), className = 'animate-bottom', ), ], # body style style = dict( ), ), ## ], # body div style = dict( # width = '1150px', width = '1450px', margin = '0 auto', ) ) ####################################################################### ######################### CALLBACKS ######################### ####################################################################### ## # Hidden button callbacks ## @app.callback( Output('G_hidden-cache-submit-button', 'children'), [Input('G_submit_button', 'n_clicks')]) def update_submit_button_time(n_clicks): return '%s' % (time.time()) @app.callback( Output('G_hidden-sort-module-interaction', 'children'), [Input('G_row_dropdown-columns', 'n_clicks'), Input('G_row_dropdown-sortcol', 'n_clicks')]) def update_sort_time(v1, v2): return '%s' % (time.time()) @app.callback( Output('G_hidden-clickData', 'children'), [Input('G_plot-stats', 'clickData')]) def update_hidden_clickdata(clickData): return '%s %s' % (time.time(), clickData['points'][0]['pointNumber']) ## # URL callbacks ## @app.callback( Output('G_genome-radio', 'value'), [Input('G_url', 'pathname')], [State('G_genome-radio', 'value')]) def update_genome_build_from_url(url, default_value): valid_flag, dd = lib.parse_valid_url_path_gene(url) if valid_flag: return dd['genome_build'] return default_value @app.callback( Output('G_gene-dropdown', 'value'), [Input('G_url', 'pathname')], [State('G_gene-dropdown', 'value')]) def update_gene_from_url(url, default_value): valid_flag, dd = lib.parse_valid_url_path_gene(url) if valid_flag: return dd['gene'] return default_value @app.callback( Output('G_celltype_dropdown', 'value'), [Input('G_url', 'pathname')], [State('G_celltype_dropdown', 'value')]) def update_celltype_from_url(url, default_value): valid_flag, dd = lib.parse_valid_url_path_gene(url) if valid_flag: return dd['celltype'] return default_value @app.callback( Output('G_dropdown-sortcol', 'value'), [Input('G_dropdown-sortcol', 'options')], [State('G_dropdown-sortcol', 'value'), State('G_url', 'pathname')]) def update_sortcols_from_url(options, default_value, url): valid_flag, dd = lib.parse_valid_url_path_gene(url) if not valid_flag or dd['sort_by'] == '-': return default_value else: all_options = [s['value'] for s in options] idx = int(dd['sort_by']) return sorted(all_options)[idx] @app.callback( Output('G_sortdirection', 'value'), [Input('G_url', 'pathname')], [State('G_sortdirection', 'value')]) def update_sortdir_from_url(url, default_value): valid_flag, dd = lib.parse_valid_url_path_gene(url) if valid_flag: return dd['sort_dir'] else: return default_value @app.callback( Output('G_dropdown-columns', 'value'), [Input('G_url', 'pathname')], [State('G_dropdown-columns', 'value'), State('G_dropdown-columns', 'options')]) def update_columns_from_url(url, default_value, options): all_options = [s['value'] for s in options] valid_flag, dd = lib.parse_valid_url_path_gene(url) if valid_flag: value = [] alphabetical_options = sorted(all_options) for idx, flag in enumerate(dd['chosen_columns']): if flag == '1': value.append(alphabetical_options[idx]) return value else: return default_value ## # Header callbacks ## @app.callback( Output('G_gene-dropdown', 'options'), [Input('G_genome-radio', 'value')]) def update_gene_dropdown_choices(genome_build): stats_dir = os.path.dirname(os.path.realpath(__file__)) + '/statistics/' if genome_build == 'mm10': return generalStats.mm10_choices elif genome_build == 'hg38': return generalStats.hg38_choices @app.callback( Output('G_submit_button', 'children'), [Input('G_gene-dropdown', 'value')], [State('G_submit_button', 'children')]) def update_submit_button_text(selected_gene, prev_value): if selected_gene is None: return 'SELECT A GENE' else: return 'SUBMIT' @app.callback( Output('G_submit_button', 'style'), [Input('G_gene-dropdown', 'value')], [State('G_submit_button', 'style')]) def update_submit_button_style(selected_gene, style): if selected_gene is None: style['backgroundColor'] = '#86898C' style['color'] = 'white' else: style['backgroundColor'] = '#00A0DC' style['color'] = 'white' return style ## # AWS S3 download callback ## @cache.memoize() def grab_s3_stats_cache(parameters): genome_build, gene, celltype = parameters query_fn = '%s_%s_SpCas9_%s.csv' % (genome_build, celltype, gene) local_dir = 'local-s3/' s3.Bucket('indelphi-storage').download_file(query_fn, local_dir + query_fn) all_stats = pd.read_csv(local_dir + query_fn, index_col = 0) all_stats['ID'] = all_stats.index + 1 all_stats['PAM'] = [s[63:66] for s in all_stats['Local context']] all_stats['MH strength'] = np.log(all_stats['Phi']) dd = defaultdict(list) for idx, row in all_stats.iterrows(): sm_link = lib.encode_dna_to_url_path_single(row['Local context'], 60, celltype) dd['URL'].append('%s' % (sm_link)) if row['Exon strand'] == row['gRNA strand w.r.t. exon strand']: dd['Strand'].append('+') else: dd['Strand'].append('-') if row['Exon strand'] == '+': cutsite_coord = int(row['Exon start']) + int(row['Cutsite distance to 5p boundary']) else: # for col in all_stats.columns: # print(col, row[col]) cutsite_coord = int(row['Exon start']) + int(row['Cutsite distance to 3p boundary']) dd['Cutsite coordinate'].append(cutsite_coord) for col in dd: all_stats[col] = dd[col] all_stats['Distance to 5\' exon boundary'] = all_stats['Cutsite distance to 5p boundary'] all_stats['Distance to 3\' exon boundary'] = all_stats['Cutsite distance to 3p boundary'] return all_stats @app.callback( Output('G_hidden-pred-df-stats-signal', 'children'), [Input('G_submit_button', 'n_clicks')], [State('G_genome-radio', 'value'), State('G_gene-dropdown', 'value'), State('G_celltype_dropdown', 'value')] ) def update_df_stats(n_clicks, genome_build, gene, celltype): parameters = (genome_build, gene, celltype) grab_s3_stats_cache(parameters) return parameters ## # Module header callbacks, Advanced options hiding/showing ## @app.callback( Output('G_hidden-selected-genome', 'children'), [Input('G_table-stats-signal', 'children')], [State('G_genome-radio', 'value')] ) def update_hidden_selected_genome(signal, genome): return genome @app.callback( Output('G_hidden-selected-gene', 'children'), [Input('G_table-stats-signal', 'children')], [State('G_gene-dropdown', 'value')] ) def update_hidden_selected_gene(signal, gene): return gene @app.callback( Output('G_postcomp_module_header', 'children'), [Input('G_table-stats-signal', 'children'), Input('G_hidden-selected-genome', 'children'), Input('G_hidden-selected-gene', 'children')] ) def update_postcomp_module_header(table_signal, genome_build, gene): df = make_table_stats_cache(table_signal) return 'Results of %s SpCas9 (NGG) gRNAs targeting %s in %s' % (len(df), gene, genome_build) ## # kgID, column selection and sorting callbacks ## @app.callback( Output('G_dropdown-sortcol', 'options'), [Input('G_dropdown-columns', 'value')]) def update_sortcol_options(values): options = [] for value in values: options.append({'label': value, 'value': value}) return options @app.callback( Output('G_dropdown-kgid', 'options'), [Input('G_dropdown-kgid', 'value')], [State('G_hidden-pred-df-stats-signal', 'children')] ) def update_dropdown_kgid_options(value, signal): if signal == 'init': assert False, 'init' stats = grab_s3_stats_cache(signal) kgids = list(set(stats['kgID'])) sizes = [len(stats[stats['kgID'] == kgid]) for kgid in kgids] options = [] total_size_of_selected = sum([sizes[kgids.index(s)] for s in value]) for kgid, size in zip(kgids, sizes): curr_opt = {'label': '%s (%s gRNAs)' % (kgid, size), 'value': kgid} if kgid not in value: if size + total_size_of_selected > 1000: curr_opt['disabled'] = True options.append(curr_opt) return options @app.callback( Output('G_dropdown-kgid', 'value'), [Input('G_hidden-pred-df-stats-signal', 'children')] ) def update_dropdown_kgid_value(signal): if signal == 'init': assert False, 'init' stats = grab_s3_stats_cache(signal) kgids = set(stats['kgID']) sizes = [len(stats[stats['kgID'] == kgid]) for kgid in kgids] kgids_sorted = [x for _,x in sorted(zip(sizes, kgids), reverse = True)] sizes_sorted = sorted(sizes, reverse = True) # Select the largest possible for idx in range(len(sizes_sorted)): if sizes_sorted[idx] > 1000: sizes_sorted = sizes_sorted[1:] kgids_sorted = kgids_sorted[1:] else: break for idx in range(1, len(sizes_sorted)): if sum(sizes_sorted[:idx]) > 1000: return kgids_sorted[:idx - 1] return kgids_sorted ## # Stats table callbacks ## @cache.memoize(timeout = cache_timeout) def make_table_stats_cache(parameters): parameters = json.loads(parameters) signal, chosen_columns, sort_col, sort_direction, kgids = parameters stats = grab_s3_stats_cache(signal) # Drop unselected kgids stats = stats[stats['kgID'].isin(kgids)] assert len(stats) <= 1000 # Drop extra cols drop_cols = [ '1-bp ins frequency', 'MH del frequency', 'MHless del frequency', ] stats = stats.drop(drop_cols, axis = 1) # Rename to shorter versions stats = lib.rename_batch_columns(stats) # Sort by, if possible if sort_col is not None and sort_direction is not None: if sort_direction == 'Ascending': ascending_flag = True else: ascending_flag = False stats = stats.sort_values(by = sort_col, ascending = ascending_flag) # Reformat floats stats_cols = list(stats.columns) nonstat_cols = [ 'ID', 'PAM', 'URL', 'Cas9 type', 'Celltype', 'Chromosome', 'Cutsite distance to 3p boundary', 'Cutsite distance to 5p boundary', 'Exon end', # 'Exon number', 'Exon start', 'Exon strand', 'Gene symbol', 'Genome', 'Local context', 'Local cutsite', 'gRNA', 'gRNA strand w.r.t. exon strand', 'kgID', 'Strand', 'Cutsite coordinate', ] for nonstat_col in nonstat_cols: stats_cols.remove(nonstat_col) for stat_col in stats_cols: # Filter down to selected columns if stat_col not in chosen_columns: stats.drop(stat_col, axis = 1, inplace = True) continue # Reformat if stat_col in ['Precision', 'MH strength']: stats[stat_col] = [float('%.2f' % (s)) for s in stats[stat_col]] else: stats[stat_col] = [float('%.1f' % (s)) for s in stats[stat_col]] # Reorder columns stats = stats[nonstat_cols + lib.order_chosen_columns(chosen_columns)] stats = stats.reset_index(drop = True) return stats @app.callback( Output('G_table-stats-signal', 'children'), [Input('G_hidden-pred-df-stats-signal', 'children'), Input('G_dropdown-columns', 'value'), Input('G_dropdown-sortcol', 'value'), Input('G_sortdirection', 'value'), Input('G_dropdown-kgid', 'value'), ]) def update_stats_table(signal, chosen_columns, sort_col, sort_direction, kgids): if signal == 'init': assert False, 'init' parameters = (signal, chosen_columns, sort_col, sort_direction, kgids) parameters = json.dumps(parameters) make_table_stats_cache(parameters) return parameters @app.callback( Output('G_table-stats', 'selected_row_indices'), [Input('G_hidden-clickData', 'children'), Input('G_hidden-cache-submit-button', 'children'), Input('G_dropdown-columns', 'value'), Input('G_dropdown-sortcol', 'value'), Input('G_table-stats-signal', 'children')], [State('G_table-stats', 'selected_row_indices'), State('G_hidden-sort-module-interaction', 'children'), State('G_hidden-selected-id', 'children'), State('G_url', 'pathname'), State('G_postcomputation_settings', 'n_clicks'), State('G_plot-stats-div', 'n_clicks'), State('G_submit_button', 'n_clicks'), ]) def update_statstable_selected(clickData, submit_time, col_values, sortcol_value, table_signal, selected_row_indices, sort_time, prev_id, url, nc1, nc2, nc_submit): if not bool(nc1 and nc2) and nc_submit == 1: # On page load, select row from URL valid_flag, dd = lib.parse_valid_url_path_gene(url) if valid_flag: if dd['row_select'] != '-': return [int(dd['row_select'])] # Only allow selecting one point in plot-stats submit_time = float(submit_time) sort_time = float(sort_time) click_time = float(clickData.split()[0]) click_idx = clickData.split()[1] if click_idx == 'init': return [] else: click_idx = int(click_idx) submit_intxn = bool(submit_time > max(sort_time, click_time)) click_intxn = bool(click_time > max(sort_time, submit_time)) sort_intxn = bool(sort_time > max(click_time, submit_time)) print('Submit: %s' % (submit_intxn)) print('Click: %s' % (click_intxn)) print('Sort: %s' % (sort_intxn)) if sort_intxn and prev_id != '': # If changing sort col or direction, clear the selected rows. Otherwise, the wrong row is selected after sorting. Preferably, keep the selected row and update the index. selected_row_indices = [] df = make_table_stats_cache(table_signal) # new_idx = int(df[df['ID'] == int(prev_id)].index[0]) id_list = list(df['ID']) real_new_idx = id_list.index(int(prev_id)) display_new_idx = len(df) - real_new_idx - 1 new_idx = display_new_idx selected_row_indices = [new_idx] elif submit_intxn: # if hitting submit button, clear the selected rows. Otherwise, selecting a row M > number of rows N in new query, will fail selected_row_indices = [] elif click_intxn: # Must be triggered by clickData # Update selections in table based on clicking plot if selected_row_indices != [click_idx]: selected_row_indices = [click_idx] else: # Point already selected, user clicked on same point twice: # so, deselect selected_row_indices = [] return selected_row_indices @app.callback( Output('G_hidden-selected-id', 'children'), [Input('G_table-stats', 'selected_row_indices')], [State('G_table-stats-signal', 'children')]) def update_hidden_selected_id(selected_idx, table_signal): if len(selected_idx) == 0: return '' idx = selected_idx[0] df = make_table_stats_cache(table_signal) return list(df['ID'])[idx] ## # Plot stats callback: styles, hide when no figure ## @app.callback( Output('G_plot-stats-div', 'style'), [Input('G_plot-stats', 'figure')]) def update_stats_plot_style(fig): if fig is None: return {'display': 'none'} else: return {} @app.callback( Output('G_hist-stats-div', 'style'), [Input('G_hist-stats', 'figure')]) def update_hist_plot_style(fig): if fig is None: return {'display': 'none'} else: return {} @app.callback( Output('G_postcomputation_settings', 'style'), [Input('G_plot-stats', 'figure')]) def update_postcomputation_settings_style(fig): if fig is None: return {'display': 'none'} else: return {} ######################################################## # Plot stats callback ######################################################## @app.callback( Output('G_plot-stats', 'figure'), [Input('G_table-stats-signal', 'children'), Input('G_table-stats', 'selected_row_indices')]) def update_stats_plot(table_signal, selected_row_indices): df = make_table_stats_cache(table_signal) # Determine statistics to plot stats_cols = lib.order_chosen_columns(list(df.columns)) fig = plotly.tools.make_subplots( rows = 1, cols = len(stats_cols), shared_yaxes = True) # Color selected markers if len(selected_row_indices) > 0: selected_row_index = selected_row_indices[0] else: selected_row_index = None selected_line = dict() yrange = np.arange(1, len(df.index) + 1) # Generate each plot for idx, stats_col in enumerate(stats_cols): subplot_num = idx + 1 marker = {'color': [lib.get_color(stats_col)] * len(df)} for i in (selected_row_indices or []): marker['color'][i] = '#000000' # Gray lines fig.append_trace( go.Bar( x = df[stats_col][::-1], y = yrange, orientation = 'h', hoverinfo = 'skip', width = 0.1, opacity = 0.2, marker = dict( color = 'gray', ) ), 1, subplot_num ) # Scatter fig.append_trace( go.Scattergl( x = df[stats_col][::-1], y = yrange, mode = 'markers', marker = marker, name = '', ), 1, subplot_num ) if selected_row_index is not None: selected_line[subplot_num] = (df.index[selected_row_index], df[stats_col][len(df) - selected_row_index - 1]) # Format y tick texts: ID, gRNA, PAM, orientation, URL. yticktexts = [] fw_ids = lib.get_fixedwidth_ID(df['ID']) fw_kgids = lib.get_fixedwidth_items(df['kgID']) fw_coords = lib.get_fixedwidth_items(df['Cutsite coordinate']) for idx, row in df.iterrows(): row_text = '%s %s %s %s %s %s <a href="%s">details</a> %s' % (row['gRNA'], row['PAM'], row['Chromosome'], fw_coords[idx], row['Strand'], fw_kgids[idx], row['URL'], fw_ids[idx]) yticktexts.append(row_text) # Subplot formatting fig['layout']['barmode'] = 'stack' fig['layout']['yaxis1'].update( fixedrange = True, # autorange = False, tickvals = yrange, range = [min(yrange) - 1, max(yrange) + 1], ticktext = yticktexts[::-1], tickfont = dict( size = 12, family = 'monospace', ), zeroline = True, zerolinewidth = 2, # autorange = 'reversed', ) all_shapes = [] x_domains = lib.get_x_domains(len(stats_cols)) for idx, stats_col in enumerate(stats_cols): subplot_num = idx + 1 [xmin, xmax] = lib.get_batch_statcol_xrange(df[stats_col], stats_col) fig['layout']['xaxis%s' % (subplot_num)].update( # title = stats_col, domain = x_domains[idx], fixedrange = True, # showgrid = False, showgrid = True, zeroline = False, titlefont = dict( size = 12, ), range = [xmin, xmax], # showspikes = True, # spikesnap = 'cursor', # spikemode = 'across+marker', # spikedash = 'solid', # spikethickness = 1, # spikecolor = '#777', ) if selected_row_index is not None: all_shapes.append( lib.get_batch_select_line( x0 = selected_line[subplot_num][1], x1 = selected_line[subplot_num][1], y0 = 0, y1 = len(df), xref = 'x%s' % (subplot_num), yref = 'y1', ) ) all_shapes.append( lib.get_batch_select_line( x0 = xmin, x1 = xmax, y0 = selected_line[subplot_num][0] + 1, y1 = selected_line[subplot_num][0] + 1, xref = 'x%s' % (subplot_num), yref = 'y1', ) ) fig['layout']['shapes'] = all_shapes # Global figure formatting fig['layout']['showlegend'] = False fig['layout']['hovermode'] = 'y' # fig['layout']['spikedistance'] = -1 fig['layout']['width'] = 455 + len(stats_cols) * 150 fig['layout']['height'] = 150 + len(df) * 11 fig['layout']['margin'] = { 'l': 430, 'r': 25, 't': 0, 'b': 150, } return fig @app.callback( Output('G_hist-stats', 'figure'), [Input('G_table-stats-signal', 'children'), Input('G_table-stats', 'selected_row_indices')]) def update_hist_plot(table_signal, selected_row_indices): df = make_table_stats_cache(table_signal) # if len(df) <= 5: # return '' # Determine statistics to plot stats_cols = lib.order_chosen_columns(list(df.columns)) fig = plotly.tools.make_subplots( rows = 1, cols = len(stats_cols)) # Color selected markers if len(selected_row_indices) > 0: selected_row_index = selected_row_indices[0] else: selected_row_index = None selected_line = dict() # Generate each plot for idx, stats_col in enumerate(stats_cols): subplot_num = idx + 1 fig.append_trace( go.Histogram( x = df[stats_col], marker = dict(color = lib.get_color(stats_col)), name = '', opacity = 0.4, ), 1, subplot_num ) if selected_row_index is not None: selected_line[subplot_num] = (df.index[selected_row_index], df[stats_col][len(df) - selected_row_index - 1]) # Subplot formatting all_shapes = [] x_domains = lib.get_x_domains(len(stats_cols)) for idx, stats_col in enumerate(stats_cols): subplot_num = idx + 1 fig['layout']['yaxis%s' % (subplot_num)].update( fixedrange = True, showticklabels = False, showgrid = False, zeroline = False, ) fig['layout']['xaxis%s' % (subplot_num)].update( domain = x_domains[idx], title = stats_col, fixedrange = True, showgrid = True, zeroline = False, ticks = 'outside', ticklen = 3, tickcolor = '#eee', tickangle = 0, # disable automatic tick rotation range = lib.get_batch_statcol_xrange(df[stats_col], stats_col), ) if selected_row_index is not None: all_shapes.append( lib.get_batch_select_line( x0 = selected_line[subplot_num][1], x1 = selected_line[subplot_num][1], y0 = 0, y1 = len(df) / 2.5, xref = 'x%s' % (subplot_num), yref = 'y1', ) ) fig['layout']['shapes'] = all_shapes # Global figure formatting fig['layout']['paper_bgcolor'] = 'rgba(255, 255, 255, 0)' fig['layout']['plot_bgcolor'] = 'rgba(255, 255, 255, 0)' fig['layout']['showlegend'] = False fig['layout']['width'] = 455 + len(stats_cols) * 150 fig['layout']['height'] = 100 fig['layout']['margin'] = { 'l': 430, 'r': 25, 't': 0, # 't': 60, # 'b': 25, 'b': 40, } return fig ## # Download callbacks ## @app.callback( Output('G_download-link', 'href'), [Input('G_hidden-pred-df-stats-signal', 'children')]) def update_link(signal): if signal == 'init': assert False, 'init' stats = grab_s3_stats_cache(signal) # Drop extra cols drop_cols = [ '1-bp ins frequency', 'MH del frequency', 'MHless del frequency', ] stats = stats.drop(drop_cols, axis = 1) # Rename to shorter versions stats = lib.rename_batch_columns(stats) # Reformat floats stats_cols = list(stats.columns) nonstat_cols = [ 'ID', 'PAM', 'URL', 'Cas9 type', 'Celltype', 'Chromosome', 'Cutsite distance to 3p boundary', 'Cutsite distance to 5p boundary', 'Exon end', # 'Exon number', 'Exon start', 'Exon strand', 'Gene symbol', 'Genome', 'Local context', 'Local cutsite', 'gRNA', 'gRNA strand w.r.t. exon strand', 'kgID', 'Strand', 'Cutsite coordinate', ] for nonstat_col in nonstat_cols: stats_cols.remove(nonstat_col) for stat_col in stats_cols: # Reformat if stat_col in ['Precision', 'MH strength']: stats[stat_col] = [float('%.2f' % (s)) for s in stats[stat_col]] else: stats[stat_col] = [float('%.1f' % (s)) for s in stats[stat_col]] # Reorder columns stats = stats[nonstat_cols + lib.order_chosen_columns(stats_cols)] time = str(datetime.datetime.now()).replace(' ', '_').replace(':', '-') link_fn = '/dash/urlToDownloadGene?value={}'.format(time) stats.to_csv('user-csvs/%s.csv' % (time), index = False) return link_fn @app.callback( Output('G_download-link', 'children'), [Input('G_hidden-pred-df-stats-signal', 'children')]) def update_link_text(signal): if signal == 'init': assert False, 'init' stats = grab_s3_stats_cache(signal) num_grnas = len(stats) num_kgids = len(set(stats['kgID'])) return '📑 Download full table of predictions for %s gRNAs and %s kgIDs' % (num_grnas, num_kgids) ## # Flask serving ## @app.server.route('/dash/urlToDownloadGene') def download_csv_gene(): value = flask.request.args.get('value') # create a dynamic csv or file here using `StringIO` # (instead of writing to the file system) local_csv_fn = value.split('/')[-1] return flask.send_file( open('user-csvs/%s.csv' % (local_csv_fn), 'rb'), mimetype = 'text/csv', attachment_filename = 'inDelphi_gene_output.csv', as_attachment = True, ) ## # Page link callback ## @app.callback( Output('G_page-link', 'href'), [Input('G_genome-radio', 'value'), Input('G_gene-dropdown', 'value'), Input('G_celltype_dropdown', 'value'), Input('G_dropdown-columns', 'value'), Input('G_dropdown-columns', 'options'), Input('G_dropdown-sortcol', 'value'), Input('G_sortdirection', 'value'), Input('G_table-stats', 'selected_row_indices'), ]) def update_pagelink(genome_build, gene, celltype, chosen_columns, column_options, sort_by, sort_dir, selected_row): url = '%s' % (lib.encode_url_path_gene(genome_build, gene, celltype, chosen_columns, column_options, sort_by, sort_dir, selected_row)) return url
{ // AXIS getAxis(1, 0, 0, 20) // getAxis(1, 1, pilot) function getAxis (needGlobalAxis=true, needLocalAxis=false, origin=false, globalSize=8, localSize=2) { if (needGlobalAxis) { globalAxis(globalSize) } if (needLocalAxis && origin) { const localOrigin = localAxis(localSize) localOrigin.parent = origin return localOrigin } } function axis3 (size, nameList, back) { const V3 = BABYLON.Vector3 const anchorSize = 0.05 * size const axisX = BABYLON.Mesh.CreateLines(nameList[0], [ back ? new V3(-size, 0, 0) : V3.Zero(), new V3(size, 0, 0), new V3(size * 0.95, anchorSize, 0), new V3(size, 0, 0), new V3(size * 0.95, -anchorSize, 0) ], scene) axisX.color = new BABYLON.Color3(1, 0, 0) const axisY = BABYLON.Mesh.CreateLines(nameList[1], [ back ? new V3(0, -size, 0) : V3.Zero(), new V3(0, size, 0), new V3(-anchorSize, size * 0.95, 0), new V3(0, size, 0), new V3(anchorSize, size * 0.95, 0) ], scene) axisY.color = new BABYLON.Color3(0, 1, 0) const axisZ = BABYLON.Mesh.CreateLines(nameList[2], [ back ? new V3(0, 0, -size) : V3.Zero(), new V3(0, 0, size), new V3(0, -anchorSize, size * 0.95), new V3(0, 0, size), new V3(0, anchorSize, size * 0.95) ], scene) axisZ.color = new BABYLON.Color3(0, 0, 1) return {axisX, axisY, axisZ} } function globalAxis (size) { function makeTextPlane (text, color, size) { const dynamicTexture = new BABYLON.DynamicTexture('DynamicTexture', 50, scene, true) dynamicTexture.hasAlpha = true dynamicTexture.drawText(text, 5, 40, 'bold 36px Arial', color, 'transparent', true) const plane = new BABYLON.Mesh.CreatePlane('TextPlane', size, scene, true) plane.material = new BABYLON.StandardMaterial('TextPlaneMaterial', scene) plane.material.backFaceCulling = false plane.material.specularColor = new BABYLON.Color3(0, 0, 0) plane.material.diffuseTexture = dynamicTexture return plane } const xChar = makeTextPlane('X', 'red', size / 10) xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0) const yChar = makeTextPlane('Y', 'green', size / 10) yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size) var zChar = makeTextPlane('Z', 'blue', size / 10) zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size) const {axisX, axisY, axisZ} = axis3(size, ['X', 'Y', 'Z'].map(axis => `axis${axis}`)) } function localAxis (size) { const {axisX: localAxisX, axisY: localAxisY, axisZ: localAxisZ} = axis3(size, ['X', 'Y', 'Z'].map(axis => `localAxis${axis}`)) const localOrigin = new BABYLON.Mesh('localOrigin', scene) localOrigin.isVisible = false localAxisX.parent = localOrigin localAxisY.parent = localOrigin localAxisZ.parent = localOrigin // localAxisZM.parent = localOrigin return localOrigin } }
# Configuration file for ipython-nbconvert. c = get_config() #------------------------------------------------------------------------------ # NbConvertApp configuration #------------------------------------------------------------------------------ # This application is used to convert notebook files (*.ipynb) to various other # formats. # # WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES. # NbConvertApp will inherit config from: BaseIPythonApplication, Application # The IPython profile to use. # c.NbConvertApp.profile = u'default' # The export format to be used. # c.NbConvertApp.export_format = 'html' # List of notebooks to convert. Wildcards are supported. Filenames passed # positionally will be added to the list. # c.NbConvertApp.notebooks = [] # PostProcessor class used to write the results of the conversion # c.NbConvertApp.postprocessor_class = u'' # Writer class used to write the results of the conversion # c.NbConvertApp.writer_class = 'FilesWriter' # Set the log level by value or name. # c.NbConvertApp.log_level = 30 # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.NbConvertApp.extra_config_file = u'' # Whether to create profile dir if it doesn't exist # c.NbConvertApp.auto_create = False # overwrite base name use for output files. can only be used when converting one # notebook at a time. # c.NbConvertApp.output_base = '' # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This option can also be specified through the environment # variable IPYTHONDIR. # c.NbConvertApp.ipython_dir = u'' # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.NbConvertApp.copy_config_files = False # The date format used by logging formatters for %(asctime)s # c.NbConvertApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # The Logging format template # c.NbConvertApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.NbConvertApp.verbose_crash = False # Whether to apply a suffix prior to the extension (only relevant when # converting to notebook format). The suffix is determined by the exporter, and # is usually '.nbconvert'. # c.NbConvertApp.use_output_suffix = True # Whether to overwrite existing config files when copying # c.NbConvertApp.overwrite = False #------------------------------------------------------------------------------ # NbConvertBase configuration #------------------------------------------------------------------------------ # Global configurable class for shared config # # Useful for display data priority that might be use by many transformers # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.NbConvertBase.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # DEPRECATED default highlight language, please use language_info metadata # instead # c.NbConvertBase.default_language = 'ipython' #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = u'' #------------------------------------------------------------------------------ # Exporter configuration #------------------------------------------------------------------------------ # Class containing methods that sequentially run a list of preprocessors on a # NotebookNode object and then return the modified NotebookNode object and # accompanying resources dict. # Extension of the file that should be written to disk # c.Exporter.file_extension = '.txt' # List of preprocessors, by name or namespace, to enable. # c.Exporter.preprocessors = [] # List of preprocessors available by default, by name, namespace, instance, or # type. # c.Exporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] #------------------------------------------------------------------------------ # HTMLExporter configuration #------------------------------------------------------------------------------ # Exports a basic HTML document. This exporter assists with the export of HTML. # Inherit from it if you are writing your own HTML template and need custom # preprocessors/filters. If you don't need custom preprocessors/ filters, just # change the 'template_file' config option. # HTMLExporter will inherit config from: TemplateExporter, Exporter # # c.HTMLExporter.jinja_variable_block_start = '' # # c.HTMLExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.HTMLExporter.raw_mimetypes = [] # Name of the template file to use # c.HTMLExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.HTMLExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.HTMLExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.HTMLExporter.file_extension = '.txt' # # c.HTMLExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.HTMLExporter.filters = {} # # c.HTMLExporter.jinja_comment_block_start = '' # # c.HTMLExporter.jinja_logic_block_end = '' # # c.HTMLExporter.jinja_logic_block_start = '' # # c.HTMLExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.HTMLExporter.preprocessors = [] #------------------------------------------------------------------------------ # LatexExporter configuration #------------------------------------------------------------------------------ # Exports to a Latex template. Inherit from this class if your template is # LaTeX based and you need custom tranformers/filters. Inherit from it if you # are writing your own HTML template and need custom tranformers/filters. If # you don't need custom tranformers/filters, just change the 'template_file' # config option. Place your template in the special "/latex" subfolder of the # "../templates" folder. # LatexExporter will inherit config from: TemplateExporter, Exporter # # c.LatexExporter.jinja_variable_block_start = '(((' # # c.LatexExporter.jinja_variable_block_end = ')))' # formats of raw cells to be included in this Exporter's output. # c.LatexExporter.raw_mimetypes = [] # Name of the template file to use # c.LatexExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.LatexExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.LatexExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.LatexExporter.file_extension = '.txt' # # c.LatexExporter.jinja_comment_block_end = '=))' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.LatexExporter.filters = {} # # c.LatexExporter.jinja_comment_block_start = '((=' # # c.LatexExporter.jinja_logic_block_end = '*))' # # c.LatexExporter.jinja_logic_block_start = '((*' # # c.LatexExporter.template_extension = '.tplx' # List of preprocessors, by name or namespace, to enable. # c.LatexExporter.preprocessors = [] #------------------------------------------------------------------------------ # MarkdownExporter configuration #------------------------------------------------------------------------------ # Exports to a markdown document (.md) # MarkdownExporter will inherit config from: TemplateExporter, Exporter # # c.MarkdownExporter.jinja_variable_block_start = '' # # c.MarkdownExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.MarkdownExporter.raw_mimetypes = [] # Name of the template file to use # c.MarkdownExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.MarkdownExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.MarkdownExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.MarkdownExporter.file_extension = '.txt' # # c.MarkdownExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.MarkdownExporter.filters = {} # # c.MarkdownExporter.jinja_comment_block_start = '' # # c.MarkdownExporter.jinja_logic_block_end = '' # # c.MarkdownExporter.jinja_logic_block_start = '' # # c.MarkdownExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.MarkdownExporter.preprocessors = [] #------------------------------------------------------------------------------ # NotebookExporter configuration #------------------------------------------------------------------------------ # Exports to an IPython notebook. # NotebookExporter will inherit config from: Exporter # The nbformat version to write. Use this to downgrade notebooks. # c.NotebookExporter.nbformat_version = 4 # Extension of the file that should be written to disk # c.NotebookExporter.file_extension = '.txt' # List of preprocessors, by name or namespace, to enable. # c.NotebookExporter.preprocessors = [] # List of preprocessors available by default, by name, namespace, instance, or # type. # c.NotebookExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] #------------------------------------------------------------------------------ # PDFExporter configuration #------------------------------------------------------------------------------ # Writer designed to write to PDF files # PDFExporter will inherit config from: LatexExporter, TemplateExporter, # Exporter # File extensions of temp files to remove after running. # c.PDFExporter.temp_file_exts = ['.aux', '.bbl', '.blg', '.idx', '.log', '.out'] # # c.PDFExporter.jinja_variable_block_start = '(((' # # c.PDFExporter.jinja_logic_block_start = '((*' # Whether to display the output of latex commands. # c.PDFExporter.verbose = False # formats of raw cells to be included in this Exporter's output. # c.PDFExporter.raw_mimetypes = [] # Shell command used to run bibtex. # c.PDFExporter.bib_command = [u'bibtex', u'{filename}'] # List of preprocessors available by default, by name, namespace, instance, or # type. # c.PDFExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.PDFExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.PDFExporter.file_extension = '.txt' # # c.PDFExporter.jinja_comment_block_end = '=))' # # c.PDFExporter.jinja_variable_block_end = ')))' # # c.PDFExporter.template_extension = '.tplx' # List of preprocessors, by name or namespace, to enable. # c.PDFExporter.preprocessors = [] # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.PDFExporter.filters = {} # # c.PDFExporter.jinja_comment_block_start = '((=' # Name of the template file to use # c.PDFExporter.template_file = u'default' # How many times latex will be called. # c.PDFExporter.latex_count = 3 # # c.PDFExporter.jinja_logic_block_end = '*))' # Shell command used to compile latex. # c.PDFExporter.latex_command = [u'pdflatex', u'{filename}'] #------------------------------------------------------------------------------ # PythonExporter configuration #------------------------------------------------------------------------------ # Exports a Python code file. # PythonExporter will inherit config from: TemplateExporter, Exporter # # c.PythonExporter.jinja_variable_block_start = '' # # c.PythonExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.PythonExporter.raw_mimetypes = [] # Name of the template file to use # c.PythonExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.PythonExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.PythonExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.PythonExporter.file_extension = '.txt' # # c.PythonExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.PythonExporter.filters = {} # # c.PythonExporter.jinja_comment_block_start = '' # # c.PythonExporter.jinja_logic_block_end = '' # # c.PythonExporter.jinja_logic_block_start = '' # # c.PythonExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.PythonExporter.preprocessors = [] #------------------------------------------------------------------------------ # RSTExporter configuration #------------------------------------------------------------------------------ # Exports restructured text documents. # RSTExporter will inherit config from: TemplateExporter, Exporter # # c.RSTExporter.jinja_variable_block_start = '' # # c.RSTExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.RSTExporter.raw_mimetypes = [] # Name of the template file to use # c.RSTExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.RSTExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.RSTExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.RSTExporter.file_extension = '.txt' # # c.RSTExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.RSTExporter.filters = {} # # c.RSTExporter.jinja_comment_block_start = '' # # c.RSTExporter.jinja_logic_block_end = '' # # c.RSTExporter.jinja_logic_block_start = '' # # c.RSTExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.RSTExporter.preprocessors = [] #------------------------------------------------------------------------------ # SlidesExporter configuration #------------------------------------------------------------------------------ # Exports HTML slides with reveal.js # SlidesExporter will inherit config from: HTMLExporter, TemplateExporter, # Exporter # # c.SlidesExporter.jinja_variable_block_start = '' # # c.SlidesExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.SlidesExporter.raw_mimetypes = [] # Name of the template file to use # c.SlidesExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.SlidesExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.SlidesExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.SlidesExporter.file_extension = '.txt' # # c.SlidesExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.SlidesExporter.filters = {} # # c.SlidesExporter.jinja_comment_block_start = '' # # c.SlidesExporter.jinja_logic_block_end = '' # # c.SlidesExporter.jinja_logic_block_start = '' # # c.SlidesExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.SlidesExporter.preprocessors = [] #------------------------------------------------------------------------------ # TemplateExporter configuration #------------------------------------------------------------------------------ # Exports notebooks into other file formats. Uses Jinja 2 templating engine to # output new formats. Inherit from this class if you are creating a new # template type along with new filters/preprocessors. If the filters/ # preprocessors provided by default suffice, there is no need to inherit from # this class. Instead, override the template_file and file_extension traits via # a config file. # # - citation2latex - highlight2html - filter_data_type - markdown2html - # markdown2rst - get_lines - ansi2latex - strip_ansi - add_prompts - # comment_lines - ascii_only - markdown2latex - escape_latex - add_anchor - # ipython2python - posix_path - highlight2latex - path2url - prevent_list_blocks # - ansi2html - wrap_text - indent - strip_dollars - html2text - # strip_files_prefix # TemplateExporter will inherit config from: Exporter # # c.TemplateExporter.jinja_variable_block_start = '' # # c.TemplateExporter.jinja_variable_block_end = '' # formats of raw cells to be included in this Exporter's output. # c.TemplateExporter.raw_mimetypes = [] # Name of the template file to use # c.TemplateExporter.template_file = u'default' # List of preprocessors available by default, by name, namespace, instance, or # type. # c.TemplateExporter.default_preprocessors = ['IPython.nbconvert.preprocessors.ExecutePreprocessor', 'IPython.nbconvert.preprocessors.ClearOutputPreprocessor', 'IPython.nbconvert.preprocessors.coalesce_streams', 'IPython.nbconvert.preprocessors.SVG2PDFPreprocessor', 'IPython.nbconvert.preprocessors.CSSHTMLHeaderPreprocessor', 'IPython.nbconvert.preprocessors.RevealHelpPreprocessor', 'IPython.nbconvert.preprocessors.LatexPreprocessor', 'IPython.nbconvert.preprocessors.HighlightMagicsPreprocessor', 'IPython.nbconvert.preprocessors.ExtractOutputPreprocessor'] # # c.TemplateExporter.template_path = ['.'] # Extension of the file that should be written to disk # c.TemplateExporter.file_extension = '.txt' # # c.TemplateExporter.jinja_comment_block_end = '' # Dictionary of filters, by name and namespace, to add to the Jinja environment. # c.TemplateExporter.filters = {} # # c.TemplateExporter.jinja_comment_block_start = '' # # c.TemplateExporter.jinja_logic_block_end = '' # # c.TemplateExporter.jinja_logic_block_start = '' # # c.TemplateExporter.template_extension = '.tpl' # List of preprocessors, by name or namespace, to enable. # c.TemplateExporter.preprocessors = [] #------------------------------------------------------------------------------ # CSSHTMLHeaderPreprocessor configuration #------------------------------------------------------------------------------ # Preprocessor used to pre-process notebook for HTML output. Adds IPython # notebook front-end CSS and Pygments CSS to HTML output. # CSSHTMLHeaderPreprocessor will inherit config from: Preprocessor, # NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.CSSHTMLHeaderPreprocessor.default_language = 'ipython' # CSS highlight class identifier # c.CSSHTMLHeaderPreprocessor.highlight_class = '.highlight' # # c.CSSHTMLHeaderPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.CSSHTMLHeaderPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # ClearOutputPreprocessor configuration #------------------------------------------------------------------------------ # Removes the output from all code cells in a notebook. # ClearOutputPreprocessor will inherit config from: Preprocessor, NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ClearOutputPreprocessor.default_language = 'ipython' # # c.ClearOutputPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ClearOutputPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # ConvertFiguresPreprocessor configuration #------------------------------------------------------------------------------ # Converts all of the outputs in a notebook from one format to another. # ConvertFiguresPreprocessor will inherit config from: Preprocessor, # NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ConvertFiguresPreprocessor.default_language = 'ipython' # Format the converter writes # c.ConvertFiguresPreprocessor.to_format = u'' # # c.ConvertFiguresPreprocessor.enabled = False # Format the converter accepts # c.ConvertFiguresPreprocessor.from_format = u'' # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ConvertFiguresPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # ExecutePreprocessor configuration #------------------------------------------------------------------------------ # Executes all the cells in a notebook # ExecutePreprocessor will inherit config from: Preprocessor, NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ExecutePreprocessor.default_language = 'ipython' # If execution of a cell times out, interrupt the kernel and continue executing # other cells rather than throwing an error and stopping. # c.ExecutePreprocessor.interrupt_on_timeout = False # # c.ExecutePreprocessor.enabled = False # The time to wait (in seconds) for output from executions. # c.ExecutePreprocessor.timeout = 30 # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ExecutePreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # ExtractOutputPreprocessor configuration #------------------------------------------------------------------------------ # Extracts all of the outputs from the notebook file. The extracted outputs # are returned in the 'resources' dictionary. # ExtractOutputPreprocessor will inherit config from: Preprocessor, # NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.ExtractOutputPreprocessor.default_language = 'ipython' # # c.ExtractOutputPreprocessor.output_filename_template = '{unique_key}_{cell_index}_{index}{extension}' # # c.ExtractOutputPreprocessor.extract_output_types = set(['image/png', 'application/pdf', 'image/jpeg', 'image/svg+xml']) # # c.ExtractOutputPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ExtractOutputPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # HighlightMagicsPreprocessor configuration #------------------------------------------------------------------------------ # Detects and tags code cells that use a different languages than Python. # HighlightMagicsPreprocessor will inherit config from: Preprocessor, # NbConvertBase # Syntax highlighting for magic's extension languages. Each item associates a # language magic extension such as %%R, with a pygments lexer such as r. # c.HighlightMagicsPreprocessor.languages = {} # # c.HighlightMagicsPreprocessor.enabled = False # DEPRECATED default highlight language, please use language_info metadata # instead # c.HighlightMagicsPreprocessor.default_language = 'ipython' # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.HighlightMagicsPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # LatexPreprocessor configuration #------------------------------------------------------------------------------ # Preprocessor for latex destined documents. # # Mainly populates the `latex` key in the resources dict, adding definitions for # pygments highlight styles. # LatexPreprocessor will inherit config from: Preprocessor, NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.LatexPreprocessor.default_language = 'ipython' # # c.LatexPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.LatexPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # Preprocessor configuration #------------------------------------------------------------------------------ # A configurable preprocessor # # Inherit from this class if you wish to have configurability for your # preprocessor. # # Any configurable traitlets this class exposed will be configurable in profiles # using c.SubClassName.attribute = value # # you can overwrite :meth:`preprocess_cell` to apply a transformation # independently on each cell or :meth:`preprocess` if you prefer your own logic. # See corresponding docstring for informations. # # Disabled by default and can be enabled via the config by # 'c.YourPreprocessorName.enabled = True' # Preprocessor will inherit config from: NbConvertBase # DEPRECATED default highlight language, please use language_info metadata # instead # c.Preprocessor.default_language = 'ipython' # # c.Preprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.Preprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # RevealHelpPreprocessor configuration #------------------------------------------------------------------------------ # RevealHelpPreprocessor will inherit config from: Preprocessor, NbConvertBase # The URL prefix for reveal.js. This can be a a relative URL for a local copy of # reveal.js, or point to a CDN. # # For speaker notes to work, a local reveal.js prefix must be used. # c.RevealHelpPreprocessor.url_prefix = 'reveal.js' # DEPRECATED default highlight language, please use language_info metadata # instead # c.RevealHelpPreprocessor.default_language = 'ipython' # # c.RevealHelpPreprocessor.enabled = False # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.RevealHelpPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] #------------------------------------------------------------------------------ # SVG2PDFPreprocessor configuration #------------------------------------------------------------------------------ # Converts all of the outputs in a notebook from SVG to PDF. # SVG2PDFPreprocessor will inherit config from: ConvertFiguresPreprocessor, # Preprocessor, NbConvertBase # Format the converter accepts # c.SVG2PDFPreprocessor.from_format = u'' # DEPRECATED default highlight language, please use language_info metadata # instead # c.SVG2PDFPreprocessor.default_language = 'ipython' # # c.SVG2PDFPreprocessor.enabled = False # Format the converter writes # c.SVG2PDFPreprocessor.to_format = u'' # The command to use for converting SVG to PDF # # This string is a template, which will be formatted with the keys to_filename # and from_filename. # # The conversion call must read the SVG from {from_flename}, and write a PDF to # {to_filename}. # c.SVG2PDFPreprocessor.command = u'' # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.SVG2PDFPreprocessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # The path to Inkscape, if necessary # c.SVG2PDFPreprocessor.inkscape = u'' #------------------------------------------------------------------------------ # FilesWriter configuration #------------------------------------------------------------------------------ # Consumes nbconvert output and produces files. # FilesWriter will inherit config from: WriterBase, NbConvertBase # List of the files that the notebook references. Files will be included with # written output. # c.FilesWriter.files = [] # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.FilesWriter.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # Directory to write output to. Leave blank to output to the current directory # c.FilesWriter.build_directory = '' # DEPRECATED default highlight language, please use language_info metadata # instead # c.FilesWriter.default_language = 'ipython' # When copying files that the notebook depends on, copy them in relation to this # path, such that the destination filename will be os.path.relpath(filename, # relpath). If FilesWriter is operating on a notebook that already exists # elsewhere on disk, then the default will be the directory containing that # notebook. # c.FilesWriter.relpath = '' #------------------------------------------------------------------------------ # StdoutWriter configuration #------------------------------------------------------------------------------ # Consumes output from nbconvert export...() methods and writes to the stdout # stream. # StdoutWriter will inherit config from: WriterBase, NbConvertBase # List of the files that the notebook references. Files will be included with # written output. # c.StdoutWriter.files = [] # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.StdoutWriter.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # DEPRECATED default highlight language, please use language_info metadata # instead # c.StdoutWriter.default_language = 'ipython' #------------------------------------------------------------------------------ # WriterBase configuration #------------------------------------------------------------------------------ # Consumes output from nbconvert export...() methods and writes to a useful # location. # WriterBase will inherit config from: NbConvertBase # List of the files that the notebook references. Files will be included with # written output. # c.WriterBase.files = [] # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.WriterBase.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # DEPRECATED default highlight language, please use language_info metadata # instead # c.WriterBase.default_language = 'ipython' #------------------------------------------------------------------------------ # PostProcessorBase configuration #------------------------------------------------------------------------------ # PostProcessorBase will inherit config from: NbConvertBase # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.PostProcessorBase.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # DEPRECATED default highlight language, please use language_info metadata # instead # c.PostProcessorBase.default_language = 'ipython' #------------------------------------------------------------------------------ # ServePostProcessor configuration #------------------------------------------------------------------------------ # Post processor designed to serve files # # Proxies reveal.js requests to a CDN if no local reveal.js is present # ServePostProcessor will inherit config from: PostProcessorBase, NbConvertBase # The IP address to listen on. # c.ServePostProcessor.ip = '127.0.0.1' # URL prefix for reveal.js # c.ServePostProcessor.reveal_prefix = 'reveal.js' # DEPRECATED default highlight language, please use language_info metadata # instead # c.ServePostProcessor.default_language = 'ipython' # port for the server to listen on. # c.ServePostProcessor.port = 8000 # An ordered list of preferred output type, the first encountered will usually # be used when converting discarding the others. # c.ServePostProcessor.display_data_priority = ['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'] # Should the browser be opened automatically? # c.ServePostProcessor.open_in_browser = True # URL for reveal.js CDN. # c.ServePostProcessor.reveal_cdn = 'https://cdn.jsdelivr.net/reveal.js/2.6.2'
#ifndef __CONFIG_REQUEST #define __CONFIG_REQUEST #include <stdlib.h> uint8_t getVideoMode(); uint8_t getLineCount(); #endif
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const team_detail_nop = { "resource": "teamplayerdashboard", "parameters": { "MeasureType": "Base", "PerMode": "PerGame", "PlusMinus": "N", "PaceAdjust": "N", "Rank": "N", "LeagueID": "00", "Season": "2017-18", "SeasonType": "Regular Season", "PORound": null, "TeamID": 1610612740, "Outcome": null, "Location": null, "Month": 0, "SeasonSegment": null, "DateFrom": null, "DateTo": null, "OpponentTeamID": 0, "VsConference": null, "VsDivision": null, "GameSegment": null, "Period": 0, "ShotClockRange": null, "LastNGames": 0 }, "resultSets": [{ "name": "TeamOverall", "headers": ["GROUP_SET", "TEAM_ID", "TEAM_NAME", "GROUP_VALUE", "GP", "W", "L", "W_PCT", "MIN", "FGM", "FGA", "FG_PCT", "FG3M", "FG3A", "FG3_PCT", "FTM", "FTA", "FT_PCT", "OREB", "DREB", "REB", "AST", "TOV", "STL", "BLK", "BLKA", "PF", "PFD", "PTS", "PLUS_MINUS", "GP_RANK", "W_RANK", "L_RANK", "W_PCT_RANK", "MIN_RANK", "FGM_RANK", "FGA_RANK", "FG_PCT_RANK", "FG3M_RANK", "FG3A_RANK", "FG3_PCT_RANK", "FTM_RANK", "FTA_RANK", "FT_PCT_RANK", "OREB_RANK", "DREB_RANK", "REB_RANK", "AST_RANK", "TOV_RANK", "STL_RANK", "BLK_RANK", "BLKA_RANK", "PF_RANK", "PFD_RANK", "PTS_RANK", "PLUS_MINUS_RANK"], "rowSet": [ ["Overall", 1610612740, "New Orleans Pelicans", "2017-18", 82, 48, 34, 0.585000, 48.7, 42.700000, 88.300000, 0.483, 10.200000, 28.200000, 0.362, 16.100000, 20.900000, 0.772, 8.700000, 35.700000, 44.300000, 26.800000, 14.9, 8.000000, 5.900000, 4.200000, 19.100000, 20.400000, 111.700000, 1.3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] }, { "name": "PlayersSeasonTotals", "headers": ["GROUP_SET", "PLAYER_ID", "PLAYER_NAME", "GP", "W", "L", "W_PCT", "MIN", "FGM", "FGA", "FG_PCT", "FG3M", "FG3A", "FG3_PCT", "FTM", "FTA", "FT_PCT", "OREB", "DREB", "REB", "AST", "TOV", "STL", "BLK", "BLKA", "PF", "PFD", "PTS", "PLUS_MINUS", "NBA_FANTASY_PTS", "DD2", "TD3", "GP_RANK", "W_RANK", "L_RANK", "W_PCT_RANK", "MIN_RANK", "FGM_RANK", "FGA_RANK", "FG_PCT_RANK", "FG3M_RANK", "FG3A_RANK", "FG3_PCT_RANK", "FTM_RANK", "FTA_RANK", "FT_PCT_RANK", "OREB_RANK", "DREB_RANK", "REB_RANK", "AST_RANK", "TOV_RANK", "STL_RANK", "BLK_RANK", "BLKA_RANK", "PF_RANK", "PFD_RANK", "PTS_RANK", "PLUS_MINUS_RANK", "NBA_FANTASY_PTS_RANK", "DD2_RANK", "TD3_RANK"], "rowSet": [ ["Players", 203076, "Anthony Davis", 75, 45, 30, 0.600000, 36.4, 10.400000, 19.500000, 0.534, 0.700000, 2.200000, 0.34, 6.600000, 8.000000, 0.828, 2.500000, 8.600000, 11.100000, 2.300000, 2.200000, 1.500000, 2.600000, 0.600000, 2.100000, 7.400000, 28.100000, 3.900000, 55.1, 50, 1, 4, 4, 5, 9, 1, 1, 1, 2, 10, 10, 10, 1, 2, 4, 1, 2, 2, 6, 4, 2, 1, 4, 5, 2, 1, 2, 1, 1, 3], ["Players", 1628429, "Charles Cooke", 13, 8, 5, 0.615000, 2.9, 0.200000, 1.100000, 0.143, 0.100000, 0.600000, 0.125, 0.100000, 0.200000, 0.5, 0.000000, 0.200000, 0.200000, 0.100000, 0.100000, 0.100000, 0.000000, 0.100000, 0.000000, 0.200000, 0.500000, -0.700000, 0.9, 0, 0, 16, 15, 16, 7, 23, 23, 22, 23, 18, 15, 18, 19, 19, 17, 21, 21, 23, 21, 21, 18, 19, 20, 23, 19, 23, 12, 23, 7, 5], ["Players", 1627767, "Cheick Diallo", 52, 29, 23, 0.558000, 11.2, 2.000000, 3.400000, 0.58, 0.000000, 0.000000, 0.0, 1.000000, 1.300000, 0.758, 0.900000, 3.200000, 4.100000, 0.400000, 0.500000, 0.200000, 0.400000, 0.300000, 1.600000, 0.900000, 4.900000, -2.000000, 11.6, 3, 0, 7, 7, 7, 17, 14, 11, 15, 1, 19, 20, 19, 5, 5, 10, 8, 6, 6, 18, 14, 16, 6, 12, 11, 6, 12, 17, 13, 6, 5], ["Players", 201967, "Dante Cunningham", 51, 28, 23, 0.549000, 21.9, 1.900000, 4.400000, 0.44, 0.700000, 2.100000, 0.324, 0.400000, 0.700000, 0.556, 1.000000, 2.800000, 3.800000, 0.500000, 0.300000, 0.500000, 0.300000, 0.300000, 1.500000, 0.700000, 5.000000, -0.600000, 12.5, 0, 0, 8, 8, 7, 18, 8, 13, 11, 12, 11, 11, 15, 13, 13, 14, 6, 8, 8, 16, 17, 9, 7, 11, 13, 13, 11, 11, 11, 7, 5], ["Players", 203121, "Darius Miller", 82, 48, 34, 0.585000, 23.7, 2.600000, 5.900000, 0.444, 1.800000, 4.400000, 0.411, 0.700000, 0.800000, 0.866, 0.200000, 1.800000, 2.000000, 1.400000, 0.700000, 0.300000, 0.200000, 0.100000, 2.000000, 0.500000, 7.800000, -0.300000, 13.1, 0, 0, 1, 1, 1, 11, 7, 8, 8, 11, 3, 4, 7, 6, 10, 3, 18, 13, 14, 12, 13, 13, 8, 19, 7, 16, 7, 10, 9, 7, 5], ["Players", 202732, "DeAndre Liggins", 27, 18, 9, 0.667000, 9.0, 0.700000, 1.500000, 0.439, 0.300000, 0.600000, 0.471, 0.000000, 0.000000, 0.0, 0.100000, 0.900000, 1.000000, 0.800000, 0.300000, 0.400000, 0.100000, 0.200000, 0.700000, 0.100000, 1.600000, -3.700000, 5.2, 0, 0, 12, 12, 14, 2, 16, 18, 19, 13, 14, 14, 5, 20, 20, 20, 20, 16, 17, 15, 19, 12, 12, 17, 20, 20, 18, 22, 16, 7, 5], ["Players", 202326, "DeMarcus Cousins", 48, 27, 21, 0.563000, 36.2, 8.500000, 18.000000, 0.47, 2.200000, 6.100000, 0.354, 6.100000, 8.200000, 0.746, 2.200000, 10.700000, 12.900000, 5.400000, 5.000000, 1.600000, 1.600000, 1.300000, 3.800000, 7.800000, 25.200000, 1.700000, 53.3, 38, 3, 9, 9, 9, 16, 2, 2, 2, 7, 2, 2, 9, 2, 1, 11, 2, 1, 1, 3, 1, 1, 2, 1, 1, 1, 2, 5, 2, 2, 1], ["Players", 202734, "E'Twaun Moore", 82, 48, 34, 0.585000, 31.5, 5.200000, 10.100000, 0.508, 1.600000, 3.700000, 0.425, 0.600000, 0.800000, 0.706, 0.700000, 2.200000, 2.900000, 2.300000, 1.200000, 1.000000, 0.100000, 0.400000, 2.200000, 0.900000, 12.500000, 1.800000, 21.4, 0, 0, 1, 1, 1, 11, 4, 5, 5, 3, 5, 5, 6, 9, 9, 12, 11, 10, 10, 7, 6, 6, 13, 7, 4, 8, 5, 4, 6, 7, 5], ["Players", 2731, "Emeka Okafor", 26, 16, 10, 0.615000, 13.6, 1.800000, 3.700000, 0.505, 0.000000, 0.000000, 0.0, 0.700000, 0.800000, 0.818, 1.800000, 2.800000, 4.600000, 0.300000, 0.500000, 0.300000, 1.000000, 0.400000, 1.200000, 0.800000, 4.400000, 0.000000, 13.7, 0, 0, 13, 13, 11, 7, 12, 14, 13, 4, 19, 20, 19, 7, 8, 5, 3, 7, 4, 19, 15, 14, 3, 8, 15, 9, 14, 8, 8, 7, 5], ["Players", 203546, "Ian Clark", 74, 43, 31, 0.581000, 19.7, 3.000000, 6.700000, 0.448, 0.800000, 2.600000, 0.318, 0.600000, 0.800000, 0.763, 0.100000, 1.600000, 1.700000, 1.500000, 0.800000, 0.400000, 0.100000, 0.400000, 1.600000, 0.700000, 7.400000, 0.400000, 12.7, 0, 0, 5, 5, 4, 13, 10, 7, 7, 9, 8, 7, 16, 8, 11, 9, 19, 14, 15, 10, 11, 11, 16, 10, 10, 12, 8, 6, 10, 7, 5], ["Players", 1627883, "Jalen Jones", 4, 1, 3, 0.250000, 4.8, 0.300000, 1.000000, 0.25, 0.300000, 0.300000, 1.0, 0.500000, 0.500000, 1.0, 0.000000, 0.800000, 0.800000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.500000, 0.300000, 1.300000, -1.800000, 2.2, 0, 0, 21, 22, 18, 22, 20, 22, 23, 20, 15, 17, 1, 10, 15, 1, 21, 17, 19, 22, 22, 20, 19, 21, 22, 17, 20, 16, 22, 7, 5], ["Players", 2749, "Jameer Nelson", 43, 23, 20, 0.535000, 20.9, 2.000000, 4.800000, 0.41, 0.900000, 2.600000, 0.364, 0.300000, 0.400000, 0.765, 0.300000, 2.000000, 2.200000, 3.600000, 1.300000, 0.500000, 0.100000, 0.100000, 1.600000, 0.900000, 5.100000, -1.200000, 13.8, 0, 0, 10, 10, 10, 20, 9, 12, 10, 17, 7, 8, 8, 15, 17, 8, 16, 12, 12, 4, 5, 8, 18, 18, 12, 7, 10, 15, 7, 7, 5], ["Players", 202348, "Jordan Crawford", 5, 3, 2, 0.600000, 10.7, 2.400000, 5.400000, 0.444, 1.600000, 2.800000, 0.571, 0.200000, 0.200000, 1.0, 0.400000, 0.400000, 0.800000, 2.600000, 1.000000, 0.200000, 0.200000, 0.400000, 1.400000, 0.000000, 6.600000, -3.800000, 11.7, 0, 0, 19, 20, 21, 9, 15, 9, 9, 10, 4, 6, 3, 18, 18, 1, 14, 18, 18, 5, 8, 17, 9, 9, 14, 22, 9, 23, 12, 7, 5], ["Players", 2746, "Josh Smith", 3, 2, 1, 0.667000, 3.9, 0.300000, 1.300000, 0.25, 0.000000, 0.000000, 0.0, 0.000000, 0.000000, 0.0, 1.000000, 0.300000, 1.300000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.700000, -3.300000, 2.3, 0, 0, 23, 21, 22, 2, 22, 21, 20, 20, 19, 20, 19, 20, 20, 20, 5, 20, 16, 22, 22, 20, 19, 21, 16, 22, 22, 21, 21, 7, 5], ["Players", 201950, "Jrue Holiday", 81, 47, 34, 0.580000, 36.1, 7.600000, 15.400000, 0.494, 1.500000, 4.400000, 0.337, 2.300000, 2.900000, 0.786, 0.800000, 3.700000, 4.500000, 6.000000, 2.600000, 1.500000, 0.800000, 0.700000, 2.500000, 2.800000, 19.000000, 4.000000, 37.7, 8, 1, 3, 3, 1, 14, 3, 3, 3, 5, 6, 3, 11, 3, 3, 7, 9, 4, 5, 2, 2, 3, 5, 3, 2, 3, 3, 1, 3, 4, 3], ["Players", 203580, "Larry Drew II", 7, 4, 3, 0.571000, 7.9, 0.900000, 2.400000, 0.353, 0.400000, 0.900000, 0.5, 0.000000, 0.000000, 0.0, 0.300000, 0.000000, 0.300000, 1.100000, 0.300000, 0.000000, 0.000000, 0.000000, 0.600000, 0.100000, 2.100000, -1.100000, 3.9, 0, 0, 18, 18, 18, 15, 18, 17, 17, 18, 12, 13, 4, 20, 20, 20, 15, 22, 21, 13, 18, 20, 19, 21, 21, 21, 17, 14, 20, 7, 5], ["Players", 1628455, "Mike James", 4, 1, 3, 0.250000, 4.5, 0.500000, 2.300000, 0.222, 0.000000, 0.300000, 0.0, 0.000000, 0.000000, 0.0, 0.300000, 0.000000, 0.300000, 1.500000, 0.300000, 0.300000, 0.000000, 0.300000, 0.800000, 0.300000, 1.000000, -2.500000, 4.1, 0, 0, 21, 22, 18, 22, 21, 19, 18, 22, 19, 17, 19, 20, 20, 20, 17, 22, 22, 9, 20, 15, 19, 13, 19, 17, 21, 19, 19, 7, 5], ["Players", 202703, "Nikola Mirotic", 30, 20, 10, 0.667000, 29.1, 5.400000, 12.700000, 0.427, 2.200000, 6.600000, 0.335, 1.600000, 1.900000, 0.81, 1.400000, 6.800000, 8.200000, 1.400000, 1.000000, 1.000000, 0.900000, 0.200000, 2.100000, 2.200000, 14.600000, 2.800000, 31.0, 8, 0, 11, 11, 11, 2, 5, 4, 4, 16, 1, 1, 12, 4, 4, 6, 4, 3, 3, 11, 7, 5, 4, 16, 6, 4, 4, 3, 4, 4, 5], ["Players", 201600, "Omer Asik", 14, 7, 7, 0.500000, 8.6, 0.500000, 1.100000, 0.438, 0.000000, 0.000000, 0.0, 0.300000, 0.900000, 0.333, 0.500000, 2.100000, 2.600000, 0.100000, 0.400000, 0.100000, 0.100000, 0.200000, 1.000000, 0.700000, 1.300000, -0.200000, 5.0, 0, 0, 15, 17, 15, 21, 17, 19, 21, 14, 19, 20, 19, 16, 7, 19, 12, 11, 11, 20, 16, 19, 14, 15, 16, 14, 19, 9, 18, 7, 5], ["Players", 200765, "Rajon Rondo", 65, 41, 24, 0.631000, 26.2, 3.600000, 7.600000, 0.468, 0.800000, 2.300000, 0.333, 0.400000, 0.700000, 0.543, 0.500000, 3.600000, 4.000000, 8.200000, 2.300000, 1.100000, 0.200000, 0.400000, 1.800000, 1.100000, 8.300000, 0.300000, 26.8, 15, 2, 6, 6, 6, 6, 6, 6, 6, 8, 9, 9, 13, 14, 12, 15, 13, 5, 7, 1, 3, 4, 11, 6, 9, 5, 6, 7, 5, 3, 2], ["Players", 203524, "Solomon Hill", 12, 8, 4, 0.667000, 15.6, 0.900000, 3.400000, 0.268, 0.300000, 1.800000, 0.19, 0.300000, 0.500000, 0.5, 0.800000, 2.300000, 3.000000, 1.800000, 0.800000, 0.600000, 0.100000, 0.300000, 1.800000, 0.700000, 2.400000, -2.200000, 10.0, 0, 0, 17, 15, 17, 2, 11, 16, 14, 19, 13, 12, 17, 17, 15, 17, 10, 9, 9, 8, 12, 7, 17, 13, 8, 15, 16, 18, 14, 7, 5], ["Players", 2754, "Tony Allen", 22, 12, 10, 0.545000, 12.4, 2.000000, 4.100000, 0.484, 0.200000, 0.500000, 0.333, 0.500000, 1.000000, 0.524, 0.900000, 1.200000, 2.100000, 0.400000, 0.900000, 0.500000, 0.100000, 0.500000, 2.200000, 0.800000, 4.700000, -0.900000, 8.9, 0, 0, 14, 14, 11, 19, 13, 10, 12, 6, 17, 16, 13, 10, 6, 16, 7, 15, 13, 17, 9, 10, 15, 5, 3, 11, 13, 13, 15, 7, 5], ["Players", 1627215, "Walter Lemon Jr.", 5, 4, 1, 0.800000, 7.0, 1.400000, 3.200000, 0.438, 0.200000, 0.200000, 1.0, 0.400000, 0.600000, 0.667, 0.000000, 0.400000, 0.400000, 1.000000, 0.800000, 0.000000, 0.200000, 0.800000, 1.000000, 0.800000, 3.400000, -3.000000, 5.2, 0, 0, 19, 18, 22, 1, 19, 15, 16, 14, 16, 19, 1, 12, 14, 13, 21, 18, 20, 14, 10, 20, 9, 2, 16, 10, 15, 20, 17, 7, 5] ] }] }; exports.default = JSON.stringify(team_detail_nop); //# sourceMappingURL=team_detail_nop.js.map
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # */AIPND-revision/intropyproject-classify-pet-images/classify_images.py # # PROGRAMMER: Jhon Alexander Holguin B. # DATE CREATED: 26/12/2018 # REVISED DATE: # PURPOSE: Create a function classify_images that uses the classifier function # to create the classifier labels and then compares the classifier # labels to the pet image labels. This function inputs: # -The Image Folder as image_dir within classify_images and function # and as in_arg.dir for function call within main. # -The results dictionary as results_dic within classify_images # function and results for the functin call within main. # -The CNN model architecture as model wihtin classify_images function # and in_arg.arch for the function call within main. # This function uses the extend function to add items to the list # that's the 'value' of the results dictionary. You will be adding the # classifier label as the item at index 1 of the list and the comparison # of the pet and classifier labels as the item at index 2 of the list. # ## # Imports classifier function for using CNN to classify images from classifier import classifier # TODO 3: Define classify_images function below, specifically replace the None # below by the function definition of the classify_images function. # Notice that this function doesn't return anything because the # results_dic dictionary that is passed into the function is a mutable # data type so no return is needed. # def classify_images(images_dir, results_dic, model): """ Creates classifier labels with classifier function, compares pet labels to the classifier labels, and adds the classifier label and the comparison of the labels to the results dictionary using the extend function. Be sure to format the classifier labels so that they will match your pet image labels. The format will include putting the classifier labels in all lower case letters and strip the leading and trailing whitespace characters from them. For example, the Classifier function returns = 'Maltese dog, Maltese terrier, Maltese' so the classifier label = 'maltese dog, maltese terrier, maltese'. Recall that dog names from the classifier function can be a string of dog names separated by commas when a particular breed of dog has multiple dog names associated with that breed. For example, you will find pet images of a 'dalmatian'(pet label) and it will match to the classifier label 'dalmatian, coach dog, carriage dog' if the classifier function correctly classified the pet images of dalmatians. PLEASE NOTE: This function uses the classifier() function defined in classifier.py within this function. The proper use of this function is in test_classifier.py Please refer to this program prior to using the classifier() function to classify images within this function Parameters: images_dir - The (full) path to the folder of images that are to be classified by the classifier function (string) results_dic - Results Dictionary with 'key' as image filename and 'value' as a List. Where the list will contain the following items: index 0 = pet image label (string) --- where index 1 & index 2 are added by this function --- NEW - index 1 = classifier label (string) NEW - index 2 = 1/0 (int) where 1 = match between pet image and classifer labels and 0 = no match between labels model - Indicates which CNN model architecture will be used by the classifier function to classify the pet images, values must be either: resnet alexnet vgg (string) Returns: None - results_dic is mutable data type so no return needed. """ NO_CONST = 0 YES_CONST = 1 print("Classifying images...") for label_key in results_dic: label_found = NO_CONST file_path = images_dir + label_key classifier_result = classifier(images_dir + label_key, model).lower().strip() results_dic[label_key].append(classifier_result) if results_dic[label_key][0] in classifier_result: label_found = YES_CONST results_dic[label_key].append(label_found)
/** * Simple benchmark which compares eventloop speed with Fibers sync * * Note: Using process.nextTick in sum() function is not represents the real * situation. In real live our we use I/O with external sources like * network or fs. There's no need to use Sync/Fibers with code without I/O. * So, even if we change process.nextTick to setTimeout() on 3 ms, the result * will be almost same as native one, because asynchronous function time will * seriously reduce Sync/Fibers wrapper cost. * * The more I/O in your app, the cheaper cost of Fibers. * * On Macbook Pro | 2.66 GHz i7 | DDR3 1067 MHz | OSX 10.7.3 | node v0.6.18, node-fibers v0.6.8 * * Event-loop took 163 ms * Sync took 486 ms (x2) * Futures took 7216 ms (x44) * async() took 542 ms (x3) * async().sync() took 468 ms (x2) * Fibers.future took 1452 ms (x8) * Fiber took 422 ms (x2) * * REAL result: * * Event-loop took 354 ms * Sync took 361 ms (x1) * Futures took 370 ms (x1) * async() took 353 ms (x0) * async().sync() took 351 ms (x0) * Fibers.future took 350 ms (x0) * Fiber took 350 ms (x0) */ var Sync = require('..'); var max = 100000; function sum(a, b, callback) { process.nextTick(function(){ callback(null, a + b); }); } var sumAsync = function (a, b, callback) { var f = Fiber.current; process.nextTick(function(){ f.run(a + b); }); Fiber.yield(); }.async(); /* REAL var max = 100; var sum = function(a, b, callback) { setTimeout(function(){ callback(null, a + b); }, 3); } var sumAsync = function (a, b, callback) { var f = Fiber.current; setTimeout(function(){ f.run(a + b); }, 3); Fiber.yield(); }.async(); */ function loop(i, callback) { sum(3, 4, function(){ if (i < max) { loop(i + 1, callback); } else { callback(); } }) } var start = new Date(); loop(0, function(){ var nativeTime = new Date - start; console.log('Event-loop took %d ms', nativeTime); // Test sync Sync(function(){ var start = new Date(); for(var i = 0; i <= max; i++) { sum.sync(null, 3, 4); } var syncTime = new Date - start; console.log('Sync took %d ms (x%d)', syncTime, ~~ (syncTime / nativeTime)); var start = new Date(); for(var i = 0; i <= max; i++) { sum.future(null, 3, 4).yield(); } var futureTime = new Date - start; console.log('Futures took %d ms (x%d)', futureTime, ~~ (futureTime / nativeTime)); var start = new Date(); for(var i = 0; i <= max; i++) { sumAsync(3, 4); } var asyncTime = new Date - start; console.log('async() took %d ms (x%d)', asyncTime, ~~ (asyncTime / nativeTime)); var start = new Date(); for(var i = 0; i <= max; i++) { sumAsync.sync(null, 3, 4); } var asyncSyncTime = new Date - start; console.log('async().sync() took %d ms (x%d)', asyncSyncTime, ~~ (asyncSyncTime / nativeTime)); var Future = require('fibers/future'); var sumFuture = Future.wrap(sum); var start = new Date(); for(var i = 0; i <= max; i++) { Future.wait(sumFuture(3, 4)); } var fibersFutureTime = new Date - start; console.log('Fibers.future took %d ms (x%d)', fibersFutureTime, ~~ (fibersFutureTime / nativeTime)); // Test Fibers Fiber(function(){ var f = Fiber.current; var start = new Date(); for(var i = 0; i <= max; i++) { sum(3, 4, function() { f.run(); }); Fiber.yield(); } var fiberTime = new Date - start; console.log('Fiber took %d ms (x%d)', fiberTime, ~~ (fiberTime / nativeTime)); }).run(); }) });
import sys, wx sys.path.append('../../') from sciwx.widgets import ParaDialog if __name__ == '__main__': para = {'name':'yxdragon', 'age':10, 'h':1.72, 'w':70, 'sport':True, 'sys':'Mac', 'lan':['C/C++', 'Python'], 'c':(255,0,0)} view = [('lab', 'lab', 'This is a questionnaire'), (str, 'name', 'name', 'please'), (int, 'age', (0,150), 0, 'age', 'years old'), (float, 'h', (0.3, 2.5), 2, 'height', 'm'), ('slide', 'w', (1, 150), 0, 'weight','kg'), (bool, 'sport', 'do you like sport'), (list, 'sys', ['Windows','Mac','Linux'], str, 'favourite', 'system'), ('chos', 'lan', ['C/C++','Java','Python'], 'lanuage you like(multi)'), ('color', 'c', 'which', 'you like')] app = wx.App() pd = ParaDialog(None, 'Test') pd.init_view(view, para, preview=True, modal=False) pd.pack() pd.ShowModal() print(para) app.MainLoop()
/** * 网络请求的公共方法 * 1.基本请求 * 2.为了后续获取数据方便,promise处理:fetch axios基于promise * 3.对获取数据的状态处理:loadding toast * 4.对请求头的处理!!!机型、大小、系统、屏幕 */ let store = require("../utils/store.js") let system = store.getSystemInfo(); const clientInfo = { "clientType": "mp", "appnm": "iwen", "model": system.model, "os": system.system, "screen": system.screenWidth + "*" + system.screenHeight, "version": App.version, "chennel": "miniprogram" } module.exports = { // 封装 wx.request 为 fetch() fetch: (url, data = {}, option = {}) => { let { loading = true, toast = true, method = 'get' } = option; return new Promise((resolve, reject) => { if (loading) { wx.showLoading({ title: '加载中...', mask: true }) } let env = App.config.baseApi; wx.request({ url: env + url, data, method, header: { "clientInfo": JSON.stringify(clientInfo) }, success: function (result) { let res = result.data; // { code:0,data:"",message:"" } if (res.code == 0) { if (loading) { wx.hideLoading(); } resolve(res.data); } else { if (toast) { wx.showToast({ mask: true, title: res.message, icon: "none" }) } else { wx.hideLoading(); } } }, fail: function (e = { code: -1, msg: errMsg, errMeg }) { let msg = e.errMsg; // 自己测试出来 if (msg == "request:fail timeout") { msg = '请求超时,请稍后处理'; } wx.showToast({ title: msg, icon: "none" }) reject(e); } }) }) } }
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Classes for different algorithms of reduction and broadcasting.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import copy import multiprocessing.dummy import multiprocessing.pool import threading import six from tensorflow.python.client import device_lib from tensorflow.python.distribute import collective_util from tensorflow.python.distribute import cross_device_utils from tensorflow.python.distribute import device_util from tensorflow.python.distribute import distribute_utils from tensorflow.python.distribute import ps_values from tensorflow.python.distribute import reduce_util from tensorflow.python.distribute import tpu_values from tensorflow.python.distribute import values as value_lib from tensorflow.python.distribute import values_util from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import kernels from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import nest from tensorflow.python.util.tf_export import tf_export from tensorflow.tools.docs import doc_controls def check_destinations(destinations): """Checks whether `destinations` is not empty. Args: destinations: a `DistributedValues`, variable, or string object. Returns: Boolean which is True if `destinations` is not empty. """ # Calling bool() on a ResourceVariable is not allowed. if isinstance(destinations, (resource_variable_ops.BaseResourceVariable, ops.Tensor)): return bool(destinations.device) return bool(destinations) def validate_destinations(destinations): """Validates the `destination` is one of expected types.""" if not isinstance( destinations, (value_lib.DistributedValues, ops.Tensor, ps_values.AggregatingVariable, six.string_types, tpu_values.TPUMirroredVariable )) and not resource_variable_ops.is_resource_variable(destinations): raise ValueError("destinations must be one of a `DistributedValues` object," " a tf.Variable object, or a device string.") if not check_destinations(destinations): raise ValueError("destinations can not be empty") def reduce_non_distributed_value( reduce_op, value, destinations, num_replicas_in_graph): """Reduce a non-DistributedValue `value` to `destinations`.""" if isinstance(value, value_lib.DistributedValues): raise ValueError("You are passing a `DistributedValues` to " "`reduce_non_distributed_value`, which is not allowed.") # If the same value is present on all replicas then the PerReplica value will # be a single value. We also handle the case when `value` is a single value # and equal to 0. # TODO:(b/138823479): handle the tensor value properly. if not tensor_util.is_tf_type(value) and value == 0: return 0 # If there is only a single value and the reduce op is MEAN, # that value should be on all destinations. if reduce_op == reduce_util.ReduceOp.MEAN: return value elif num_replicas_in_graph != 1: # We do not support a reduce op of SUM if the value is the same across # all replicas. We call this as part of assign functions for # MirroredVariables and summing up identical values across replicas is not # clearly defined. raise ValueError("A non-DistributedValues value %s cannot be reduced with " "the given reduce op %s." % (value, reduce_op)) else: validate_destinations(destinations) return simple_broadcast(value, destinations) def _make_tensor_into_per_replica(input_tensor): """Converts a single tensor into a PerReplica object.""" if isinstance(input_tensor, (tuple, list)): raise ValueError("Cannot convert `input_tensor` to a `PerReplica` object, " "got %r but expected a object that is not a tuple or list." % (input_tensor,)) if isinstance(input_tensor, value_lib.PerReplica): return input_tensor elif hasattr(input_tensor, "device"): return value_lib.PerReplica((input_tensor,)) else: raise ValueError("Cannot convert `input_tensor` to a `PerReplica` object " "because it doesn't have device set.") def _normalize_value_destination_pairs(value_destination_pairs): """Converts each tensor into a PerReplica object in the input list.""" result = [] value_destination_pairs = list(value_destination_pairs) if not isinstance(value_destination_pairs, (list, tuple)): raise ValueError("`value_destination_pairs` should be a list or tuple") for pair in value_destination_pairs: if not isinstance(pair, tuple): raise ValueError( "Each element of `value_destination_pairs` should be a tuple.") if len(pair) != 2: raise ValueError("Each element of `value_destination_pairs` should be a " "tuple of size 2.") per_replica = _make_tensor_into_per_replica(pair[0]) result.append((per_replica, pair[1])) return result def _validate_value_destination_pairs(value_destination_pairs): """Validates value_destination_pairs are valid.""" # TODO(yuefengz): raise exceptions instead of returning False. if not value_destination_pairs: return False if not isinstance(value_destination_pairs, (list, tuple)): return False if not all(isinstance(pair, tuple) for pair in value_destination_pairs): return False if not all(isinstance(v[0], value_lib.PerReplica) for v in value_destination_pairs): return False return True # TODO(yuefengz): consider calling this function in the caller of # CrossDeviceOps. def get_devices_from(destinations): if isinstance(destinations, value_lib.DistributedValues): return destinations._devices # pylint: disable=protected-access elif isinstance(destinations, six.string_types): return (device_util.resolve(destinations),) return (device_util.resolve(destinations.device),) def _devices_match(left, right): return left is right or set(get_devices_from(left)) == set( get_devices_from(right)) def _all_devices_match(value_destination_pairs): if not all(_devices_match(v, d) for v, d in value_destination_pairs): return False if not all(_devices_match(v, value_destination_pairs[0][0]) for v, _ in value_destination_pairs[1:]): return False return True def simple_broadcast(value, destinations, always_mirrored=False): """Broadcast `value` to `destinations` using simple copies.""" devices = get_devices_from(destinations) if len(devices) == 1 and not always_mirrored: return cross_device_utils.copy_tensor_or_indexed_slices_to_device( value, devices[0]) else: value_updates = [] for d in devices: value_updates.append( cross_device_utils.copy_tensor_or_indexed_slices_to_device(value, d)) return distribute_utils.regroup(value_updates, wrap_class=value_lib.Mirrored) def _simple_reduce(per_replica_value, reduce_to_device, accumulation_fn, reduce_op): """Reduces the value by accumulation_fn and reduce_op.""" all_values = per_replica_value.values if not all_values: raise ValueError("`per_replica_value` must be non-empty") count = len(all_values) with ops.device(reduce_to_device): with context.device_policy(context.DEVICE_PLACEMENT_SILENT): reduced = cross_device_utils.aggregate_tensors_or_indexed_slices( all_values, accumulation_fn) if reduce_op == reduce_util.ReduceOp.MEAN: reduced = cross_device_utils.divide_by_n_tensors_or_indexed_slices( reduced, count) elif reduce_op != reduce_util.ReduceOp.SUM: raise ValueError("`reduce_op` must be Reduce.SUM or Reduce.MEAN.") return reduced def _simple_gather(per_replica_value, reduce_to_device, axis): """Concatenate all values in the DistributedValues input and return.""" all_values = per_replica_value.values if not all_values: raise ValueError("`per_replica_value` must be non-empty") with ops.device(reduce_to_device): with context.device_policy(context.DEVICE_PLACEMENT_SILENT): gathered = array_ops.concat(all_values, axis) return gathered @tf_export("distribute.CrossDeviceOps") class CrossDeviceOps(object): """Base class for cross-device reduction and broadcasting algorithms. The main purpose of this class is to be passed to `tf.distribute.MirroredStrategy` in order to choose among different cross device communication implementations. Prefer using the methods of `tf.distribute.Strategy` instead of the ones of this class. Implementations: * `tf.distribute.ReductionToOneDevice` * `tf.distribute.NcclAllReduce` * `tf.distribute.HierarchicalCopyAllReduce` """ def __init__(self): pass @property def _num_between_graph_workers(self): # Returns 1 by default, the value may be overridden by sub classes. return 1 def reduce(self, reduce_op, per_replica_value, destinations, options=None): """Reduce `per_replica_value` to `destinations`. See `tf.distribute.StrategyExtended.reduce_to`. This can only be called in the cross-replica context. Args: reduce_op: a `tf.distribute.ReduceOp` specifying how values should be combined. per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` like object. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to reduce to. To perform an all-reduce, pass the same to `value` and `destinations`. Note that if it's a `tf.Variable`, the value is reduced to the devices of that variable, and this method doesn't update the variable. options: a `tf.distribute.experimental.CommunicationOptions`. See `tf.distribute.experimental.CommunicationOptions` for details. Returns: A `tf.Tensor` or `tf.distribute.DistributedValues`. Raises: ValueError: if per_replica_value can't be converted to a `tf.distribute.DistributedValues` or if destinations is not a string, `tf.Variable` or `tf.distribute.DistributedValues`. """ if options is None: options = collective_util.Options() if not isinstance(per_replica_value, value_lib.DistributedValues): per_replica_value = _make_tensor_into_per_replica(per_replica_value) validate_destinations(destinations) # Shortcut if `per_replica_value` only contains one value. if self._num_between_graph_workers == 1 and len( per_replica_value.values) == 1 and _devices_match( per_replica_value, destinations): with ops.device(per_replica_value.values[0].device): v = array_ops.identity(per_replica_value.values[0]) return distribute_utils.regroup((v,), wrap_class=value_lib.Mirrored) if options is None: options = collective_util.Options() return self.reduce_implementation(reduce_op, per_replica_value, destinations, options) def _gather(self, per_replica_value, destinations, axis, options=None): """Gather `per_replica_value` to `destinations`. Args: per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` like object. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to gather to. To perform an all-gather, pass the same to `value` and `destinations`. Note that if it's a `tf.Variable`, the value is gathered to the devices of that variable, and this method doesn't update the variable. axis: specifies the dimension to gather along within each replica's tensor. options: a `tf.distribute.experimental.CommunicationOptions`. See `tf.distribute.experimental.CommunicationOptions` for details. Returns: A `tf.Tensor` or `tf.distribute.DistributedValues` Raises: ValueError: if per_replica_value can't be converted to a `tf.distribute.DistributedValues` or if destinations is not a string, `tf.Variable` or `tf.distribute.DistributedValues`. """ if isinstance(per_replica_value, ops.IndexedSlices): raise NotImplementedError("gather/all_gather does not support " "IndexedSlices") if options is None: options = collective_util.Options() if not isinstance(per_replica_value, value_lib.DistributedValues): per_replica_value = _make_tensor_into_per_replica(per_replica_value) validate_destinations(destinations) # Shortcut if `per_replica_value` only contains one value. if self._num_between_graph_workers == 1 and len( per_replica_value.values) == 1 and _devices_match( per_replica_value, destinations): with ops.device(per_replica_value.values[0].device): v = array_ops.identity(per_replica_value.values[0]) return distribute_utils.regroup((v,), wrap_class=value_lib.Mirrored) return self._gather_implementation(per_replica_value, destinations, axis, options) def _gather_implementation(self, per_replica_value, destinations, axis, options): """Implementation of `gather` method of `tf.distribute.CrossDeviceOps`. Overriding this method is useful for subclass implementers. Args: per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` like object. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to gather to. To perform an all-gather, pass the same to `value` and `destinations`. Note that if it's a `tf.Variable`, the value is gathered to the devices of that variable, this method doesn't update the variable. axis: specifies the dimension to gather along within each replica's tensor. options: a `tf.distribute.experimental.CommunicationOptions`. See `tf.distribute.experimental.CommunicationOptions` for details. Returns: A `tf.Tensor` or `tf.distribute.DistributedValues`. Raises: ValueError: if per_replica_value can't be converted to a `tf.distribute.DistributedValues` or if destinations is not a string, `tf.Variable` or `tf.distribute.DistributedValues`. """ raise NotImplementedError( "_gather method must be implemented in descendants.") def batch_reduce(self, reduce_op, value_destination_pairs, options=None): """Reduce values to destinations in batches. See `tf.distribute.StrategyExtended.batch_reduce_to`. This can only be called in the cross-replica context. Args: reduce_op: a `tf.distribute.ReduceOp` specifying how values should be combined. value_destination_pairs: a sequence of (value, destinations) pairs. See `tf.distribute.CrossDeviceOps.reduce` for descriptions. options: a `tf.distribute.experimental.CommunicationOptions`. See `tf.distribute.experimental.CommunicationOptions` for details. Returns: A list of `tf.Tensor` or `tf.distribute.DistributedValues`, one per pair in `value_destination_pairs`. Raises: ValueError: if `value_destination_pairs` is not an iterable of tuples of `tf.distribute.DistributedValues` and destinations. """ if options is None: options = collective_util.Options() # TODO(yuefengz): if destinations are different, split into several # `_batch_reduce` invocations. if not _validate_value_destination_pairs(value_destination_pairs): # If the first element of each pair is a tensor, we try to turn it into a # PerReplica object. value_destination_pairs = _normalize_value_destination_pairs( value_destination_pairs) for _, d in value_destination_pairs: validate_destinations(d) # Shortcut all PerReplica objects only contain one value. if self._num_between_graph_workers == 1 and _all_devices_match( value_destination_pairs) and len( value_destination_pairs[0][0].values) == 1: return [ distribute_utils.regroup(v.values, wrap_class=value_lib.Mirrored) for v, _ in value_destination_pairs ] if options is None: options = collective_util.Options() return self.batch_reduce_implementation(reduce_op, value_destination_pairs, options) def broadcast(self, tensor, destinations): """Broadcast `tensor` to `destinations`. This can only be called in the cross-replica context. Args: tensor: a `tf.Tensor` like object. The value to broadcast. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to broadcast to. Note that if it's a `tf.Variable`, the value is broadcasted to the devices of that variable, this method doesn't update the variable. Returns: A `tf.Tensor` or `tf.distribute.DistributedValues`. """ validate_destinations(destinations) return self.broadcast_implementation(tensor, destinations) @doc_controls.for_subclass_implementers def reduce_implementation(self, reduce_op, per_replica_value, destinations, options): """Implementation of `reduce`. Overriding this method is useful for subclass implementers. Args: reduce_op: a `tf.distribute.ReduceOp` specifying how values should be combined. per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` like object. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to reduce to. To perform an all-reduce, pass the same to `value` and `destinations`. Note that if it's a `tf.Variable`, the value is reduced to the devices of that variable, this method doesn't update the variable. options: a `tf.distribute.experimental.CommunicationOptions`. See `tf.distribute.experimental.CommunicationOptions` for details. Returns: A `tf.Tensor` or `tf.distribute.DistributedValues`. Raises: ValueError: if per_replica_value can't be converted to a `tf.distribute.DistributedValues` or if destinations is not a string, `tf.Variable` or `tf.distribute.DistributedValues`. """ raise NotImplementedError( "_reduce method must be implemented in descendants.") @doc_controls.for_subclass_implementers def batch_reduce_implementation(self, reduce_op, value_destination_pairs, options): """Implementation of `batch_reduce`. Overriding this method is useful for subclass implementers. Args: reduce_op: a `tf.distribute.ReduceOp` specifying how values should be combined. value_destination_pairs: a sequence of (value, destinations) pairs. See `reduce` for descriptions. options: a `tf.distribute.experimental.CommunicationOptions`. See `tf.distribute.experimental.CommunicationOptions` for details. Returns: A list of `tf.Tensor` or `tf.distribute.DistributedValues`, one per pair in `value_destination_pairs`. Raises: ValueError: if `value_destination_pairs` is not an iterable of tuples of `tf.distribute.DistributedValues` and destinations. """ raise NotImplementedError( "batch_reduce_implementation method must be implemented in descendants." ) @doc_controls.for_subclass_implementers def broadcast_implementation(self, tensor, destinations): """Implementation of `broadcast`. Args: tensor: a `tf.Tensor` like object. The value to broadcast. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to broadcast to. `destinations`. Note that if it's a `tf.Variable`, the value is broadcasted to the devices of that variable, this method doesn't update the variable. Returns: A `tf.Tensor` or `tf.distribute.DistributedValues`. """ return simple_broadcast(tensor, destinations, always_mirrored=True) # ========================== Collective APIs ================================ # # Different than `reduce`, `batch_reduce` and `broadcast` which must be called # in cross-replcia context, collective APIs are to be called in replica # context. def _all_reduce(self, reduce_op, value, replica_id, options): """All-reduce the `value` across all replicas so that all get the result. `value` can be a nested structure of tensors. The implementation should generally batch the all-reduces when possible. `options` can be set to hint the batching behavior. This API must be called in a replica context. Args: reduce_op: A `tf.distribute.ReduceOp` value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". value: Value to be reduced. A tensor or a nested structure of tensors. replica_id: An interger indicating the id of the replica where this all_reduce is called under. This is the local replica id that ranges from 0 to len(local_devices) - 1. options: A `tf.distribute.experimental.CommunicationOptions`. Returns: A tensor or a nested strucutre of tensors with the reduced values. The structure is the same as `value`. """ raise NotImplementedError("_all_reduce must be implemented in descendants.") @tf_export("distribute.ReductionToOneDevice") class ReductionToOneDevice(CrossDeviceOps): """A CrossDeviceOps implementation that copies values to one device to reduce. This implementation always copies values to one device to reduce them, then broadcast reduced values to the destinations. It doesn't support efficient batching. Here is how you can use `ReductionToOneDevice` in `tf.distribute.MirroredStrategy`: ``` strategy = tf.distribute.MirroredStrategy( cross_device_ops=tf.distribute.ReductionToOneDevice()) ``` """ def __init__(self, reduce_to_device=None, accumulation_fn=None): """Initializes with a device to reduce to and a way to accumulate. Args: reduce_to_device: the intermediate device to reduce to. If None, reduce to the first device in `destinations` of the `reduce` method. accumulation_fn: a function that does accumulation. If None, `tf.math.add_n` is used. """ self.reduce_to_device = reduce_to_device self.accumulation_fn = accumulation_fn or math_ops.add_n super(ReductionToOneDevice, self).__init__() def reduce_implementation(self, reduce_op, per_replica_value, destinations, options): del options # Unused. if check_destinations(destinations): devices = get_devices_from(destinations) else: devices = get_devices_from(per_replica_value) reduce_to_device = self.reduce_to_device or devices[0] logging.log_first_n( logging.INFO, "Reduce to %s then broadcast to %r." % (reduce_to_device, devices), 10) reduced = _simple_reduce(per_replica_value, reduce_to_device, self.accumulation_fn, reduce_op) return self.broadcast(reduced, destinations) def _gather_implementation(self, per_replica_value, destinations, axis, options): del options # Unused. if check_destinations(destinations): devices = get_devices_from(destinations) else: devices = get_devices_from(per_replica_value) reduce_to_device = self.reduce_to_device or devices[0] logging.log_first_n( logging.INFO, "Gather to %s then broadcast to %r." % (reduce_to_device, devices), 10) gathered = _simple_gather(per_replica_value, reduce_to_device, axis) return self.broadcast(gathered, destinations) def batch_reduce_implementation(self, reduce_op, value_destination_pairs, options): return [ self.reduce_implementation( reduce_op, t, destinations=v, options=options) for t, v in value_destination_pairs ] def _group_value_by_device(per_replica_values): """Group values into sublists by their devices. This grouping is needed to call the all-reduce library because it expects a list of the following form: [[(grad0_gpu0, v0_gpu0), (grad1_gpu0, v1_gpu0), (grad2_gpu0, v2_gpu0) ...], [(grad0_gpu1, v0_gpu1), (grad1_gpu1, v1_gpu1), (grad2_gpu1, v2_gpu1) ...], [(grad0_gpu2, v0_gpu2), (grad1_gpu0, v1_gpu2), (grad2_gpu0, v2_gpu2) ...], ... ] Args: per_replica_values: a list of PerReplica objects. Returns: a list of lists, each sublist has components for its corresponding device of PerReplica objects, paired with a None. """ destinations = per_replica_values[0]._devices # pylint: disable=protected-access grouped = [[] for _ in range(len(destinations))] for per_replica_value in per_replica_values: # pylint: disable=protected-access for i, v in enumerate(per_replica_value.values): assert per_replica_value._devices == destinations grouped[i].append((v, None)) return grouped def _ungroup_and_make_mirrored(grouped_reduced, destinations, reduce_op, num_between_graph_workers=1): """Ungroup results from all-reduce and make Mirrored objects. Each all-reduce result will be divided by the number of destinations before Mirrored objects are created if reduce_op is "mean". Args: grouped_reduced: a list of lists, each sublist has components for each device, paired with a None. It is the result from cross_device_utils.aggregate_gradients_using*. destinations: a value to colocate the result with. reduce_op: Indicates how values will be aggregated. Accepted values are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. num_between_graph_workers: number of workers in the between-graph replication. Returns: a list of Mirrored objects. """ num_replicas = len(get_devices_from(destinations)) * num_between_graph_workers index = [[] for _ in range(len(grouped_reduced[0]))] for per_replica_reduced in grouped_reduced: for i, (v, _) in enumerate(per_replica_reduced): if reduce_op == reduce_util.ReduceOp.MEAN: with ops.device(v.device): index[i].append(v / num_replicas) else: index[i].append(v) return [distribute_utils.regroup( v, wrap_class=value_lib.Mirrored) for v in index] class _ConcatAndSplitPacker(object): """Concatenate and split tensors for reduction.""" def __init__(self, num_packs=1): """Initialize the _ConcatAndSplitPacker object. Args: num_packs: specifies the number of split packs that will be formed. Raises: ValueError: if num_packs is not greater than 0. """ if num_packs <= 0: raise ValueError("num_packs must be greater than zero.") self.num_packs = num_packs def pack(self, grouped_grads_and_vars): """Pack tensors.""" self.grouped_grads_and_vars = grouped_grads_and_vars self.all_device_shapes = [] self.all_device_sizes = [] device_grad_packs = [] for device_grads_and_vars in grouped_grads_and_vars: with ops.colocate_with(device_grads_and_vars[0][0]): # Flatten all the grads. flat_grads = [ array_ops.reshape(g, [-1]) for g, _ in device_grads_and_vars ] # Remember the original shape of all the grads. device_shapes = [array_ops.shape(g) for g, _ in device_grads_and_vars] # Remember the original sizes of all the grads. device_sizes = [array_ops.size(g) for g, _ in device_grads_and_vars] # Concat all the flat grads into a big flat tensor. concat_grads = array_ops.concat(flat_grads, 0) # Split the big tensor into num_splits packs. In cases where the # total size is not divisible num_splits, the last pack gets # more elements. # TODO(zhengxq): it is also possible to optimize away all the concat # as well. num_splits = self.num_packs # The array_ops.size function will sometimes remove static shapes. So if # all gradient shapes are defined, we use another method to get the # total size. # TODO(yuefengz): move this logic to array_ops.size. if all(g.shape.is_fully_defined() for g, _ in device_grads_and_vars): total_grad_size = sum( [g.shape.num_elements() for g, _ in device_grads_and_vars]) else: total_grad_size = array_ops.size(concat_grads) split_size = total_grad_size // num_splits split_size_last = total_grad_size - split_size * (num_splits - 1) split_sizes = [split_size] * (num_splits - 1) + [split_size_last] grad_packs = array_ops.split(concat_grads, split_sizes) # Ready to aggregate the repacked gradients, with fake variables. # TODO(zhengxq): It is hacky to have to use fake variables. # We should remove the need for variables in # aggregate_gradients_using*. device_grad_packs.append(zip(grad_packs, [None] * num_splits)) self.all_device_shapes.append(device_shapes) self.all_device_sizes.append(device_sizes) return device_grad_packs def unpack(self, summed_device_grad_packs): """Reverse the pack.""" aggregated_device_grads = [] for (summed_device_grad_packs, device_grads_and_vars, device_shapes, device_sizes) in zip( summed_device_grad_packs, self.grouped_grads_and_vars, self.all_device_shapes, self.all_device_sizes): # pylint: enable=line-too-long # Reverse the packing operations in the previous steps. Form the # summed gradients back into their original shapes. with ops.colocate_with(summed_device_grad_packs[0][0]): # Form a list of the summed grad packs. device_grad_packs = [g for g, _ in summed_device_grad_packs] # Concat them back into a big flat tensor. device_grads_concat = array_ops.concat(device_grad_packs, 0) # Split the tensors back into their original sizes. grads_with_sizes = array_ops.split(device_grads_concat, device_sizes) # Reshape the tensors back into their original shapes. grads_with_shapes = [ array_ops.reshape(grad, shape) for shape, grad in zip(device_shapes, grads_with_sizes) ] # Form the list with the original list of variables. summed_device_grads = [ (g, v) for g, (_, v) in zip(grads_with_shapes, device_grads_and_vars) ] aggregated_device_grads.append(summed_device_grads) return aggregated_device_grads def _pack_tensors(device_grads, num_packs=0): """Pack tensors if specified.""" if num_packs > 0: tensor_packer = _ConcatAndSplitPacker(num_packs) device_grad_packs = tensor_packer.pack(device_grads) else: tensor_packer = None device_grad_packs = device_grads return device_grad_packs, tensor_packer def _unpack_tensors(reduced, tensor_packer=None): """Unpack tensors if they are packed before all-reduce.""" if tensor_packer: return tensor_packer.unpack(reduced) return reduced class AllReduceCrossDeviceOps(CrossDeviceOps): """All-reduce implementation of CrossDeviceOps. It performs all-reduce when applicable using NCCL or hierarchical copy. For the batch API, tensors will be repacked or aggregated for more efficient cross-device transportation. For reduces that are not all-reduce, it falls back to `tf.distribute.ReductionToOneDevice`. """ def __init__(self, all_reduce_alg="nccl", num_packs=1): """Initializes the object. Args: all_reduce_alg: the all-reduce algorithm to use, currently only "nccl" or "hierarchical_copy" are supported. num_packs: a non-negative integer. The number of packs to split values into. If zero, no packing will be done. """ self._all_reduce_alg = all_reduce_alg self._num_packs = num_packs self._simple_cross_replica_ops = ReductionToOneDevice() super(AllReduceCrossDeviceOps, self).__init__() def reduce_implementation(self, reduce_op, per_replica_value, destinations, options): del options # Unused. # To use NCCL or all-reduce, source and destination devices should match, # and none of the devices should be CPU. if (_devices_match(per_replica_value, destinations) and not any("cpu" in d.lower() for d in get_devices_from(destinations))): return self._batch_all_reduce(reduce_op, [per_replica_value])[0] else: return self._simple_cross_replica_ops.reduce(reduce_op, per_replica_value, destinations) def batch_reduce_implementation(self, reduce_op, value_destination_pairs, options): if _all_devices_match(value_destination_pairs): return self._batch_all_reduce(reduce_op, [v[0] for v in value_destination_pairs]) else: return [ self.reduce_implementation(reduce_op, value, dest, options) for value, dest in value_destination_pairs ] def _batch_all_reduce(self, reduce_op, per_replica_values): """All-reduce algorithm in a batch.""" dense_values, dense_indices, sparse_values, sparse_indices = ( cross_device_utils.split_by_sparsity(per_replica_values)) if dense_values: dense_results = self._do_batch_all_reduce(reduce_op, dense_values) else: dense_results = [] if sparse_values: sparse_results = self._do_batch_all_reduce_sparse(reduce_op, sparse_values) else: sparse_results = [] return cross_device_utils.stitch_values(((dense_results, dense_indices), (sparse_results, sparse_indices))) def _do_batch_all_reduce(self, reduce_op, dense_values): """Run batch all-reduces.""" logging.log_first_n( logging.INFO, "batch_all_reduce: %d all-reduces with algorithm = %s, num_packs = %d" % (len(dense_values), self._all_reduce_alg, self._num_packs), 10) destinations = dense_values[0]._devices # pylint: disable=protected-access grouped = _group_value_by_device(dense_values) # device_grad_packs: # [[(t0_gpu0, None), (t1_gpu0, None)], [(t0_gpu1, None), (t1_gpu1, None)]] device_grad_packs, tensor_packer = _pack_tensors(grouped, self._num_packs) # The actual aggregation of the repacked gradients. Note that they are # sharded among different aggregation trees. So it is important to strike # the balance on num_splits. if self._all_reduce_alg == "nccl": # TODO(yuefengz): merge this into the all-reduce library. reduced = cross_device_utils.aggregate_gradients_using_nccl( device_grad_packs) else: # TODO(yuefengz): check that gpu ids in `destinations` are in ascending # order. reduced = ( cross_device_utils.aggregate_gradients_using_hierarchical_copy( destinations, device_grad_packs)) reduced = _unpack_tensors(reduced, tensor_packer) return _ungroup_and_make_mirrored(reduced, dense_values[0], reduce_op) def _do_batch_all_reduce_sparse(self, reduce_op, sparse_values): """Run batch all-reduce for sparse values.""" logging.log_first_n( logging.WARN, "Efficient allreduce is not supported for %d IndexedSlices" % len(sparse_values), 10) # Use `sparse_values` as destinations to do all-reduces. It is effectively # an allgather under the hood but not an efficient one. return self._simple_cross_replica_ops.batch_reduce( reduce_op, zip(sparse_values, sparse_values)) def _gather_implementation(self, per_replica_value, destinations, axis, options): logging.warning("gather/all_gather with NCCL or HierarchicalCopy is not " "supported. Falling back to gather on one device and " "then broadcast. We're working on a more efficient " "implementation.") return ReductionToOneDevice()._gather(per_replica_value, destinations, axis, # pylint: disable=protected-access options) # For compatibility with code using the old name of `AllReduceCrossDeviceOps`. AllReduceCrossTowerOps = AllReduceCrossDeviceOps AllReduceSpecTuple = collections.namedtuple("AllReduceSpecTuple", "alg shards limit") @tf_export("distribute.NcclAllReduce") class NcclAllReduce(AllReduceCrossDeviceOps): """NCCL all-reduce implementation of CrossDeviceOps. It uses Nvidia NCCL for all-reduce. For the batch API, tensors will be repacked or aggregated for more efficient cross-device transportation. For reduces that are not all-reduce, it falls back to `tf.distribute.ReductionToOneDevice`. Here is how you can use `NcclAllReduce` in `tf.distribute.MirroredStrategy`: ``` strategy = tf.distribute.MirroredStrategy( cross_device_ops=tf.distribute.NcclAllReduce()) ``` """ def __init__(self, num_packs=1): """Initializes the object. Args: num_packs: a non-negative integer. The number of packs to split values into. If zero, no packing will be done. Raises: ValueError: if `num_packs` is negative. """ if num_packs < 0: raise ValueError( "NCCL all-reduce requires num_packs >= 0, but {} is specified".format( num_packs)) super(NcclAllReduce, self).__init__( all_reduce_alg="nccl", num_packs=num_packs) @tf_export("distribute.HierarchicalCopyAllReduce") class HierarchicalCopyAllReduce(AllReduceCrossDeviceOps): """Hierarchical copy all-reduce implementation of CrossDeviceOps. It reduces to one GPU along edges in some hierarchy and broadcasts back to each GPU along the same path. For the batch API, tensors will be repacked or aggregated for more efficient cross-device transportation. This is a reduction created for Nvidia DGX-1 which assumes GPUs connects like that on DGX-1 machine. If you have different GPU inter-connections, it is likely that it would be slower than `tf.distribute.ReductionToOneDevice`. For reduces that are not all-reduce, it falls back to `tf.distribute.ReductionToOneDevice`. Here is how you can use `HierarchicalCopyAllReduce` in `tf.distribute.MirroredStrategy`: ``` strategy = tf.distribute.MirroredStrategy( cross_device_ops=tf.distribute.HierarchicalCopyAllReduce()) ``` """ def __init__(self, num_packs=1): """Initializes the object. Args: num_packs: a non-negative integer. The number of packs to split values into. If zero, no packing will be done. Raises: ValueError if `num_packs` is negative. """ if num_packs < 0: raise ValueError( "HierarchicalCopy requires num_packs >= 0, but {} is specified" .format(num_packs)) super(HierarchicalCopyAllReduce, self).__init__( all_reduce_alg="hierarchical_copy", num_packs=num_packs) # TODO(crccw): remove after migrating all callers. CollectiveCommunication = collective_util.CommunicationImplementation CommunicationImplementation = collective_util.CommunicationImplementation # TODO(yuefengz): support in-graph collective all-reduce. class CollectiveAllReduce(CrossDeviceOps): """All-reduce cross device ops using collective ops. In the between-graph replicated training, it will still do all-reduces across all workers and then put results on the right destinations. """ def __init__(self, devices, group_size, collective_keys=None): """Initializes the object. Args: devices: a list of device strings to run collectives on. group_size: the global group size. For between-graph replicated training it's the total number of devices across all workers. collective_keys: an optional CollectiveKey object. """ if group_size % len(devices) > 0: raise ValueError("group_size must be divisible by the number of devices.") self._group_size = group_size self._collective_keys = (collective_keys or cross_device_utils.CollectiveKeys()) # This lock guards all collective launches, i.e. calls to # cross_device_utils.build_collectve_*. # # In a multi threaded eager program we need to ensure different groups of # collectives don't interleave each other, otherwise there could be # deadlocks. E.g. if two user threads both are launching collectives: # user-thread-0 device0 device1 # user-thread-1 device0 device1 # In eager mode, we use one thread per device to launch collective ops, so # the above launch sequences end up with the following queues: # device-0 collective-0 collective-1 # device-1 collective-1 collective-0 # This deadlocks since neither collective is able to finish. self._lock = threading.Lock() self._devices = tuple(device_util.canonicalize(d) for d in devices) group_key = self._collective_keys.get_group_key(self._devices) self._launchers = [] # Whether to only use NCCL for batched all-reduce when NCCL is requested. # This is because of the lack of mechanism to order NCCL operations # deterministically. self._limited_nccl = False for device in self._devices: launcher = cross_device_utils.CollectiveReplicaLauncher( group_key, group_size, self._collective_keys, device) self._launchers.append(launcher) if not launcher.can_order_nccl(): self._limited_nccl = True self._pool = multiprocessing.pool.ThreadPool(len(self._devices)) super(CollectiveAllReduce, self).__init__() @property def _num_between_graph_workers(self): # Currently we only support equal number of devices on each worker. return self._group_size / len(self._devices) def _all_reduce(self, reduce_op, value, replica_id, options): """Implements CrossDeviceOps.all_reduce.""" # TODO(b/122840926): reuse this method in _batch_all_reduce. flat_values = nest.flatten(value) if isinstance(flat_values[0], ops.IndexedSlices): raise NotImplementedError("all_reduce doesn't support IndexedSlices.") batch_size = len(flat_values) implementation = options.implementation.value # If NCCL launches can't be ordered (self._limited_nccl == True), we only # use NCCL only when batch_size > 1, hoping that there's only one batched # all-reduce, which is the gradients. if (self._limited_nccl and options.implementation == CommunicationImplementation.NCCL and batch_size == 1): implementation = CommunicationImplementation.AUTO.value # Reverse the lists so that there's better chance that values follows # the order in which they are calculated (e.g. when they're gradients), so # as to overlap calculation with communication. However, this may not be # optimal for cases like gradients of complicated non-sequential models. # # Note that we reverse the list before packing so that the first pack won't # be too small, since it's more likely for first few packs to have long # queuing time due to concurrent intense computation. # # TODO(b/147393503): explore solutions for optimal ordering. flat_values.reverse() packs = cross_device_utils.group_by_size(flat_values, options.bytes_per_pack) launcher = self._launchers[replica_id] if not context.executing_eagerly() and replica_id == 0: logging.info( "Collective all_reduce: %d all-reduces, num_devices = %d, " "group_size = %d, implementation = %s, num_packs = %d", batch_size, len(self._launchers), self._group_size, implementation, len(packs)) flat_results = launcher.batch_all_reduce(packs, implementation, options.timeout_seconds) if reduce_op == reduce_util.ReduceOp.MEAN: for i, v in enumerate(flat_results): flat_results[i] = v / self._group_size flat_results.reverse() return nest.pack_sequence_as(value, flat_results) def reduce_implementation(self, reduce_op, per_replica_value, destinations, options): values_util.mark_as_unsaveable() all_reduced = self._batch_all_reduce(reduce_op, [per_replica_value], options)[0] devices = get_devices_from(destinations) if _devices_match(per_replica_value, destinations): return all_reduced # Convert `all_reduced` to a `Mirrored` object, as a simple and uniform # utility to access component for a particular device. if not isinstance(all_reduced, value_lib.Mirrored): all_reduced = value_lib.Mirrored([all_reduced]) # If we got this far, the destination devices do not match the all-reduce # devices, so we must map from one to the other. index = [] # We must add these control dependencies, otherwise we can get deadlock. with ops.control_dependencies(all_reduced.values): for d in devices: with ops.device(d): for v in all_reduced.values: if v.device == d: index.append(array_ops.identity(v)) break else: # TODO(josh11b): Once we add support for model parallelism, get the # copy from the corresponding replica instead of the primary. index.append(array_ops.identity(all_reduced._primary)) # pylint: disable=protected-access return distribute_utils.regroup(index, wrap_class=value_lib.Mirrored) def batch_reduce_implementation(self, reduce_op, value_destination_pairs, options): values_util.mark_as_unsaveable() all_devices_match = _all_devices_match(value_destination_pairs) if all_devices_match: return self._batch_all_reduce(reduce_op, [v[0] for v in value_destination_pairs], options) else: if not all_devices_match: logging.log_first_n( logging.WARN, "Efficient batch_reduce is not supported if " "destinations are different.", 10) return [ self.reduce_implementation(reduce_op, value, dest, options) for value, dest in value_destination_pairs ] def _batch_all_reduce(self, reduce_op, per_replica_values, options): """All reduce algorithm in a batch.""" dense_values, dense_indices, sparse_values, sparse_indices = ( cross_device_utils.split_by_sparsity(per_replica_values)) if dense_values: dense_results = self._do_batch_all_reduce_dense(reduce_op, dense_values, options) else: dense_results = [] if sparse_values: sparse_results = self._do_batch_all_reduce_sparse(reduce_op, sparse_values, options) else: sparse_results = [] return cross_device_utils.stitch_values( ((dense_results, dense_indices), (sparse_results, sparse_indices))) def _do_batch_all_reduce_dense(self, reduce_op, per_replica_values, options): """All-reduce across all workers in a batch.""" batch_size = len(per_replica_values) implementation = options.implementation.value # For now, we use NCCL only when batch_size > 1 since we don't have a way to # order NCCL launches. We're hoping that there's only one batched # all-reduce, which is the gradients. # TODO(b/132575814): switch to NCCL for all collectives when communication # is NCCL if and only if we can order collectives deterministically. if (self._limited_nccl and options.implementation == CommunicationImplementation.NCCL and batch_size == 1): implementation = CommunicationImplementation.AUTO.value # Reverse the lists so that there's better chance that values follows # the order in which they are calculated (e.g. when they're gradients), so # as to overlap calculation with communication. However, this may not be # optimal for cases like gradients of complicated non-sequential models. # # Note that we reverse the list before packing so that the first pack won't # be too small, since it's more likely for first few packs to have long # queuing time due to concurrent intense computation. # # TODO(b/147393503): explore solutions for optimal ordering. values_by_device = [[] for _ in range(len(self._devices))] for per_replica in reversed(per_replica_values): for i in range(len(self._devices)): values_by_device[i].append(per_replica.values[i]) if context.executing_eagerly(): def thread_fn(device_id): with context.eager_mode(): packs = cross_device_utils.group_by_size(values_by_device[device_id], options.bytes_per_pack) return self._launchers[device_id].batch_all_reduce( packs, implementation, options.timeout_seconds) num_devices = len(self._devices) with self._lock: outputs_by_device = self._pool.map(thread_fn, list(range(num_devices))) else: outputs_by_device = [] with self._lock: for i in range(len(self._devices)): packs = cross_device_utils.group_by_size( values_by_device[i], options.bytes_per_pack) if i == 0: logging.info( "Collective batch_all_reduce: %d all-reduces, num_devices = %d," " group_size = %d, implementation = %s, num_packs = %d", batch_size, len(self._launchers), self._group_size, implementation, len(packs)) outputs_by_device.append(self._launchers[i].batch_all_reduce( packs, implementation, options.timeout_seconds)) mirrored = [] for values in zip(*outputs_by_device): if reduce_op == reduce_util.ReduceOp.MEAN: values = list(values) for i, v in enumerate(values): with ops.device(v.device): values[i] = v / self._group_size mirrored.append( distribute_utils.regroup(values, wrap_class=value_lib.Mirrored)) # Reverse the order of reduced value to recover the order in the input. return list(reversed(mirrored)) def _do_batch_all_reduce_sparse(self, reduce_op, per_replica_values, options): """All-reduce IndexedSlices across all workers in a batch.""" logging.log_first_n( logging.INFO, "Collective batch_all_reduce for IndexedSlices: " "%d all-reduces, group_size = %d" % (len(per_replica_values), self._group_size), 10) implementation = options.implementation.value # For now, we use NCCL only when batch_size > 1. # TODO(b/132575814): switch to NCCL for all collectives when implementation # is NCCL. if (self._limited_nccl and options.implementation == CommunicationImplementation.NCCL and len(per_replica_values) == 1): implementation = CommunicationImplementation.AUTO.value gathered_values = [] with self._lock: for per_replica in per_replica_values: outputs = [] for i in range(len(self._devices)): outputs.append(self._launchers[i].all_reduce_indexed_slices( per_replica.values[i], implementation, options.timeout_seconds)) gathered_values.append(outputs) mirrored = [] for value in gathered_values: if reduce_op == reduce_util.ReduceOp.MEAN: # Assume each worker has the same number of replicas. for i, v in enumerate(value): with ops.device(v.device): value[i].values = value[i].values / self._group_size mirrored.append( distribute_utils.regroup(value, wrap_class=value_lib.Mirrored)) return mirrored def _gather_implementation(self, per_replica_value, destinations, axis, options): all_gathered = self._batch_all_gather([per_replica_value], axis, options)[0] values_util.mark_as_unsaveable() devices = get_devices_from(destinations) if _devices_match(per_replica_value, destinations): return all_gathered # Convert `all_gathered` to a `Mirrored` object, as a simple and uniform # utility to access component for a particular device. if not isinstance(all_gathered, value_lib.Mirrored): all_gathered = value_lib.Mirrored([all_gathered]) # If we got this far, the destination devices do not match the all-gather # devices, so we must map from one to the other. index = [] # We must add these control dependencies, otherwise we can get deadlock. with ops.control_dependencies(all_gathered.values): for d in devices: with ops.device(d): for v in all_gathered.values: if v.device == d: index.append(array_ops.identity(v)) break else: index.append(array_ops.identity(all_gathered._primary)) # pylint: disable=protected-access return distribute_utils.regroup(index, wrap_class=value_lib.Mirrored) def _batch_all_gather(self, per_replica_values, axis, options): """all gather multiple per-replica-values.""" batch_size = len(per_replica_values) # Pass options.implementation to the runtime as a communication # implementation hint. implementation = options.implementation.value # For now, we use NCCL only when batch_size > 1. # TODO(b/132575814): switch to NCCL for all collectives when implementation # is NCCL. if (options.implementation == CommunicationImplementation.NCCL and batch_size == 1): implementation = CommunicationImplementation.AUTO.value logging.log_first_n( logging.INFO, "Collective batch_all_gather: %d all-gathers, " "num_devices = %d, group_size = %d, implementation = %s, " % (batch_size, len(self._devices), self._group_size, implementation), 10) def compute_gathered_values(): gathered_values = [] with self._lock, ops.name_scope("allgather"): for per_replica in per_replica_values: outputs = [] for i in range(len(self._devices)): outputs.append(self._launchers[i].all_gather( per_replica.values[i], axis, implementation, options.timeout_seconds)) gathered_values.append(outputs) return gathered_values if context.executing_eagerly(): gathered_values = def_function.function(compute_gathered_values)() else: gathered_values = compute_gathered_values() mirrored = [] for value in gathered_values: mirrored.append( distribute_utils.regroup(value, wrap_class=value_lib.Mirrored)) return mirrored def __deepcopy__(self, memo): # distribute_coordinator deep-copies the strategy object, so # CollectiveAllReduce needs to support deep copy as well. collective_keys = copy.deepcopy(self._collective_keys, memo) return CollectiveAllReduce(self._devices, self._group_size, collective_keys) def select_cross_device_ops(devices, session_config=None): """Find the best `CrossDeviceOps` locally given a `tf.compat.v1.ConfigProto`. Args: devices: a list of devices passed to `tf.distribute.Strategy`. session_config: a `tf.compat.v1.ConfigProto` or `None`. If `None`, it will make decision based on all logical devices. Returns: A subclass of `CrossDeviceOps`. """ requested_devices = set(device_util.canonicalize(d) for d in devices) if ops.executing_eagerly_outside_functions(): logical_gpus = context.context().list_logical_devices(device_type="GPU") physical_gpus = context.context().list_physical_devices(device_type="GPU") if len(logical_gpus) != len(physical_gpus): logging.warning("NCCL is not supported when using virtual GPUs, falling" "back to reduction to one device") return ReductionToOneDevice() machine_devices = context.context().list_logical_devices() else: machine_devices = device_lib.list_local_devices( session_config=session_config) using_devices = set() for d in machine_devices: if device_util.canonicalize(d.name) in requested_devices: using_devices.add(d.name) if len(using_devices) != len(requested_devices): logging.warning( "Some requested devices in `tf.distribute.Strategy` are not visible " "to TensorFlow: %s", ",".join(list(requested_devices - using_devices))) if any("gpu" not in d.lower() for d in requested_devices): logging.warning("There are non-GPU devices in `tf.distribute.Strategy`, " "not using nccl allreduce.") return ReductionToOneDevice() if kernels.get_registered_kernels_for_op("NcclAllReduce"): return NcclAllReduce(num_packs=1) else: logging.warning("Nccl kernel is not found, not using nccl allreduce.") return ReductionToOneDevice()
#!/usr/bin/env python """ Author : Ken Youens-Clark <[email protected]> Purpose: Python program to write a Python program """ import argparse import os import re import subprocess import sys from datetime import date from pathlib import Path from typing import NamedTuple class Args(NamedTuple): program: str name: str email: str purpose: str overwrite: bool # -------------------------------------------------- def get_args() -> Args: """Get arguments""" parser = argparse.ArgumentParser( description='Create Python argparse program', formatter_class=argparse.ArgumentDefaultsHelpFormatter) defaults = get_defaults() username = os.getenv('USER') or 'Gwon' hostname = os.getenv('HOSTNAME') or 'localhost' parser.add_argument('program', help='Program name', type=str) parser.add_argument('-n', '--name', type=str, default=defaults.get('name', username), help='Name for docstring') parser.add_argument('-e', '--email', type=str, default=defaults.get('email', f'{username}@{hostname}'), help='Email for docstring') parser.add_argument('-p', '--purpose', type=str, default=defaults.get('purpose', 'Rock the Casbah'), help='Purpose for docstring') parser.add_argument('-f', '--force', help='Overwrite existing', action='store_true') args = parser.parse_args() args.program = args.program.strip().replace('-', '_') if not args.program: parser.error(f'Not a usable filename "{args.program}"') return Args(args.program, args.name, args.email, args.purpose, args.force) # -------------------------------------------------- def main() -> None: """Make a jazz noise here""" args = get_args() program = args.program if os.path.isfile(program) and not args.overwrite: answer = input(f'"{program}" exists. Overwrite? [yN] ') if not answer.lower().startswith('y'): sys.exit('Will not overwrite. Bye!') print(body(args), file=open(program, 'wt'), end='') subprocess.run(['chmod', '+x', program]) print(f'Done, see new script "{program}."') # -------------------------------------------------- def body(args: Args) -> str: """ The program template """ today = str(date.today()) return f"""#!/usr/bin/env python \"\"\" Author : {args.name}{' <' + args.email + '>' if args.email else ''} Date : {today} Purpose: {args.purpose} \"\"\" import argparse # -------------------------------------------------- def get_args(): \"\"\"Get command-line arguments\"\"\" parser = argparse.ArgumentParser( description='{args.purpose}', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('positional', metavar='str', help='A positional argument') parser.add_argument('-a', '--arg', help='A named string argument', metavar='str', type=str, default='') parser.add_argument('-i', '--int', help='A named integer argument', metavar='int', type=int, default=0) parser.add_argument('-f', '--file', help='A readable file', metavar='FILE', type=argparse.FileType('rt'), default=None) parser.add_argument('-o', '--on', help='A boolean flag', action='store_true') return parser.parse_args() # -------------------------------------------------- def main(): \"\"\"Make a jazz noise here\"\"\" args = get_args() str_arg = args.arg int_arg = args.int file_arg = args.file flag_arg = args.on pos_arg = args.positional print(f'str_arg = "{{str_arg}}"') print(f'int_arg = "{{int_arg}}"') print('file_arg = "{{}}"'.format(file_arg.name if file_arg else '')) print(f'flag_arg = "{{flag_arg}}"') print(f'positional = "{{pos_arg}}"') # -------------------------------------------------- if __name__ == '__main__': main() """ # -------------------------------------------------- def get_defaults(): """Get defaults from ~/.new.py""" rc = os.path.join(str(Path.home()), '.new.py') defaults = {} if os.path.isfile(rc): for line in open(rc): match = re.match('([^=]+)=([^=]+)', line) if match: key, val = map(str.strip, match.groups()) if key and val: defaults[key] = val return defaults # -------------------------------------------------- if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # # setup.py # xman # # Created by Alan D Snow, 2017. # BSD 3-Clause from setuptools import setup, find_packages requires = [ 'descartes', 'gazar', 'matplotlib', 'numpy', 'shapely', ] setup(name='xman', version='0.0.1', description="Cross section (X-Section) extractor and Manning's " "roughness (N) solver.", # long_description='', author='Alan D. Snow', author_email='[email protected]', url='https://github.com/snowman2/xman', license='BSD 3-Clause', keywords='cross section, mannning, hydraulics, hydrology', packages=find_packages(), classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], install_requires=requires, extras_require={ 'tests': [ 'coveralls', 'flake8', 'pytest', 'pytest-cov', 'pylint', ], 'docs': [ 'mock', 'sphinx', 'sphinxcontrib-napoleon', ] }, )
from ordered_set import OrderedSet from modelindex.models.BaseModelIndex import BaseModelIndex from modelindex.models.CollectionList import CollectionList from modelindex.models.Library import Library from modelindex.models.ModelList import ModelList from modelindex.utils import lowercase_keys, load_any_file, full_filepath, load_any_files_wildcard, \ expand_wildcard_path, merge_lists_data class ModelIndex(BaseModelIndex): """ModelIndex is the root object for the whole model index. """ COMMON_FIELDS = [ "Models", "Collections", ] def __init__(self, data: dict = None, filepath: str = None, _path_to_readme: str = None, is_root: bool = False, ): """ Args: data (dict): The root model index as a dictionary filepath (str): The path from which it was loaded _path_to_readme (str): The path to the readme file (if loaded from there) is_root (bool): If this is the root ModelIndex instance for the whole project """ check_errors = OrderedSet() if data is None: data = {} d = { "Models": ModelList(_filepath=filepath), "Collections": CollectionList(_filepath=filepath), "Library": None, } lc_keys = lowercase_keys(data) if "models" in lc_keys: models = data[lc_keys["models"]] # Syntax: Models: <path to file(s)> if models is not None and isinstance(models, str): models_list = [] for model_file in expand_wildcard_path(models, filepath): try: models_list.append(ModelList.from_file(model_file, filepath)) except (IOError, ValueError) as e: check_errors.add(str(e)) models = merge_lists_data(models_list) # Syntax: Models: list[ model dict ] elif models is not None and not isinstance(models, ModelList): models = ModelList(models, filepath, _path_to_readme) d["Models"] = models if "collections" in lc_keys: collections = data[lc_keys["collections"]] # Syntax: Collections: <path to file(s)> if collections is not None and isinstance(collections, str): collections_list = [] for model_file in expand_wildcard_path(collections, filepath): try: collections_list.append(CollectionList.from_file(model_file, filepath)) except (IOError, ValueError) as e: check_errors.add(str(e)) collections = merge_lists_data(collections_list) # Syntax: Collections: list[ model dict ] elif collections is not None and not isinstance(collections, CollectionList): collections = CollectionList(collections, filepath, _path_to_readme) d["Collections"] = collections if "library" in lc_keys: lib = data[lc_keys["library"]] if isinstance(lib, dict): d["Library"] = Library.from_dict(lib, filepath) elif isinstance(lib, str): d["Library"] = Library.from_file(lib, filepath) else: check_errors.add("Mis-formatted `Library` entry: expected a dict or a filepath but got something else.") if "import" in lc_keys: imp = data[lc_keys["import"]] if not isinstance(imp, list): imp = list(imp) for import_file in imp: try: for relpath in expand_wildcard_path(import_file, filepath): raw, md_name = load_any_file(relpath, filepath) fullpath = full_filepath(relpath, filepath) mi = ModelIndex.from_dict(raw, fullpath, md_name) if mi.models: for model in mi.models: d["Models"].add(model) if mi.collections: for col in mi.collections: d["Collections"].add(col) if mi.library: d["Library"] = mi.library except (IOError, ValueError) as e: check_errors.add(str(e)) super().__init__( data=d, filepath=filepath, check_errors=check_errors, ) self.lc_keys = lowercase_keys(data) self.is_root = is_root if is_root: self.build_models_with_collections() def build_models_with_collections(self): # Apply the metadata inheritance from the collection col_by_name = {} for col in self.collections: col_by_name[col.name] = col for model in self.models: col_name = model.in_collection if col_name: if col_name in col_by_name: col = col_by_name[col_name] model.build_full_model(col) else: model.check_errors.add( f"Invalid collection name `{col_name}`" ) @staticmethod def from_dict(d: dict, filepath: str = None, _path_to_readme: str = None, is_root: bool = False): """Construct a ModelIndex from a dictionary Args: data (dict): The root model index as a dictionary filepath (str): The path from which it was loaded _path_to_readme (str): Path to the README.md file if loaded from there is_root (str): If this is the root ModelIndex for the whole project """ return ModelIndex(d, filepath, _path_to_readme, is_root) @property def models(self) -> ModelList: """Get the list of models in the ModelIndex.""" return self.data["Models"] @models.setter def models(self, value): """Set the list of models in the ModelIndex.""" self.data["Models"] = value @property def collections(self) -> CollectionList: """Get the list of collections in the ModelIndex.""" return self.data["Collections"] @collections.setter def collections(self, value): """Set the list of collections in the ModelIndex""" self.data["Collections"] = value @property def library(self) -> Library: """Get the library metadata""" return self.data["Library"] @library.setter def library(self, value): """Set the library metadata""" self.data["Library"] = value
import _plotly_utils.basevalidators class NameValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name='name', parent_name='streamtube', **kwargs): super(NameValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='style', role='info', **kwargs )
class HTTPClientError(Exception): pass class TooManyRedirects(HTTPClientError): pass class StreamAlreadyConsumed(HTTPClientError): pass class TooManyConnections(HTTPClientError): pass class RequestTimeout(HTTPClientError): pass class TooManyInvalidResponses(HTTPClientError): pass class MissingSchema(HTTPClientError): pass
""" 20210511: This script is intended to run an example version of end-to-end processing. TODO: MTH5 updated so that run provides a channel which returns a channel response. It seems like we need both a Run and a RunTS object to be able to access calibration info and data in the same environment TO ACCESS CHANNEL-SPECIFIC FILTERS LOOK HERE: #check_run_channels_have_expected_properties() """ import datetime from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.signal as ssig import time import xarray as xr from aurora.signal.windowing_scheme import WindowingScheme # from iris_mt_scratch.sandbox.time_series.multivariate_time_series import MultiVariateTimeSeries from iris_mt_scratch.general_helper_functions import DATA_DIR from iris_mt_scratch.general_helper_functions import FIGURES_BUCKET from iris_mt_scratch.general_helper_functions import TEST_BAND_FILE from iris_mt_scratch.general_helper_functions import read_complex, save_complex from iris_mt_scratch.sandbox.io_helpers.test_data import get_example_array_list from iris_mt_scratch.sandbox.io_helpers.test_data import get_example_data from iris_mt_scratch.sandbox.io_helpers.test_data import TEST_DATA_SET_CONFIGS from iris_mt_scratch.sandbox.time_series.frequency_band import FrequencyBands from iris_mt_scratch.sandbox.time_series.frequency_band_helpers import extract_band from iris_mt_scratch.sandbox.time_series.frequency_band_helpers import frequency_band_edges from iris_mt_scratch.sandbox.time_series.mth5_helpers import cast_run_to_run_ts from iris_mt_scratch.sandbox.time_series.mth5_helpers import get_experiment_from_obspy_inventory from iris_mt_scratch.sandbox.time_series.mth5_helpers import get_experiment_from_xml_path from iris_mt_scratch.sandbox.time_series.mth5_helpers import HEXY from iris_mt_scratch.sandbox.time_series.mth5_helpers import check_run_channels_have_expected_properties from iris_mt_scratch.sandbox.time_series.mth5_helpers import embed_experiment_into_run from iris_mt_scratch.sandbox.transfer_function.iter_control import IterControl from iris_mt_scratch.sandbox.transfer_function.transfer_function_header \ import TransferFunctionHeader from iris_mt_scratch.sandbox.transfer_function.TTF import TTF from iris_mt_scratch.sandbox.transfer_function.TTFZ import TTFZ from iris_mt_scratch.sandbox.transfer_function\ .transfer_function_driver import test_regression from iris_mt_scratch.sandbox.transfer_function.TRME import TRME from iris_mt_scratch.sandbox.transfer_function.TRegression import RegressionEstimator def set_driver_parameters(): driver_parameters = {} driver_parameters["run_ts_from_xml_01"] = 1#False #True driver_parameters["initialize_data"] = True driver_parameters["dataset_id"] = "pkd_test_00" driver_parameters["BULK SPECTRA"] = False return driver_parameters def test_runts_from_xml(dataset_id, runts_obj=False): dataset_id = "pkd_test_00" # test_dataset_config = TEST_DATA_SET_CONFIGS[dataset_id] inventory = test_dataset_config.get_inventory_from_iris(ensure_inventory_stages_are_named=True) experiment = get_experiment_from_obspy_inventory(inventory) # experiment.surveys[0].filters["fir_fs2d5"] # experiment.surveys[0].filters["fir_fs2d5"].decimation_input_sample_rate # hx.channel_response_filter.filters_list[3].name # hx.channel_response_filter.filters_list[3].decimation_input_sample_rate test_dataset_config.save_xml(experiment) h5_path = Path("PKD.h5") run_obj = embed_experiment_into_run("PKD", experiment, h5_path=h5_path) if runts_obj: array_list = get_example_array_list(components_list=HEXY, load_actual=True, station_id="PKD") runts_obj = cast_run_to_run_ts(run_obj, array_list=array_list) return experiment, run_obj, runts_obj def main(): """ Returns ------- """ t0 = time.time() driver_parameters = set_driver_parameters() dataset_id = driver_parameters["dataset_id"] #<TEST RunTS FROM XML> if driver_parameters["run_ts_from_xml_01"]: experiment, run_obj, runts_obj = test_runts_from_xml(dataset_id, runts_obj=True) #</TEST RunTS FROM XML> #<INITIALIZE DATA AND METADATA> if driver_parameters["initialize_data"]: #ADD from_miniseed pkd_mvts = get_example_data(station_id="PKD", component_station_label=False) #</INITIALIZE DATA> #<PROCESS DATA> #<BULK SPECTRA CALIBRATION> if driver_parameters["BULK SPECTRA"]: windowing_scheme = WindowingScheme(taper_family="hamming", num_samples_window=288000, num_samples_overlap=0, sampling_rate=40.0) windowed_obj = windowing_scheme.apply_sliding_window(pkd_mvts.dataset) tapered_obj = windowing_scheme.apply_taper(windowed_obj) fft_obj = windowing_scheme.apply_fft(tapered_obj) from iris_mt_scratch.sandbox.time_series.test_calibration import \ parkfield_sanity_check show_response_curves = False show_spectra = False # Maybe better to make parkfield_sanity_check start from run_ts and # run_obj once we have run_ts behaving correct w.r.t. data channels? parkfield_sanity_check(fft_obj, run_obj, figures_path=FIGURES_BUCKET, show_response_curves=show_response_curves, show_spectra=show_spectra) #</BULK SPECTRA CALIBRATION> #<FC SERIES> #<CONFIG> # <AT EACH DECIMATION LEVEL> SAMPLING_RATE = 40.0; print("NEED TO GET SAMPLING RATE FROM MTH5") NUM_SAMPLES_WINDOW = 256 NUM_SAMPLES_OVERLAP = 192 UNITS = "SI" BAND_SETUP = "EMTF" #"logspace" BAND_SETUP_FILE = "bs_256.cfg" #optional, only when BAND_SETUP=="EMTF" #BAND_LOWER_BOUND = 0.1; #optional, only when BAND_SETUP=="XXXX" #BAND_UPPER_BOUND = 1.1; #optional, only when BAND_SETUP=="XXXX" #NUMBER_OF_BANDS = 8 #optional, only when BAND_SETUP=="XXXX" #NUMBER_OF_BANDS_PER_DECADE = 8#optional, only when BAND_SETUP=="XXXX" TF_LOCAL_SITE = "PKD " #This comes from mth5/mt_metadata aurora#18 TF_REMOTE_SITE = None #"SAO" #This comes from mth5/mt_metadata aurora#18 TF_PROCESSING_SCHEME = "OLS"#""RME" #"OLS","RME", #required TF_INPUT_CHANNELS = ["hx", "hy"] #optional, default ["hx", "hy"] TF_OUTPUT_CHANNELS = ["ex", "ey"] #optional, default ["ex", "ey", "hz"] TF_REFERENCE_CHANNELS = None #optional, default ["hx", "hy"], MAX_NUMBER_OF_ITERATIONS = 10 # </AT EACH DEIMATION LEVEL> DECIMATIONS = [1,4,4,4] #</CONFIG> filters_dict = experiment.surveys[0].filters #<DEFINE WINDOWING/TAPER PARAMETERS> windowing_scheme = WindowingScheme(taper_family="hamming", num_samples_window=NUM_SAMPLES_WINDOW, num_samples_overlap=NUM_SAMPLES_OVERLAP, sampling_rate=SAMPLING_RATE) windowed_obj = windowing_scheme.apply_sliding_window(pkd_mvts.dataset) print("windowed_obj", windowed_obj) tapered_obj = windowing_scheme.apply_taper(windowed_obj) print("tapered_obj", tapered_obj) print("ADD A FLAG TO THESE SO YOU KNOW IF TAPER IS APPLIED OR NOT") stft_obj = windowing_scheme.apply_fft(tapered_obj)#, pkd_mvts.sample_rate) print("stft_obj", stft_obj) #<CALIBRATE> for channel_id in stft_obj.keys(): mth5_channel = run_obj.get_channel(channel_id) channel_filter = mth5_channel.channel_response_filter calibration_response = channel_filter.complex_response(stft_obj.frequency.data) if UNITS=="SI": if channel_id[0].lower() =='h': calibration_response /= 1e-9 #SI Units stft_obj[channel_id].data /= calibration_response print("multiply") # <CALIBRATE> stft_obj_xrda = stft_obj.to_array("channel") frequencies = stft_obj.frequency.data[1:] #print(f"Lower Bound:{frequencies[0]}, Upper bound:{frequencies[-1]}") frequency_bands = FrequencyBands() if BAND_SETUP=="EMTF": frequency_bands.from_emtf_band_setup(filepath=BAND_SETUP_FILE, sampling_rate=SAMPLING_RATE, decimation_level=1, num_samples_window=NUM_SAMPLES_WINDOW) elif BAND_SETUP=="XXXX": print("TODO:Write a method to choose lower and upper bounds, " "and number of bands to split it into") band_edges = frequency_band_edges(frequencies[1], frequencies[-1], num_bands=8) band_edges_2d = np.vstack((band_edges[:-1], band_edges[1:])).T frequency_bands = FrequencyBands(band_edges=band_edges) transfer_function_header = TransferFunctionHeader( processing_scheme=TF_PROCESSING_SCHEME, local_site=TF_LOCAL_SITE, remote_site=TF_REMOTE_SITE, input_channels=TF_INPUT_CHANNELS, output_channels=TF_OUTPUT_CHANNELS, reference_channels=TF_REFERENCE_CHANNELS) transfer_function_obj = TTFZ(transfer_function_header, frequency_bands.number_of_bands) #TODO: Make TTF take a FrequencyBands object, not num_bands for i_band in range(frequency_bands.number_of_bands): band = frequency_bands.band(i_band) band_dataarray = extract_band(band, stft_obj_xrda) save_band = False if save_band: save_complex(band_da, TEST_BAND_FILE) band_da = read_complex(TEST_BAND_FILE) ### band_dataset = band_dataarray.to_dataset("channel") X = band_dataset[TF_INPUT_CHANNELS] Y = band_dataset[TF_OUTPUT_CHANNELS] if TF_PROCESSING_SCHEME=="OLS": regression_estimator = RegressionEstimator(X=X, Y=Y) Z = regression_estimator.estimate_ols() print(f"{TF_PROCESSING_SCHEME}, \n {Z}") #elif TF_PROCESSING_SCHEME=="RME": iter_control = IterControl(max_number_of_iterations=MAX_NUMBER_OF_ITERATIONS) regression_estimator = TRME(X=X, Y=Y, iter_control=iter_control) Z = regression_estimator.estimate() print(f"RME{TF_PROCESSING_SCHEME}, \n {Z}") else: print(f"processing_scheme {TF_PROCESSING_SCHEME} not supported") print(f"processing_scheme must be one of OLS, RME " f"not supported") raise Exception ### #Z = test_regression(band_da) print(f"elapsed {time.time()-t0}") #print(f"Z \n {Z}") T = band.center_period #i_band, regression_estimator, T transfer_function_obj.set_tf(i_band, regression_estimator, T) print("Yay!") print("OK") transfer_function_obj.apparent_resistivity() from iris_mt_scratch.sandbox.transfer_function.rho_plot import RhoPlot plotter = RhoPlot(transfer_function_obj) fig, axs = plt.subplots(nrows=2) plotter.rho_sub_plot(axs[0]) plotter.phase_sub_plot(axs[1]) #plotter.rho_plot2() #plotter.phase_plot() plt.show() print("OK") if __name__ == "__main__": main() print("Fin")
// File name: ExtremeC_exampels_chapter1_3.c // Description: Example 1.3 #include <stdio.h> #define PRINT(a) printf("%d\n", a); #define LOOP(v, s, e) for (int v = s; v <= e; v++) { #define ENDLOOP } int main(int argc, char** argv) { LOOP(counter, 1, 10) PRINT(counter) ENDLOOP return 0; }
from .typehoon import Typehoon
# this code cracks the affine cipher import re from ngram_score import ngram_score fitness = ngram_score('quadgrams.txt') # load our quadgram statistics from pycipher import Affine def break_affine(ctext): # make sure ciphertext has all spacing/punc removed and is uppercase ctext = re.sub('[^A-Z]','',ctext.upper()) # try all posiible keys, return the one with the highest fitness scores = [] for i in [1,3,5,7,9,11,15,17,19,21,23,25]: scores.extend([(fitness.score(Affine(i,j).decipher(ctext)),(i,j)) for j in range(0,25)]) return max(scores) # example ciphertext ctext = 'QUVNLAUVILZKVZZZVNHIVQUFSFZHWZQLQHQLJSNLAUVI' max_key = break_affine(ctext) print 'best candidate with key (a,b) = '+str(max_key[1])+':' print Affine(max_key[1][0],max_key[1][1]).decipher(ctext)
(window.webpackJsonp=window.webpackJsonp||[]).push([[794],{"drX/":function(a,o,e){var s,i,n;!function(r){if("object"==typeof a.exports){var d=r(0,o);void 0!==d&&(a.exports=d)}else i=[e,o],void 0===(n="function"==typeof(s=r)?s.apply(o,i):s)||(a.exports=n)}(function(a,o){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var e=void 0;o.default=["ff-Latn-NG",[["subaka","kikii\u0257e"],e,e],e,[["d","a","m","n","n","m","h"],["dew","aa\u0253","maw","nje","naa","mwd","hbi"],["dewo","aa\u0253nde","mawbaare","njeslaare","naasaande","mawnde","hoore-biir"],["dew","aa\u0253","maw","nje","naa","mwd","hbi"]],e,[["s","c","m","s","d","k","m","j","s","y","j","b"],["sii","col","mbo","see","duu","kor","mor","juk","slt","yar","jol","bow"],["siilo","colte","mbooy","see\u0257to","duujal","korse","morso","juko","siilto","yarkomaa","jolal","bowte"]],e,[["H-I","C-I"],e,["Hade Iisa","Caggal Iisa"]],1,[6,0],["d/M/y","d MMM, y","d MMMM y","EEEE d MMMM y"],["HH:mm","HH:mm:ss","HH:mm:ss z","HH:mm:ss zzzz"],["{1} {0}",e,e,e],[",","\xa0",";","%","+","-","E","\xd7","\u2030","\u221e","NaN",":"],["#,##0.###","#,##0%","#,##0.00\xa0\xa4","#E0"],"NGN","\u20a6","Nayraa Nijeriyaa",{JPY:["JP\xa5","\xa5"],NGN:["\u20a6"],USD:["US$","$"]},"ltr",function(a){var o=Math.floor(Math.abs(a));return 0===o||1===o?1:5}]})}}]);
from django.conf.urls import url from . import views urlpatterns = [ url(r'^administrator/$', views.administrator, name='administrator'), url(r'^administrator/(?P<userRequest_student_id>\d+)/okay/$', views.okay, name='okay'), url(r'^administrator/(?P<user_student_id>\d+)/detail/$',views.detail,name='detail'), url(r'^administrator/(?P<user_student_id>\d+)/modify/$',views.modify,name='modify'), url(r'^administrator/mainImage_edit/$',views.mainImage_edit,name='mainImage_edit'), #url(r'^administrator/mainImage_detail/$',views.mainImage_detail,name='mainImage_detail'), ]
import Types from '../../src/types'; import sinon from 'sinon'; import { urls, testMPID, apiKey } from './config'; var mockServer; describe('Server Model', function() { var event = { messageType: Types.MessageType.PageEvent, name: 'foo page', data: { 'foo-attr': 'foo-val' }, eventType: Types.EventType.Navigation, customFlags:{ 'foo-flag': 'foo-flag-val' } }; beforeEach(function() { mockServer = sinon.createFakeServer(); mockServer.respondImmediately = true; mockServer.respondWith(urls.eventsV2, [ 200, {}, JSON.stringify({ mpid: testMPID, Store: {}}) ]); mockServer.respondWith(urls.identify, [ 200, {}, JSON.stringify({ mpid: testMPID, is_logged_in: false }), ]); mParticle.init(apiKey, window.mParticle.config); }); afterEach(function() { mockServer.restore(); }); it('Should not convert data plan object to server DTO when no id or version is set', function(done) { let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); let upload = mParticle .getInstance() ._ServerModel.convertEventToDTO(sdkEvent, false); upload.should.not.have.property('dp_id'); upload.should.not.have.property('dp_v'); done(); }); it('Should convert data plan id to server DTO', function(done) { mParticle._resetForTests(); mParticle.config.dataPlan = { planId: 'plan-slug' }; mParticle.init('foo', mParticle.config); let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); let upload = mParticle .getInstance() ._ServerModel.convertEventToDTO(sdkEvent, false); upload.should.have.property('dp_id', 'plan-slug'); upload.should.not.have.property('dp_v'); done(); }); it('Should not convert data plan object to server DTO when no id is set', function(done) { mParticle._resetForTests(); mParticle.config.dataPlan = { planVersion: 5 }; mParticle.init('foo', mParticle.config); let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); let upload = mParticle .getInstance() ._ServerModel.convertEventToDTO(sdkEvent, false); upload.should.not.have.property('dp_id'); upload.should.not.have.property('dp_v'); done(); }); it('Should convert entire data plan object to server DTO', function(done) { mParticle._resetForTests(); mParticle.config.dataPlan = { planId: 'plan-slug', planVersion: 10 }; mParticle.init('foo', mParticle.config); let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); let upload = mParticle .getInstance() ._ServerModel.convertEventToDTO(sdkEvent, false); upload.should.have.property('dp_id', 'plan-slug'); upload.should.have.property('dp_v', 10); done(); }); it('Should convert complete consent object', function(done) { var consentState = mParticle .getInstance() ._Consent.createConsentState(); consentState.addGDPRConsentState( 'foo', mParticle .getInstance() ._Consent.createPrivacyConsent( true, 10, 'foo document', 'foo location', 'foo hardware id' ) ); var consent = mParticle .getInstance() ._ServerModel.convertToConsentStateDTO(consentState); consent.should.be.ok(); consent.should.have.property('gdpr'); consent.gdpr.should.have.property('foo'); consent.gdpr.foo.should.have.property('c', true); consent.gdpr.foo.should.have.property('ts', 10); consent.gdpr.foo.should.have.property('d', 'foo document'); consent.gdpr.foo.should.have.property('l', 'foo location'); consent.gdpr.foo.should.have.property('h', 'foo hardware id'); done(); }); it('Should not append user info when no user', function(done) { mParticle.getInstance()._Store.should.be.ok; let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); sdkEvent.should.be.ok; Should(sdkEvent.UserIdentities).not.be.ok; Should(sdkEvent.UserAttributes).not.be.ok; Should(sdkEvent.ConsentState).not.be.ok; done(); }); it('Should append all user info when user is present', function(done) { mParticle.getInstance()._Store.should.be.ok; var consentState = mParticle .getInstance() ._Consent.createConsentState(); consentState.addGDPRConsentState( 'foo', mParticle .getInstance() ._Consent.createPrivacyConsent( true, 10, 'foo document', 'foo location', 'foo hardware id' ) ); window.mParticle.getInstance().Identity.getCurrentUser = () => { return { getUserIdentities: () => { return { userIdentities: { customerid: '1234567', email: 'foo-email', other: 'foo-other', other2: 'foo-other2', other3: 'foo-other3', other4: 'foo-other4', }, }; }, getAllUserAttributes: () => { return { 'foo-user-attr': 'foo-attr-value', 'foo-user-attr-list': ['item1', 'item2'], }; }, getMPID: () => { return '98765'; }, getConsentState: () => { return consentState; }, }; }; let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); sdkEvent.should.be.ok; sdkEvent.UserIdentities.should.be.ok; sdkEvent.MPID.should.be.ok; sdkEvent.UserAttributes.should.be.ok; sdkEvent.ConsentState.should.be.ok; done(); }); it('Should append identities when user present', function(done) { let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); sdkEvent.should.be.ok; Should(sdkEvent.UserIdentities).not.be.ok; var user = { getUserIdentities: () => { return { userIdentities: { customerid: '1234567', email: 'foo-email', other: 'foo-other', other2: 'foo-other2', other3: 'foo-other3', other4: 'foo-other4', not_a_valid_id: 'foo', }, }; }, getAllUserAttributes: () => { return null; }, getMPID: () => { return null; }, getConsentState: () => { return null; }, }; var identityMapping = {}; identityMapping[Types.IdentityType.CustomerId] = '1234567'; identityMapping[Types.IdentityType.Email] = 'foo-email'; identityMapping[Types.IdentityType.Other] = 'foo-other'; identityMapping[Types.IdentityType.Other2] = 'foo-other2'; identityMapping[Types.IdentityType.Other3] = 'foo-other3'; identityMapping[Types.IdentityType.Other4] = 'foo-other4'; mParticle.getInstance()._ServerModel.appendUserInfo(user, sdkEvent); sdkEvent.UserIdentities.should.be.ok; sdkEvent.UserIdentities.length.should.equal(6); sdkEvent.UserIdentities.forEach(function(id) { var type = id.Type; var value = id.Identity; identityMapping[type].should.equal(value); }); done(); }); it('Should append user attributes when user present', function(done) { let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); sdkEvent.should.be.ok; Should(sdkEvent.UserAttributes).not.be.ok; var attributes = { foo: 'bar', 'foo-arr': ['bar1', 'bar2'] }; var user = { getUserIdentities: () => { return { userIdentites: {} }; }, getAllUserAttributes: () => { return attributes; }, getMPID: () => { return null; }, getConsentState: () => { return null; }, }; mParticle.getInstance()._ServerModel.appendUserInfo(user, sdkEvent); sdkEvent.UserAttributes.should.be.ok; sdkEvent.UserAttributes.should.deepEqual(attributes); done(); }); it('Should append mpid when user present', function(done) { let sdkEvent = mParticle .getInstance() ._ServerModel.createEventObject(event); sdkEvent.should.be.ok; Should(sdkEvent.MPID).not.be.ok; var user = { getUserIdentities: () => { return { userIdentites: {} }; }, getAllUserAttributes: () => { return null; }, getMPID: () => { return '98765'; }, getConsentState: () => { return null; }, }; mParticle.getInstance()._ServerModel.appendUserInfo(user, sdkEvent); sdkEvent.MPID.should.be.ok; sdkEvent.MPID.should.equal('98765'); done(); }); });
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";var r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};var l=function(){return(l=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function u(e,a,s,c){return new(s=s||Promise)(function(n,t){function r(e){try{o(c.next(e))}catch(e){t(e)}}function i(e){try{o(c.throw(e))}catch(e){t(e)}}function o(e){var t;e.done?n(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(r,i)}o((c=c.apply(e,a||[])).next())})}function p(n,r){var i,o,a,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},e={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function(t){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,o&&(a=2&t[0]?o.return:t[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,t[1])).done)return a;switch(o=0,(t=a?[2&t[0],a.value]:t)[0]){case 0:case 1:a=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,o=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(a=0<(a=s.trys).length&&a[a.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!a||t[1]>a[0]&&t[1]<a[3])){s.label=t[1];break}if(6===t[0]&&s.label<a[1]){s.label=a[1],a=t;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(t);break}a[2]&&s.ops.pop(),s.trys.pop();continue}t=r.call(n,s)}catch(e){t=[6,e],o=0}finally{i=a=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,e])}}}function f(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&r>=e.length?void 0:e)&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function d(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||0<t--)&&!(r=o.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function a(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||((r=r||Array.prototype.slice.call(t,0,i))[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}var i=(e.prototype.wrapCallback=function(n){var r=this;return function(e,t){e?r.reject(e):r.resolve(t),"function"==typeof n&&(r.promise.catch(function(){}),1===n.length?n(e):n(e,t))}},e);function e(){var n=this;this.reject=function(){},this.resolve=function(){},this.promise=new Promise(function(e,t){n.resolve=e,n.reject=t})}var o,s=(function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}(c,o=Error),c);function c(e,t,n){t=o.call(this,t)||this;return t.code=e,t.customData=n,t.name="FirebaseError",Object.setPrototypeOf(t,c.prototype),Error.captureStackTrace&&Error.captureStackTrace(t,h.prototype.create),t}var h=(t.prototype.create=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r,i=t[0]||{},o=this.service+"/"+e,e=this.errors[e],e=e?(r=i,e.replace(m,function(e,t){var n=r[t];return null!=n?String(n):"<"+t+"?>"})):"Error",e=this.serviceName+": "+e+" ("+o+").";return new s(o,e,i)},t);function t(e,t,n){this.service=e,this.serviceName=t,this.errors=n}var m=/\{\$([^}]+)}/g;function g(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function v(e,t){if(e===t)return 1;for(var n=Object.keys(e),r=Object.keys(t),i=0,o=n;i<o.length;i++){var a=o[i];if(!r.includes(a))return;var s=e[a],c=t[a];if(y(s)&&y(c)){if(!v(s,c))return}else if(s!==c)return}for(var u=0,l=r;u<l.length;u++){a=l[u];if(!n.includes(a))return}return 1}function y(e){return null!==e&&"object"==typeof e}var b=(n.prototype.setInstantiationMode=function(e){return this.instantiationMode=e,this},n.prototype.setMultipleInstances=function(e){return this.multipleInstances=e,this},n.prototype.setServiceProps=function(e){return this.serviceProps=e,this},n.prototype.setInstanceCreatedCallback=function(e){return this.onInstanceCreated=e,this},n);function n(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}var _="[DEFAULT]",w=(I.prototype.get=function(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){e=new i;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise},I.prototype.getImmediate=function(t){var e=this.normalizeInstanceIdentifier(null==t?void 0:t.identifier),t=null!==(t=null==t?void 0:t.optional)&&void 0!==t&&t;if(!this.isInitialized(e)&&!this.shouldAutoInitialize()){if(t)return null;throw Error("Service "+this.name+" is not available")}try{return this.getOrInitializeService({instanceIdentifier:e})}catch(e){if(t)return null;throw e}},I.prototype.getComponent=function(){return this.component},I.prototype.setComponent=function(e){var t,n;if(e.name!==this.name)throw Error("Mismatching Component "+e.name+" for Provider "+this.name+".");if(this.component)throw Error("Component for "+this.name+" has already been provided");if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:_})}catch(e){}try{for(var r=f(this.instancesDeferred.entries()),i=r.next();!i.done;i=r.next()){var o=d(i.value,2),a=o[0],s=o[1],c=this.normalizeInstanceIdentifier(a);try{var u=this.getOrInitializeService({instanceIdentifier:c});s.resolve(u)}catch(e){}}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}}},I.prototype.clearInstance=function(e){this.instancesDeferred.delete(e=void 0===e?_:e),this.instancesOptions.delete(e),this.instances.delete(e)},I.prototype.delete=function(){return u(this,void 0,void 0,function(){var t;return p(this,function(e){switch(e.label){case 0:return t=Array.from(this.instances.values()),[4,Promise.all(a(a([],d(t.filter(function(e){return"INTERNAL"in e}).map(function(e){return e.INTERNAL.delete()}))),d(t.filter(function(e){return"_delete"in e}).map(function(e){return e._delete()}))))];case 1:return e.sent(),[2]}})})},I.prototype.isComponentSet=function(){return null!=this.component},I.prototype.isInitialized=function(e){return this.instances.has(e=void 0===e?_:e)},I.prototype.getOptions=function(e){return this.instancesOptions.get(e=void 0===e?_:e)||{}},I.prototype.initialize=function(e){var t,n,r=(e=void 0===e?{}:e).options,r=void 0===r?{}:r,i=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(i))throw Error(this.name+"("+i+") has already been initialized");if(!this.isComponentSet())throw Error("Component "+this.name+" has not been registered yet");var o=this.getOrInitializeService({instanceIdentifier:i,options:r});try{for(var a=f(this.instancesDeferred.entries()),s=a.next();!s.done;s=a.next()){var c=d(s.value,2),u=c[0],l=c[1];i===this.normalizeInstanceIdentifier(u)&&l.resolve(o)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},I.prototype.onInit=function(e,t){var n=this.normalizeInstanceIdentifier(t),r=null!==(t=this.onInitCallbacks.get(n))&&void 0!==t?t:new Set;r.add(e),this.onInitCallbacks.set(n,r);t=this.instances.get(n);return t&&e(t,n),function(){r.delete(e)}},I.prototype.invokeOnInitCallbacks=function(e,t){var n,r,i=this.onInitCallbacks.get(t);if(i)try{for(var o=f(i),a=o.next();!a.done;a=o.next()){var s=a.value;try{s(e,t)}catch(e){}}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},I.prototype.getOrInitializeService=function(e){var t=e.instanceIdentifier,n=e.options,r=void 0===n?{}:n,e=this.instances.get(t);if(!e&&this.component&&(e=this.component.instanceFactory(this.container,{instanceIdentifier:(n=t)===_?void 0:n,options:r}),this.instances.set(t,e),this.instancesOptions.set(t,r),this.invokeOnInitCallbacks(e,t),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,t,e)}catch(e){}return e||null},I.prototype.normalizeInstanceIdentifier=function(e){return void 0===e&&(e=_),!this.component||this.component.multipleInstances?e:_},I.prototype.shouldAutoInitialize=function(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode},I);function I(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}var E=(S.prototype.addComponent=function(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error("Component "+e.name+" has already been registered with "+this.name);t.setComponent(e)},S.prototype.addOrOverwriteComponent=function(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)},S.prototype.getProvider=function(e){if(this.providers.has(e))return this.providers.get(e);var t=new w(e,this);return this.providers.set(e,t),t},S.prototype.getProviders=function(){return Array.from(this.providers.values())},S);function S(e){this.name=e,this.providers=new Map}var T,O=[];(K=T=T||{})[K.DEBUG=0]="DEBUG",K[K.VERBOSE=1]="VERBOSE",K[K.INFO=2]="INFO",K[K.WARN=3]="WARN",K[K.ERROR=4]="ERROR",K[K.SILENT=5]="SILENT";function C(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(t<e.logLevel)){var i=(new Date).toISOString(),o=P[t];if(!o)throw new Error("Attempted to log a message with an invalid logType (value: "+t+")");console[o].apply(console,a(["["+i+"] "+e.name+":"],n))}}var A={debug:T.DEBUG,verbose:T.VERBOSE,info:T.INFO,warn:T.WARN,error:T.ERROR,silent:T.SILENT},N=T.INFO,P=((pt={})[T.DEBUG]="log",pt[T.VERBOSE]="log",pt[T.INFO]="info",pt[T.WARN]="warn",pt[T.ERROR]="error",pt),k=(Object.defineProperty(D.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){if(!(e in T))throw new TypeError('Invalid value "'+e+'" assigned to `logLevel`');this._logLevel=e},enumerable:!1,configurable:!0}),D.prototype.setLogLevel=function(e){this._logLevel="string"==typeof e?A[e]:e},Object.defineProperty(D.prototype,"logHandler",{get:function(){return this._logHandler},set:function(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"userLogHandler",{get:function(){return this._userLogHandler},set:function(e){this._userLogHandler=e},enumerable:!1,configurable:!0}),D.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,a([this,T.DEBUG],e)),this._logHandler.apply(this,a([this,T.DEBUG],e))},D.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,a([this,T.VERBOSE],e)),this._logHandler.apply(this,a([this,T.VERBOSE],e))},D.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,a([this,T.INFO],e)),this._logHandler.apply(this,a([this,T.INFO],e))},D.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,a([this,T.WARN],e)),this._logHandler.apply(this,a([this,T.WARN],e))},D.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._userLogHandler&&this._userLogHandler.apply(this,a([this,T.ERROR],e)),this._logHandler.apply(this,a([this,T.ERROR],e))},D);function D(e){this.name=e,this._logLevel=N,this._logHandler=C,this._userLogHandler=null,O.push(this)}function j(a,t){for(var e=0,n=O;e<n.length;e++)!function(e){var o=null;t&&t.level&&(o=A[t.level]),e.userLogHandler=null===a?null:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=n.map(function(e){if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(function(e){return e}).join(" ");t>=(null!=o?o:e.logLevel)&&a({level:T[t].toLowerCase(),message:i,args:n,type:e.name})}}(n[e])}var R=(L.prototype.getPlatformInfoString=function(){return this.container.getProviders().map(function(e){if(function(e){e=e.getComponent();return"VERSION"===(null==e?void 0:e.type)}(e)){e=e.getImmediate();return e.library+"/"+e.version}return null}).filter(function(e){return e}).join(" ")},L);function L(e){this.container=e}var M="@firebase/app",x=new k("@firebase/app"),B="[DEFAULT]",F=((K={})[M]="fire-core",K["@firebase/app-compat"]="fire-core-compat",K["@firebase/analytics"]="fire-analytics",K["@firebase/analytics-compat"]="fire-analytics-compat",K["@firebase/app-check"]="fire-app-check",K["@firebase/app-check-compat"]="fire-app-check-compat",K["@firebase/auth"]="fire-auth",K["@firebase/auth-compat"]="fire-auth-compat",K["@firebase/database"]="fire-rtdb",K["@firebase/database-compat"]="fire-rtdb-compat",K["@firebase/functions"]="fire-fn",K["@firebase/functions-compat"]="fire-fn-compat",K["@firebase/installations"]="fire-iid",K["@firebase/installations-compat"]="fire-iid-compat",K["@firebase/messaging"]="fire-fcm",K["@firebase/messaging-compat"]="fire-fcm-compat",K["@firebase/performance"]="fire-perf",K["@firebase/performance-compat"]="fire-perf-compat",K["@firebase/remote-config"]="fire-rc",K["@firebase/remote-config-compat"]="fire-rc-compat",K["@firebase/storage"]="fire-gcs",K["@firebase/storage-compat"]="fire-gcs-compat",K["@firebase/firestore"]="fire-fst",K["@firebase/firestore-compat"]="fire-fst-compat",K["fire-js"]="fire-js",K.firebase="fire-js-all",K),U=new Map,q=new Map;function z(t,n){try{t.container.addComponent(n)}catch(e){x.debug("Component "+n.name+" failed to register with FirebaseApp "+t.name,e)}}function V(e){var t,n,r=e.name;if(q.has(r))return x.debug("There were multiple attempts to register component "+r+"."),!1;q.set(r,e);try{for(var i=f(U.values()),o=i.next();!o.done;o=i.next())z(o.value,e)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return!0}function H(e,t){return e.container.getProvider(t)}var K=((pt={})["no-app"]="No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()",pt["bad-app-name"]="Illegal App name: '{$appName}",pt["duplicate-app"]="Firebase App named '{$appName}' already exists with different options or config",pt["app-deleted"]="Firebase App named '{$appName}' already deleted",pt["invalid-app-argument"]="firebase.{$appName}() takes either no argument or a Firebase App instance.",pt["invalid-log-argument"]="First argument to `onLog` must be null or a function.",pt),$=new h("app","Firebase",K),W=(Object.defineProperty(G.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed(),this._automaticDataCollectionEnabled},set:function(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"name",{get:function(){return this.checkDestroyed(),this._name},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"options",{get:function(){return this.checkDestroyed(),this._options},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"config",{get:function(){return this.checkDestroyed(),this._config},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"container",{get:function(){return this._container},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"isDeleted",{get:function(){return this._isDeleted},set:function(e){this._isDeleted=e},enumerable:!1,configurable:!0}),G.prototype.checkDestroyed=function(){if(this.isDeleted)throw $.create("app-deleted",{appName:this._name})},G);function G(e,t,n){var r=this;this._isDeleted=!1,this._options=l({},e),this._config=l({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new b("app",function(){return r},"PUBLIC"))}var J,Y="9.1.0";function X(e,t){var n,r,i=l({name:B,automaticDataCollectionEnabled:!1},t="object"!=typeof(t=void 0===t?{}:t)?{name:t}:t),o=i.name;if("string"!=typeof o||!o)throw $.create("bad-app-name",{appName:String(o)});t=U.get(o);if(t){if(v(e,t.options)&&v(i,t.config))return t;throw $.create("duplicate-app",{appName:o})}var a=new E(o);try{for(var s=f(q.values()),c=s.next();!c.done;c=s.next()){var u=c.value;a.addComponent(u)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}i=new W(e,i,a);return U.set(o,i),i}function Z(n){return u(this,void 0,void 0,function(){var t;return p(this,function(e){switch(e.label){case 0:return(t=n.name,U.has(t))?(U.delete(t),[4,Promise.all(n.container.getProviders().map(function(e){return e.delete()}))]):[3,2];case 1:e.sent(),n.isDeleted=!0,e.label=2;case 2:return[2]}})})}function Q(e,t,n){var r=null!==(i=F[e])&&void 0!==i?i:e;n&&(r+="-"+n);var i=r.match(/\s|\//),e=t.match(/\s|\//);if(i||e){n=['Unable to register library "'+r+'" with version "'+t+'":'];return i&&n.push('library name "'+r+'" contains illegal characters (whitespace or "/")'),i&&e&&n.push("and"),e&&n.push('version name "'+t+'" contains illegal characters (whitespace or "/")'),void x.warn(n.join(" "))}V(new b(r+"-version",function(){return{library:r,version:t}},"VERSION"))}function ee(e,t){if(null!==e&&"function"!=typeof e)throw $.create("invalid-log-argument");j(e,t)}function te(e){var t;t=e,O.forEach(function(e){e.setLogLevel(t)})}V(new b("platform-logger",function(e){return new R(e)},"PRIVATE")),Q(M,"0.7.1",J),Q("fire-js","");var ne=Object.freeze({__proto__:null,SDK_VERSION:Y,_DEFAULT_ENTRY_NAME:B,_addComponent:z,_addOrOverwriteComponent:function(e,t){e.container.addOrOverwriteComponent(t)},_apps:U,_clearComponents:function(){q.clear()},_components:q,_getProvider:H,_registerComponent:V,_removeServiceInstance:function(e,t,n){void 0===n&&(n=B),H(e,t).clearInstance(n)},deleteApp:Z,getApp:function(e){var t=U.get(e=void 0===e?B:e);if(!t)throw $.create("no-app",{appName:e});return t},getApps:function(){return Array.from(U.values())},initializeApp:X,onLog:ee,registerVersion:Q,setLogLevel:te,FirebaseError:s}),re=(Object.defineProperty(ie.prototype,"automaticDataCollectionEnabled",{get:function(){return this._delegate.automaticDataCollectionEnabled},set:function(e){this.automaticDataCollectionEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(ie.prototype,"name",{get:function(){return this._delegate.name},enumerable:!1,configurable:!0}),Object.defineProperty(ie.prototype,"options",{get:function(){return this._delegate.options},enumerable:!1,configurable:!0}),ie.prototype.delete=function(){return this.firebase.INTERNAL.removeApp(this.name),Z(this._delegate)},ie.prototype._getService=function(e,t){return void 0===t&&(t=B),this._delegate.checkDestroyed(),this._delegate.container.getProvider(e).getImmediate({identifier:t})},ie);function ie(e,t){var n=this;this._delegate=e,this.firebase=t,z(e,new b("app-compat",function(){return n},"PUBLIC"))}var K=((pt={})["no-app"]="No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()",pt["invalid-app-argument"]="firebase.{$appName}() takes either no argument or a Firebase App instance.",pt),oe=new h("app-compat","Firebase",K);function ae(i){var n={},o={__esModule:!0,initializeApp:function(e,t){void 0===t&&(t={});e=X(e,t);if(g(n,e.name))return n[e.name];t=new i(e,o);return n[e.name]=t},app:a,registerVersion:Q,setLogLevel:te,onLog:ee,apps:null,SDK_VERSION:Y,INTERNAL:{registerComponent:function(n){var r=n.name,t=r.replace("-compat","");{var e;V(n)&&"PUBLIC"===n.type&&(e=function(e){if("function"!=typeof(e=void 0===e?a():e)[t])throw oe.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:return new Date(n.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(var r in n)n.hasOwnProperty(r)&&"__proto__"!==r&&(t[r]=e(t[r],n[r]));return t}(e,n.serviceProps),o[t]=e,i.prototype[t]=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._getService.bind(this,r).apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?o[t]:null},removeApp:function(e){delete n[e]},useAsService:function(e,t){return"serverAuth"!==t?t:null},modularAPIs:ne}};function a(e){if(!g(n,e=e||B))throw oe.create("no-app",{appName:e});return n[e]}return o.default=o,Object.defineProperty(o,"apps",{get:function(){return Object.keys(n).map(function(e){return n[e]})}}),a.App=i,o}var se=function(){var e=ae(re);e.SDK_VERSION=e.SDK_VERSION+"_LITE";var t=e.INTERNAL.registerComponent;return e.INTERNAL.registerComponent=function(e){if("PUBLIC"!==e.type||e.name.includes("performance")||e.name.includes("installations"))return t(e);throw Error(name+" cannot register with the standalone perf instance")},e}();Q("@firebase/app-compat","0.1.2","lite");function ce(n){return new Promise(function(e,t){n.onsuccess=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function ue(n,r,i){var o,e=new Promise(function(e,t){ce(o=n[r].apply(n,i)).then(e,t)});return e.request=o,e}function le(e,n,t){t.forEach(function(t){Object.defineProperty(e.prototype,t,{get:function(){return this[n][t]},set:function(e){this[n][t]=e}})})}function pe(t,n,r,e){e.forEach(function(e){e in r.prototype&&(t.prototype[e]=function(){return ue(this[n],e,arguments)})})}function fe(t,n,r,e){e.forEach(function(e){e in r.prototype&&(t.prototype[e]=function(){return this[n][e].apply(this[n],arguments)})})}function de(e,r,t,n){n.forEach(function(n){n in t.prototype&&(e.prototype[n]=function(){return e=this[r],(t=ue(e,n,arguments)).then(function(e){if(e)return new me(e,t.request)});var e,t})})}function he(e){this._index=e}function me(e,t){this._cursor=e,this._request=t}function ge(e){this._store=e}function ve(n){this._tx=n,this.complete=new Promise(function(e,t){n.oncomplete=function(){e()},n.onerror=function(){t(n.error)},n.onabort=function(){t(n.error)}})}function ye(e,t,n){this._db=e,this.oldVersion=t,this.transaction=new ve(n)}function be(e){this._db=e}se.registerVersion("firebase","9.1.0","app-compat"),le(he,"_index",["name","keyPath","multiEntry","unique"]),pe(he,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),de(he,"_index",IDBIndex,["openCursor","openKeyCursor"]),le(me,"_cursor",["direction","key","primaryKey","value"]),pe(me,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach(function(n){n in IDBCursor.prototype&&(me.prototype[n]=function(){var t=this,e=arguments;return Promise.resolve().then(function(){return t._cursor[n].apply(t._cursor,e),ce(t._request).then(function(e){if(e)return new me(e,t._request)})})})}),ge.prototype.createIndex=function(){return new he(this._store.createIndex.apply(this._store,arguments))},ge.prototype.index=function(){return new he(this._store.index.apply(this._store,arguments))},le(ge,"_store",["name","keyPath","indexNames","autoIncrement"]),pe(ge,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),de(ge,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),fe(ge,"_store",IDBObjectStore,["deleteIndex"]),ve.prototype.objectStore=function(){return new ge(this._tx.objectStore.apply(this._tx,arguments))},le(ve,"_tx",["objectStoreNames","mode"]),fe(ve,"_tx",IDBTransaction,["abort"]),ye.prototype.createObjectStore=function(){return new ge(this._db.createObjectStore.apply(this._db,arguments))},le(ye,"_db",["name","version","objectStoreNames"]),fe(ye,"_db",IDBDatabase,["deleteObjectStore","close"]),be.prototype.transaction=function(){return new ve(this._db.transaction.apply(this._db,arguments))},le(be,"_db",["name","version","objectStoreNames"]),fe(be,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach(function(i){[ge,he].forEach(function(e){i in e.prototype&&(e.prototype[i.replace("open","iterate")]=function(){var e=(n=arguments,Array.prototype.slice.call(n)),t=e[e.length-1],n=this._store||this._index,r=n[i].apply(n,e.slice(0,-1));r.onsuccess=function(){t(r.result)}})})}),[he,ge].forEach(function(e){e.prototype.getAll||(e.prototype.getAll=function(e,n){var r=this,i=[];return new Promise(function(t){r.iterateCursor(e,function(e){e?(i.push(e.value),void 0===n||i.length!=n?e.continue():t(i)):t(i)})})})});var _e=1e4,we="w:0.5.1",Ie="FIS_v2",Ee="https://firebaseinstallations.googleapis.com/v1",Se=36e5,K=((pt={})["missing-app-config-values"]='Missing App configuration value: "{$valueName}"',pt["not-registered"]="Firebase Installation is not registered.",pt["installation-not-found"]="Firebase Installation not found.",pt["request-failed"]='{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',pt["app-offline"]="Could not process request. Application offline.",pt["delete-pending-registration"]="Can't delete installation while there is a pending registration request.",pt),Te=new h("installations","Installations",K);function Oe(e){return e instanceof s&&e.code.includes("request-failed")}function Ce(e){e=e.projectId;return Ee+"/projects/"+e+"/installations"}function Ae(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}function Ne(n,r){return u(this,void 0,void 0,function(){var t;return p(this,function(e){switch(e.label){case 0:return[4,r.json()];case 1:return t=e.sent(),t=t.error,[2,Te.create("request-failed",{requestName:n,serverCode:t.code,serverMessage:t.message,serverStatus:t.status})]}})})}function Pe(e){e=e.apiKey;return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function ke(e,t){t=t.refreshToken,e=Pe(e);return e.append("Authorization",Ie+" "+t),e}function De(n){return u(this,void 0,void 0,function(){var t;return p(this,function(e){switch(e.label){case 0:return[4,n()];case 1:return 500<=(t=e.sent()).status&&t.status<600?[2,n()]:[2,t]}})})}function je(t){return new Promise(function(e){setTimeout(e,t)})}var Re=/^[cdef][\w-]{21}$/,Le="";function Me(){try{var e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;var t=function(e){return btoa(String.fromCharCode.apply(String,a([],d(e)))).replace(/\+/g,"-").replace(/\//g,"_")}(e).substr(0,22);return Re.test(t)?t:Le}catch(e){return Le}}function xe(e){return e.appName+"!"+e.appId}var Be=new Map;function Fe(e,t){e=xe(e);Ue(e,t),function(e,t){var n=function(){!qe&&"BroadcastChannel"in self&&((qe=new BroadcastChannel("[Firebase] FID Change")).onmessage=function(e){Ue(e.data.key,e.data.fid)});return qe}();n&&n.postMessage({key:e,fid:t});0===Be.size&&qe&&(qe.close(),qe=null)}(e,t)}function Ue(e,t){var n,r,e=Be.get(e);if(e)try{for(var i=f(e),o=i.next();!o.done;o=i.next())(0,o.value)(t)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}var qe=null;var ze="firebase-installations-store",Ve=null;function He(){var e,t,n;return Ve||(e=1,t=function(e){0===e.oldVersion&&e.createObjectStore(ze)},(n=(e=ue(indexedDB,"open",["firebase-installations-database",e])).request)&&(n.onupgradeneeded=function(e){t&&t(new ye(n.result,e.oldVersion,n.transaction))}),Ve=e.then(function(e){return new be(e)})),Ve}function Ke(o,a){return u(this,void 0,void 0,function(){var t,n,r,i;return p(this,function(e){switch(e.label){case 0:return t=xe(o),[4,He()];case 1:return r=e.sent(),n=r.transaction(ze,"readwrite"),[4,(r=n.objectStore(ze)).get(t)];case 2:return i=e.sent(),[4,r.put(a,t)];case 3:return e.sent(),[4,n.complete];case 4:return e.sent(),i&&i.fid===a.fid||Fe(o,a.fid),[2,a]}})})}function $e(r){return u(this,void 0,void 0,function(){var t,n;return p(this,function(e){switch(e.label){case 0:return t=xe(r),[4,He()];case 1:return n=e.sent(),[4,(n=n.transaction(ze,"readwrite")).objectStore(ze).delete(t)];case 2:return e.sent(),[4,n.complete];case 3:return e.sent(),[2]}})})}function We(a,s){return u(this,void 0,void 0,function(){var t,n,r,i,o;return p(this,function(e){switch(e.label){case 0:return t=xe(a),[4,He()];case 1:return r=e.sent(),n=r.transaction(ze,"readwrite"),[4,(r=n.objectStore(ze)).get(t)];case 2:return i=e.sent(),void 0!==(o=s(i))?[3,4]:[4,r.delete(t)];case 3:return e.sent(),[3,6];case 4:return[4,r.put(o,t)];case 5:e.sent(),e.label=6;case 6:return[4,n.complete];case 7:return e.sent(),!o||i&&i.fid===o.fid||Fe(a,o.fid),[2,o]}})})}function Ge(i){return u(this,void 0,void 0,function(){var t,n,r;return p(this,function(e){switch(e.label){case 0:return[4,We(i,function(e){e=Ye(e||{fid:Me(),registrationStatus:0}),e=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:function(i){return u(this,void 0,void 0,function(){var t,n,r;return p(this,function(e){switch(e.label){case 0:return[4,Je(i)];case 1:t=e.sent(),e.label=2;case 2:return 1!==t.registrationStatus?[3,5]:[4,je(100)];case 3:return e.sent(),[4,Je(i)];case 4:return t=e.sent(),[3,2];case 5:return 0!==t.registrationStatus?[3,7]:[4,Ge(i)];case 6:return r=e.sent(),n=r.installationEntry,(r=r.registrationPromise)?[2,r]:[2,n];case 7:return[2,t]}})})}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Te.create("app-offline"));return{installationEntry:t,registrationPromise:n}}t={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},e=function(r,i){return u(this,void 0,void 0,function(){var t,n;return p(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,7]),[4,function(a,e){var s=e.fid;return u(this,void 0,void 0,function(){var t,n,r,i,o;return p(this,function(e){switch(e.label){case 0:return t=Ce(a),n=Pe(a),o={fid:s,authVersion:Ie,appId:a.appId,sdkVersion:we},r={method:"POST",headers:n,body:JSON.stringify(o)},[4,De(function(){return fetch(t,r)})];case 1:return(i=e.sent()).ok?[4,i.json()]:[3,3];case 2:return o=e.sent(),[2,{fid:o.fid||s,registrationStatus:2,refreshToken:o.refreshToken,authToken:Ae(o.authToken)}];case 3:return[4,Ne("Create Installation",i)];case 4:throw e.sent()}})})}(r,i)];case 1:return t=e.sent(),[2,Ke(r,t)];case 2:return Oe(n=e.sent())&&409===n.customData.serverCode?[4,$e(r)]:[3,4];case 3:return e.sent(),[3,6];case 4:return[4,Ke(r,{fid:i.fid,registrationStatus:0})];case 5:e.sent(),e.label=6;case 6:throw n;case 7:return[2]}})})}(e,t);return{installationEntry:t,registrationPromise:e}}}(i,e);return t=e.registrationPromise,e.installationEntry})];case 1:return(n=e.sent()).fid!==Le?[3,3]:(r={},[4,t]);case 2:return[2,(r.installationEntry=e.sent(),r)];case 3:return[2,{installationEntry:n,registrationPromise:t}]}})})}function Je(e){return We(e,function(e){if(!e)throw Te.create("installation-not-found");return Ye(e)})}function Ye(e){return 1===(t=e).registrationStatus&&t.registrationTime+_e<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}function Xe(e,a){var s=e.appConfig,c=e.platformLoggerProvider;return u(this,void 0,void 0,function(){var t,n,r,i,o;return p(this,function(e){switch(e.label){case 0:return t=function(e,t){t=t.fid;return Ce(e)+"/"+t+"/authTokens:generate"}(s,a),n=ke(s,a),(o=c.getImmediate({optional:!0}))&&n.append("x-firebase-client",o.getPlatformInfoString()),o={installation:{sdkVersion:we}},r={method:"POST",headers:n,body:JSON.stringify(o)},[4,De(function(){return fetch(t,r)})];case 1:return(i=e.sent()).ok?[4,i.json()]:[3,3];case 2:return o=e.sent(),[2,Ae(o)];case 3:return[4,Ne("Generate Auth Token",i)];case 4:throw e.sent()}})})}function Ze(i,o){return void 0===o&&(o=!1),u(this,void 0,void 0,function(){var r,t,n;return p(this,function(e){switch(e.label){case 0:return[4,We(i.appConfig,function(e){if(!et(e))throw Te.create("not-registered");var t,n=e.authToken;if(o||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+Se}(t)){if(1===n.requestStatus)return r=function(r,i){return u(this,void 0,void 0,function(){var t,n;return p(this,function(e){switch(e.label){case 0:return[4,Qe(r.appConfig)];case 1:t=e.sent(),e.label=2;case 2:return 1!==t.authToken.requestStatus?[3,5]:[4,je(100)];case 3:return e.sent(),[4,Qe(r.appConfig)];case 4:return t=e.sent(),[3,2];case 5:return 0===(n=t.authToken).requestStatus?[2,Ze(r,i)]:[2,n]}})})}(i,o),e;if(!navigator.onLine)throw Te.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},l(l({},t),{authToken:n}));return r=function(i,o){return u(this,void 0,void 0,function(){var t,n,r;return p(this,function(e){switch(e.label){case 0:return e.trys.push([0,3,,8]),[4,Xe(i,o)];case 1:return t=e.sent(),r=l(l({},o),{authToken:t}),[4,Ke(i.appConfig,r)];case 2:return e.sent(),[2,t];case 3:return!Oe(n=e.sent())||401!==n.customData.serverCode&&404!==n.customData.serverCode?[3,5]:[4,$e(i.appConfig)];case 4:return e.sent(),[3,7];case 5:return r=l(l({},o),{authToken:{requestStatus:0}}),[4,Ke(i.appConfig,r)];case 6:e.sent(),e.label=7;case 7:throw n;case 8:return[2]}})})}(i,n),n}return e})];case 1:return t=e.sent(),r?[4,r]:[3,3];case 2:return n=e.sent(),[3,4];case 3:n=t.authToken,e.label=4;case 4:return[2,n]}})})}function Qe(e){return We(e,function(e){if(!et(e))throw Te.create("not-registered");var t=e.authToken;return 1===(t=t).requestStatus&&t.requestTime+_e<Date.now()?l(l({},e),{authToken:{requestStatus:0}}):e})}function et(e){return void 0!==e&&2===e.registrationStatus}function tt(n,r){return void 0===r&&(r=!1),u(this,void 0,void 0,function(){var t;return p(this,function(e){switch(e.label){case 0:return[4,function(n){return u(this,void 0,void 0,function(){var t;return p(this,function(e){switch(e.label){case 0:return[4,Ge(n)];case 1:return(t=e.sent().registrationPromise)?[4,t]:[3,3];case 2:e.sent(),e.label=3;case 3:return[2]}})})}((t=n).appConfig)];case 1:return e.sent(),[4,Ze(t,r)];case 2:return[2,e.sent().token]}})})}function nt(e){return Te.create("missing-app-config-values",{valueName:e})}function rt(e){var t=H(e.getProvider("app").getImmediate(),it).getImmediate();return{getId:function(){return function(i){return u(this,void 0,void 0,function(){var t,n,r;return p(this,function(e){switch(e.label){case 0:return[4,Ge((t=i).appConfig)];case 1:return n=e.sent(),r=n.installationEntry,(n.registrationPromise||Ze(t)).catch(console.error),[2,r.fid]}})})}(t)},getToken:function(e){return tt(t,e)}}}var it="installations";V(new b(it,function(e){e=e.getProvider("app").getImmediate();return{app:e,appConfig:function(e){var t,n;if(!e||!e.options)throw nt("App Configuration");if(!e.name)throw nt("App Name");try{for(var r=f(["projectId","apiKey","appId"]),i=r.next();!i.done;i=r.next()){var o=i.value;if(!e.options[o])throw nt(o)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(e),platformLoggerProvider:H(e,"platform-logger"),_delete:function(){return Promise.resolve()}}},"PUBLIC")),V(new b("installations-internal",rt,"PRIVATE")),Q("@firebase/installations","0.5.1");var ot,at,st="0.5.1",ct="FB-PERF-TRACE-MEASURE",ut="@firebase/performance/config",lt="@firebase/performance/configexpire",pt="Performance",K=((K={})["trace started"]="Trace {$traceName} was started before.",K["trace stopped"]="Trace {$traceName} is not running.",K["nonpositive trace startTime"]="Trace {$traceName} startTime should be positive.",K["nonpositive trace duration"]="Trace {$traceName} duration should be positive.",K["no window"]="Window is not available.",K["no app id"]="App id is not available.",K["no project id"]="Project id is not available.",K["no api key"]="Api key is not available.",K["invalid cc log"]="Attempted to queue invalid cc event",K["FB not default"]="Performance can only start when Firebase app instance is the default one.",K["RC response not ok"]="RC response is not ok",K["invalid attribute name"]="Attribute name {$attributeName} is invalid.",K["invalid attribute value"]="Attribute value {$attributeValue} is invalid.",K["invalid custom metric name"]="Custom metric name {$customMetricName} is invalid",K["invalid String merger input"]="Input for String merger is invalid, contact support team to resolve.",K["already initialized"]="initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance.",K),ft=new h("performance",pt,K),dt=new k(pt);dt.logLevel=T.INFO;var ht,mt,gt=(vt.prototype.getUrl=function(){return this.windowLocation.href.split("?")[0]},vt.prototype.mark=function(e){this.performance&&this.performance.mark&&this.performance.mark(e)},vt.prototype.measure=function(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)},vt.prototype.getEntriesByType=function(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]},vt.prototype.getEntriesByName=function(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]},vt.prototype.getTimeOrigin=function(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)},vt.prototype.requiredApisAvailable=function(){return fetch&&Promise&&"undefined"!=typeof navigator&&navigator.cookieEnabled?"object"==typeof indexedDB||(dt.info("IndexedDB is not supported by current browswer"),!1):(dt.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)},vt.prototype.setupObserver=function(e,i){this.PerformanceObserver&&new this.PerformanceObserver(function(e){for(var t=0,n=e.getEntries();t<n.length;t++){var r=n[t];i(r)}}).observe({entryTypes:[e]})},vt.getInstance=function(){return ot=void 0===ot?new vt(at):ot},vt);function vt(e){if(!(this.window=e))throw ft.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay)}function yt(e,t){var n=e.length-t.length;if(n<0||1<n)throw ft.create("invalid String merger input");for(var r=[],i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}var bt,_t=(wt.prototype.getFlTransportFullUrl=function(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)},wt.getInstance=function(){return mt=void 0===mt?new wt:mt},wt);function wt(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=yt("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=yt("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}(pt=bt=bt||{})[pt.UNKNOWN=0]="UNKNOWN",pt[pt.VISIBLE=1]="VISIBLE",pt[pt.HIDDEN=2]="HIDDEN";var It=["firebase_","google_","ga_"],Et=new RegExp("^[a-zA-Z]\\w*$");function St(){switch(gt.getInstance().document.visibilityState){case"visible":return bt.VISIBLE;case"hidden":return bt.HIDDEN;default:return bt.UNKNOWN}}function Tt(e){e=null===(e=e.options)||void 0===e?void 0:e.appId;if(!e)throw ft.create("no app id");return e}var Ot="0.0.1",Ct={loggingEnabled:!0},At="FIREBASE_INSTALLATIONS_AUTH";function Nt(e,t){var r,i,n=function(){var e=gt.getInstance().localStorage;if(e){var t=e.getItem(lt);if(t&&function(e){return Number(e)>Date.now()}(t)){e=e.getItem(ut);if(e)try{return JSON.parse(e)}catch(e){return}}}}();return n?(kt(n),Promise.resolve()):(i=t,function(e){return(e=e.getToken()).then(function(e){}),e}((r=e).installations).then(function(e){var t=function(e){if(!(e=null===(e=e.options)||void 0===e?void 0:e.projectId))throw ft.create("no project id");return e}(r.app),n=function(e){if(!(e=null===(e=e.options)||void 0===e?void 0:e.apiKey))throw ft.create("no api key");return e}(r.app),e=new Request("https://firebaseremoteconfig.googleapis.com/v1/projects/"+t+"/namespaces/fireperf:fetch?key="+n,{method:"POST",headers:{Authorization:At+" "+e},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:Tt(r.app),app_version:st,sdk_version:Ot})});return fetch(e).then(function(e){if(e.ok)return e.json();throw ft.create("RC response not ok")})}).catch(function(){dt.info(Pt)}).then(kt).then(function(e){var t;t=e,e=gt.getInstance().localStorage,t&&e&&(e.setItem(ut,JSON.stringify(t)),e.setItem(lt,String(Date.now()+60*_t.getInstance().configTimeToLive*60*1e3)))},function(){}))}var Pt="Could not fetch config, will use default configs";function kt(e){if(!e)return e;var t=_t.getInstance(),n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=Ct.loggingEnabled,n.fpr_log_source&&(t.logSource=Number(n.fpr_log_source)),n.fpr_log_endpoint_url&&(t.logEndPointUrl=n.fpr_log_endpoint_url),n.fpr_log_transport_key&&(t.transportKey=n.fpr_log_transport_key),void 0!==n.fpr_vc_network_request_sampling_rate&&(t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate)),void 0!==n.fpr_vc_trace_sampling_rate&&(t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate)),t.logTraceAfterSampling=Dt(t.tracesSamplingRate),t.logNetworkAfterSampling=Dt(t.networkRequestsSamplingRate),e}function Dt(e){return Math.random()<=e}var jt,Rt=1;function Lt(e){var t;return Rt=2,jt=jt||(t=e,function(){var n=gt.getInstance().document;return new Promise(function(e){var t;n&&"complete"!==n.readyState?(t=function(){"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())},n.addEventListener("readystatechange",t)):e()})}().then(function(){return(e=(e=t.installations).getId()).then(function(e){ht=e}),e;var e}).then(function(e){return Nt(t,e)}).then(Mt,Mt))}function Mt(){Rt=3}var xt,Bt=1e4,Ft=3,Ut=1e3,qt=Ft,zt=[],Vt=!1;function Ht(e){setTimeout(function(){var e,t;if(0!==qt)return zt.length?(e=zt.splice(0,Ut),t=e.map(function(e){return{source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)}}),void function(e,r){return function(e){var t=_t.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(function(e){return e.ok||dt.info("Call to Firebase backend failed."),e.json()}).then(function(e){var t=Number(e.nextRequestWaitMillis),n=Bt;isNaN(t)||(n=Math.max(t,n));e=e.logResponseDetails;Array.isArray(e)&&0<e.length&&"RETRY_REQUEST_LATER"===e[0].responseAction&&(zt=a(a([],r),zt),dt.info("Retry transport request later.")),qt=Ft,Ht(n)})}({request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:_t.getInstance().logSource,log_event:t},e).catch(function(){zt=a(a([],e),zt),qt--,dt.info("Tries left: "+qt+"."),Ht(Bt)})):Ht(Bt)},e)}function Kt(n){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];!function(e){if(!e.eventTime||!e.message)throw ft.create("invalid cc log");zt=a(a([],zt),[e])}({message:n.apply(void 0,e),eventTime:Date.now()})}}function $t(e,t){(xt=xt||Kt(Jt))(e,t)}function Wt(e){var t=_t.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&gt.getInstance().requiredApisAvailable()&&(e.isAuto&&St()!==bt.VISIBLE||(3===Rt?Gt(e):Lt(e.performanceController).then(function(){return Gt(e)},function(){return Gt(e)})))}function Gt(e){var t;!ht||(t=_t.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(function(){return $t(e,1)},0)}function Jt(e,t){return 0===t?(t={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},t={application_info:Yt(e.performanceController.app),network_request_metric:t},JSON.stringify(t)):function(e){var t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);t={application_info:Yt(e.performanceController.app),trace_metric:t};return JSON.stringify(t)}(e)}function Yt(e){return{google_app_id:Tt(e),app_instance_id:ht,web_app_info:{sdk_version:st,page_url:gt.getInstance().getUrl(),service_worker_status:"serviceWorker"in(e=gt.getInstance().navigator)?e.serviceWorker.controller?2:3:1,visibility_state:St(),effective_connection_type:function(){var e=gt.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}()},application_process_state:0}}var Xt=["_fp","_fcp","_fid"];var Zt=(Qt.prototype.start=function(){if(1!==this.state)throw ft.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2},Qt.prototype.stop=function(){if(2!==this.state)throw ft.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),Wt(this)},Qt.prototype.record=function(e,t,n){if(e<=0)throw ft.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw ft.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=l({},n.attributes)),n&&n.metrics)for(var r=0,i=Object.keys(n.metrics);r<i.length;r++){var o=i[r];isNaN(Number(n.metrics[o]))||(this.counters[o]=Number(Math.floor(n.metrics[o])))}Wt(this)},Qt.prototype.incrementMetric=function(e,t){void 0===t&&(t=1),void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)},Qt.prototype.putMetric=function(e,t){if(n=e,r=this.name,0===n.length||100<n.length||!(r&&r.startsWith("_wt_")&&-1<Xt.indexOf(n))&&n.startsWith("_"))throw ft.create("invalid custom metric name",{customMetricName:e});var n,r;this.counters[e]=(e=t,(t=Math.floor(e))<e&&dt.info("Metric value should be an Integer, setting the value as : "+t+"."),t)},Qt.prototype.getMetric=function(e){return this.counters[e]||0},Qt.prototype.putAttribute=function(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!It.some(function(e){return n.startsWith(e)})&&!!n.match(Et)),r=0!==(r=t).length&&r.length<=100;if(i&&r)this.customAttributes[e]=t;else{if(!i)throw ft.create("invalid attribute name",{attributeName:e});if(!r)throw ft.create("invalid attribute value",{attributeValue:t})}},Qt.prototype.getAttribute=function(e){return this.customAttributes[e]},Qt.prototype.removeAttribute=function(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]},Qt.prototype.getAttributes=function(){return l({},this.customAttributes)},Qt.prototype.setStartTime=function(e){this.startTimeUs=e},Qt.prototype.setDuration=function(e){this.durationUs=e},Qt.prototype.calculateTraceMetrics=function(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))},Qt.createOobTrace=function(e,t,n,r){var i=gt.getInstance().getUrl();i&&(e=new Qt(e,"_wt_"+i,!0),i=Math.floor(1e3*gt.getInstance().getTimeOrigin()),e.setStartTime(i),t&&t[0]&&(e.setDuration(Math.floor(1e3*t[0].duration)),e.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),e.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),e.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd))),n&&((t=n.find(function(e){return"first-paint"===e.name}))&&t.startTime&&e.putMetric("_fp",Math.floor(1e3*t.startTime)),(n=n.find(function(e){return"first-contentful-paint"===e.name}))&&n.startTime&&e.putMetric("_fcp",Math.floor(1e3*n.startTime)),r&&e.putMetric("_fid",Math.floor(1e3*r))),Wt(e))},Qt.createUserTimingTrace=function(e,t){Wt(new Qt(e,t,!1,t))},Qt);function Qt(e,t,n,r){void 0===n&&(n=!1),this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=gt.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark="FB-PERF-TRACE-START-"+this.randomId+"-"+this.name,this.traceStopMark="FB-PERF-TRACE-STOP-"+this.randomId+"-"+this.name,this.traceMeasure=r||ct+"-"+this.randomId+"-"+this.name,r&&this.calculateTraceMetrics())}function en(e,t){var n,r,i,o=t;o&&void 0!==o.responseStart&&(r=gt.getInstance().getTimeOrigin(),i=Math.floor(1e3*(o.startTime+r)),t=o.responseStart?Math.floor(1e3*(o.responseStart-o.startTime)):void 0,r=Math.floor(1e3*(o.responseEnd-o.startTime)),o={performanceController:e,url:o.name&&o.name.split("?")[0],responsePayloadBytes:o.transferSize,startTimeUs:i,timeToResponseInitiatedUs:t,timeToResponseCompletedUs:r},n=o,(i=_t.getInstance()).instrumentationEnabled&&(t=n.url,r=i.logEndPointUrl.split("?")[0],o=i.flTransportEndpointUrl.split("?")[0],t!==r&&t!==o&&i.loggingEnabled&&i.logNetworkAfterSampling&&setTimeout(function(){return $t(n,0)},0)))}var tn=5e3;function nn(e){ht&&(setTimeout(function(){return function(t){var e=gt.getInstance(),n=e.getEntriesByType("navigation"),r=e.getEntriesByType("paint");{var i;e.onFirstInputDelay?(i=setTimeout(function(){Zt.createOobTrace(t,n,r),i=void 0},tn),e.onFirstInputDelay(function(e){i&&(clearTimeout(i),Zt.createOobTrace(t,n,r,e))})):Zt.createOobTrace(t,n,r)}}(e)},0),setTimeout(function(){return function(t){for(var e=gt.getInstance(),n=e.getEntriesByType("resource"),r=0,i=n;r<i.length;r++){var o=i[r];en(t,o)}e.setupObserver("resource",function(e){return en(t,e)})}(e)},0),setTimeout(function(){return function(t){for(var e=gt.getInstance(),n=e.getEntriesByType("measure"),r=0,i=n;r<i.length;r++){var o=i[r];rn(t,o)}e.setupObserver("measure",function(e){return rn(t,e)})}(e)},0))}function rn(e,t){t=t.name;t.substring(0,ct.length)!==ct&&Zt.createUserTimingTrace(e,t)}var on=(an.prototype._init=function(e){var t=this;this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),gt.getInstance().requiredApisAvailable()?new Promise(function(e,t){try{var n=!0,r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=function(){i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=function(){n=!1},i.onerror=function(){var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}).then(function(e){e&&(Vt||(Ht(5500),Vt=!0),Lt(t).then(function(){return nn(t)},function(){return nn(t)}),t.initialized=!0)}).catch(function(e){dt.info("Environment doesn't support IndexedDB: "+e)}):dt.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))},Object.defineProperty(an.prototype,"instrumentationEnabled",{get:function(){return _t.getInstance().instrumentationEnabled},set:function(e){_t.getInstance().instrumentationEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(an.prototype,"dataCollectionEnabled",{get:function(){return _t.getInstance().dataCollectionEnabled},set:function(e){_t.getInstance().dataCollectionEnabled=e},enumerable:!1,configurable:!0}),an);function an(e,t){this.app=e,this.installations=t,this.initialized=!1}var sn="[DEFAULT]";V(new b("performance",function(e,t){var n=t.options,t=e.getProvider("app").getImmediate(),e=e.getProvider("installations-internal").getImmediate();if(t.name!==sn)throw ft.create("FB not default");if("undefined"==typeof window)throw ft.create("no window");at=window;e=new on(t,e);return e._init(n),e},"PUBLIC")),Q("@firebase/performance","0.5.1");var cn=(Object.defineProperty(un.prototype,"instrumentationEnabled",{get:function(){return this._delegate.instrumentationEnabled},set:function(e){this._delegate.instrumentationEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(un.prototype,"dataCollectionEnabled",{get:function(){return this._delegate.dataCollectionEnabled},set:function(e){this._delegate.dataCollectionEnabled=e},enumerable:!1,configurable:!0}),un.prototype.trace=function(e){return t=this._delegate,t=(n=t)&&n._delegate?n._delegate:n,new Zt(t,e);var t,n},un);function un(e,t){this.app=e,this._delegate=t}var ln;function pn(e){var t=e.getProvider("app-compat").getImmediate(),e=e.getProvider("performance").getImmediate();return new cn(t,e)}(ln=se).INTERNAL.registerComponent(new b("performance-compat",pn,"PUBLIC")),ln.registerVersion("@firebase/performance-compat","0.1.1");return se.registerVersion("firebase","9.1.0","compat-lite"),se}); //# sourceMappingURL=firebase-performance-standalone-compat.js.map
/** * @file llplacesfolderview.h * @brief llplacesfolderview used within llplacesinventorypanel * @author [email protected] * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #ifndef LL_LLPLACESFOLDERVIEW_H #define LL_LLPLACESFOLDERVIEW_H #include "llfolderview.h" #include "llinventorypanel.h" class LLLandmarksPanel; class LLPlacesFolderView : public LLFolderView { public: struct Params : public LLInitParam::Block<Params, LLFolderView::Params> { Params() {} }; LLPlacesFolderView(const LLFolderView::Params& p); /** * Handles right mouse down * * Contains workaround for EXT-2786: sets current selected list for landmark * panel using @c mParentLandmarksPanel which is set in @c LLLandmarksPanel::initLandmarksPanel */ /*virtual*/ BOOL handleRightMouseDown( S32 x, S32 y, MASK mask ); /*virtual*/ void updateMenu(); void setupMenuHandle(LLInventoryType::EType asset_type, LLHandle<LLView> menu_handle); void setParentLandmarksPanel(LLLandmarksPanel* panel) { mParentLandmarksPanel = panel; } private: /** * holds pointer to landmark panel. This pointer is used in @c LLPlacesFolderView::handleRightMouseDown */ LLLandmarksPanel* mParentLandmarksPanel; typedef std::map<LLInventoryType::EType, LLHandle<LLView> > inventory_type_menu_handle_t; inventory_type_menu_handle_t mMenuHandlesByInventoryType; }; #endif // LL_LLPLACESFOLDERVIEW_H
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): if matrix: new = [] for rows in matrix: new.append([n ** 2 for n in rows]) return new
""" Reporter for CSV output that can be opened with MS Excel or other tools. """ import csv from typing import List from tracematrix.item import TraceItem from tracematrix.reporters.base_reporter import Reporter class CsvReporter(Reporter): """Creates reports in .csv format""" @staticmethod def write( outputfile: str, rows: List[TraceItem], columns: List[TraceItem] ) -> None: fieldnames = [""] + [req.id for req in columns] + ["total"] with open(outputfile, "w", encoding="utf8", newline="") as outfile: writer = csv.DictWriter(outfile, fieldnames, delimiter=";") writer.writeheader() for testcase in rows: rowdict = {"": testcase.id} for traced_req in testcase.traced_to: rowdict[traced_req.id] = "x" rowdict["total"] = len(testcase.traced_to) writer.writerow(rowdict) result_row = {"": "total"} for req in columns: result_row[req.id] = len(req.traced_to) writer.writerow(result_row)
from typing import Any, List, Optional from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from abing import crud, models, schemas from abing.routes import deps router = APIRouter() @router.get("/", response_model=List[schemas.Arm]) async def get_arms( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100, experiment_id: Optional[int] = None, current_user: models.User = Depends(deps.get_current_active_user), ): arm_list = crud.arm.get_list( db, skip=skip, limit=limit, experiment_id=experiment_id ) return arm_list @router.get("/{id}", response_model=schemas.Arm) async def get_arm( id: int, db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: return crud.arm.get(db=db, id=id) @router.post("/", response_model=schemas.Arm) async def create_arm( arm_in: schemas.ArmCreate, db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_active_user), ): experiment = crud.experiment.get(db=db, id=arm_in.experiment_id) if not experiment: raise HTTPException(status_code=404, detail="experiment not found") arm_in = arm_in.dict() features = arm_in.pop("features", []) arm = crud.arm.create(db=db, obj_in=arm_in) for feature in features: feature_in = {**feature, "arm_id": arm.id} feature_out = crud.feature.create(db=db, obj_in=feature_in) return arm @router.post("/bulk", response_model=List[schemas.Arm]) async def create_arms( arms_in: List[schemas.ArmCreate], db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_active_user), ): created_arms = list() for arm_in in arms_in: experiment = crud.experiment.get(db=db, id=arm_in.experiment_id) if not experiment: raise HTTPException(status_code=404, detail="experiment not found") arm_in = arm_in.dict() features = arm_in.pop("features", []) or [] arm = crud.arm.create(db=db, obj_in=arm_in) for feature in features: feature_in = {**feature, "arm_id": arm.id} feature_out = crud.feature.create(db=db, obj_in=feature_in) created_arms.append(arm) return created_arms @router.put("/{id}") def update_arm( *, db: Session = Depends(deps.get_db), id: int, arm_in: schemas.ArmUpdate, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: arm = crud.arm.get(db=db, id=id) if not arm: raise HTTPException(status_code=404, detail="arm not found") arm = crud.arm.update(db=db, db_obj=arm, obj_in=arm_in) return arm @router.delete("/{id}") def delete_arm( *, db: Session = Depends(deps.get_db), id: int, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: arm = crud.arm.get(db=db, id=id) experiment_id = arm.experiment_id if not arm: raise HTTPException(status_code=404, detail="arm not found") crud.arm.remove(db=db, id=id) return { "message": f"Arm {id} is removed!", "type": "arm", "arm_id": id, "experiment_id": experiment_id, }
var searchData= [ ['gesture_2ehpp',['gesture.hpp',['../gesture_8hpp.html',1,'']]], ['givereadable',['giveReadable',['../classlimited__paj7620.html#a56be0ef14ee4d319862dd46ef67e7fe0',1,'limited_paj7620']]] ];
import Vue from 'vue' import axios from 'axios' import { getToken } from '@/utils/auth' import { MessageBox } from 'element-ui' import router from '../router' var interceptorsNum = 0 const $axios = axios.create({ withCredentials: false, baseURL: process.env.BASE_API }) // request interceptor $axios.interceptors.request.use( config => { config.headers['X-Token'] = getToken() config.headers['Authorization'] = 'Bearer ' + getToken() if (config.method === 'get' || config.method === 'GET') { const query = config.data let link = '' for (const key in query) { link += '&' + key + '=' + query[key] } if (link.substr(1)) { config.url += '?' + link.substr(1) } } return config }, error => { Promise.reject(error) } ) $axios.interceptors.response.use( response => { if (response.data.code === 409) { return (() => { if (interceptorsNum === 0) { interceptorsNum++ MessageBox.alert('登录信息失效, 请重新登录?', '提示', { confirmButtonText: '确定', callback: action => { try { localStorage.removeItem('userName') localStorage.removeItem('Admin-Token') const error = { error: '登录信息失效' } throw (error) } catch (error) { router.push('/login') interceptorsNum = 0 } } }) } return response })() } return response }, error => { return Promise.reject(error) } ) Vue.prototype.$axios = $axios export default $axios
import logging import requests import json from requests.exceptions import HTTPError, ConnectionError import traceback from decimal import Decimal as D from django.db import transaction from django.conf import settings from django.core.validators import URLValidator from django.utils import six from django.contrib import messages from django.http import Http404, HttpResponse, JsonResponse, HttpResponseRedirect from django.core.urlresolvers import reverse, reverse_lazy from django.utils.translation import ugettext as _ from django.template.loader import get_template # from ledger.payment import forms, models from ledger.payments.helpers import is_payment_admin from oscar.core.loading import get_class, get_model, get_classes from oscar.apps.checkout import signals from oscar.apps.shipping.methods import NoShippingRequired # from ledger.payments.models import Invoice, BpointToken, OracleInterfaceSystem, LinkedInvoiceGroupIncrementer, LinkedInvoice from ledger.accounts.models import EmailUser from ledger.payments.facade import invoice_facade, bpoint_facade, bpay_facade from ledger.payments.utils import isLedgerURL, systemid_check, LinkedInvoiceCreate from ledger.api import models as ledgerapi_models from ledger.api import utils as ledgerapi_utils from ledger.payments.bpoint.gateway import Gateway from ledger.basket.models import Basket Order = get_model('order', 'Order') CorePaymentDetailsView = get_class('checkout.views','PaymentDetailsView') CoreIndexView = get_class('checkout.views','IndexView') CoreThankYouView = get_class('checkout.views','ThankYouView') UserAddress = get_model('address','UserAddress') RedirectRequired, UnableToTakePayment, PaymentError \ = get_classes('payment.exceptions', ['RedirectRequired', 'UnableToTakePayment', 'PaymentError']) UnableToPlaceOrder = get_class('order.exceptions', 'UnableToPlaceOrder') CheckoutSessionData = get_class( 'checkout.utils', 'CheckoutSessionData') # Standard logger for checkout events logger = logging.getLogger('oscar.checkout') class IndexView(CoreIndexView): success_url = reverse_lazy('checkout:payment-details') class FallbackMissing(Exception): pass def proper_errorpage(self,url,r,e): messages.error(r,str(e)) if isLedgerURL(url): return HttpResponseRedirect(url) else: return HttpResponseRedirect(reverse('payments:payments-error')) def get(self, request, *args, **kwargs): # We redirect immediately to shipping address stage if the user is # signed in. if True: # We raise a signal to indicate that the user has entered the # checkout process so analytics tools can track this event. signals.start_checkout.send_robust( sender=self, request=request) return self.get_success_response() return super(IndexView, self).get(request, *args, **kwargs) class PaymentDetailsView(CorePaymentDetailsView): pre_conditions = [ 'check_if_checkout_is_active', 'check_basket_is_not_empty', 'check_basket_is_valid', 'check_user_email_is_captured', 'check_shipping_data_is_captured' ] def get_skip_conditions(self, request): if not self.preview: # Payment details should only be collected if necessary return ['skip_unless_payment_is_required','skip_payment_if_proxy'] return super(PaymentDetailsView, self).get_skip_conditions(request) def get(self, request, *args, **kwargs): if self.skip_preview_if_free(request) or self.skip_if_proxy(): return self.handle_place_order_submission(request) if self.checkout_session.proxy() and not self.preview: self.checkout_session.pay_by('other') return super(PaymentDetailsView, self).get(request, *args, **kwargs) def skip_if_proxy(self): if self.preview and self.checkout_session.proxy(): return True return False def skip_preview_if_free(self, request): if self.preview: # Check to see if payment is actually required for this order. shipping_address = self.get_shipping_address(request.basket) shipping_method = self.get_shipping_method( request.basket, shipping_address) if shipping_method: shipping_charge = shipping_method.calculate(request.basket) else: # It's unusual to get here as a shipping method should be set by # the time this skip-condition is called. In the absence of any # other evidence, we assume the shipping charge is zero. shipping_charge = prices.Price( currency=request.basket.currency, excl_tax=D('0.00'), tax=D('0.00') ) total = self.get_order_totals(request.basket, shipping_charge) if total.excl_tax == D('0.00'): self.checkout_session.is_free_basket(True) return True return False def check_for_refund(self, request): print ("skip_preview_if_refund") if self.preview: # Check to see if payment is actually required for this order. shipping_address = self.get_shipping_address(request.basket) shipping_method = self.get_shipping_method( request.basket, shipping_address) if shipping_method: shipping_charge = shipping_method.calculate(request.basket) else: # It's unusual to get here as a shipping method should be set by # the time this skip-condition is called. In the absence of any # other evidence, we assume the shipping charge is zero. shipping_charge = prices.Price( currency=request.basket.currency, excl_tax=D('0.00'), tax=D('0.00') ) total = self.get_order_totals(request.basket, shipping_charge) print ("REFUND check") print (total) if total.excl_tax == D('0.00'): self.checkout_session.is_free_basket(True) return True return False def get_context_data(self, **kwargs): """ Add data for Bpoint. """ # Override method so the bankcard and billing address forms can be # added to the context. ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) method = self.checkout_session.payment_method() custom_template = self.checkout_session.custom_template() system_id = self.checkout_session.system() system_id_zeroed=system_id.replace('S','0') ctx['store_card'] = True user = None # only load stored cards if the user is an admin or has legitimately logged in if self.checkout_session.basket_owner() and is_payment_admin(self.request.user): user = EmailUser.objects.get(id=int(self.checkout_session.basket_owner())) elif self.request.user.is_authenticated(): user = self.request.user elif self.checkout_session.get_user_logged_in(): if 'LEDGER_API_KEY' in self.request.COOKIES: apikey = self.request.COOKIES['LEDGER_API_KEY'] if ledgerapi_models.API.objects.filter(api_key=apikey,active=1).count(): if ledgerapi_utils.api_allow(ledgerapi_utils.get_client_ip(self.request),apikey) is True: user = EmailUser.objects.get(id=int(self.checkout_session.get_user_logged_in())) if user: cards = user.stored_cards.all().filter(system_id=system_id_zeroed) if cards: ctx['cards'] = cards ctx['custom_template'] = custom_template ctx['bpay_allowed'] = settings.BPAY_ALLOWED ctx['payment_method'] = method ctx['bankcard_form'] = kwargs.get( 'bankcard_form', forms.BankcardForm()) ctx['billing_address_form'] = kwargs.get( 'billing_address_form', forms.BillingAddressForm()) ctx['amount_override'] = None if self.checkout_session.get_amount_override(): ctx['amount_override'] =self.checkout_session.get_amount_override() if self.checkout_session.get_session_type(): ctx['session_type'] = self.checkout_session.get_session_type() #print (request.COOKIES.get('logged_in_status')) ctx['NO_HEADER'] = 'false' ctx['PAYMENT_API_WRAPPER'] = 'false' if self.request.COOKIES.get('no_header') == 'true': ctx['NO_HEADER'] = 'true' if self.request.COOKIES.get('payment_api_wrapper') == 'true': self.template_name = "checkout/payment_details_api_wrapper.html" #self.checkout_session.set_guest_email('[email protected]') ctx['PAYMENT_API_WRAPPER'] = 'true' return ctx def post(self, request, *args, **kwargs): # Override so we can validate the bankcard/billingaddress submission. # If it is valid, we render the preview screen with the forms hidden # within it. When the preview is submitted, we pick up the 'action' # parameters and actually place the order. if request.POST.get('action', '') == 'place_order': if self.checkout_session.payment_method() == 'card': return self.do_place_order(request) else: return self.handle_place_order_submission(request) # Validate the payment method payment_method = request.POST.get('payment_method', '') if payment_method == 'bpay' and settings.BPAY_ALLOWED: self.checkout_session.pay_by('bpay') elif payment_method == 'card': self.checkout_session.pay_by('card') elif payment_method: # someone's trying to pull a fast one, refresh the page self.preview = False return self.render_to_response(self.get_context_data()) # Get if user wants to store the card store_card = request.POST.get('store_card',False) self.checkout_session.permit_store_card(bool(store_card)) # Get if user wants to checkout using a stored card checkout_token = request.POST.get('checkout_token',False) if checkout_token: self.checkout_session.checkout_using_token(request.POST.get('card','')) if self.checkout_session.payment_method() == 'card' and not checkout_token: bankcard_form = forms.BankcardForm(request.POST) if not bankcard_form.is_valid(): # Form validation failed, render page again with errors self.preview = False ctx = self.get_context_data( bankcard_form=bankcard_form) return self.render_to_response(ctx) # Render preview with bankcard hidden if self.checkout_session.payment_method() == 'card' and not checkout_token: return self.render_preview(request,bankcard_form=bankcard_form) else: return self.render_preview(request) def do_place_order(self, request): # Helper method to check that the hidden forms wasn't tinkered # with. if request.COOKIES.get('payment_api_wrapper') == 'true': if 'LEDGER_API_KEY' in request.COOKIES: apikey = request.COOKIES['LEDGER_API_KEY'] if ledgerapi_models.API.objects.filter(api_key=apikey,active=1).count(): if ledgerapi_utils.api_allow(ledgerapi_utils.get_client_ip(request),apikey) is True: PAYMENT_INTERFACE_SYSTEM_PROJECT_CODE = request.POST.get('PAYMENT_INTERFACE_SYSTEM_PROJECT_CODE','') PAYMENT_INTERFACE_SYSTEM_ID = request.POST.get('PAYMENT_INTERFACE_SYSTEM_ID','') ois = OracleInterfaceSystem.objects.get(id=int(PAYMENT_INTERFACE_SYSTEM_ID), system_id=PAYMENT_INTERFACE_SYSTEM_PROJECT_CODE) bpoint_facade.gateway = Gateway( ois.bpoint_username, ois.bpoint_password, ois.bpoint_merchant_num, ois.bpoint_currency, ois.bpoint_biller_code, ois.bpoint_test, ois.id ) # END GET CRIDENTIAL FROM MODEL #return self.render_payment_message(self.request, error=None,) if not self.checkout_session.checkout_token(): bankcard_form = forms.BankcardForm(request.POST) if not bankcard_form.is_valid(): messages.error(request, "Invalid submission") if self.request.COOKIES.get('payment_api_wrapper') == 'true': return self.render_payment_message(self.request, error=None,) #HttpResponse("ERROR PLEASE CHECK") return HttpResponseRedirect(reverse('checkout:payment-details')) if self.request.COOKIES.get('payment_api_wrapper') == 'true': try: submission = self.build_submission() if not self.checkout_session.checkout_token(): submission['payment_kwargs']['bankcard'] = bankcard_form.bankcard return self.submit(**submission) except: return self.render_payment_message(self.request, error="ERROR Taking payment",) else: # Attempt to submit the order, passing the bankcard object so that it # gets passed back to the 'handle_payment' method below. submission = self.build_submission() if not self.checkout_session.checkout_token(): submission['payment_kwargs']['bankcard'] = bankcard_form.bankcard return self.submit(**submission) def render_payment_message(self, request, **kwargs): """ Show the payment details page This method is useful if the submission from the payment details view is invalid and needs to be re-rendered with form errors showing. """ self.preview = False ctx = self.get_context_data(**kwargs) #self.template_name = "checkout/payment_messgaes.html" self.template_name = "checkout/preview-ledger-api.html" return self.render_to_response(ctx) def createInvoiceLinks(self,invoice): basket_id = self.checkout_session.get_submitted_basket_id() LinkedInvoiceCreate(invoice, basket_id) return #basket_id = self.checkout_session.get_submitted_basket_id() #basket = Basket.objects.get(id=basket_id) #system_id = basket.system.replace("S","0") #ois = OracleInterfaceSystem.objects.get(system_id=system_id) #li = None #lig = None #if LinkedInvoice.objects.filter(system_identifier=ois,booking_reference=basket.booking_reference, booking_reference_linked=basket.booking_reference_link).count(): # print ("LinkedInvoice already exists, not dupilication") #else: # if basket.booking_reference_link: # if len(basket.booking_reference_link) > 0: # li = LinkedInvoice.objects.filter(system_identifier=ois,booking_reference=basket.booking_reference_link) # if li.count() > 0: # lig = li[0].invoice_group_id # if lig is None: # lig = LinkedInvoiceGroupIncrementer.objects.create(system_identifier=ois) # lininv = LinkedInvoice.objects.create(invoice_reference=invoice.reference, system_identifier=ois,booking_reference=basket.booking_reference,booking_reference_linked=basket.booking_reference_link, invoice_group_id=lig) def doInvoice(self,order_number,total,**kwargs): method = self.checkout_session.bpay_method() system = self.checkout_session.system() icrn_format = self.checkout_session.icrn_format() # Generate the string to be used to generate the icrn crn_string = '{0}{1}'.format(systemid_check(system),order_number) if method == 'crn': invoice = invoice_facade.create_invoice_crn( order_number, total.incl_tax, crn_string, system, self.checkout_session.get_invoice_text() if self.checkout_session.get_invoice_text() else '', self.checkout_session.payment_method() if self.checkout_session.payment_method() else None ) self.createInvoiceLinks(invoice) return invoice elif method == 'icrn': invoice = invoice_facade.create_invoice_icrn( order_number, total.incl_tax, crn_string, icrn_format, system, self.checkout_session.get_invoice_text() if self.checkout_session.get_invoice_text() else '', self.checkout_session.payment_method() if self.checkout_session.payment_method() else None ) self.createInvoiceLinks(invoice) return invoice else: raise ValueError('{0} is not a supported BPAY method.'.format(method)) def handle_last_check(self,url): logger.info('checkout --> handle_last_check:'+str(url)) try: res = requests.get(url,cookies=self.request.COOKIES, verify=False) res.raise_for_status() response = json.loads(res.content.decode('utf-8')).get('status') if response != 'approved': error = json.loads(res.content.decode('utf-8')).get('error',None) if error: raise ValueError('Payment could not be completed at this moment due to the following error \n {}'.format(error)) else: raise ValueError('Payment could not be completed at this moment.') except requests.exceptions.HTTPError as e: if 400 <= e.response.status_code < 500: http_error_msg = '{} Client Error: {} for url: {} > {}'.format(e.response.status_code, e.response.reason, e.response.url,e.response._content) elif 500 <= e.response.status_code < 600: http_error_msg = '{} Server Error: {} for url: {}'.format(e.response.status_code, e.response.reason, e.response.url) e.message = http_error_msg e.args = (http_error_msg,) raise PaymentError(e) def handle_payment(self, order_number, total, **kwargs): """ Make submission """ logger.info('Order #%s: handling payment', order_number) system_id = self.checkout_session.system() system_id_zeroed=system_id.replace('S','0') # Using preauth here (two-stage model). You could use payment to # perform the preauth and capture in one step. with transaction.atomic(): method = self.checkout_session.payment_method() # Last point to use the check url to see if the payment should be permitted if self.checkout_session.get_last_check(): logger.info('Order #%s: handling payment --> self.checkout_session.get_last_check', order_number) self.handle_last_check(self.checkout_session.get_last_check()) if self.checkout_session.free_basket(): logger.info('Order #%s: handling payment --> self.checkout_session.free_basket', order_number) self.doInvoice(order_number,total) else: logger.info('Order #%s: handling payment --> else', order_number) if method == 'card': try: #Generate Invoice logger.info('Order #%s: doInvoice with method: '+str(method), order_number) invoice = self.doInvoice(order_number,total) # Swap user if in session if 'LEDGER_API_KEY' in self.request.COOKIES: apikey = self.request.COOKIES['LEDGER_API_KEY'] if ledgerapi_models.API.objects.filter(api_key=apikey,active=1).count(): if ledgerapi_utils.api_allow(ledgerapi_utils.get_client_ip(self.request),apikey) is True: user_logged_in = EmailUser.objects.get(id=int(self.checkout_session.get_user_logged_in())) else: user_logged_in = self.request.user else: user_logged_in = self.request.user if self.checkout_session.basket_owner(): user = EmailUser.objects.get(id=int(self.checkout_session.basket_owner())) else: user = self.request.user # START - need to grab user from api after verifing API KEYS #user = EmailUser.objects.get(email='[email protected]') # END - need to grab user from api after verifing API KEYS # Get the payment action for bpoint card_method = self.checkout_session.card_method() # Check if the user is paying using a stored card if self.checkout_session.checkout_token(): logger.info('Order #%s: self.checkout_session.checkout_token: '+str(method), order_number) try: token = BpointToken.objects.get(id=self.checkout_session.checkout_token()) except BpointToken.DoesNotExist: raise ValueError('This stored card does not exist.') if self.checkout_session.invoice_association(): invoice.token = '{}|{}|{}'.format(token.DVToken,token.expiry_date.strftime("%m%y"),token.last_digits) invoice.save() else: if self.checkout_session.get_amount_override() is not None: amount_override = self.checkout_session.get_amount_override() bpoint_facade.pay_with_storedtoken(card_method,'internet','single',token.id,order_number,invoice.reference, amount_override) else: bpoint_facade.pay_with_storedtoken(card_method,'internet','single',token.id,order_number,invoice.reference, total.incl_tax) else: logger.info('Order #%s: self.checkout_session.checkout_token:else: '+str(method), order_number) # Store card if user wants to store card if self.checkout_session.store_card(): logger.info('Order #%s: self.checkout_session.store_card '+str(method), order_number) resp = bpoint_facade.create_token(user_logged_in,invoice.reference,kwargs['bankcard'],True,system_id_zeroed) if self.checkout_session.invoice_association(): invoice.token = resp invoice.save() else: bankcard = kwargs['bankcard'] bankcard.last_digits = bankcard.number[-4:] if self.checkout_session.get_amount_override() is not None: amount_override = self.checkout_session.get_amount_override() resp = bpoint_facade.post_transaction(card_method,'internet','single',order_number,invoice.reference, amount_override,bankcard) else: resp = bpoint_facade.post_transaction(card_method,'internet','single',order_number,invoice.reference, total.incl_tax,bankcard) else: logger.info('Order #%s: self.checkout_session.store_card:else: '+str(method), order_number) if self.checkout_session.invoice_association(): logger.info('Order #%s: self.checkout_session.invoice_association '+str(method), order_number) resp = bpoint_facade.create_token(user_logged_in,invoice.reference,kwargs['bankcard'],False,system_id_zeroed) invoice.token = resp invoice.save() else: logger.info('Order #%s: self.checkout_session.invoice_association:else '+str(method), order_number) bankcard = kwargs['bankcard'] bankcard.last_digits = bankcard.number[-4:] if self.checkout_session.get_amount_override() is not None: amount_override = self.checkout_session.get_amount_override() resp = bpoint_facade.post_transaction(card_method,'internet','single',order_number,invoice.reference,amount_override ,bankcard) else: resp = bpoint_facade.post_transaction(card_method,'internet','single',order_number,invoice.reference, total.incl_tax,bankcard) #resp = bpoint_facade.post_transaction(card_method,'internet','single',order_number,invoice.reference, float(15.00),bankcard) if not self.checkout_session.invoice_association(): logger.info('Order #%s: if not self.checkout_session.invoice_association '+str(method), order_number) # Record payment source and event source_type, is_created = models.SourceType.objects.get_or_create( name='Bpoint') # amount_allocated if action is preauth and amount_debited if action is payment if card_method == 'payment': logger.info('Order #%s: card_method payment '+str(method), order_number) source = source_type.sources.model( source_type=source_type, amount_debited=total.incl_tax, currency=total.currency) elif card_method == 'preauth': logger.info('Order #%s: card_method preauth '+str(method), order_number) source = source_type.sources.model( source_type=source_type, amount_allocated=total.incl_tax, currency=total.currency) logger.info('Order #%s: payment source '+str(method), order_number) self.add_payment_source(source) self.add_payment_event('Paid', total.incl_tax) except Exception as e: traceback.print_exc() raise else: #Generate Invoice logger.info('Order #%s: doInvoice with method: '+str(method), order_number) self.doInvoice(order_number,total) def submit(self, user, basket, shipping_address, shipping_method, # noqa (too complex (10)) shipping_charge, billing_address, order_total, payment_kwargs=None, order_kwargs=None): """ Submit a basket for order placement. The process runs as follows: * Generate an order number * Freeze the basket so it cannot be modified any more (important when redirecting the user to another site for payment as it prevents the basket being manipulated during the payment process). * Attempt to take payment for the order - If payment is successful, place the order - If a redirect is required (eg PayPal, 3DSecure), redirect - If payment is unsuccessful, show an appropriate error message :basket: The basket to submit. :payment_kwargs: Additional kwargs to pass to the handle_payment method. It normally makes sense to pass form instances (rather than model instances) so that the forms can be re-rendered correctly if payment fails. :order_kwargs: Additional kwargs to pass to the place_order method """ payment_api_wrapper = self.request.COOKIES.get('payment_api_wrapper','false') #basket.is_tax_known = True #print ("BASKET LOADED SUBMIT") #print (basket) #print (basket.is_tax_known) if payment_kwargs is None: payment_kwargs = {} if order_kwargs is None: order_kwargs = {} # Taxes must be known at this point assert basket.is_tax_known, ( "Basket tax must be set before a user can place an order") assert shipping_charge.is_tax_known, ( "Shipping charge tax must be set before a user can place an order") # We generate the order number first as this will be used # in payment requests (ie before the order model has been # created). We also save it in the session for multi-stage # checkouts (eg where we redirect to a 3rd party site and place # the order on a different request). order_number = self.generate_order_number(basket) self.checkout_session.set_order_number(order_number) logger.info("Order #%s: beginning submission process for basket #%d", order_number, basket.id) # Freeze the basket so it cannot be manipulated while the customer is # completing payment on a 3rd party site. Also, store a reference to # the basket in the session so that we know which basket to thaw if we # get an unsuccessful payment response when redirecting to a 3rd party # site. self.freeze_basket(basket) self.checkout_session.set_submitted_basket(basket) # We define a general error message for when an unanticipated payment # error occurs. error_msg = _("A problem occurred while processing payment for this " "order - no payment has been taken.") if settings.BPAY_ALLOWED: error_msg += _(" Please " "use the pay later option if this problem persists") signals.pre_payment.send_robust(sender=self, view=self) try: self.handle_payment(order_number, order_total, **payment_kwargs) except RedirectRequired as e: # Redirect required (eg PayPal, 3DS) logger.info("Order #%s: redirecting to %s", order_number, e.url) return http.HttpResponseRedirect(e.url) except UnableToTakePayment as e: # Something went wrong with payment but in an anticipated way. Eg # their bankcard has expired, wrong card number - that kind of # thing. This type of exception is supposed to set a friendly error # message that makes sense to the customer. msg = six.text_type(e) + '.' if settings.BPAY_ALLOWED: msg += ' You can alternatively use the pay later option.' logger.warning( "Order #%s: unable to take payment (%s) - restoring basket", order_number, msg) self.restore_frozen_basket() # We assume that the details submitted on the payment details view # were invalid (eg expired bankcard). if payment_api_wrapper == 'true': return self.render_payment_message(self.request, error=msg,) else: return self.render_payment_details(self.request, error=msg, **payment_kwargs) except PaymentError as e: # A general payment error - Something went wrong which wasn't # anticipated. Eg, the payment gateway is down (it happens), your # credentials are wrong - that king of thing. # It makes sense to configure the checkout logger to # mail admins on an error as this issue warrants some further # investigation. msg = six.text_type(e) logger.error("Order #%s: payment error (%s)", order_number, msg, exc_info=True) self.restore_frozen_basket() if payment_api_wrapper == 'true': return self.render_payment_message(self.request, error=error_msg,) else: return self.render_preview(self.request, error=error_msg, **payment_kwargs) except Exception as e: # Unhandled exception - hopefully, you will only ever see this in # development... traceback.print_exc() logger.error( "Order #%s: unhandled exception while taking payment (%s)", order_number, e, exc_info=True) self.restore_frozen_basket() if payment_api_wrapper == 'true': return self.render_payment_message(self.request, error=error_msg,) else: return self.render_preview(self.request, error=error_msg, **payment_kwargs) logger.info("Order #%s: payment successful, PRE placing order", order_number) signals.post_payment.send_robust(sender=self, view=self) # If all is ok with payment, try and place order logger.info("Order #%s: payment successful, placing order", order_number) try: return self.handle_order_placement( order_number, user, basket, shipping_address, shipping_method, shipping_charge, billing_address, order_total, **order_kwargs) except UnableToPlaceOrder as e: # It's possible that something will go wrong while trying to # actually place an order. Not a good situation to be in as a # payment transaction may already have taken place, but needs # to be handled gracefully. msg = six.text_type(e) logger.error("Order #%s: unable to place order - %s", order_number, msg, exc_info=True) self.restore_frozen_basket() if payment_api_wrapper == 'true': return self.render_payment_message(self.request, error=msg,) else: return self.render_preview(self.request, error=msg, **payment_kwargs) # ========= # Thank you # ========= class ThankYouView(CoreThankYouView): """ Displays the 'thank you' page which summarises the order just submitted. """ template_name = 'checkout/thank_you.html' context_object_name = 'order' order_id = None return_url = None def get_context_data(self, **kwargs): # Override method so the return_url and order and invoice_id can be # added to the context. ctx = super(ThankYouView, self).get_context_data(**kwargs) order = ctx['order'] invoice_ref = Invoice.objects.get(order_number=order.number).reference ctx['invoice_ref'] = invoice_ref ctx['return_url'] = '{}?order_id={}&invoice_ref={}'.format(self.return_url,order.id,invoice_ref) return ctx def get_object(self): # We allow superusers to force an order thank-you page for testing order = None if self.request.user.is_superuser: if 'order_number' in self.request.GET: order = Order._default_manager.get( number=self.request.GET['order_number']) elif 'order_id' in self.request.GET: order = Order._default_manager.get( id=self.request.GET['order_id']) if not order: if 'checkout_order_id' in self.request.session: order = Order._default_manager.get( pk=self.request.session['checkout_order_id']) self.order_id = self.request.session['checkout_order_id'] else: raise http.Http404(_("No order found")) if'checkout_return_url' in self.request.session: self.return_url = self.request.session['checkout_return_url'] #del self.request.session['checkout_return_url'] return order
import { useNavigation } from '@react-navigation/native' import React, { useEffect } from 'react' import { View, StyleSheet, Dimensions, Pressable } from 'react-native' import { PanGestureHandler } from 'react-native-gesture-handler' import Animated, { runOnJS, useAnimatedGestureHandler, useAnimatedStyle, useSharedValue, withSpring} from 'react-native-reanimated' import Typography from '../componenets/Typography' import { Ionicons } from '@expo/vector-icons'; const list = [ { name: 'Get a meeting link to share', icon:'link', action: '' }, { name: 'Start an instant meeting', icon:'videocam-outline', action: '' }, { name: 'Schedule in Google Calender', icon:'ios-calendar-outline', action: '' }, ] export default function NewMeeting({open}) { const animatedValue = useSharedValue(500) const navigation = useNavigation() const handleNavigation = () => { navigation.goBack() } useEffect(() => { animatedValue.value = 0 }, []) const panhandler = useAnimatedGestureHandler({ onStart:({absoluteY}, ctx) => { ctx.startPostion = animatedValue.value }, onActive: ({translationY}, ctx) => { if (animatedValue.value > -10) { animatedValue.value = translationY + ctx.startPostion } }, onEnd: () => { if (animatedValue.value < 150) { animatedValue.value = 0 } else{ animatedValue.value = 500 runOnJS(handleNavigation)() } }, }) const animatedViewStyle = useAnimatedStyle(() => ({ transform: [{translateY: withSpring(animatedValue.value, {overshootClamping:true})}] })) return ( <View style={styles.container} > <Pressable style={{flex:1}} onPress={handleNavigation} /> <PanGestureHandler onGestureEvent={panhandler} > <Animated.View style={[styles.text, animatedViewStyle]} > <View style={{alignItems:'center', padding:10}} > <View style={{backgroundColor:'gray', width:50, height:10, borderRadius:20}} /> </View> <View style={{padding:20, justifyContent:'space-around', height:200}} > { list.map(item => ( <View key={item.name} style={styles.list} > <Ionicons name={item.icon} size={24} color="black" style={{paddingRight:20}} /> <Typography text = {item.name} bold /> </View> )) } <Pressable onPress={handleNavigation} style={styles.list}> <Ionicons name='close' size={24} color="black" style={{paddingRight:20}} /> <Typography text="Close" bold /> </Pressable> </View> </Animated.View> </PanGestureHandler> </View> ) } const styles = StyleSheet.create({ container:{ backgroundColor: 'rgba(15, 15, 15, 0.5)', width:Dimensions.get('window').width, height:Dimensions.get('window').height, position:'absolute', top:0, overflow:'hidden' }, text:{ backgroundColor:'white', paddingBottom:10, }, list:{ paddingVertical:10, flexDirection:'row', alignItems:'center' } })
from sympy import symbols, Symbol, nan, oo, zoo, I, sinh, sin, acot, pi, atan, \ acos, Rational, sqrt, asin, acot, cot, coth, E, S, tan, tanh, cos, \ cosh, atan2, exp, log, asinh, acoth, atanh, O, cancel, Matrix, re, im def test_sin(): x, y = symbols('x,y') r = Symbol('r', real=True) k = Symbol('k', integer=True) assert sin(nan) == nan assert sin(oo*I) == oo*I assert sin(-oo*I) == -oo*I assert sin(oo).args[0] == oo assert sin(0) == 0 assert sin(asin(x)) == x assert sin(atan(x)) == x / sqrt(1 + x**2) assert sin(acos(x)) == sqrt(1 - x**2) assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x) assert sin(pi*I) == sinh(pi)*I assert sin(-pi*I) == -sinh(pi)*I assert sin(-2*I) == -sinh(2)*I assert sin(pi) == 0 assert sin(-pi) == 0 assert sin(2*pi) == 0 assert sin(-2*pi) == 0 assert sin(-3*10**73*pi) == 0 assert sin(7*10**103*pi) == 0 assert sin(pi/2) == 1 assert sin(-pi/2) == -1 assert sin(5*pi/2) == 1 assert sin(7*pi/2) == -1 assert sin(pi/3) == S.Half*sqrt(3) assert sin(-2*pi/3) == -S.Half*sqrt(3) assert sin(pi/4) == S.Half*sqrt(2) assert sin(-pi/4) == -S.Half*sqrt(2) assert sin(17*pi/4) == S.Half*sqrt(2) assert sin(-3*pi/4) == -S.Half*sqrt(2) assert sin(pi/6) == S.Half assert sin(-pi/6) == -S.Half assert sin(7*pi/6) == -S.Half assert sin(-5*pi/6) == -S.Half assert sin(1*pi/5) == sqrt((5 - sqrt(5)) / 8) assert sin(2*pi/5) == sqrt((5 + sqrt(5)) / 8) assert sin(3*pi/5) == sin(2*pi/5) assert sin(4*pi/5) == sin(1*pi/5) assert sin(6*pi/5) == -sin(1*pi/5) assert sin(8*pi/5) == -sin(2*pi/5) assert sin(-1273*pi/5) == -sin(2*pi/5) assert sin(104*pi/105) == sin(pi/105) assert sin(106*pi/105) == -sin(pi/105) assert sin(-104*pi/105) == -sin(pi/105) assert sin(-106*pi/105) == sin(pi/105) assert sin(x*I) == sinh(x)*I assert sin(k*pi) == 0 assert sin(17*k*pi) == 0 assert sin(k*pi*I) == sinh(k*pi)*I assert sin(r).is_real == True assert isinstance(sin( re(x) - im(y)), sin) == True assert isinstance(sin(-re(x) + im(y)), sin) == False def test_sin_rewrite(): x = Symbol('x') assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2 assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2) assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2) def test_trig_symmetry(): x = Symbol('x') y = Symbol('y') k = Symbol('k', integer=True) assert sin(-x) == -sin(x) assert cos(-x) == cos(x) assert tan(-x) == -tan(x) assert cot(-x) == -cot(x) assert sin(x+pi) == -sin(x) assert sin(x+2*pi) == sin(x) assert sin(x+3*pi) == -sin(x) assert sin(x+4*pi) == sin(x) assert sin(x-5*pi) == -sin(x) assert cos(x+pi) == -cos(x) assert cos(x+2*pi) == cos(x) assert cos(x+3*pi) == -cos(x) assert cos(x+4*pi) == cos(x) assert cos(x-5*pi) == -cos(x) assert tan(x+pi) == tan(x) assert tan(x-3*pi) == tan(x) assert cot(x+pi) == cot(x) assert cot(x-3*pi) == cot(x) assert sin(pi/2-x) == cos(x) assert sin(3*pi/2-x) == -cos(x) assert sin(5*pi/2-x) == cos(x) assert cos(pi/2-x) == sin(x) assert cos(3*pi/2-x) == -sin(x) assert cos(5*pi/2-x) == sin(x) assert tan(pi/2-x) == cot(x) assert tan(3*pi/2-x) == cot(x) assert tan(5*pi/2-x) == cot(x) assert cot(pi/2-x) == tan(x) assert cot(3*pi/2-x) == tan(x) assert cot(5*pi/2-x) == tan(x) assert sin(pi/2+x) == cos(x) assert cos(pi/2+x) == -sin(x) assert tan(pi/2+x) == -cot(x) assert cot(pi/2+x) == -tan(x) def test_cos(): x, y = symbols('x,y') r = Symbol('r', real=True) k = Symbol('k', integer=True) assert cos(nan) == nan assert cos(oo*I) == oo assert cos(-oo*I) == oo assert cos(0) == 1 assert cos(acos(x)) == x assert cos(atan(x)) == 1 / sqrt(1 + x**2) assert cos(asin(x)) == sqrt(1 - x**2) assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2) assert cos(pi*I) == cosh(pi) assert cos(-pi*I) == cosh(pi) assert cos(-2*I) == cosh(2) assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos((-3*10**73+1)*pi/2) == 0 assert cos((7*10**103+1)*pi/2) == 0 assert cos(pi) == -1 assert cos(-pi) == -1 assert cos(2*pi)==1 assert cos(5*pi) == -1 assert cos(8*pi) == 1 assert cos(pi/3) == S.Half assert cos(-2*pi/3) == -S.Half assert cos(pi/4) == S.Half*sqrt(2) assert cos(-pi/4) == S.Half*sqrt(2) assert cos(11*pi/4) == -S.Half*sqrt(2) assert cos(-3*pi/4) == -S.Half*sqrt(2) assert cos(pi/6) == S.Half*sqrt(3) assert cos(-pi/6) == S.Half*sqrt(3) assert cos(7*pi/6) == -S.Half*sqrt(3) assert cos(-5*pi/6) == -S.Half*sqrt(3) assert cos(1*pi/5) == (sqrt(5) + 1)/4 assert cos(2*pi/5) == (sqrt(5) - 1)/4 assert cos(3*pi/5) == -cos(2*pi/5) assert cos(4*pi/5) == -cos(1*pi/5) assert cos(6*pi/5) == -cos(1*pi/5) assert cos(8*pi/5) == cos(2*pi/5) assert cos(-1273*pi/5) == -cos(2*pi/5) assert cos(104*pi/105) == -cos(pi/105) assert cos(106*pi/105) == -cos(pi/105) assert cos(-104*pi/105) == -cos(pi/105) assert cos(-106*pi/105) == -cos(pi/105) assert cos(x*I) == cosh(x) assert cos(k*pi*I) == cosh(k*pi) assert cos(r).is_real == True assert cos(k*pi) == (-1)**k assert cos(2*k*pi) == 1 def test_cos_rewrite(): x = Symbol('x') assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2 assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2) assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2) def test_tan(): x, y = symbols('x,y') r = Symbol('r', real=True) k = Symbol('k', integer=True) assert tan(nan) == nan assert tan(oo*I) == I assert tan(-oo*I) == -I assert tan(0) == 0 assert tan(atan(x)) == x assert tan(asin(x)) == x / sqrt(1 - x**2) assert tan(acos(x)) == sqrt(1 - x**2) / x assert tan(acot(x)) == 1 / x assert tan(pi*I) == tanh(pi)*I assert tan(-pi*I) == -tanh(pi)*I assert tan(-2*I) == -tanh(2)*I assert tan(pi) == 0 assert tan(-pi) == 0 assert tan(2*pi) == 0 assert tan(-2*pi) == 0 assert tan(-3*10**73*pi) == 0 assert tan(pi/2) == zoo assert tan(3*pi/2) == zoo assert tan(pi/3) == sqrt(3) assert tan(-2*pi/3) == sqrt(3) assert tan(pi/4) == S.One assert tan(-pi/4) == -S.One assert tan(17*pi/4) == S.One assert tan(-3*pi/4) == S.One assert tan(pi/6) == 1/sqrt(3) assert tan(-pi/6) == -1/sqrt(3) assert tan(7*pi/6) == 1/sqrt(3) assert tan(-5*pi/6) == 1/sqrt(3) assert tan(x*I) == tanh(x)*I assert tan(k*pi) == 0 assert tan(17*k*pi) == 0 assert tan(k*pi*I) == tanh(k*pi)*I assert tan(r).is_real == True assert tan(10*pi/7) == tan(3*pi/7) assert tan(11*pi/7) == -tan(3*pi/7) assert tan(-11*pi/7) == tan(3*pi/7) def test_tan_rewrite(): x = Symbol('x') neg_exp, pos_exp = exp(-x*I), exp(x*I) assert tan(x).rewrite(exp) == I*(neg_exp-pos_exp)/(neg_exp+pos_exp) assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x) assert tan(x).rewrite(cos) == -cos(x + S.Pi/2)/cos(x) assert tan(x).rewrite(cot) == 1/cot(x) def test_cot(): x, y = symbols('x,y') r = Symbol('r', real=True) k = Symbol('k', integer=True) assert cot(nan) == nan assert cot(oo*I) == -I assert cot(-oo*I) == I assert cot(0) == zoo assert cot(2*pi) == zoo assert cot(acot(x)) == x assert cot(atan(x)) == 1 / x assert cot(asin(x)) == sqrt(1 - x**2) / x assert cot(acos(x)) == x / sqrt(1 - x**2) assert cot(pi*I) == -coth(pi)*I assert cot(-pi*I) == coth(pi)*I assert cot(-2*I) == coth(2)*I assert cot(pi) == cot(2*pi) == cot(3*pi) assert cot(-pi) == cot(-2*pi) == cot(-3*pi) assert cot(pi/2) == 0 assert cot(-pi/2) == 0 assert cot(5*pi/2) == 0 assert cot(7*pi/2) == 0 assert cot(pi/3) == 1/sqrt(3) assert cot(-2*pi/3) == 1/sqrt(3) assert cot(pi/4) == S.One assert cot(-pi/4) == -S.One assert cot(17*pi/4) == S.One assert cot(-3*pi/4) == S.One assert cot(pi/6) == sqrt(3) assert cot(-pi/6) == -sqrt(3) assert cot(7*pi/6) == sqrt(3) assert cot(-5*pi/6) == sqrt(3) assert cot(x*I) == -coth(x)*I assert cot(k*pi*I) == -coth(k*pi)*I assert cot(r).is_real == True assert cot(10*pi/7) == cot(3*pi/7) assert cot(11*pi/7) == -cot(3*pi/7) assert cot(-11*pi/7) == cot(3*pi/7) def test_cot_rewrite(): x = Symbol('x') neg_exp, pos_exp = exp(-x*I), exp(x*I) assert cot(x).rewrite(exp) == I*(pos_exp+neg_exp)/(pos_exp-neg_exp) assert cot(x).rewrite(sin) == 2*sin(2*x)/sin(x)**2 assert cot(x).rewrite(cos) == -cos(x)/cos(x + S.Pi/2) assert cot(x).rewrite(tan) == 1/tan(x) def test_asin(): x = Symbol('x') assert asin(nan) == nan assert asin(oo) == -I*oo assert asin(-oo) == I*oo # Note: asin(-x) = - asin(x) assert asin(0) == 0 assert asin(1) == pi/2 assert asin(-1) == -pi/2 assert asin(sqrt(3)/2) == pi/3 assert asin(-sqrt(3)/2) == -pi/3 assert asin(sqrt(2)/2) == pi/4 assert asin(-sqrt(2)/2) == -pi/4 assert asin(sqrt((5-sqrt(5))/8)) == pi/5 assert asin(-sqrt((5-sqrt(5))/8)) == -pi/5 assert asin(Rational(1,2)) == pi/6 assert asin(-Rational(1,2)) == -pi/6 assert asin((sqrt(2-sqrt(2)))/2) == pi/8 assert asin(-(sqrt(2-sqrt(2)))/2) == -pi/8 assert asin((sqrt(5)-1)/4) == pi/10 assert asin(-(sqrt(5)-1)/4) == -pi/10 assert asin((sqrt(3)-1)/sqrt(2**3)) == pi/12 assert asin(-(sqrt(3)-1)/sqrt(2**3)) == -pi/12 assert asin(x).diff(x) == 1/sqrt(1-x**2) assert asin(0.2).is_real == True assert asin(-2).is_real == False assert asin(-2*I) == -I*asinh(2) def test_asin_series(): x = Symbol('x') assert asin(x).series(x, 0, 9) == \ x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9) t5 = asin(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112 def test_asin_rewrite(): x = Symbol('x') assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2)) assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2))) assert asin(x).rewrite(acos) == S.Pi/2 - acos(x) def test_acos(): x = Symbol('x') r = Symbol('r', real=True) assert acos(nan) == nan assert acos(oo) == I*oo assert acos(-oo) == -I*oo # Note: acos(-x) = pi - acos(x) assert acos(0) == pi/2 assert acos(Rational(1,2)) == pi/3 assert acos(-Rational(1,2)) == (2*pi)/3 assert acos(1) == 0 assert acos(-1) == pi assert acos(sqrt(2)/2) == pi/4 assert acos(-sqrt(2)/2) == (3*pi)/4 assert acos(x).diff(x) == -1/sqrt(1-x**2) assert acos(0.2).is_real == True assert acos(-2).is_real == False def test_acos_series(): x = Symbol('x') assert acos(x).series(x, 0, 8) == \ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8) assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8) t5 = acos(x).taylor_term(5, x) assert t5 == -3*x**5/40 assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112 def test_acos_rewrite(): x = Symbol('x') assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2)) assert acos(0).rewrite(atan) == S.Pi/2 assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log) assert acos(x).rewrite(asin) == S.Pi/2 - asin(x) def test_atan(): x = Symbol('x') r = Symbol('r', real=True) assert atan(nan) == nan assert atan(oo) == pi/2 assert atan(-oo) == -pi/2 assert atan(0) == 0 assert atan(1) == pi/4 assert atan(sqrt(3)) == pi/3 assert atan(oo) == pi/2 assert atan(x).diff(x) == 1/(1+x**2) assert atan(r).is_real == True assert atan(-2*I) == -I*atanh(2) def test_atan_rewrite(): x = Symbol('x') assert atan(x).rewrite(log) == I*log((1 - I*x)/(1 + I*x))/2 def test_atan2(): assert atan2(0, 0) == S.NaN assert atan2(0, 1) == 0 assert atan2(1, 0) == pi/2 assert atan2(1, -1) == 3*pi/4 assert atan2(-1, 1) == -pi/4 assert atan2(0, -1) == pi def test_acot(): x = Symbol('x') r = Symbol('r', real=True) assert acot(nan) == nan assert acot(-oo) == 0 assert acot(oo) == 0 assert acot(1) == pi/4 assert acot(0) == pi/2 assert acot(sqrt(3)/3) == pi/3 assert acot(1/sqrt(3)) == pi/3 assert acot(-1/sqrt(3)) == -pi/3 assert acot(x).diff(x) == -1/(1+x**2) assert acot(r).is_real == True assert acot(I*pi) == -I*acoth(pi) assert acot(-2*I) == I*acoth(2) def test_acot_rewrite(): x = Symbol('x') assert acot(x).rewrite(log) == I*log((x - I)/(x + I))/2 def test_attributes(): x = Symbol('x') assert sin(x).args == (x,) def test_sincos_rewrite(): x = Symbol("x") y = Symbol("y") assert sin(pi/2-x) == cos(x) assert sin(pi-x) == sin(x) assert cos(pi/2-x) == sin(x) assert cos(pi-x) == -cos(x) def _check_even_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> f(x) arg : -x """ return func(arg).args[0] == -arg def _check_odd_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> -f(x) arg : -x """ return func(arg).func.is_Mul def _check_no_rewrite(func, arg): """Checks that the expr is not rewritten""" return func(arg).args[0] == arg def test_evenodd_rewrite(): x, y = symbols('x,y') a = cos(2) #negative b = sin(1) #positive even = [cos] odd = [sin, tan, cot, asin, atan, acot] with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x-y] for func in even: for expr in with_minus: assert _check_even_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func(x-y) == func(y-x) #it doesn't matter which form is canonical for func in odd: for expr in with_minus: assert _check_odd_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func(x-y) == -func(y-x) #it doesn't matter which form is canonical def test_issue1448(): x = Symbol('x') assert cot(x).inverse() == acot assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2) assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2) assert tan(x).rewrite(cot) == 1/cot(x) assert cot(x).fdiff() == -1 - cot(x)**2 def test_as_leading_term_issue2173(): x = Symbol('x') assert sin(x).as_leading_term(x) == x assert cos(x).as_leading_term(x) == 1 assert tan(x).as_leading_term(x) == x assert cot(x).as_leading_term(x) == 1/x assert asin(x).as_leading_term(x) == x assert acos(x).as_leading_term(x) == x assert atan(x).as_leading_term(x) == x assert acot(x).as_leading_term(x) == x def test_atan2_expansion(): x, y = symbols("x,y") assert cancel(atan2(x+1,x**2).diff(x) - atan((x+1)/x**2).diff(x)) == 0 assert cancel(atan(x/y).series(x, 0, 5) - atan2(x, y).series(x, 0, 5) \ + atan2(0, y) - atan(0)) == O(x**5) assert cancel(atan(x/y).series(y, 1, 4) - atan2(x, y).series(y, 1, 4) \ + atan2(x, 1) - atan(x)) == O(y**4) assert cancel(atan((x+y)/y).series(y, 1, 3) - atan2(x+y, y).series(y, 1, 3) \ + atan2(1+x, 1) - atan(1+x)) == O(y**3) assert Matrix([atan2(x, y)]).jacobian([x, y]) \ == Matrix([[y/(x**2+y**2), -x/(x**2+y**2)]]) def test_aseries(): x = Symbol('x') def t(n, v, d, e): assert abs(n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e t(atan, 0.1, '+', 1e-5) t(atan, -0.1, '-', 1e-5) t(acot, 0.1, '+', 1e-5) t(acot, -0.1, '-', 1e-5) def test_issueXXX(): i = Symbol('i', integer=True) e = Symbol('e', even=True) o = Symbol('o', odd=True) x = Symbol('x') # unknown parity for variable assert cos(4*i*pi) == 1 assert sin(4*i*pi) == 0 assert tan(4*i*pi) == 0 assert cot(4*i*pi) == zoo assert cos(3*i*pi) == cos(pi*i) # +/-1 assert sin(3*i*pi) == 0 assert tan(3*i*pi) == 0 assert cot(3*i*pi) == zoo assert cos(4.0*i*pi) == 1 assert sin(4.0*i*pi) == 0 assert tan(4.0*i*pi) == 0 assert cot(4.0*i*pi) == zoo assert cos(3.0*i*pi) == cos(pi*i) # +/-1 assert sin(3.0*i*pi) == 0 assert tan(3.0*i*pi) == 0 assert cot(3.0*i*pi) == zoo assert cos(4.5*i*pi) == cos(0.5*pi*i) assert sin(4.5*i*pi) == sin(0.5*pi*i) assert tan(4.5*i*pi) == tan(0.5*pi*i) assert cot(4.5*i*pi) == cot(0.5*pi*i) # parity of variable is known assert cos(4*e*pi) == 1 assert sin(4*e*pi) == 0 assert tan(4*e*pi) == 0 assert cot(4*e*pi) == zoo assert cos(3*e*pi) == 1 assert sin(3*e*pi) == 0 assert tan(3*e*pi) == 0 assert cot(3*e*pi) == zoo assert cos(4.0*e*pi) == 1 assert sin(4.0*e*pi) == 0 assert tan(4.0*e*pi) == 0 assert cot(4.0*e*pi) == zoo assert cos(3.0*e*pi) == 1 assert sin(3.0*e*pi) == 0 assert tan(3.0*e*pi) == 0 assert cot(3.0*e*pi) == zoo assert cos(4.5*e*pi) == cos(0.5*pi*e) assert sin(4.5*e*pi) == sin(0.5*pi*e) assert tan(4.5*e*pi) == tan(0.5*pi*e) assert cot(4.5*e*pi) == cot(0.5*pi*e) assert cos(4*o*pi) == 1 assert sin(4*o*pi) == 0 assert tan(4*o*pi) == 0 assert cot(4*o*pi) == zoo assert cos(3*o*pi) == -1 assert sin(3*o*pi) == 0 assert tan(3*o*pi) == 0 assert cot(3*o*pi) == zoo assert cos(4.0*o*pi) == 1 assert sin(4.0*o*pi) == 0 assert tan(4.0*o*pi) == 0 assert cot(4.0*o*pi) == zoo assert cos(3.0*o*pi) == -1 assert sin(3.0*o*pi) == 0 assert tan(3.0*o*pi) == 0 assert cot(3.0*o*pi) == zoo assert cos(4.5*o*pi) == cos(0.5*pi*o) assert sin(4.5*o*pi) == sin(0.5*pi*o) assert tan(4.5*o*pi) == tan(0.5*pi*o) assert cot(4.5*o*pi) == cot(0.5*pi*o) # x could be imaginary assert cos(4*x*pi) == cos(4*pi*x) assert sin(4*x*pi) == sin(4*pi*x) assert tan(4*x*pi) == tan(4*pi*x) assert cot(4*x*pi) == cot(4*pi*x) assert cos(3*x*pi) == cos(3*pi*x) assert sin(3*x*pi) == sin(3*pi*x) assert tan(3*x*pi) == tan(3*pi*x) assert cot(3*x*pi) == cot(3*pi*x) assert cos(4.0*x*pi) == cos(4.0*pi*x) assert sin(4.0*x*pi) == sin(4.0*pi*x) assert tan(4.0*x*pi) == tan(4.0*pi*x) assert cot(4.0*x*pi) == cot(4.0*pi*x) assert cos(3.0*x*pi) == cos(3.0*pi*x) assert sin(3.0*x*pi) == sin(3.0*pi*x) assert tan(3.0*x*pi) == tan(3.0*pi*x) assert cot(3.0*x*pi) == cot(3.0*pi*x) assert cos(4.5*x*pi) == cos(4.5*pi*x) assert sin(4.5*x*pi) == sin(4.5*pi*x) assert tan(4.5*x*pi) == tan(4.5*pi*x) assert cot(4.5*x*pi) == cot(4.5*pi*x)
// REACT // OPEN LAYERS import Feature from "ol/Feature"; import * as ol from "ol"; import { Image as ImageLayer } from "ol/layer.js"; import ImageWMS from "ol/source/ImageWMS.js"; import { GeoJSON } from "ol/format.js"; import { Tile,OSM, TileArcGISRest, TileImage, Vector as VectorSource } from "ol/source.js"; import TileLayer from "ol/layer/Tile.js"; import TileGrid from "ol/tilegrid/TileGrid.js"; import Point from "ol/geom/Point"; import VectorLayer from "ol/layer/Vector"; import Vector from "ol/source/Vector"; import { getTopLeft } from "ol/extent.js"; import { easeOut } from "ol/easing"; import { Fill, Stroke, Style, Circle as CircleStyle, Text as TextStyle } from "ol/style"; import XYZ from "ol/source/XYZ.js"; import { unByKey } from "ol/Observable.js"; import WKT from "ol/format/WKT.js"; import { transform } from "ol/proj.js"; import Projection from "ol/proj/Projection.js"; import proj4 from "proj4"; import { register } from "ol/proj/proj4"; import { fromLonLat } from "ol/proj"; import { getVectorContext } from "ol/render"; import {stableSort} from 'ol/array'; import {DOM_ROW_HEIGHT} from "../utilities/utilities"; //OTHER import shortid from "shortid"; export const OL_VIEW_PAN = { UP:'up',DOWN:'down',LEFT:'left',RIGHT:'right'}; export const OL_SRC_PARAM_TYPE = { LAYERS:'layers'}; export const OL_SOURCE_TYPE= {NONE:'none',IMAGE:'image',VECTOR:'vector',WMS:'wms'}; var MV_OL_PAN_DETLA_X_METER= -1; var MV_OL_PAN_DETLA_Y_METER= -1; var MV_LAYER_NEXT_Z_INDEX=1; const OL_PAN_DETLA_PIXEL=40; const PIXEL_VALUE=150; const START_PIXEL_POS=[PIXEL_VALUE,PIXEL_VALUE]; const END_PIXEL_POS=[PIXEL_VALUE+OL_PAN_DETLA_PIXEL,PIXEL_VALUE+OL_PAN_DETLA_PIXEL]; const OL_ZINDEX={TOP_PRE_LAYER:9999,BASE_LAYER:0}; // URL FRIENDLY STRING ID export function getUID() { return shortid.generate(); } /** * To add the open layer object into the map. * Note: the map object of openlayers has to exist. * @param {{displayName,visible,olLayer,olSource}} olLayerObj */ export function olAddLayerToView(olLayerObj,baseMapOrPreLayer=false, sourceType = OL_SOURCE_TYPE.NONE, zIndex=MV_LAYER_NEXT_Z_INDEX) { if(window.map !== undefined && olLayerObj !==undefined && olLayerObj.olLayer!== undefined ) { let olLayer=olLayerObj.olLayer; let olSource=olLayerObj.olSource; if(olSource === null || olSource ===undefined){ olSource=olLayer.getSource(); } window.map.addLayer(olLayer); olLayer.setZIndex(zIndex); if(zIndex === MV_LAYER_NEXT_Z_INDEX ) { MV_LAYER_NEXT_Z_INDEX++; } if(olSource!==undefined) { //register the tile loading event olTileSource_RegEvent(olLayerObj.olSource); } /* { * displayName:name, * baseOrTopPreLayer: true/false, //the layer for base map or top presentation layer * visible: true/false, * zIndex: zIndexValue, * orig_zIndex: initial zIndex value of a layer * olLayer: layer of openlayers, * height: dom_Row_height, //default of DOM_ROW_HEIGHT * } * */ let dis_Layer= { displayName:olLayerObj.displayName, baseOrTopPreLayer:baseMapOrPreLayer, sourceType: sourceType, visible: olLayerObj.visible, zIndex: zIndex, orig_zIndex: zIndex, olLayer: olLayer } window.LayersInView.add(dis_Layer); //fire the layer added event: window.emitter.emit("refreshOLDisplayList",dis_Layer); } } /** * To remove a openlayer layer from map * @param {{olLayer,olSource}} olLayerObj */ export function olRemoveLayerFromView(olLayerObj) { if(window.map !== undefined && olLayerObj !==undefined && olLayerObj.olLayer!== undefined ) { let olLayer=olLayerObj.olLayer; let olSource=(olLayerObj.olSource !==undefined)? olLayerObj.olSource:olLayer.getSource(); window.map.removeLayer(olLayer); if(olSource!==undefined) { //clean the cache tiles olSource.clear(); } //remove it from display list: window.LayersInView.remove({olLayer: olLayer}); //fire the layer added event: window.emitter.emit("refreshOLDisplayList",olLayerObj); } } //return ol view export function olGetViewFromMap() { if(window.map !== undefined) { return window.map.getView(); } return undefined; } //render the map export function olMapViewUpdate(){ window.map.render(); } export function olViewAnimate(newPos,zoomLevel,dValue=2000) { let view=olGetViewFromMap(); if(view !== undefined) { view.animate({ center: newPos, zoom: zoomLevel!==undefined? zoomLevel:"", duration: dValue}); } } //get the zoom level export function olViewZoom() { let view=olGetViewFromMap(); if(view !== undefined) { return view.getZoom(); } return -1; } function updatePanDetla(){ let start = window.map.getCoordinateFromPixel(START_PIXEL_POS); let endPos = window.map.getCoordinateFromPixel(END_PIXEL_POS); MV_OL_PAN_DETLA_X_METER=endPos[0]-start[0]; MV_OL_PAN_DETLA_Y_METER=endPos[1]-start[1]; } //set the zoom level export function olViewZoomTo(zoomLevel) { let view=olGetViewFromMap(); if(view !== undefined) { view.setZoom(zoomLevel); updatePanDetla(); } } export function olViewCenter() { let view=olGetViewFromMap(); if(view !== undefined) { return view.getCenter(); } return undefined; } //pan view to new location export function olPanView(panDir) { let center=olViewCenter(); if(MV_OL_PAN_DETLA_X_METER<0) { updatePanDetla(); } switch(panDir) { case OL_VIEW_PAN.UP: center[1] -=MV_OL_PAN_DETLA_Y_METER; break; case OL_VIEW_PAN.DOWN: center[1] +=MV_OL_PAN_DETLA_Y_METER; break; case OL_VIEW_PAN.LEFT: center[0] -=MV_OL_PAN_DETLA_X_METER; break; case OL_VIEW_PAN.RIGHT: center[0] +=MV_OL_PAN_DETLA_X_METER; break; default: return; } olViewAnimate(center,olViewZoom(),200); } /** * To regist the events of loading tiles,tile loaded and loading errors. * Note: the event will send the current ol tile source object back to handler. * @param {TileSource} olTileSource */ export function olTileSource_RegEvent(olTileSource) { if(olTileSource!== undefined && (olTileSource instanceof Tile)) { olTileSource.on('tileloadstart', function() { window.emitter.emit('tileloadstart',olTileSource); }); olTileSource.on('tileloadend', function() { window.emitter.emit('tileloadend',olTileSource); }); olTileSource.on('tileloaderror', function() { window.emitter.emit('tileloaderror',olTileSource); }); return true; } return false; } /** * The function is to add postrender event handler to map. * @param {callbackfunction} functionRef */ export function ol_MapPostRender_CB(functionRef) { if(window.map !== undefined) { window.map.on("postrender", functionRef); } } /** * The function is to add key down event handler to openlayer viewport. * * @param {callbackfunction} functionRef */ export function ol_SetKeyDown_CB(functionRef) { if(window.map !== undefined) { window.map.getViewport().addEventListener("keydown", functionRef,true); } } /** * Get the source associating the layer. */ export function olGetSource(olLayer) { let olSource=undefined; if(olLayer !==null && olLayer!== undefined) { olSource = olLayer.getSource(); } return olSource; } /** * To update the parameter of the source object. * @param {Object} source //the source object of openlayers * @param {String} paramType //the type of parameter * @param {objecct} value //the new value of specified param */ export function olUpdateSourceParams(olSource,paramType,value) { let result=false; if(olSource!==undefined) { switch(paramType){ case OL_SRC_PARAM_TYPE.LAYERS: olSource.updateParams({'LAYERS':value}); result=true; break; default: break; } } return result; } /** * Return the attribute value based on the specified name of layer of Openlayers. * @param {oOject} layer // the layer object of openlayers * @param {String} attrName //attribute name of layer object */ export function olGetLayerAttrib(layer,attrName) { return layer.get(attrName); } /** * sw * @param {Object} olLayer // the layer object of openlayers * @param {int} newIndex // the zIndex value of olLayer */ export function olSetZIndex(olLayer,newIndex) { if(olLayer!== undefined && olLayer!==null) { olLayer.setZIndex(newIndex); olMapViewUpdate(); } }
/*eslint max-nested-callbacks: [2, 4]*/ /*global clearInterval: false, clearTimeout: false, document: false, event: false, frames: false, history: false, Image: false, location: false, name: false, navigator: false, Option: false, parent: false, screen: false, setInterval: false, setTimeout: false, window: false, XMLHttpRequest: false, FormData: false */ /*global removeColumn, sequenceColumn, colorColumn, priorityColumn, valueColumn, travelerLinkColumn, aliasColumn, addedByColumn, addedOnColumn, ownerColumn, deviceColumn, tagsColumn, sharedWithColumn, sharedGroupColumn, sDomNoTools*/ /*global moment: false, ajax401: false, updateAjaxURL: false, disableAjaxCache: false, prefix: false, Holder*/ function cleanTagForm() { $('#new-tag') .closest('li') .remove(); $('#add-tag').prop('disabled', false); } function setStatus(s) { $.ajax({ url: './status', type: 'PUT', contentType: 'application/json', data: JSON.stringify({ status: s, }), }) .done(function() { // TODO: avoid refresh the whole page document.location.href = window.location.pathname; }) .fail(function(jqXHR) { if (jqXHR.status !== 401) { $('#message').append( '<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>Cannot change the status: ' + jqXHR.responseText + '</div>' ); $(window).scrollTop($('#message div:last-child').offset().top - 40); } }) .always(); } function changeEvents() { $('input.config, select.config').change(function() { $(this).addClass('input-changed'); $(this).css({ border: '1px solid #c09853', 'box-shadow': '0 0 5px rgba(192, 152, 83, 1)', }); if ($('#save').prop('disabled')) { $('#save').prop('disabled', false); } }); } function tagEvents() { $('#add-tag').click(function(e) { e.preventDefault(); // add an input and a button add $('#add-tag').prop('disabled', true); $('#tags').append( '<li><form class="form-inline"><input id="new-tag" type="text"> <button id="confirm" class="btn btn-primary">Confirm</button> <button id="cancel" class="btn">Cancel</button></form></li>' ); $('#cancel').click(function(cancelE) { cancelE.preventDefault(); cleanTagForm(); }); $('#confirm').click(function(confirmE) { var newTag = $('#new-tag') .val() .trim(); confirmE.preventDefault(); if (newTag) { $.ajax({ url: './tags/', type: 'POST', contentType: 'application/json', data: JSON.stringify({ newtag: newTag, }), }) .done(function() { $('#tags').append( '<li><span class="tag">' + newTag + '</span> <button class="btn btn-small btn-warning remove-tag"><i class="fa fa-trash-o fa-lg"></i></button></li>' ); }) .fail(function(jqXHR) { if (jqXHR.status !== 401) { $('#message').append( '<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>Cannot add the tag</div>' ); $(window).scrollTop( $('#message div:last-child').offset().top - 40 ); } }) .always(function() { cleanTagForm(); }); } }); }); $('#tags').on('click', '.remove-tag', function(e) { e.preventDefault(); var $that = $(this); $.ajax({ url: './tags/' + encodeURIComponent($that.siblings('span.tag').text()), type: 'DELETE', }) .done(function() { $that.closest('li').remove(); }) .fail(function(jqXHR) { if (jqXHR.status !== 401) { $('#message').append( '<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>Cannot remove the tag</div>' ); $(window).scrollTop($('#message div:last-child').offset().top - 40); } }); }); } function editEvents(initValue) { $('span.editable').editable( function(value) { var that = this; if (value === initValue[that.id]) { return value; } var data = {}; data[that.id] = value; $.ajax({ url: './config', type: 'PUT', contentType: 'application/json', data: JSON.stringify(data), success: function() { initValue[that.id] = value; }, error: function(jqXHR) { $(that).text(initValue[that.id]); $('#message').append( '<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>Cannot update the binder config : ' + jqXHR.responseText + '</div>' ); $(window).scrollTop($('#message div:last-child').offset().top - 40); }, }); return value; }, { type: 'textarea', rows: 1, cols: 120, style: 'display: inline', cancel: 'Cancel', submit: 'Update', indicator: 'Updating...', tooltip: 'Click to edit...', } ); $('button.editable').click(function() { $(this) .siblings('span.editable') .first() .click(); }); } function removeWork(id, cb) { $.ajax({ url: './works/' + id, type: 'DELETE', }) .done(function() { $('#' + id).wrap('<del></del>'); $('#' + id).addClass('text-success'); cb(null); }) .fail(function(jqXHR, status, error) { $('#' + id).append(' : ' + jqXHR.responseText); $('#' + id).addClass('text-error'); cb(error); }); } function updateWorks(updates, cb) { $.ajax({ url: './works/', type: 'PUT', contentType: 'application/json', data: JSON.stringify(updates), }) .done(function(data, status, jqXHR) { var timestamp = jqXHR.getResponseHeader('Date'); timestamp = livespan(timestamp); var updateMsg = '<div class="alert alert-success"><button class="close" data-dismiss="alert">x</button>Works updated ' + timestamp + '</div>'; $('#message').append(updateMsg); if (jqXHR.status !== 204) { cb(null, data); } }) .fail(function(jqXHR, status, error) { $('#message').append( '<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>Cannot update the works: ' + jqXHR.responseText + '</div>' ); $(window).scrollTop($('#message div:last-child').offset().top - 40); cb(error); }); } function getUpdate(element, updates, table) { var td = element.parentNode; var workData = table.fnGetData(td.parentNode); var workID = workData._id; var aoColumns = table.fnSettings().aoColumns; var columnDef = aoColumns[table.fnGetPosition(td)[2]]; var property = columnDef.mData; var oldValue = table.fnGetData(td); var newValue; if (columnDef.sType === 'numeric') { newValue = Number($(element).val()); } else { newValue = $(element).val(); } if (newValue !== oldValue) { if (!updates[workID]) { updates[workID] = {}; } updates[workID][property] = newValue; } } $(function() { updateAjaxURL(prefix); ajax401(prefix); disableAjaxCache(); $.livestamp.interval(30 * 1000); $('#save').prop('disabled', true); $('span.time').each(function() { $(this).text( moment($(this).text()).format('dddd, MMMM Do YYYY, h:mm:ss a') ); }); var initValue = { title: $('#title').text(), description: $('#description').text(), }; var workAoColumns = [ removeColumn, sequenceColumn, priorityColumn, valueColumn, colorColumn, travelerLinkColumn, aliasColumn, addedByColumn, addedOnColumn, ownerColumn, deviceColumn, tagsColumn, sharedWithColumn, sharedGroupColumn, ]; var works; var worksTable = $('#work-table').dataTable({ sAjaxSource: './works/json', sAjaxDataProp: 'works', bAutoWidth: false, bPaginate: false, iDisplayLength: 10, aLengthMenu: [[10, -1], [10, 'All']], oLanguage: { sLoadingRecords: 'Please wait - loading data from the server ...', }, bDeferRender: true, aoColumns: workAoColumns, fnInitComplete: function() { Holder.run({ images: 'img.user', }); works = worksTable.fnGetData(); changeEvents(); }, aaSorting: [[1, 'asc'], [2, 'asc']], sDom: sDomNoTools, }); $('#work-table').on('click', 'a.remove', function() { $('#modalLabel').html('Remove the following work from this binder?'); $('#modal .modal-body').empty(); var row = $(this).closest('tr')[0]; var data = worksTable.fnGetData(row); $('#modal .modal-body').append( '<div class="target" id="' + data._id + '"><b>' + data.alias + '</b>, added ' + moment(data.addedOn).fromNow() + '</div>' ); $('#modal .modal-footer').html( '<button id="remove" class="btn btn-primary">Confirm</button><button id="return" data-dismiss="modal" aria-hidden="true" class="btn">Return</button>' ); $('#modal').modal('show'); $('#remove').click(function() { $('#remove').prop('disabled', true); removeWork(data._id, function(err) { if (!err) { worksTable.fnDeleteRow(row); } }); }); }); $('#active').click(function() { setStatus(1); }); $('#complete').click(function() { setStatus(2); }); $('#more').click(function() { setStatus(1); }); $('#save').click(function() { $('#save').prop('disabled', true); var updates = {}; $('input.input-changed, select.input-changed').each(function( index, element ) { getUpdate(element, updates, worksTable); }); if (!$.isEmptyObject(updates)) { updateWorks(updates, function(err, data) { if (!err) { data.forEach(function(newW) { works.forEach(function(w) { if (newW._id === w._id) { w.sequence = newW.sequence; w.priority = newW.priority; w.value = newW.value; w.color = newW.color; } }); }); worksTable.fnClearTable(); worksTable.fnAddData(works); changeEvents(); } }); } }); editEvents(initValue); tagEvents(); });
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AnttechAiCvOcrBusinesslicenseIdentifyModel import AnttechAiCvOcrBusinesslicenseIdentifyModel class AnttechAiCvOcrBusinesslicenseIdentifyRequest(object): def __init__(self, biz_model=None): self._biz_model = biz_model self._biz_content = None self._version = "1.0" self._terminal_type = None self._terminal_info = None self._prod_code = None self._notify_url = None self._return_url = None self._udf_params = None self._need_encrypt = False @property def biz_model(self): return self._biz_model @biz_model.setter def biz_model(self, value): self._biz_model = value @property def biz_content(self): return self._biz_content @biz_content.setter def biz_content(self, value): if isinstance(value, AnttechAiCvOcrBusinesslicenseIdentifyModel): self._biz_content = value else: self._biz_content = AnttechAiCvOcrBusinesslicenseIdentifyModel.from_alipay_dict(value) @property def version(self): return self._version @version.setter def version(self, value): self._version = value @property def terminal_type(self): return self._terminal_type @terminal_type.setter def terminal_type(self, value): self._terminal_type = value @property def terminal_info(self): return self._terminal_info @terminal_info.setter def terminal_info(self, value): self._terminal_info = value @property def prod_code(self): return self._prod_code @prod_code.setter def prod_code(self, value): self._prod_code = value @property def notify_url(self): return self._notify_url @notify_url.setter def notify_url(self, value): self._notify_url = value @property def return_url(self): return self._return_url @return_url.setter def return_url(self, value): self._return_url = value @property def udf_params(self): return self._udf_params @udf_params.setter def udf_params(self, value): if not isinstance(value, dict): return self._udf_params = value @property def need_encrypt(self): return self._need_encrypt @need_encrypt.setter def need_encrypt(self, value): self._need_encrypt = value def add_other_text_param(self, key, value): if not self.udf_params: self.udf_params = dict() self.udf_params[key] = value def get_params(self): params = dict() params[P_METHOD] = 'anttech.ai.cv.ocr.businesslicense.identify' params[P_VERSION] = self.version if self.biz_model: params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':')) if self.biz_content: if hasattr(self.biz_content, 'to_alipay_dict'): params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':')) else: params['biz_content'] = self.biz_content if self.terminal_type: params['terminal_type'] = self.terminal_type if self.terminal_info: params['terminal_info'] = self.terminal_info if self.prod_code: params['prod_code'] = self.prod_code if self.notify_url: params['notify_url'] = self.notify_url if self.return_url: params['return_url'] = self.return_url if self.udf_params: params.update(self.udf_params) return params def get_multipart_params(self): multipart_params = dict() return multipart_params
!function(t){"use strict";function i(i){this.$pins=i,this.tasks=[],this.timerId=null,this.deferred=new t.Deferred}function n(t){this.img=t,this.initialWidth=t.width,this.initialHeight=t.height,this.img.isError=!1,this.img.onerror=function(){this.isError=!0}}var e=e||{now:Date.now||function(){return(new Date).getTime()},throttle:function(t,i,n){var s,r,o,a=null,h=0;n||(n={});var l=function(){h=!1===n.leading?0:e.now(),a=null,o=t.apply(s,r),a||(s=r=null)};return function(){var c=e.now();h||!1!==n.leading||(h=c);var u=i-(c-h);return s=this,r=arguments,u<=0||u>i?(a&&(clearTimeout(a),a=null),h=c,o=t.apply(s,r),a||(s=r=null)):a||!1===n.trailing||(a=setTimeout(l,u)),o}},debounce:function(t,i,n){var s,r,o,a,h,l=function(){var c=e.now()-a;c<i&&c>=0?s=setTimeout(l,i-c):(s=null,n||(h=t.apply(o,r),s||(o=r=null)))};return function(){o=this,r=arguments,a=e.now();var c=n&&!s;return s||(s=setTimeout(l,i)),c&&(h=t.apply(o,r),o=r=null),h}}},s=function(i,n){this.$element=t(i),this.options=t.extend({},s.DEFAULTS,n),this.id=Math.random().toString().slice(2),this.$fakePin=null,this.$container=null,this.$pins=null,this.pinWidth=null,this.imgWidth=null,this.lefts=[],this.tops=[],this.init().calculateWidth().calculatePosition().sail(),t(window).on("resize.mystist.waterfall"+this.id,e.debounce(t.proxy(function(){t(window).off("scroll.mystist.waterfall"+this.id),this.calculateWidth().calculatePosition().ship(r.getLoadedPins.call(this))},this),777))};s.VERSION="0.2.8",s.DEFAULTS={},s.prototype.init=function(){return this.initPins().initAttributes(),this},s.prototype.initPins=function(){var i=this.$element.children().length>0?this.$element.children().remove():t(this.$element.data("bootstrap-waterfall-template"));return this.$pins=r.decorate(i),this},s.prototype.initAttributes=function(){return this.$fakePin=this.$pins.first().clone(),this.$container=t("<div />").css("position","relative"),this.$element.html(this.$container),this},s.prototype.calculateWidth=function(){var t=this.$fakePin.clone();return this.$container.append(t.css("opacity",0)),this.pinWidth=t.outerWidth(!0),this.imgWidth=t.find("img:eq(0)").css("width","100%").width(),t.remove(),this},s.prototype.calculatePosition=function(){for(var t=parseInt(this.$container.width()/this.pinWidth,10),i=[],n=[],e=0;e<t;e++)i.push(e*this.pinWidth),n.push(0);return this.lefts=i,this.tops=n,this},s.prototype.sail=function(){var n=r.getToLoadPins.call(this);return new i(n).load().run().deferred.done(t.proxy(function(){this.ship(n)},this)),this},s.prototype.ship=function(i){return this.render(i).updateHeight(),t(window).on("scroll.mystist.waterfall"+this.id,e.throttle(t.proxy(function(){if(r.isWantMore.call(this)){t(window).off("scroll.mystist.waterfall"+this.id),this.sail();var i=r.getRemainingPins.call(this).length;i<=r.getSteps.call(this)&&i>0&&this.$element.trigger("finishing.mystist.waterfall")}},this),500)),this},s.prototype.render=function(i){var n=this;return i.each(function(){n.placePin(t(this))}),this},s.prototype.placePin=function(t){var i=o.indexOf(this.tops,Math.min.apply(null,this.tops)),n=r.getPosition.call(this,i);return t.css({position:"absolute",left:n.left,top:n.top}),t.data("bootstrap-waterfall-pin")&&r.setImageHeight.call(this,t),t.data("bootstrap-waterfall-src")&&(r.makeImageAvailable.call(this,t),t.removeData("bootstrap-waterfall-src")),this.$container.append(t),r.updatePosition.call(this,i,t),this},s.prototype.updateHeight=function(){var t=o.indexOf(this.tops,Math.max.apply(null,this.tops));return this.$container.height(this.tops[t]),this},s.prototype.destroy=function(){return t(window).off("scroll.mystist.waterfall"+this.id),t(window).off("resize.mystist.waterfall"+this.id),this.$element.empty().removeData("mystist.waterfall"),this},s.prototype.addPins=function(i){this.$pins=this.$pins.add(r.decorate(i)),t(window).trigger("scroll.mystist.waterfall"+this.id)};var r={decorate:function(i){return i.map(function(){var i=t(this).find("img:eq(0)");if(i.length>0)return t(this).data("bootstrap-waterfall-src",i.attr("src")),i.attr("src","data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),this})},getRemainingPins:function(){return this.$pins.map(function(){if(t(this).find("img").length>0&&t(this).data("bootstrap-waterfall-src"))return t(this)})},getSteps:function(){return 3*parseInt(this.$container.width()/this.pinWidth,10)},getToLoadPins:function(){return r.getRemainingPins.call(this).slice(0,r.getSteps.call(this))},getLoadedPins:function(){return this.$pins.map(function(){if(t(this).find("img").length>0&&!t(this).data("bootstrap-waterfall-src"))return t(this)})},isWantMore:function(){return t(window).scrollTop()+t(window).height()>o.getDocHeight()-377},getPosition:function(t){return{left:this.lefts[t],top:this.tops[t]}},setImageHeight:function(t){var i=t.data("bootstrap-waterfall-pin"),n=this.imgWidth*i.img.height/i.img.width;t.find("img:eq(0)").css({height:n,width:"auto"})},makeImageAvailable:function(t){t.find("img:eq(0)").attr("src",t.data("bootstrap-waterfall-src"))},updatePosition:function(t,i){this.tops[t]+=i.outerHeight(!0)}};i.prototype.load=function(){var i=this;return this.$pins.each(function(){var e=new Image;e.src=t(this).data("bootstrap-waterfall-src");var s=new n(e);i.tasks.push(s),t(this).data("bootstrap-waterfall-pin",s)}),this},i.prototype.run=function(){return this.timerId=setInterval(t.proxy(function(){this.isDone()?this.stop():this.check()},this),40),this},i.prototype.isDone=function(){return 0===this.tasks.length},i.prototype.stop=function(){clearInterval(this.timerId),this.timerId=null,this.deferred.resolve()},i.prototype.check=function(){for(var t=0;t<this.tasks.length;t++){this.tasks[t].isLoaded()&&this.tasks.splice(t--,1)}},n.prototype.isLoaded=function(){return!!this.img.isError||this.img.width!==this.initialWidth||this.img.height!==this.initialHeight||this.img.width*this.img.height>1024};var o={getDocHeight:function(){var t=document;return Math.max(t.body.scrollHeight,t.documentElement.scrollHeight,t.body.offsetHeight,t.documentElement.offsetHeight,t.body.clientHeight,t.documentElement.clientHeight)},indexOf:function(t,i){if(null==t)return-1;for(var n=0,e=t.length;n<e;n++)if(t[n]===i)return n;return-1}},a=t.fn.waterfall;t.fn.waterfall=function(i){return this.each(function(){var n=t(this),e=n.data("mystist.waterfall"),r="object"==typeof i&&i;e&&"string"!=typeof i&&e.destroy()&&(e=null),e||n.data("mystist.waterfall",e=new s(this,r)),"string"==typeof i&&e[i]()})},t.fn.waterfall.Constructor=s,t.fn.waterfall.noConflict=function(){return t.fn.waterfall=a,this}}(jQuery);
"""This file contains all information for a GraphicsView with additional features. These features contain: - Default scene - Quick addition of graphviz code - Default drag mode = scrollhanddrag - Zooming ==> Inspired on https://stackoverflow.com/a/19114517 Author: Randy Paredis Date: 01/01/2020 """ from PyQt5 import QtWidgets, QtCore, QtSvg, QtGui from main.extra import IOHandler, isSVG, Constants import os Config = IOHandler.IOHandler.get_preferences() FILE_TYPES_OUT = { "Windows Bitmap Format": ["bmp"], "JPEG": ["jpg", "jpeg"], "Portable Network Graphics": ["png"], "Portable Pixmap": ["ppm"], "X11 Bitmap": ["xbm"], "X11 Pixmap": ["xpm"] } class GraphicsView(QtWidgets.QWidget): zoomed = QtCore.pyqtSignal(float) def __init__(self, mainwindow, parent=None, controls=False): super(GraphicsView, self).__init__(parent) self.mainwindow = mainwindow self._scene = QtWidgets.QGraphicsScene() self._view = QtWidgets.QGraphicsView(self._scene, parent) self._view.wheelEvent = self.viewWheelEvent self._view.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.layout = QtWidgets.QGridLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self._view, 0, 0, 1, -1) self.controls = controls self.zoom_factor_base = 2.0 self.zoom_factor_scroll = 1.0015 self.zoom_level_min = 0.1 self.zoom_level_max = 4.5 self.zoomlevel = 1.0 self.pb_zoom_out = QtWidgets.QPushButton(QtGui.QIcon(":/icons/tango/list-remove.png"), "") self.pb_zoom_out.setToolTip("Zoom Out") self.pb_zoom_out.clicked.connect(self.zoomOut) self.slider_zoom = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.slider_zoom.setSingleStep(0) self.slider_zoom.setPageStep(0) self.slider_zoom.setTickPosition(QtWidgets.QSlider.TicksBothSides) self.slider_zoom.setTickInterval(10) self.slider_zoom.sliderMoved.connect(lambda x: self.zoomTo(float(x) / 100)) self.setMinZoomLevel(self.zoom_level_min) self.setMaxZoomLevel(self.zoom_level_max) self.slider_zoom.setValue(100) self.pb_zoom_in = QtWidgets.QPushButton(QtGui.QIcon(":/icons/tango/list-add.png"), "") self.pb_zoom_in.setToolTip("Zoom In") self.pb_zoom_in.clicked.connect(self.zoomIn) self.lb_zoom = QtWidgets.QLabel("100%") self.pb_zoom_reset = QtWidgets.QPushButton("Reset") self.pb_zoom_reset.setToolTip("Reset Zoom Level") self.pb_zoom_reset.clicked.connect(self.resetZoom) self.zoomed.connect(self._zoomed) self.pb_zoom_fit = QtWidgets.QPushButton(QtGui.QIcon(":/icons/tango/view-fullscreen.png"), "") self.pb_zoom_fit.setToolTip("Zoom to Fit") self.pb_zoom_fit.clicked.connect(self.zoomToFit) self.pb_save = QtWidgets.QPushButton(QtGui.QIcon(":/icons/tango/image-x-generic.png"), "") self.pb_save.setToolTip("Export to Image...") self.pb_save.clicked.connect(self.save) self.layout.addWidget(self.pb_zoom_out, 1, 0) self.layout.addWidget(self.slider_zoom, 1, 1) self.layout.addWidget(self.lb_zoom, 1, 2) self.layout.addWidget(self.pb_zoom_in, 1, 3) self.layout.addWidget(self.pb_zoom_reset, 1, 4) self.layout.addWidget(self.pb_zoom_fit, 1, 5) self.layout.addWidget(self.pb_save, 1, 6) self.setLayout(self.layout) self.setControls(self.controls) def setMaxZoomLevel(self, level): self.zoom_level_max = level self.slider_zoom.setMaximum(level * 100) def setMinZoomLevel(self, level): self.zoom_level_min = level self.slider_zoom.setMinimum(level * 100) def setZoomFactorBase(self, factor): self.zoom_factor_base = factor def setControls(self, enabled: bool): self.controls = enabled self.pb_zoom_out.setVisible(self.controls) self.pb_zoom_in.setVisible(self.controls) self.pb_zoom_reset.setVisible(self.controls) self.slider_zoom.setVisible(self.controls) self.lb_zoom.setVisible(self.controls) if self.controls: self._view.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag) else: self._view.setDragMode(QtWidgets.QGraphicsView.NoDrag) def _zoomed(self, zoomlevel): if self.controls: self.slider_zoom.setValue(zoomlevel * 100) self.lb_zoom.setText("%6.2f%%" % (zoomlevel * 100)) self.pb_zoom_in.setDisabled(self.isMaximalZoomed()) self.pb_zoom_out.setDisabled(self.isMinimalZoomed()) def isMinimalZoomed(self): return self.zoom_level_min == self.zoomlevel def isMaximalZoomed(self): return self.zoom_level_max == self.zoomlevel def clear(self): self._scene.clear() self._scene.deleteLater() self._view.setScene(QtWidgets.QGraphicsScene()) self._scene = self._view.scene() def add(self, bdata): if isSVG(bdata): svgRenderer = QtSvg.QSvgRenderer(bdata) dot = QtSvg.QGraphicsSvgItem() dot.setSharedRenderer(svgRenderer) self._scene.addItem(dot) else: image = QtGui.QImage() image.loadFromData(bdata) pixmap = QtGui.QPixmap.fromImage(image) self._scene.addPixmap(pixmap) margin = 25 sr = self._scene.itemsBoundingRect() sr.adjust(-margin, -margin, margin, margin) self._scene.setSceneRect(sr) @QtCore.pyqtSlot(QtCore.QPoint, name="centerOn") def centerOn(self, point): self._view.centerOn(point) @QtCore.pyqtSlot(float, name="zoom") def zoom(self, factor): if self.zoomlevel * factor > self.zoom_level_max: return self.zoomTo(self.zoom_level_max) if self.zoomlevel * factor < self.zoom_level_min: return self.zoomTo(self.zoom_level_min) self._view.scale(factor, factor) self.zoomlevel *= factor self.zoomed.emit(self.zoomlevel) @QtCore.pyqtSlot(name="resetZoom") def resetZoom(self): self.zoomTo(1.0) @QtCore.pyqtSlot(float, name="zoomTo") def zoomTo(self, zoomlevel): self.zoom(float(zoomlevel) / self.zoomlevel) @QtCore.pyqtSlot(name="zoomIn") def zoomIn(self): self.zoom(self.zoom_factor_base) @QtCore.pyqtSlot(name="zoomOut") def zoomOut(self): self.zoom(1.0 / self.zoom_factor_base) @QtCore.pyqtSlot(name="zoomToFit") def zoomToFit(self): rect = self._view.frameRect() sceneRect = self._scene.itemsBoundingRect() w = rect.width() / sceneRect.width() h = rect.height() / sceneRect.height() self.zoomTo(min(w, h)) def save(self): options, folder = self.mainwindow.io() fileName, t = QtWidgets.QFileDialog \ .getSaveFileName(self, "Export a File", folder, Constants.file_list(FILE_TYPES_OUT), options=options) if fileName: ext = fileName.split(".")[-1] rext = Constants.obtain_exts(t) if fileName == ext: ext = rext[0] fileName += "." + ext if os.path.isfile(fileName): yes = self.question("File already exists!", "This file already exists. Are you sure, you want " "to replace it?") if not yes: # Reboot file chooser window return self.save() # Do the actual saving self._scene.clearSelection() # If there were to be any selections, these would also render to the file self._scene.setSceneRect(self._scene.itemsBoundingRect()) image = QtGui.QImage(self._scene.sceneRect().size().toSize(), QtGui.QImage.Format_ARGB32) image.fill(QtCore.Qt.transparent) painter = QtGui.QPainter(image) painter.setRenderHint(QtGui.QPainter.Antialiasing) self._scene.render(painter) image.save(fileName) painter.end() def viewWheelEvent(self, event: QtGui.QWheelEvent): mods = Config.value("view/scrollKey").split(" + ") modifiers = QtCore.Qt.NoModifier alt = False for m in mods: if m == "CTRL": modifiers |= QtCore.Qt.ControlModifier elif m == "ALT": modifiers |= QtCore.Qt.AltModifier alt = True elif m == "SHIFT": modifiers |= QtCore.Qt.ShiftModifier elif m == "META": modifiers |= QtCore.Qt.MetaModifier if event.modifiers() == modifiers: delta = event.angleDelta() if alt: angle = delta.x() else: angle = delta.y() factor = pow(self.zoom_factor_scroll, angle) self.zoom(factor) else: QtWidgets.QGraphicsView.wheelEvent(self._view, event)
/* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <AK/Assertions.h> #include <AK/NonnullRefPtr.h> #include <AK/Weakable.h> namespace Web { // FIXME: I wish I didn't have to forward declare these, but I can't seem to avoid // it if I still want to have for_each_in_subtree_of_type<U> inline here. class Node; class LayoutNode; template<typename T> bool is(const Node&); template<typename T> bool is(const LayoutNode&); template<typename T> class TreeNode : public Weakable<T> { public: void ref() { ASSERT(m_ref_count); ++m_ref_count; } void unref() { ASSERT(m_ref_count); if (!--m_ref_count) { if (m_next_sibling) m_next_sibling->m_previous_sibling = m_previous_sibling; if (m_previous_sibling) m_previous_sibling->m_next_sibling = m_next_sibling; T* next_child; for (auto* child = m_first_child; child; child = next_child) { next_child = child->m_next_sibling; child->m_parent = nullptr; child->unref(); } delete static_cast<T*>(this); } } int ref_count() const { return m_ref_count; } T* parent() { return m_parent; } const T* parent() const { return m_parent; } bool has_children() const { return m_first_child; } T* next_sibling() { return m_next_sibling; } T* previous_sibling() { return m_previous_sibling; } T* first_child() { return m_first_child; } T* last_child() { return m_last_child; } const T* next_sibling() const { return m_next_sibling; } const T* previous_sibling() const { return m_previous_sibling; } const T* first_child() const { return m_first_child; } const T* last_child() const { return m_last_child; } int child_count() const { int count = 0; for (auto* child = first_child(); child; child = child->next_sibling()) ++count; return count; } T* child_at_index(int index) { int count = 0; for (auto* child = first_child(); child; child = child->next_sibling()) { if (count == index) return child; ++count; } return nullptr; } const T* child_at_index(int index) const { return const_cast<TreeNode*>(this)->child_at_index(index); } bool is_ancestor_of(const TreeNode&) const; void prepend_child(NonnullRefPtr<T> node); void append_child(NonnullRefPtr<T> node, bool notify = true); void insert_before(NonnullRefPtr<T> node, RefPtr<T> child, bool notify = true); NonnullRefPtr<T> remove_child(NonnullRefPtr<T> node); void donate_all_children_to(T& node); bool is_child_allowed(const T&) const { return true; } T* next_in_pre_order() { if (first_child()) return first_child(); T* node; if (!(node = next_sibling())) { node = parent(); while (node && !node->next_sibling()) node = node->parent(); if (node) node = node->next_sibling(); } return node; } const T* next_in_pre_order() const { return const_cast<TreeNode*>(this)->next_in_pre_order(); } template<typename Callback> IterationDecision for_each_in_subtree(Callback callback) const { if (callback(static_cast<const T&>(*this)) == IterationDecision::Break) return IterationDecision::Break; for (auto* child = first_child(); child; child = child->next_sibling()) { if (child->for_each_in_subtree(callback) == IterationDecision::Break) return IterationDecision::Break; } return IterationDecision::Continue; } template<typename Callback> IterationDecision for_each_in_subtree(Callback callback) { if (callback(static_cast<T&>(*this)) == IterationDecision::Break) return IterationDecision::Break; for (auto* child = first_child(); child; child = child->next_sibling()) { if (child->for_each_in_subtree(callback) == IterationDecision::Break) return IterationDecision::Break; } return IterationDecision::Continue; } template<typename U, typename Callback> IterationDecision for_each_in_subtree_of_type(Callback callback) { if (is<U>(static_cast<const T&>(*this))) { if (callback(static_cast<U&>(*this)) == IterationDecision::Break) return IterationDecision::Break; } for (auto* child = first_child(); child; child = child->next_sibling()) { if (child->template for_each_in_subtree_of_type<U>(callback) == IterationDecision::Break) return IterationDecision::Break; } return IterationDecision::Continue; } template<typename U, typename Callback> IterationDecision for_each_in_subtree_of_type(Callback callback) const { if (is<U>(static_cast<const T&>(*this))) { if (callback(static_cast<const U&>(*this)) == IterationDecision::Break) return IterationDecision::Break; } for (auto* child = first_child(); child; child = child->next_sibling()) { if (child->template for_each_in_subtree_of_type<U>(callback) == IterationDecision::Break) return IterationDecision::Break; } return IterationDecision::Continue; } protected: TreeNode() { } private: int m_ref_count { 1 }; T* m_parent { nullptr }; T* m_first_child { nullptr }; T* m_last_child { nullptr }; T* m_next_sibling { nullptr }; T* m_previous_sibling { nullptr }; }; template<typename T> inline NonnullRefPtr<T> TreeNode<T>::remove_child(NonnullRefPtr<T> node) { ASSERT(node->m_parent == this); if (m_first_child == node) m_first_child = node->m_next_sibling; if (m_last_child == node) m_last_child = node->m_previous_sibling; if (node->m_next_sibling) node->m_next_sibling->m_previous_sibling = node->m_previous_sibling; if (node->m_previous_sibling) node->m_previous_sibling->m_next_sibling = node->m_next_sibling; node->m_next_sibling = nullptr; node->m_previous_sibling = nullptr; node->m_parent = nullptr; node->removed_from(static_cast<T&>(*this)); node->unref(); static_cast<T*>(this)->children_changed(); return node; } template<typename T> inline void TreeNode<T>::append_child(NonnullRefPtr<T> node, bool notify) { ASSERT(!node->m_parent); if (!static_cast<T*>(this)->is_child_allowed(*node)) return; if (m_last_child) m_last_child->m_next_sibling = node.ptr(); node->m_previous_sibling = m_last_child; node->m_parent = static_cast<T*>(this); m_last_child = node.ptr(); if (!m_first_child) m_first_child = m_last_child; if (notify) node->inserted_into(static_cast<T&>(*this)); (void)node.leak_ref(); if (notify) static_cast<T*>(this)->children_changed(); } template<typename T> inline void TreeNode<T>::insert_before(NonnullRefPtr<T> node, RefPtr<T> child, bool notify) { if (!child) return append_child(move(node), notify); ASSERT(!node->m_parent); ASSERT(child->parent() == this); if (!static_cast<T*>(this)->is_child_allowed(*node)) return; node->m_previous_sibling = child->m_previous_sibling; node->m_next_sibling = child; if (m_first_child == child) m_first_child = node; node->m_parent = static_cast<T*>(this); if (notify) node->inserted_into(static_cast<T&>(*this)); (void)node.leak_ref(); if (notify) static_cast<T*>(this)->children_changed(); } template<typename T> inline void TreeNode<T>::prepend_child(NonnullRefPtr<T> node) { ASSERT(!node->m_parent); if (!static_cast<T*>(this)->is_child_allowed(*node)) return; if (m_first_child) m_first_child->m_previous_sibling = node.ptr(); node->m_next_sibling = m_first_child; node->m_parent = static_cast<T*>(this); m_first_child = node.ptr(); if (!m_last_child) m_last_child = m_first_child; node->inserted_into(static_cast<T&>(*this)); (void)node.leak_ref(); static_cast<T*>(this)->children_changed(); } template<typename T> inline void TreeNode<T>::donate_all_children_to(T& node) { for (T* child = m_first_child; child != nullptr;) { T* next_child = child->m_next_sibling; child->m_parent = nullptr; child->m_next_sibling = nullptr; child->m_previous_sibling = nullptr; node.append_child(adopt(*child)); child = next_child; } m_first_child = nullptr; m_last_child = nullptr; } template<typename T> inline bool TreeNode<T>::is_ancestor_of(const TreeNode<T>& other) const { for (auto* ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) { if (ancestor == this) return true; } return false; } }
import styled from "styled-components/native"; import { Button } from "react-native-paper"; import { Block, Text } from "galio-framework"; import { Content, Thumbnail } from "native-base"; import { Card } from "react-native-paper"; export const Container = styled.View` flex: 1; justify-content: center; align-content: center; background-color: whitesmoke; padding-left: 15px; padding-right: 15px; `; export const Title = styled.Text` color: blueviolet; text-align: center; font-size: 24px; margin-top: 10px; font-weight: 700; `; export const ServiceName = styled.Text` color: blueviolet; font-size: 24px; font-weight: 400; `; export const NoFeedback = styled.Text` color: #eb6709; font-size: 24px; margin-top: 15px; font-weight: 400; text-align: center; `; export const Reviews = styled.Text` color: #089920; font-size: 24px; margin-top: 5px; font-weight: 400; `; export const Price = styled.Text` color: #eb6709; text-align: center; font-size: 24px; font-weight: 500; `; export const ContentForCard = styled(Content)` align-content: center; text-align: center; `; export const CardPaper = styled(Card)` margin-top: 5px; `; export const ServiceButton = styled(Button)` background-color: transparent; border-radius: 60px; border-color: blueviolet; margin-left: 3px; `; export const Category = styled.Text` color: #eb6709; font-size: 16px; font-weight: 100; `; export const Description = styled(Text)` margin-top: 5px; `;
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 2 # 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, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### from .enums import * from .prefs import is_blender28 class IslandParamInfo: VCOLOR_CHNAME_PREFIX = '__uvp2_' VALUE_TO_VCOLOR = (lambda val: (val, val, val, 1.0)) if is_blender28() else (lambda val: (val, val, val)) MAX_PERCHANNEL_VALUE = 255 INT_TO_VCOLOR_CH = (lambda input: float(input) / IslandParamInfo.MAX_PERCHANNEL_VALUE) VCOLOR_CH_TO_INT = (lambda input: int(input * IslandParamInfo.MAX_PERCHANNEL_VALUE)) @classmethod def get_vcolor_chname(cls): return cls.VCOLOR_CHNAME_PREFIX + cls.VCOLOR_CHNAME_SUFFIX @classmethod def get_param_info_array(cls): param_array = [None] * UvIslandIntParams.COUNT param_array[UvIslandIntParams.GROUP] = GroupIslandParamInfo() param_array[UvIslandIntParams.ROTATION_STEP] = RotStepIslandParamInfo() param_array[UvIslandIntParams.LOCK_GROUP] = LockGroupIslandParamInfo() return param_array @classmethod def vcolor_to_param_allchannels(cls, vcolor): zero_based_value = 0 multiplier = 1 for i in range(3): zero_based_value += multiplier * cls.VCOLOR_CH_TO_INT(vcolor[i]) multiplier *= cls.MAX_PERCHANNEL_VALUE return zero_based_value + cls.MIN_VALUE @classmethod def vcolor_to_param(cls, vcolor): if cls.ALL_CHANNELS: return cls.vcolor_to_param_allchannels(vcolor) f_value = vcolor[0] return int(round((cls.MAX_VALUE - cls.MIN_VALUE) * f_value + cls.MIN_VALUE)) @classmethod def param_to_vcolor_allchannels(cls, param_value): zero_based_value = param_value - cls.MIN_VALUE ch_values = [cls.INT_TO_VCOLOR_CH(0)] * 3 for i in range(3): ch_values[i] = cls.INT_TO_VCOLOR_CH(zero_based_value % cls.MAX_PERCHANNEL_VALUE) zero_based_value //= cls.MAX_PERCHANNEL_VALUE if zero_based_value == 0: break if zero_based_value > 0: raise RuntimeError('Too large island param provided') return (ch_values[0], ch_values[1], ch_values[2], 1.0) @classmethod def param_to_vcolor(cls, param_value): if cls.ALL_CHANNELS: return cls.param_to_vcolor_allchannels(param_value) value = (float(param_value) - cls.MIN_VALUE) / (cls.MAX_VALUE - cls.MIN_VALUE) return cls.VALUE_TO_VCOLOR(value) @classmethod def get_default_vcolor(cls): return cls.param_to_vcolor(cls.DEFAULT_VALUE) @classmethod def param_to_text(cls, value): return str(value) @classmethod def param_to_color(cls, value): return (1,1,1,1) class GroupIslandParamInfoGeneric(IslandParamInfo): GROUP_COLORS = [ (0.0, 0.0, 1.0, 1.0), (1.0, 1.0, 0.0, 1.0), (0.0, 1.0, 1.0, 1.0), (0.0, 1.0, 0.0, 1.0), (1.0, 0.25, 0.0, 1.0), (1.0, 0.0, 0.25, 1.0), (0.25, 0.0, 1.0, 1.0), (0.0, 0.25, 1.0, 1.0), (1.0, 0.0, 0.0, 1.0), (0.5, 0.0, 0.5, 1.0), (1.0, 0.0, 0.5, 1.0), (1.0, 0.0, 1.0, 1.0), (0.5, 1.0, 0.0, 1.0), ] @classmethod def param_to_color(cls, value): return cls.GROUP_COLORS[value % len(cls.GROUP_COLORS)] class GroupIslandParamInfo(GroupIslandParamInfoGeneric): NAME = 'Group' VCOLOR_CHNAME_SUFFIX = 'group' ALL_CHANNELS = False MIN_VALUE = 0 MAX_VALUE = 100 DEFAULT_VALUE = MIN_VALUE PARAM_IDX = UvIslandIntParams.GROUP PROP_NAME = 'manual_group_num' class RotStepIslandParamInfo(IslandParamInfo): NAME = 'Rotation Step' VCOLOR_CHNAME_SUFFIX = 'rot_step' USE_GLOBAL_VALUE = -1 ALL_CHANNELS = False MIN_VALUE = -1 MAX_VALUE = 180 DEFAULT_VALUE = USE_GLOBAL_VALUE PARAM_IDX = UvIslandIntParams.ROTATION_STEP PROP_NAME = 'island_rot_step' @classmethod def param_to_text(cls, value): if value == cls.USE_GLOBAL_VALUE: return 'G' return str(value) class LockGroupIslandParamInfo(GroupIslandParamInfoGeneric): NAME = 'Lock Group' VCOLOR_CHNAME_SUFFIX = 'lock_group' ALL_CHANNELS = False MIN_VALUE = 0 MAX_VALUE = 100 DEFAULT_VALUE = MIN_VALUE PARAM_IDX = UvIslandIntParams.LOCK_GROUP PROP_NAME = 'lock_group_num' @classmethod def param_to_text(cls, value): if value == cls.DEFAULT_VALUE: return 'N' return str(value) class SplitOffsetParamInfo(IslandParamInfo): NAME = 'Split Offset' VCOLOR_CHNAME_SUFFIX = 'split_offset' ALL_CHANNELS = True MIN_VALUE = -1 MAX_VALUE = 10000 DEFAULT_VALUE = MIN_VALUE INVALID_VALUE = MIN_VALUE PARAM_IDX = None PROP_NAME = None class IslandParamError(RuntimeError): def __init__(self, str): super().__init__(str)
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/engine/shared_eng_freitek_dual_jet.iff" result.attribute_template_id = 8 result.stfName("space/space_item","eng_freitek_dual_jet_n") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Generates GeoJSON MCF for Indian State and Districts.""" import os import json from absl import app from absl import flags from india.geo.states import IndiaStatesMapper from india.formatters import CodeFormatter FLAGS = flags.FLAGS flags.DEFINE_string('input_state_geojson', '', 'Path to the India State geojson file.') flags.DEFINE_string('input_district_geojson', '', 'Path to the India District geojson file.') flags.DEFINE_string('output_geojson_dir', '/tmp', 'Output directory path.') # Note1: When we emit geojson string, we use two json.dumps() so it # automatically escapes all inner quotes, and encloses the entire string in # quotes. # Note2: Having the appropriate type helps downstream consumers of this data # (e.g., IPCC pipeline). _MCF_FORMAT = """ Node: india_place_{ext_id} typeOf: dcs:{place_type} {ext_id_prop}: "{ext_id}" geoJsonCoordinates: {gj_str} """ def generate(in_state, in_district, out_path): with open(in_state) as fin: with open(os.path.join(out_path, "India_States_GeoJson.mcf"), 'w') as fout: _generate_states(fin, fout) with open(in_district) as fin: with open(os.path.join(out_path, "India_Districts_GeoJson.mcf"), 'w') as fout: _generate_districts(fin, fout) def _generate_states(fin, fout): j = json.load(fin) for f in j['features']: if ('properties' not in f or 'ST_NM' not in f['properties'] or 'geometry' not in f): continue iso = IndiaStatesMapper.get_state_name_to_iso_code_mapping( f['properties']['ST_NM']) gj = json.dumps(json.dumps(f['geometry'])) fout.write( _MCF_FORMAT.format(ext_id=iso, place_type='AdministrativeArea1', ext_id_prop='isoCode', gj_str=gj)) def _generate_districts(fin, fout): j = json.load(fin) for f in j['features']: if ('properties' not in f or 'censuscode' not in f['properties'] or 'geometry' not in f): continue census2011 = str(f['properties']['censuscode']) census2011 = CodeFormatter.format_census2011_code(census2011) gj = json.dumps(json.dumps(f['geometry'])) fout.write( _MCF_FORMAT.format(ext_id=census2011, place_type='AdministrativeArea2', ext_id_prop='indianCensusAreaCode2011', gj_str=gj)) def main(_): generate(FLAGS.input_state_geojson, FLAGS.input_district_geojson, FLAGS.output_geojson_dir) if __name__ == "__main__": app.run(main)
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Reset = exports.STATUS_REJECTED = exports.STATUS_ACCEPTED = exports.TYPE_SOFT = exports.TYPE_HARD = undefined; var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _BaseCommand2 = require('./BaseCommand'); var _BaseCommand3 = _interopRequireDefault(_BaseCommand2); var _Reset = require('../../ocpp-1.6-schemas/Reset'); var _Reset2 = _interopRequireDefault(_Reset); var _ResetResponse = require('../../ocpp-1.6-schemas/ResetResponse'); var _ResetResponse2 = _interopRequireDefault(_ResetResponse); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TYPE_HARD = exports.TYPE_HARD = 'Hard'; var TYPE_SOFT = exports.TYPE_SOFT = 'Soft'; var STATUS_ACCEPTED = exports.STATUS_ACCEPTED = 'Accepted'; var STATUS_REJECTED = exports.STATUS_REJECTED = 'Rejected'; var Reset = exports.Reset = function (_BaseCommand) { (0, _inherits3.default)(Reset, _BaseCommand); function Reset(values) { (0, _classCallCheck3.default)(this, Reset); return (0, _possibleConstructorReturn3.default)(this, (Reset.__proto__ || (0, _getPrototypeOf2.default)(Reset)).call(this, _Reset2.default, _ResetResponse2.default, values)); } return Reset; }(_BaseCommand3.default); //# sourceMappingURL=Reset.js.map
import React from "react"; import { NavLink } from "react-router-dom"; import TransferList from "./TransferList"; function Sidebar() { return ( <> <div class="sidebar"> <NavLink to="/data"><h3>TRANSFER</h3></NavLink> <NavLink to="/profile"><h3>Profile</h3></NavLink> <NavLink to="/order"><h3>Order</h3></NavLink> <NavLink to="/subscription"><h3>Subscription</h3></NavLink> <NavLink to="/transaction"><h3>Transaction</h3></NavLink> </div> </> ); } export default Sidebar;
// @flow import { Given, When, Then } from 'cucumber'; import { expect } from 'chai'; import { navigateTo } from '../../../navigation/e2e/steps/helpers'; import { waitUntilWaletNamesEqual, getNameOfActiveWalletInSidebar, } from '../../../wallets/e2e/steps/helpers'; import type { Daedalus } from '../../../types'; declare var daedalus: Daedalus; Given(/^I am on the settings screen$/, async function() { await navigateTo.call(this, '/settings'); return this.client.waitForVisible('.SettingsLayout_component'); }); Given(/^I should see the "([^"]*)" wallet password dialog$/, function( dialogType ) { const selector = `.${dialogType}PasswordDialog`; return this.client.waitForVisible(selector); }); When(/^I click on the "([^"]*)" password label$/, function(label) { const selector = `.${label}Label button`; return this.client.click(selector); }); When(/^I enter wallet password:$/, async function(table) { const fields = table.hashes()[0]; await this.client.setValue( '.createPasswordDialog .newPassword input', fields.password ); await this.client.setValue( '.createPasswordDialog .repeatedPassword input', fields.repeatedPassword ); }); When(/^I submit the wallet password dialog$/, function() { return this.client.click('.confirmButton'); }); When(/^I change wallet password:$/, async function(table) { const fields = table.hashes()[0]; await this.client.setValue( '.changePasswordDialog .currentPassword input', fields.currentPassword ); await this.client.setValue( '.changePasswordDialog .newPassword input', fields.password ); await this.client.setValue( '.changePasswordDialog .repeatedPassword input', fields.repeatedPassword ); }); Then(/^I should not see the change password dialog anymore$/, function() { return this.client.waitForVisible('.changePasswordDialog', null, true); }); When( /^I toggle "Check to deactivate password" switch on the change wallet password dialog$/, function() { return this.waitAndClick('.changePasswordDialog .SimpleSwitch_switch'); } ); When(/^I enter current wallet password:$/, async function(table) { const fields = table.hashes()[0]; await this.client.setValue( '.changePasswordDialog .currentPassword input', fields.currentPassword ); }); When(/^I click on "name" input field$/, function() { return this.client.click( '.WalletSettings_component .InlineEditingInput_component' ); }); When(/^I enter new wallet name:$/, async function(table) { const fields = table.hashes()[0]; await this.client.setValue( '.WalletSettings_component .walletName input', fields.name ); }); When(/^I click outside "name" input field$/, function() { return this.client.click('.WalletSettings_component'); }); When( /^I open "Transaction assurance security level" selection dropdown$/, function() { return this.waitAndClick( '.WalletSettings_component .walletAssuranceLevel input' ); } ); When(/^I select "Strict" assurance level$/, function() { return this.waitAndClick( '//*[@class="SimpleOptions_option"]//*[contains(text(), "Strict")]' ); }); Then( /^I should have wallet with "Strict" assurance level set$/, async function() { const activeWalletName = await getNameOfActiveWalletInSidebar.call(this); const wallets = await this.client.executeAsync(done => { daedalus.stores.wallets.walletsRequest .execute() .then(done) .catch(error => done(error)); }); const activeWallet = wallets.value.find(w => w.name === activeWalletName); expect(activeWallet.assurance).to.equal('strict'); } ); Then(/^I should see new wallet name "([^"]*)"$/, async function(walletName) { return waitUntilWaletNamesEqual.call(this, walletName); }); Then(/^I should see "([^"]*)" label in password field$/, function(label) { const selector = `.${label}Label`; return this.client.waitForVisible(selector); }); Then(/^I should see the following error messages:$/, async function(data) { const error = data.hashes()[0]; const errorSelector = '.ChangeSpendingPasswordDialog_newPassword .SimpleFormField_error'; await this.client.waitForText(errorSelector); const errorsOnScreen = await this.client.getText(errorSelector); const expectedError = await this.intl(error.message); expect(errorsOnScreen).to.equal(expectedError); });
/** * Kendo UI v2016.2.714 (http://www.telerik.com/kendo-ui) * Copyright 2016 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ !function(M){"function"==typeof define&&define.amd?define(["kendo.core.min"],M):M()}(function(){!function(M,y){kendo.cultures["kk-KZ"]={name:"kk-KZ",numberFormat:{pattern:["-n"],decimals:2,",":" ",".":",",groupSize:[3],percent:{pattern:["-n%","n%"],decimals:2,",":" ",".":",",groupSize:[3],symbol:"%"},currency:{name:"Tenge",abbr:"KZT",pattern:["-$n","$n"],decimals:2,",":" ",".":"-",groupSize:[3],symbol:"₸"}},calendars:{standard:{days:{names:["Жексенбі","Дүйсенбі","Сейсенбі","Сәрсенбі","Бейсенбі","Жұма","Сенбі"],namesAbbr:["Жек","Дүй","Сей","Сәр","Бей","Жұм","Сен"],namesShort:["Жк","Дс","Сс","Ср","Бс","Жм","Сн"]},months:{names:["қаңтар","ақпан","наурыз","сәуір","мамыр","маусым","шілде","тамыз","қыркүйек","қазан","қараша","желтоқсан"],namesAbbr:["қаң","ақп","нау","сәу","мам","мау","шіл","там","қыр","қаз","қар","жел"]},AM:[""],PM:[""],patterns:{d:"d-MMM-yy",D:"d MMMM yyyy 'ж.'",F:"d MMMM yyyy 'ж.' HH:mm:ss",g:"d-MMM-yy HH:mm",G:"d-MMM-yy HH:mm:ss",m:"d MMMM",M:"d MMMM",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"HH:mm",T:"HH:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM yyyy",Y:"MMMM yyyy"},"/":"-",":":":",firstDay:1}}}}(this)}); //# sourceMappingURL=kendo.culture.kk-KZ.min.js.map
define({ root: ({ _widgetLabel: "Coordinate Conversion" }), });
from src.config import ExperimentConfig from tensorflow.python.keras.layers.core import Dropout, Masking from src.features.sequences.transformer import SequenceMetadata import tensorflow as tf from typing import Any, List, Dict from .metrics import ( MulticlassAccuracy, MulticlassTrueNegativeRate, MulticlassTruePositiveRate, PercentileSubsetMetricHelper, MultilabelNestedMetric, ) from .config import ModelConfig from .callbacks import MLFlowCallback, BestModelRestoreCallback from .initializers import FastTextInitializer import logging import mlflow import datetime def full_prediction_binary_accuracy_loss(y_true, y_pred): sum = tf.reduce_sum(y_true, axis=-1) weights = tf.where(sum > 1, x=1.0, y=sum) weights = tf.cast(weights, dtype="float32") loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) loss = tf.reduce_sum(weights * loss, axis=1) / tf.reduce_sum(weights, axis=1) return tf.reduce_mean(loss) class BaseEmbedding: config: ModelConfig num_features: int = 0 num_hidden_features: int = 0 num_connections: int = 0 basic_feature_embeddings: tf.Variable # shape: (num_features, embedding_size) basic_hidden_embeddings: tf.Variable # shape: (num_hidden_features, embedding_size) def _final_embedding_matrix(self): """Overwrite this in case embedding uses attention mechanism etc""" return self.basic_feature_embeddings def _get_kernel_regularizer(self, scope: str): if scope not in self.config.kernel_regularizer_scope: logging.debug("Regularization not enabled for %s", scope) return None elif self.config.kernel_regularizer_value <= 0.0: return None elif self.config.kernel_regularizer_type == "l2": return tf.keras.regularizers.l2(self.config.kernel_regularizer_value) elif self.config.kernel_regularizer_type == "l2": return tf.keras.regularizers.l1(self.config.kernel_regularizer_value) else: return None def _get_initializer( self, initializer_name: str, initializer_seed: int, description_vocab: Dict[int, str], ) -> tf.keras.initializers.Initializer: if initializer_name == "random_uniform": return tf.keras.initializers.GlorotUniform(seed=initializer_seed) elif initializer_name == "random_normal": return tf.keras.initializers.GlorotNormal(seed=initializer_seed) elif initializer_name == "fasttext": initializer = FastTextInitializer(self.config.embedding_dim) return initializer.get_initializer(description_vocab) else: logging.error("Unknown initializer %s", initializer_name) def _get_feature_initializer( self, description_vocab: Dict[int, str] ) -> tf.keras.initializers.Initializer: return self._get_initializer( self.config.feature_embedding_initializer, self.config.feature_embedding_initializer_seed, description_vocab, ) def _get_hidden_initializer( self, description_vocab: Dict[int, str] ) -> tf.keras.initializers.Initializer: return self._get_initializer( self.config.hidden_embedding_initializer, self.config.hidden_embedding_initializer_seed, description_vocab, ) class BaseModel: def __init__(self): self.prediction_model: tf.keras.Model = None self.embedding_layer: BaseEmbedding = None self.metrics: List[tf.keras.metrics.Metric] = [] self.config = ModelConfig() def _get_embedding_layer( self, metadata: SequenceMetadata, knowledge: Any ) -> BaseEmbedding: raise NotImplementedError("This should be implemented by the subclass!!!") def _select_distribute_strategy(self) -> tf.distribute.Strategy: if self.config.distribute_strategy == "mirrored": return tf.distribute.MirroredStrategy() elif self.config.distribute_strategy.startswith("/gpu"): return tf.distribute.OneDeviceStrategy( device=self.config.distribute_strategy ) else: return tf.distribute.get_strategy() def build(self, metadata: SequenceMetadata, knowledge: Any): self.metadata = metadata self.strategy = self._select_distribute_strategy() logging.info( "Using strategy with %d workers", self.strategy.num_replicas_in_sync ) with self.strategy.scope(): self.embedding_layer = self._get_embedding_layer(metadata, knowledge) self._log_embedding_stats() self.prediction_model = tf.keras.models.Sequential( [ tf.keras.layers.Input( shape=(metadata.max_x_length, len(metadata.x_vocab)), ), self.embedding_layer, tf.keras.layers.Masking(mask_value=0), self._get_rnn_layer(), tf.keras.layers.Dropout( rate=self.config.dropout_rate, seed=self.config.dropout_seed ), tf.keras.layers.Dense( len(metadata.y_vocab), activation=self.config.final_activation_function, kernel_regularizer=self.embedding_layer._get_kernel_regularizer( scope="prediction_dense" ), ), ] ) def _log_embedding_stats(self): mlflow.log_metric("num_features", self.embedding_layer.num_features) mlflow.log_metric( "num_hidden_features", self.embedding_layer.num_hidden_features ) mlflow.log_metric("num_connections", self.embedding_layer.num_connections) def _get_rnn_layer(self): if self.config.rnn_type == "rnn": return tf.keras.layers.SimpleRNN( units=self.config.rnn_dim, kernel_regularizer=self.embedding_layer._get_kernel_regularizer( scope="prediction_rnn" ), return_sequences=self.metadata.full_y_prediction, dropout=self.config.rnn_dropout, ) elif self.config.rnn_type == "lstm": return tf.keras.layers.LSTM( units=self.config.rnn_dim, kernel_regularizer=self.embedding_layer._get_kernel_regularizer( scope="prediction_rnn" ), return_sequences=self.metadata.full_y_prediction, dropout=self.config.rnn_dropout, ) elif self.config.rnn_type == "gru": return tf.keras.layers.GRU( units=self.config.rnn_dim, kernel_regularizer=self.embedding_layer._get_kernel_regularizer( scope="prediction_rnn" ), return_sequences=self.metadata.full_y_prediction, dropout=self.config.rnn_dropout, ) else: logging.error("Unknown rnn layer type: %s", self.config.rnn_type) def train_dataset( self, train_dataset: tf.data.Dataset, test_dataset: tf.data.Dataset, multilabel_classification: bool, n_epochs: int, ): with self.strategy.scope(): if self.metadata.full_y_prediction: self._compile_full_prediction(train_dataset) elif len(self.metadata.y_vocab) == 1: self._compile_singleclass() elif multilabel_classification: self._compile_multilabel(train_dataset) else: self._compile_multiclass(train_dataset) model_summary = [] self.prediction_model.summary(print_fn=lambda x: model_summary.append(x)) mlflow.log_text("\n".join(model_summary), artifact_file="model_summary.txt") self.history = self.prediction_model.fit( train_dataset, validation_data=test_dataset, epochs=n_epochs, callbacks=[ MLFlowCallback(), BestModelRestoreCallback( metric=self.config.best_model_metric, minimize=self.config.best_model_metric_minimize, early_stopping_epochs=self.config.early_stopping_epochs, ), ], ) def _compile_singleclass(self): self.metrics = [ tf.keras.metrics.Accuracy(), tf.keras.metrics.BinaryAccuracy(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), tf.keras.metrics.AUC(), ] self.prediction_model.compile( loss=self.config.loss, optimizer=self.config.optimizer, metrics=self.metrics, ) def _compile_full_prediction(self, train_dataset: tf.data.Dataset): self.metrics = [ MultilabelNestedMetric( nested_metric=tf.keras.metrics.CategoricalAccuracy(), name="categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), MultilabelNestedMetric( nested_metric=tf.keras.metrics.TopKCategoricalAccuracy(k=5), name="top_5_categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), MultilabelNestedMetric( nested_metric=tf.keras.metrics.TopKCategoricalAccuracy(k=10), name="top_10_categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), MultilabelNestedMetric( nested_metric=tf.keras.metrics.TopKCategoricalAccuracy(k=20), name="top_20_categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), ] metric_helper = PercentileSubsetMetricHelper( train_dataset, num_percentiles=self.config.metrics_num_percentiles, y_vocab=self.metadata.y_vocab, full_prediction=self.metadata.full_y_prediction, ) for k in [5, 10, 20]: self.metrics = ( self.metrics + metric_helper.get_accuracy_at_k_for( k=k, is_multilabel=True, use_cumulative=True ) + metric_helper.get_accuracy_at_k_for( k=k, is_multilabel=True, use_cumulative=False ) ) self.prediction_model.compile( loss=full_prediction_binary_accuracy_loss, optimizer=self.config.optimizer, metrics=self.metrics, ) def _compile_multilabel(self, train_dataset: tf.data.Dataset): self.metrics = [ MultilabelNestedMetric( nested_metric=tf.keras.metrics.CategoricalAccuracy(), name="categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), MultilabelNestedMetric( nested_metric=tf.keras.metrics.TopKCategoricalAccuracy(k=5), name="top_5_categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), MultilabelNestedMetric( nested_metric=tf.keras.metrics.TopKCategoricalAccuracy(k=10), name="top_10_categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), MultilabelNestedMetric( nested_metric=tf.keras.metrics.TopKCategoricalAccuracy(k=20), name="top_20_categorical_accuracy", full_prediction=self.metadata.full_y_prediction, ), ] metric_helper = PercentileSubsetMetricHelper( train_dataset, num_percentiles=self.config.metrics_num_percentiles, y_vocab=self.metadata.y_vocab, full_prediction=self.metadata.full_y_prediction, ) for k in [5, 10, 20]: self.metrics = ( self.metrics + metric_helper.get_accuracy_at_k_for( k=k, is_multilabel=True, use_cumulative=True ) + metric_helper.get_accuracy_at_k_for( k=k, is_multilabel=True, use_cumulative=False ) ) self.prediction_model.compile( loss=self.config.loss, optimizer=self.config.optimizer, metrics=self.metrics, ) def _compile_multiclass(self, train_dataset: tf.data.Dataset): metric_helper = PercentileSubsetMetricHelper( train_dataset, num_percentiles=self.config.metrics_num_percentiles, y_vocab=self.metadata.y_vocab, full_prediction=self.metadata.full_y_prediction, ) self.metrics = [ tf.keras.metrics.CategoricalAccuracy(), tf.keras.metrics.TopKCategoricalAccuracy( k=5, name="top_5_categorical_accuracy" ), tf.keras.metrics.TopKCategoricalAccuracy( k=10, name="top_10_categorical_accuracy" ), tf.keras.metrics.TopKCategoricalAccuracy( k=20, name="top_20_categorical_accuracy" ), ] for k in [5, 10, 20]: self.metrics = ( self.metrics + metric_helper.get_accuracy_at_k_for( k=k, is_multilabel=False, use_cumulative=True ) + metric_helper.get_accuracy_at_k_for( k=k, is_multilabel=False, use_cumulative=False ) ) self.prediction_model.compile( loss=self.config.loss, optimizer=self.config.optimizer, metrics=self.metrics, )
""" Kakuru puzzle in cpmpy. http://en.wikipedia.org/wiki/Kakuro ''' The object of the puzzle is to insert a digit from 1 to 9 inclusive into each white cell such that the sum of the numbers in each entry matches the clue associated with it and that no digit is duplicated in any entry. It is that lack of duplication that makes creating Kakuro puzzles with unique solutions possible, and which means solving a Kakuro puzzle involves investigating combinations more, compared to Sudoku in which the focus is on permutations. There is an unwritten rule for making Kakuro puzzles that each clue must have at least two numbers that add up to it. This is because including one number is mathematically trivial when solving Kakuro puzzles; one can simply disregard the number entirely and subtract it from the clue it indicates. ''' This model solves the problem at the Wikipedia page. For a larger picture, see http://en.wikipedia.org/wiki/File:Kakuro_black_box.svg The solution: 9 7 0 0 8 7 9 8 9 0 8 9 5 7 6 8 5 9 7 0 0 0 6 1 0 2 6 0 0 0 4 6 1 3 2 8 9 3 1 0 1 4 3 1 2 0 0 2 1 This cpmpy model was written by Hakan Kjellerstrand ([email protected]) See also my cpmpy page: http://hakank.org/cpmpy/ """ from cpmpy import * import cpmpy.solvers import numpy as np from cpmpy_hakank import * # # Ensure that the sum of the segments # in cc == res # def calc(cc, x, res): constraints = [] # ensure that the values are positive for i in cc: constraints += [x[i[0]-1,i[1]-1] >= 1] # sum the numbers constraints += [sum([x[i[0] - 1, i[1] - 1] for i in cc]) == res] return constraints def kakuro(): model = Model() # size of matrix n = 7 # segments # [sum, [segments]] # Note: 1-based problem = [[16, [1, 1], [1, 2]], [24, [1, 5], [1, 6], [1, 7]], [17, [2, 1], [2, 2]], [29, [2, 4], [2, 5], [2, 6], [2, 7]], [35, [3, 1], [3, 2], [3, 3], [3, 4], [3, 5]], [7, [4, 2], [4, 3]], [8, [4, 5], [4, 6]], [16, [5, 3], [5, 4], [5, 5], [5, 6], [5, 7]], [21, [6, 1], [6, 2], [6, 3], [6, 4]], [5, [6, 6], [6, 7]], [6, [7, 1], [7, 2], [7, 3]], [3, [7, 6], [7, 7]], [23, [1, 1], [2, 1], [3, 1]], [30, [1, 2], [2, 2], [3, 2], [4, 2]], [27, [1, 5], [2, 5], [3, 5], [4, 5], [5, 5]], [12, [1, 6], [2, 6]], [16, [1, 7], [2, 7]], [17, [2, 4], [3, 4]], [15, [3, 3], [4, 3], [5, 3], [6, 3], [7, 3]], [12, [4, 6], [5, 6], [6, 6], [7, 6]], [7, [5, 4], [6, 4]], [7, [5, 7], [6, 7], [7, 7]], [11, [6, 1], [7, 1]], [10, [6, 2], [7, 2]]] num_p = len(problem) # The blanks # Note: 1-based blanks = [[1, 3], [1, 4], [2, 3], [3, 6], [3, 7], [4, 1], [4, 4], [4, 7], [5, 1], [5, 2], [6, 5], [7, 4], [7, 5]] num_blanks = len(blanks) # # variables # # the set x = intvar(0,9,shape=(n,n), name="x") # # constraints # # fill the blanks with 0 for i in range(num_blanks): model += [x[blanks[i][0]-1, blanks[i][1]-1] == 0] for i in range(num_p): segment = problem[i][1::] res = problem[i][0] # sum this segment model += [calc(segment, x, res)] # all numbers in this segment must be distinct segment = [x[p[0]-1, p[1]-1] for p in segment] model += [AllDifferent(segment)] ss = CPM_ortools(model) num_solutions = 0 while ss.solve(): num_solutions += 1 for i in range(n): for j in range(n): val = x[i, j].value() if val > 0: print(val, end=" ") else: print(" ", end=" ") print() print() get_different_solution(ss,x.flat) print("num_solutions:", num_solutions) kakuro()
import {Container} from 'unstated' import {server, apiErrorAlert, defaultEventSort} from '../constants/Server' import {baseURL} from '../constants/config' import {DateTime} from 'luxon' import {map} from 'lodash' const LOCATIONS_FETCH_MIN_MINUTES = 15 const _SAMPLE_AVATARS = [ require('../../assets/avatar-female.png'), require('../../assets/avatar-male.png'), require('../../assets/avatar-female.png'), ] /* eslint-disable complexity,space-before-function-paren,camelcase */ function ticketFilter({status, ticket_pricing}) { switch (status) { case 'SoldOut': return true case 'Published': return !!ticket_pricing default: return false } } function ticketComparator({ticket_pricing: a}, {ticket_pricing: b}) { if (a === null && b === null) { return 0 } if (a === null) { return 1 } if (b === null) { return -1 } return b - a } class EventsContainer extends Container { constructor(props = {}) { super(props); this.state = { events: [], eventsById: {}, ticketTypesById: {}, paging: {}, lastUpdate: null, locations: [], selectedLocationId: null, selectedEvent: {}, }; } get eventsById() { return this.state.eventsById } get ticketTypesById() { return this.state.ticketTypesById } get ticketTypeIds() { return map(this.ticketTypesById, (_ticket, id) => id) } get selectedEvent() { return this.state.selectedEvent } get ticketsToDisplay() { const {ticketTypesById} = this.state ticketTypes = map(ticketTypesById, (ticket, _id) => ticket) return ticketTypes ? ticketTypes.filter(ticketFilter).sort(ticketComparator) : [] } locationsPromise = null locationsLastFetched = null fetchLocations = async (...args) => { // Already fetching. Wait for existing promise to finish. if (this.locationsPromise !== null) { return await this.locationsPromise } // Don't fetch more often than is sane. if (this.locationsLastFetched && this.locationsLastFetched.plus({minutes: LOCATIONS_FETCH_MIN_MINUTES}) < DateTime.local()) { return } try { // Do the fetch, lock fetching, and write down the time when we finished. await (this.locationsPromise = this._fetchLocations(...args)) this.locationsLastFetched = DateTime.local() } finally { // Always unlock so we can try to fetch again. this.locationsPromise = null } } _fetchLocations = async () => { try { const {data: {data: locations}} = await server.regions.index() await this.setState({locations}) } catch (error) { apiErrorAlert(error) } } getEvents = async (_location = null) => { try { const [{data}, ..._rest] = await Promise.all([ server.events.index(defaultEventSort), this.fetchLocations(), ]) const eventsById = {} data.data.forEach((event) => { if (!event.promo_image_url) { event.promo_image_url = `${baseURL}/images/event-placeholder.png` } eventsById[event.id] = event }) this.setState({ lastUpdate: DateTime.local(), events: data.data, eventsById, paging: data.paging, }) } catch (error) { apiErrorAlert(error) } } clearEvent = () => { this.setState({selectedEvent: {}}) } getEvent = async (id) => { try { const {data} = await server.events.read({id}) const ticketTypesById = {} if (!data.promo_image_url) { data.promo_image_url = `${baseURL}/images/event-placeholder.png` } data.ticket_types.forEach((ttype) => { ticketTypesById[ttype.id] = ttype }) this.setState({ selectedEvent: {...data}, ticketTypesById, }) } catch (error) { apiErrorAlert(error) } } changeLocation = (_index, {id}) => this.setState({selectedLocationId: id}) // allEvents will refresh all events (ie: from the index page), whereas setting it to false will refresh the interested event toggleInterest = async (event, singleEvent = false) => { const {user_is_interested, id} = event try { if (user_is_interested) { // User already interested, so delete it. const _response = await server.events.interests.remove({event_id: id}) } else { const _response = await server.events.interests.create({event_id: id}) } } catch (error) { apiErrorAlert(error, 'There was a problem selecting this event.') } finally { this.getEvents() if (singleEvent) { this.getEvent(id) } } } async replaceTicketType(ticket_type) { const {ticketTypesById} = this.state ticketTypesById[ticket_type.id] = ticket_type await this.setState({ticketTypesById}) } } export { EventsContainer, }
from jsonrpc import ServiceProxy access = ServiceProxy("http://127.0.0.1:21948") pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2)
/* ======================================================================== * Tutorial specific Javascript * * ======================================================================== * Copyright 2015 Bootbites.com (unless otherwise stated) * For license information see: http://bootbites.com/license * ======================================================================== */ var dropdownSelectors = $('.dropdown, .dropup'); // Custom function to read dropdown data // ========================= function dropdownEffectData(target) { // @todo - page level global? var effectInDefault = null, effectOutDefault = null; var dropdown = $(target), dropdownMenu = $('.dropdown-menu', target); var parentUl = dropdown.parents('ul.nav'); // If parent is ul.nav allow global effect settings if (parentUl.size() > 0) { effectInDefault = parentUl.data('dropdown-in') || null; effectOutDefault = parentUl.data('dropdown-out') || null; } return { target: target, dropdown: dropdown, dropdownMenu: dropdownMenu, effectIn: dropdownMenu.data('dropdown-in') || effectInDefault, effectOut: dropdownMenu.data('dropdown-out') || effectOutDefault, }; } // Custom function to start effect (in or out) // ========================= function dropdownEffectStart(data, effectToStart) { if (effectToStart) { data.dropdown.addClass('dropdown-animating'); data.dropdownMenu.addClass('animated'); data.dropdownMenu.addClass(effectToStart); } } // Custom function to read when animation is over // ========================= function dropdownEffectEnd(data, callbackFunc) { var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; data.dropdown.one(animationEnd, function() { data.dropdown.removeClass('dropdown-animating'); data.dropdownMenu.removeClass('animated'); data.dropdownMenu.removeClass(data.effectIn); data.dropdownMenu.removeClass(data.effectOut); // Custom callback option, used to remove open class in out effect if(typeof callbackFunc == 'function'){ callbackFunc(); } }); } // Bootstrap API hooks // ========================= dropdownSelectors.on({ "show.bs.dropdown": function () { // On show, start in effect var dropdown = dropdownEffectData(this); dropdownEffectStart(dropdown, dropdown.effectIn); }, "shown.bs.dropdown": function () { // On shown, remove in effect once complete var dropdown = dropdownEffectData(this); if (dropdown.effectIn && dropdown.effectOut) { dropdownEffectEnd(dropdown, function() {}); } }, "hide.bs.dropdown": function(e) { // On hide, start out effect var dropdown = dropdownEffectData(this); if (dropdown.effectOut) { e.preventDefault(); dropdownEffectStart(dropdown, dropdown.effectOut); dropdownEffectEnd(dropdown, function() { dropdown.dropdown.removeClass('open'); }); } }, });
# Copyright (c) 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ A filter middleware that inspects the requested URI for a version string and/or Accept headers and attempts to negotiate an API controller to return """ from oslo.config import cfg from murano.api import versions from murano.common import wsgi from murano.openstack.common.gettextutils import _ # noqa import murano.openstack.common.log as logging CONF = cfg.CONF LOG = logging.getLogger(__name__) class VersionNegotiationFilter(wsgi.Middleware): @classmethod def factory(cls, global_conf, **local_conf): def filter(app): return cls(app) return filter def __init__(self, app): self.versions_app = versions.Controller() super(VersionNegotiationFilter, self).__init__(app) def process_request(self, req): """Try to find a version first in the accept header, then the URL.""" msg = _("Determining version of request: %(method)s %(path)s" " Accept: %(accept)s") args = {'method': req.method, 'path': req.path, 'accept': req.accept} LOG.debug(msg % args) LOG.debug("Using url versioning") # Remove version in url so it doesn't conflict later req_version = self._pop_path_info(req) try: version = self._match_version_string(req_version) except ValueError: LOG.debug("Unknown version. Returning version choices.") return self.versions_app req.environ['api.version'] = version req.path_info = ''.join(('/v', str(version), req.path_info)) LOG.debug("Matched version: v%d", version) LOG.debug('new path %s' % req.path_info) return None def _match_version_string(self, subject): """Given a string, tries to match a major and/or minor version number. :param subject: The string to check :returns version found in the subject :raises ValueError if no acceptable version could be found """ if subject in ('v1',): major_version = 1 else: raise ValueError() return major_version def _pop_path_info(self, req): """'Pops' off the next segment of PATH_INFO, returns the popped segment. Do NOT push it onto SCRIPT_NAME. """ path = req.path_info if not path: return None while path.startswith('/'): path = path[1:] idx = path.find('/') if idx == -1: idx = len(path) r = path[:idx] req.path_info = path[idx:] return r
from flask import Blueprint example_ext: Blueprint = Blueprint("example", __name__, static_folder="static", template_folder="templates") from .views_api import * # noqa from .views import * # noqa
pkgname = "xtrans" pkgver = "1.4.0" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] pkgdesc = "Network API translation layer to insulate X" maintainer = "q66 <[email protected]>" license = "MIT" url = "https://xorg.freedesktop.org" source = f"$(XORG_SITE)/lib/{pkgname}-{pkgver}.tar.bz2" sha256 = "377c4491593c417946efcd2c7600d1e62639f7a8bbca391887e2c4679807d773" def post_install(self): self.install_license("COPYING")
Package.describe({ summary: "Base64 encoding and decoding", version: '1.0.2-ipc.0' }); Package.on_use(function (api) { api.export('Base64'); api.add_files('base64.js', ['client', 'server']); }); Package.on_test(function (api) { api.use('base64', ['client', 'server']); api.use(['tinytest', 'underscore', 'ejson']); api.add_files('base64_test.js', ['client', 'server']); });
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """RetinaNet configuration definition.""" import os from typing import List, Optional import dataclasses from official.core import config_definitions as cfg from official.core import exp_factory from official.modeling import hyperparams from official.modeling import optimization from official.vision.beta.configs import common from official.vision.beta.configs import decoders from official.vision.beta.configs import backbones # pylint: disable=missing-class-docstring @dataclasses.dataclass class TfExampleDecoder(hyperparams.Config): regenerate_source_id: bool = False @dataclasses.dataclass class TfExampleDecoderLabelMap(hyperparams.Config): regenerate_source_id: bool = False label_map: str = '' @dataclasses.dataclass class DataDecoder(hyperparams.OneOfConfig): type: Optional[str] = 'simple_decoder' simple_decoder: TfExampleDecoder = TfExampleDecoder() label_map_decoder: TfExampleDecoderLabelMap = TfExampleDecoderLabelMap() @dataclasses.dataclass class Parser(hyperparams.Config): num_channels: int = 3 match_threshold: float = 0.5 unmatched_threshold: float = 0.5 aug_rand_hflip: bool = False aug_scale_min: float = 1.0 aug_scale_max: float = 1.0 aug_policy: Optional[str] = None skip_crowd_during_training: bool = True max_num_instances: int = 100 @dataclasses.dataclass class DataConfig(cfg.DataConfig): """Input config for training.""" input_path: str = '' global_batch_size: int = 0 is_training: bool = False dtype: str = 'bfloat16' decoder: DataDecoder = DataDecoder() parser: Parser = Parser() shuffle_buffer_size: int = 10000 file_type: str = 'tfrecord' @dataclasses.dataclass class Anchor(hyperparams.Config): num_scales: int = 3 aspect_ratios: List[float] = dataclasses.field( default_factory=lambda: [0.5, 1.0, 2.0]) anchor_size: float = 4.0 @dataclasses.dataclass class Losses(hyperparams.Config): focal_loss_alpha: float = 0.25 focal_loss_gamma: float = 1.5 huber_loss_delta: float = 0.1 box_loss_weight: int = 50 l2_weight_decay: float = 0.0 @dataclasses.dataclass class AttributeHead(hyperparams.Config): name: str = '' type: str = 'regression' size: int = 1 @dataclasses.dataclass class RetinaNetHead(hyperparams.Config): num_convs: int = 4 num_filters: int = 256 use_separable_conv: bool = False attribute_heads: Optional[List[AttributeHead]] = None @dataclasses.dataclass class DetectionGenerator(hyperparams.Config): apply_nms: bool = True pre_nms_top_k: int = 5000 pre_nms_score_threshold: float = 0.05 nms_iou_threshold: float = 0.5 max_num_detections: int = 100 use_batched_nms: bool = False @dataclasses.dataclass class RetinaNet(hyperparams.Config): num_classes: int = 0 input_size: List[int] = dataclasses.field(default_factory=list) min_level: int = 3 max_level: int = 7 anchor: Anchor = Anchor() backbone: backbones.Backbone = backbones.Backbone( type='resnet', resnet=backbones.ResNet()) decoder: decoders.Decoder = decoders.Decoder( type='fpn', fpn=decoders.FPN()) head: RetinaNetHead = RetinaNetHead() detection_generator: DetectionGenerator = DetectionGenerator() norm_activation: common.NormActivation = common.NormActivation() @dataclasses.dataclass class ExportConfig(hyperparams.Config): output_normalized_coordinates: bool = False cast_num_detections_to_float: bool = False cast_detection_classes_to_float: bool = False @dataclasses.dataclass class RetinaNetTask(cfg.TaskConfig): model: RetinaNet = RetinaNet() train_data: DataConfig = DataConfig(is_training=True) validation_data: DataConfig = DataConfig(is_training=False) losses: Losses = Losses() init_checkpoint: Optional[str] = None init_checkpoint_modules: str = 'all' # all or backbone annotation_file: Optional[str] = None per_category_metrics: bool = False export_config: ExportConfig = ExportConfig() @exp_factory.register_config_factory('retinanet') def retinanet() -> cfg.ExperimentConfig: """RetinaNet general config.""" return cfg.ExperimentConfig( task=RetinaNetTask(), restrictions=[ 'task.train_data.is_training != None', 'task.validation_data.is_training != None' ]) COCO_INPUT_PATH_BASE = 'coco' COCO_TRAIN_EXAMPLES = 118287 COCO_VAL_EXAMPLES = 5000 @exp_factory.register_config_factory('retinanet_resnetfpn_coco') def retinanet_resnetfpn_coco() -> cfg.ExperimentConfig: """COCO object detection with RetinaNet.""" train_batch_size = 256 eval_batch_size = 8 steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size config = cfg.ExperimentConfig( runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'), task=RetinaNetTask( init_checkpoint='gs://cloud-tpu-checkpoints/vision-2.0/resnet50_imagenet/ckpt-28080', init_checkpoint_modules='backbone', annotation_file=os.path.join(COCO_INPUT_PATH_BASE, 'instances_val2017.json'), model=RetinaNet( num_classes=91, input_size=[640, 640, 3], norm_activation=common.NormActivation(use_sync_bn=False), min_level=3, max_level=7), losses=Losses(l2_weight_decay=1e-4), train_data=DataConfig( input_path=os.path.join(COCO_INPUT_PATH_BASE, 'train*'), is_training=True, global_batch_size=train_batch_size, parser=Parser( aug_rand_hflip=True, aug_scale_min=0.8, aug_scale_max=1.2)), validation_data=DataConfig( input_path=os.path.join(COCO_INPUT_PATH_BASE, 'val*'), is_training=False, global_batch_size=eval_batch_size)), trainer=cfg.TrainerConfig( train_steps=72 * steps_per_epoch, validation_steps=COCO_VAL_EXAMPLES // eval_batch_size, validation_interval=steps_per_epoch, steps_per_loop=steps_per_epoch, summary_interval=steps_per_epoch, checkpoint_interval=steps_per_epoch, optimizer_config=optimization.OptimizationConfig({ 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [ 57 * steps_per_epoch, 67 * steps_per_epoch ], 'values': [ 0.32 * train_batch_size / 256.0, 0.032 * train_batch_size / 256.0, 0.0032 * train_batch_size / 256.0 ], } }, 'warmup': { 'type': 'linear', 'linear': { 'warmup_steps': 500, 'warmup_learning_rate': 0.0067 } } })), restrictions=[ 'task.train_data.is_training != None', 'task.validation_data.is_training != None' ]) return config @exp_factory.register_config_factory('retinanet_spinenet_coco') def retinanet_spinenet_coco() -> cfg.ExperimentConfig: """COCO object detection with RetinaNet using SpineNet backbone.""" train_batch_size = 256 eval_batch_size = 8 steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size input_size = 640 config = cfg.ExperimentConfig( runtime=cfg.RuntimeConfig(mixed_precision_dtype='float32'), task=RetinaNetTask( annotation_file=os.path.join(COCO_INPUT_PATH_BASE, 'instances_val2017.json'), model=RetinaNet( backbone=backbones.Backbone( type='spinenet', spinenet=backbones.SpineNet( model_id='49', stochastic_depth_drop_rate=0.2, min_level=3, max_level=7)), decoder=decoders.Decoder( type='identity', identity=decoders.Identity()), anchor=Anchor(anchor_size=3), norm_activation=common.NormActivation( use_sync_bn=True, activation='swish'), num_classes=91, input_size=[input_size, input_size, 3], min_level=3, max_level=7), losses=Losses(l2_weight_decay=4e-5), train_data=DataConfig( input_path=os.path.join(COCO_INPUT_PATH_BASE, 'train*'), is_training=True, global_batch_size=train_batch_size, parser=Parser( aug_rand_hflip=True, aug_scale_min=0.1, aug_scale_max=2.0)), validation_data=DataConfig( input_path=os.path.join(COCO_INPUT_PATH_BASE, 'val*'), is_training=False, global_batch_size=eval_batch_size)), trainer=cfg.TrainerConfig( train_steps=500 * steps_per_epoch, validation_steps=COCO_VAL_EXAMPLES // eval_batch_size, validation_interval=steps_per_epoch, steps_per_loop=steps_per_epoch, summary_interval=steps_per_epoch, checkpoint_interval=steps_per_epoch, optimizer_config=optimization.OptimizationConfig({ 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [ 475 * steps_per_epoch, 490 * steps_per_epoch ], 'values': [ 0.32 * train_batch_size / 256.0, 0.032 * train_batch_size / 256.0, 0.0032 * train_batch_size / 256.0 ], } }, 'warmup': { 'type': 'linear', 'linear': { 'warmup_steps': 2000, 'warmup_learning_rate': 0.0067 } } })), restrictions=[ 'task.train_data.is_training != None', 'task.validation_data.is_training != None', 'task.model.min_level == task.model.backbone.spinenet.min_level', 'task.model.max_level == task.model.backbone.spinenet.max_level', ]) return config @exp_factory.register_config_factory('retinanet_mobile_coco') def retinanet_spinenet_mobile_coco() -> cfg.ExperimentConfig: """COCO object detection with mobile RetinaNet.""" train_batch_size = 256 eval_batch_size = 8 steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size input_size = 384 config = cfg.ExperimentConfig( runtime=cfg.RuntimeConfig(mixed_precision_dtype='float32'), task=RetinaNetTask( annotation_file=os.path.join(COCO_INPUT_PATH_BASE, 'instances_val2017.json'), model=RetinaNet( backbone=backbones.Backbone( type='spinenet_mobile', spinenet_mobile=backbones.SpineNetMobile( model_id='49', stochastic_depth_drop_rate=0.2, min_level=3, max_level=7, use_keras_upsampling_2d=False)), decoder=decoders.Decoder( type='identity', identity=decoders.Identity()), head=RetinaNetHead(num_filters=48, use_separable_conv=True), anchor=Anchor(anchor_size=3), norm_activation=common.NormActivation( use_sync_bn=True, activation='swish'), num_classes=91, input_size=[input_size, input_size, 3], min_level=3, max_level=7), losses=Losses(l2_weight_decay=3e-5), train_data=DataConfig( input_path=os.path.join(COCO_INPUT_PATH_BASE, 'train*'), is_training=True, global_batch_size=train_batch_size, parser=Parser( aug_rand_hflip=True, aug_scale_min=0.1, aug_scale_max=2.0)), validation_data=DataConfig( input_path=os.path.join(COCO_INPUT_PATH_BASE, 'val*'), is_training=False, global_batch_size=eval_batch_size)), trainer=cfg.TrainerConfig( train_steps=600 * steps_per_epoch, validation_steps=COCO_VAL_EXAMPLES // eval_batch_size, validation_interval=steps_per_epoch, steps_per_loop=steps_per_epoch, summary_interval=steps_per_epoch, checkpoint_interval=steps_per_epoch, optimizer_config=optimization.OptimizationConfig({ 'optimizer': { 'type': 'sgd', 'sgd': { 'momentum': 0.9 } }, 'learning_rate': { 'type': 'stepwise', 'stepwise': { 'boundaries': [ 575 * steps_per_epoch, 590 * steps_per_epoch ], 'values': [ 0.32 * train_batch_size / 256.0, 0.032 * train_batch_size / 256.0, 0.0032 * train_batch_size / 256.0 ], } }, 'warmup': { 'type': 'linear', 'linear': { 'warmup_steps': 2000, 'warmup_learning_rate': 0.0067 } } })), restrictions=[ 'task.train_data.is_training != None', 'task.validation_data.is_training != None', ]) return config
from django.contrib.syndication.views import Feed from django.conf import settings from django.urls import reverse from weblog.models import BlogPost, Translation, Category, CategoryTranslation from weblog.apps import SETTINGS as blog_settings from django.utils.translation import ugettext_lazy as _, pgettext_lazy from django.utils import translation import datetime class BlogFeed(Feed): def get_object(self, request, category_slug=None): self.current_language = translation.get_language() if self.current_language is None: self.current_language = settings.LANGUAGE_CODE if category_slug: if category_slug != 'misc': self.category = Category.objects.get(slug=category_slug) self.category_name = self.category.name if blog_settings['multilingual'] and category_slug != 'misc': category_translations = CategoryTranslation.objects.filter(category=self.category) if category_translations.count() > 0: for cat_trans in category_translations: if self.current_language[0:2] == cat_trans.language[0:2]: self.category_name = cat_trans elif category_slug == 'misc': self.category_name = pgettext_lazy('Posts without category', 'Uncategorized') return category_slug return None def title(self, obj): if obj: return _('%(blog_title)s\'s %(category_name)s RSS feed') % {'blog_title': blog_settings['blog_title'], 'category_name': self.category_name} return _('%(blog_title)s RSS feed') % {'blog_title': blog_settings['blog_title']} def link(self, obj): if obj: return reverse('weblog:CategoryIndex', kwargs={'category_slug': obj}) return reverse('weblog:Index') def description(self, obj): if obj: return _('Latest %(category_name)s blog posts on %(blog_title)s') % {'blog_title': blog_settings['blog_title'], 'category_name': self.category_name} return _('Latest blog posts on %(blog_title)s') % {'blog_title': blog_settings['blog_title']} def items(self, obj): now = datetime.datetime.now() if obj: return BlogPost.objects.filter(category__slug=obj, published=True, publish_date__lte=now).order_by('-publish_date')[:blog_settings['posts_per_page']] return BlogPost.objects.order_by('-publish_date').filter(published=True, publish_date__lte=now)[:blog_settings['posts_per_page']] def item_title(self, item): translation_exists = False post_translations = Translation.objects.filter(post=item) if post_translations.count() > 0 and blog_settings['multilingual']: orig_lang = item.original_language if len(orig_lang) < 2: orig_lang = settings.LANGUAGE_CODE[0:2] for post_translation in post_translations: if self.current_language[0:2] == post_translation.language[0:2]: return post_translation.title return item.title def item_pubdate(self, item): return item.publish_date def item_author_name(self, item): if blog_settings['show_author']: if blog_settings['use_authors_username']: return item.author.get_username() return item.author.get_full_name() return None def item_description(self, item): translation_exists = False post_translations = Translation.objects.filter(post=item) if post_translations.count() > 0 and blog_settings['multilingual']: orig_lang = item.original_language if len(orig_lang) < 2: orig_lang = settings.LANGUAGE_CODE[0:2] for post_translation in post_translations: if self.current_language[:2] == post_translation.language[:2]: return post_translation.content return item.content
''' Mingde's Matrix Mashup ''' def lambdamatrices(N): ''' Generates a lambda basis for an N-level quantum system, returns list of <N^2-1> NxN matrices (double-lists), each representing some basis vector for a traceless hamiltonian matrix ''' M = [] # generate the non-diagonal elements for r in range(1, N): for c in range(r): # imaginary hermitian matrix m = [[0] * N for i in range(N)] m[r][c] = complex(0, 1) m[c][r] = complex(0, -1) # real hermitiian matrix n = [[0] * N for i in range(N)] n[r][c] = 1 n[c][r] = 1 M.append(m) M.append(n) # generate the diagonal elements # N-1 matrices needed; traceless, hermitian for i in range(N-1): k = [[(1 if (r == c and r != i) else (-N+1 if r == c == i else 0)) for c in range(N)] for r in range(N)] # possibly the nastiest list comprehension you have ever seen # basically puts ones everywhere and another number to make sure # that the tr(k) = 0 M.append(k) return M def isHermitian(M): ''' checks if matrix is hermitian ''' N = len(M) for r in range(N): for c in range(N): if M[c][r] != complex(M[r][c].real, (-1)*M[r][c].imag): return False return True def tr(M): ''' Trace; sum of diagonals ''' return sum([M[i][i] for i in range(len(M))]) def mult(A, B): ''' Multiply 2 square matrices ''' N = len(A) result = [[0] * N for i in range(N)] for i in range(N): for j in range(N): for k in range(N): result[i][j] += A[i][k] * B[k][j] return result def showMTX(M): ''' Prints a square matrix in a somewhat tolerable format. ''' # tried to emulate numpy style print("Matrix[{0}][{0}]".format(len(M))) for r in M: for c in r: print(c, end="\t") print() print() def writeMTX(M, f): ''' Writes a square matrix to file. ''' f.write("Matrix[{0}][{0}]\n".format(len(M))) for r in M: for c in r: f.write(str(c)+"\t") f.write("\n") f.write("\n") def isBasisOrthonormal(B): for M in B: for N in ([i for i in B if i != M]): if tr(mult(M, N)): print("Offending matrices:") showMTX(M) showMTX(N) return False return True def isBasisHermitian(B): for M in B: if not isHermitian(M): return False return True if __name__ == "__main__": ''' Lets you choose some N, and will store the coorresponding matrices to a file. Also prints to screen if it's small enough. ''' inp = "" while inp != "-1": while not inp.isnumeric(): inp = input("N?\n") M = lambdamatrices(eval(inp)) with open("{0}x{0}.txt".format(eval(inp)), "w") as f: for m in M: writeMTX(m,f) if eval(inp) < 10: for m in M: showMTX(m) print("Hermitian? {}\nOrthonormal? {}".format(isBasisHermitian(M), isBasisOrthonormal(M))) inp = ""
(window.OnFileBrowserReady=function(){"TInterface"in window&&"adminscreen"in TInterface?TInterface.adminscreen.AddPanel(4,"File Browser",function(){this.TransitionTo("<div>...</div>",function(a){})}):window.setTimeout(window.OnFileBrowserReady,50)})();
#!/usr/bin/env node // Build site const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const { execSync } = require("child_process"); const html_minify = require("html-minifier").minify; const css_minify = new (require("clean-css"))({ level: 2 }); const js_minify = require("uglify-js").minify; const svg_minify = require("svgo").optimize; const json_minify = require("jsonminify"); const html_parser = require("node-html-parser").parse; const SRC_DIR = path.join(__dirname, "../src"); const BUILD_DIR = path.join(__dirname, "../build"); const DOMAIN = "https://douile.com"; const APP_PAGES = ["/", "/projects/", "/activity/", "/contact/"]; const htmlFiles = []; const fileIntegrity = new Map(); if (!fs.existsSync(SRC_DIR)) { console.error(`"${SRC_DIR}" does not exist`); process.exit(1); } if (fs.existsSync(BUILD_DIR)) { if (fs.statSync(BUILD_DIR).isDirectory()) { fs.rmSync(BUILD_DIR, { recursive: true }); } else { console.error(`"${BUILD_DIR}" is not a directory`); process.exit(1); } } console.log("Copying/minifying files..."); fs.mkdirSync(BUILD_DIR); // Copy files function copyDir(source, dest) { for (let ent of fs.readdirSync(source, { withFileTypes: true })) { if (ent.isFile()) { copyFile(source, dest, ent); } else if (ent.isDirectory()) { const dir = path.join(dest, ent.name); fs.mkdirSync(dir); copyDir(path.join(source, ent.name), dir); } } } function copyFile(src, dest, ent) { let fileType = ent.name.match(/.+\.([^\.]+)$/); fileType = fileType.length > 1 ? fileType[1] : null; src = path.join(src, ent.name); dest = path.join(dest, ent.name); switch (fileType) { case "html": { fs.writeFileSync( dest, html_minify(fs.readFileSync(src, { encoding: "utf8" }), { collapseBooleanAttributes: true, collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true, useShortDoctype: true, }) ); htmlFiles.push(dest); break; } case "css": { fs.writeFileSync( dest, css_minify.minify(fs.readFileSync(src, { encoding: "utf8" })).styles ); saveIntegrity(dest); break; } case "js": { fs.writeFileSync( dest, js_minify(fs.readFileSync(src, { encoding: "utf8" }), { v8: true, webkit: true, }).code ); saveIntegrity(dest); break; } case "svg": { fs.writeFileSync( dest, svg_minify(fs.readFileSync(src, { encoding: "utf8" }), { multipass: true, }).data ); break; } case "json": { fs.writeFileSync( dest, json_minify(fs.readFileSync(src, { encoding: "utf8" })) ); break; } default: { fs.copyFileSync(src, dest); break; } } } function relativePath(base, file) { return "/" + path.normalize(path.relative(base, file)); } function saveIntegrity(file) { const hash = crypto.createHash("sha512"); hash.update(fs.readFileSync(file)); fileIntegrity.set( relativePath(BUILD_DIR, file), "sha512-" + hash.digest("base64") ); } copyDir(SRC_DIR, BUILD_DIR); const version = execSync("git log -n 1 --format=\"%h\"").toString().trim(); console.log(`Adding script integrities (${version})`); const sitemap = []; for (let file of htmlFiles) { console.log(file); const html = html_parser(fs.readFileSync(file, { encoding: "utf8" })); for (let script of html.querySelectorAll("script")) { const src = script.getAttribute("src"); if (fileIntegrity.has(src)) { script.setAttribute("integrity", fileIntegrity.get(src)); script.setAttribute("src", src + `?v=${version}`); } } for (let style of html.querySelectorAll("link[rel=stylesheet]")) { const href = style.getAttribute("href"); if (fileIntegrity.has(href)) { style.setAttribute("integrity", fileIntegrity.get(href)); style.setAttribute("href", href + `?v=${version}`); } } if (path.basename(file) === "index.html") { const dir = path.dirname(file); const body = html.querySelector("body"); for (let page of APP_PAGES) { body.setAttribute("data-page", page); let prio = 1; if (page === "/") { fs.writeFileSync(path.join(dir, "index.html"), html.toString()); } else { const pagePath = path.join(dir, page.substring(1)); fs.mkdirSync(pagePath, { recursive: true }); fs.writeFileSync(path.join(pagePath, "index.html"), html.toString()); prio = 0.8; } sitemap.push({ loc: DOMAIN + page, priority: prio }); } } else { fs.writeFileSync(file, html.toString()); sitemap.push({ loc: DOMAIN + "/" + path.relative(BUILD_DIR, file), priority: 0.5, }); } } const now = new Date().toISOString(); fs.writeFileSync( path.join(BUILD_DIR, "sitemap.xml"), `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">` + sitemap .map( (p) => `<url><loc>${p.loc}</loc><lastmod>${now}</lastmod><priority>${p.priority}</priority></url>` ) .join("") + `</urlset>` );
# 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. import os import torch def save_checkpoint(state, checkpoint='checkpoint', filename='checkpoint.pth.tar'): filepath = os.path.join(checkpoint, filename) torch.save(state, filepath) def save_model(args, epoch, model, optimizer, lr_scheduler, is_best): if args.teacher_image_arch and args.teacher_text_arch: model_to_save = model.module.student else: model_to_save = model.module save_dict = {'epoch': epoch + 1, 'state_dict': model_to_save.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'args': vars(args)} save_checkpoint(save_dict, checkpoint=args.output_dir, filename="last.pth.tar") if is_best: save_checkpoint(save_dict, checkpoint=args.output_dir, filename="best.pth.tar")
#pragma once /* Copyright (C) 2018 Pharap (@Pharap) 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. */ #include <stdint.h> // // Declarations // template< typename Type, uint8_t Capacity > class Array; template< typename Type, uint8_t CapacityValue > class Array { public: // // Constraints // static_assert(CapacityValue > 0, "Attempt to create Array with a capacity less than 1"); static_assert(CapacityValue < 128, "Attempt to create Array with a capacity greater than 127"); // // Type Aliases // using ValueType = Type; using SizeType = uint8_t; using IndexType = uint8_t; using IndexOfType = int8_t; // // Constants // constexpr static const SizeType Capacity = CapacityValue; constexpr static const IndexType FirstIndex = 0; constexpr static const IndexType LastIndex = Capacity - 1; constexpr static const IndexOfType InvalidIndex = -1; private: // // Member Variables // ValueType items[Capacity] = {}; public: // // Common Member Functions // // O(1) constexpr bool isEmpty(void) const noexcept { return false; } // O(1) constexpr bool isFull(void) const noexcept { return true; } // O(1) constexpr SizeType getCount(void) const noexcept { return Capacity; } // O(1) constexpr SizeType getCapacity(void) const noexcept { return Capacity; } // O(1) /*constexpr*/ ValueType * getData(void) noexcept { return &this->items[FirstIndex]; } // O(1) constexpr const ValueType * getData(void) const noexcept { return &this->items[FirstIndex]; } // O(1) ValueType & operator [](const IndexType & index) { return this->items[index]; } // O(1) const ValueType & operator [](const IndexType & index) const { return this->items[index]; } // O(N) void clear(void); // O(N) void fill(const ValueType & item); // O(N) bool contains(const ValueType & item) const; // O(N) IndexOfType indexOfFirst(const ValueType & item) const; // O(N) IndexOfType indexOfLast(const ValueType & item) const; }; // // Definition // // O(N) template< typename Type, uint8_t Capacity > void Array<Type, Capacity>::clear(void) { for (IndexType i = 0; i < this->getCount(); ++i) this->items[i].~ValueType(); } // O(N) template< typename Type, uint8_t Capacity > void Array<Type, Capacity>::fill(const ValueType & item) { for (IndexType i = 0; i < this->getCount(); ++i) this->items[i] = item; } // O(N) template< typename Type, uint8_t Capacity > bool Array<Type, Capacity>::contains(const ValueType & item) const { for (IndexType i = 0; i < this->getCount(); ++i) if (this->items[i] == item) return true; return false; } // O(N) template< typename Type, uint8_t Capacity > auto Array<Type, Capacity>::indexOfFirst(const ValueType & item) const -> IndexOfType { for (IndexType i = 0; i < this->getCount(); ++i) if (this->items[i] == item) return i; return InvalidIndex; } // O(N) template< typename Type, uint8_t Capacity > auto Array<Type, Capacity>::indexOfLast(const ValueType & item) const -> IndexOfType { for (IndexType i = this->getCount() - 1; i > 0; --i) if (this->items[i] == item) return i; return InvalidIndex; } // // Empty Array // template< typename Type > class Array<Type, 0> { public: // // Type Aliases // using ValueType = Type; using SizeType = uint8_t; using IndexType = uint8_t; using IndexOfType = int8_t; // // Constants // constexpr static const SizeType Capacity = 0; constexpr static const IndexOfType InvalidIndex = -1; public: // // Common Member Functions // // O(1) constexpr bool isEmpty(void) const noexcept { return true; } // O(1) constexpr bool isFull(void) const noexcept { return true; } // O(1) constexpr SizeType getCount(void) const noexcept { return 0; } // O(1) constexpr SizeType getCapacity(void) const noexcept { return 0; } // O(1) /*constexpr*/ ValueType * getData(void) noexcept { return nullptr; } // O(1) constexpr const ValueType * getData(void) const noexcept { return nullptr; } // O(1) /*constexpr*/ ValueType & operator [](const IndexType & index) = delete; // O(1) constexpr const ValueType & operator [](const IndexType & index) const = delete; // O(1) constexpr void clear(void) noexcept { } // O(1) constexpr void fill(void) noexcept { } // O(1) constexpr bool contains(const ValueType & item) const noexcept { return false; } // O(1) constexpr IndexOfType indexOfFirst(const ValueType & item) const noexcept { return InvalidIndex; } // O(1) constexpr IndexOfType indexOfLast(const ValueType & item) const noexcept { return InvalidIndex; } };
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TASK_SEQUENCE_MANAGER_WORK_QUEUE_H_ #define BASE_TASK_SEQUENCE_MANAGER_WORK_QUEUE_H_ #include "base/base_export.h" #include "base/task/common/intrusive_heap.h" #include "base/task/sequence_manager/enqueue_order.h" #include "base/task/sequence_manager/sequenced_task_source.h" #include "base/task/sequence_manager/task_queue_impl.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/traced_value.h" namespace base { namespace sequence_manager { namespace internal { class WorkQueueSets; // This class keeps track of immediate and delayed tasks which are due to run // now. It interfaces deeply with WorkQueueSets which keeps track of which queue // (with a given priority) contains the oldest task. // // If a fence is inserted, WorkQueue behaves normally up until // TakeTaskFromWorkQueue reaches or exceeds the fence. At that point it the // API subset used by WorkQueueSets pretends the WorkQueue is empty until the // fence is removed. This functionality is a primitive intended for use by // throttling mechanisms. class BASE_EXPORT WorkQueue { public: using QueueType = internal::TaskQueueImpl::WorkQueueType; // Note |task_queue| can be null if queue_type is kNonNestable. WorkQueue(TaskQueueImpl* task_queue, const char* name, QueueType queue_type); ~WorkQueue(); // Associates this work queue with the given work queue sets. This must be // called before any tasks can be inserted into this work queue. void AssignToWorkQueueSets(WorkQueueSets* work_queue_sets); // Assigns the current set index. void AssignSetIndex(size_t work_queue_set_index); void AsValueInto(TimeTicks now, trace_event::TracedValue* state) const; // Returns true if the |tasks_| is empty. This method ignores any fences. bool Empty() const { return tasks_.empty(); } // If the |tasks_| isn't empty and a fence hasn't been reached, // |enqueue_order| gets set to the enqueue order of the front task and the // function returns true. Otherwise the function returns false. bool GetFrontTaskEnqueueOrder(EnqueueOrder* enqueue_order) const; // Returns the first task in this queue or null if the queue is empty. This // method ignores any fences. const Task* GetFrontTask() const; // Returns the last task in this queue or null if the queue is empty. This // method ignores any fences. const Task* GetBackTask() const; // Pushes the task onto the |tasks_| and if a fence hasn't been reached // it informs the WorkQueueSets if the head changed. void Push(Task task); // RAII helper that helps efficiently push N Tasks to a WorkQueue. class BASE_EXPORT TaskPusher { public: TaskPusher(const TaskPusher&) = delete; TaskPusher(TaskPusher&& other); ~TaskPusher(); void Push(Task* task); private: friend class WorkQueue; explicit TaskPusher(WorkQueue* work_queue); WorkQueue* work_queue_; const bool was_empty_; }; // Returns an RAII helper to efficiently push multiple tasks. TaskPusher CreateTaskPusher(); // Pushes the task onto the front of the |tasks_| and if it's before any // fence it informs the WorkQueueSets the head changed. Use with caution this // API can easily lead to task starvation if misused. void PushNonNestableTaskToFront(Task task); // Reloads the empty |tasks_| with // |task_queue_->TakeImmediateIncomingQueue| and if a fence hasn't been // reached it informs the WorkQueueSets if the head changed. void TakeImmediateIncomingQueueTasks(); size_t Size() const { return tasks_.size(); } size_t Capacity() const { return tasks_.capacity(); } // Pulls a task off the |tasks_| and informs the WorkQueueSets. If the // task removed had an enqueue order >= the current fence then WorkQueue // pretends to be empty as far as the WorkQueueSets is concerned. Task TakeTaskFromWorkQueue(); // Removes all canceled tasks from the head of the list. Returns true if any // tasks were removed. bool RemoveAllCanceledTasksFromFront(); const char* name() const { return name_; } TaskQueueImpl* task_queue() const { return task_queue_; } WorkQueueSets* work_queue_sets() const { return work_queue_sets_; } size_t work_queue_set_index() const { return work_queue_set_index_; } base::internal::HeapHandle heap_handle() const { return heap_handle_; } void set_heap_handle(base::internal::HeapHandle handle) { heap_handle_ = handle; } QueueType queue_type() const { return queue_type_; } // Returns true if the front task in this queue has an older enqueue order // than the front task of |other_queue|. Both queue are assumed to be // non-empty. This method ignores any fences. bool ShouldRunBefore(const WorkQueue* other_queue) const; // Submit a fence. When TakeTaskFromWorkQueue encounters a task whose // enqueue_order is >= |fence| then the WorkQueue will start pretending to be. // empty. // Inserting a fence may supersede a previous one and unblock some tasks. // Returns true if any tasks where unblocked, returns false otherwise. bool InsertFence(EnqueueOrder fence); // Submit a fence without triggering a WorkQueueSets notification. // Caller must ensure that WorkQueueSets are properly updated. // This method should not be called when a fence is already present. void InsertFenceSilently(EnqueueOrder fence); // Removes any fences that where added and if WorkQueue was pretending to be // empty, then the real value is reported to WorkQueueSets. Returns true if // any tasks where unblocked. bool RemoveFence(); // Returns true if any tasks are blocked by the fence. Returns true if the // queue is empty and fence has been set (i.e. future tasks would be blocked). // Otherwise returns false. bool BlockedByFence() const; // Shrinks |tasks_| if it's wasting memory. void MaybeShrinkQueue(); // Delete all tasks within this WorkQueue. void DeletePendingTasks(); // Test support function. This should not be used in production code. void PopTaskForTesting(); // Iterates through |tasks_| adding any that are older than |reference| to // |result|. void CollectTasksOlderThan(EnqueueOrder reference, std::vector<const Task*>* result) const; private: bool InsertFenceImpl(EnqueueOrder fence); TaskQueueImpl::TaskDeque tasks_; WorkQueueSets* work_queue_sets_ = nullptr; // NOT OWNED. TaskQueueImpl* const task_queue_; // NOT OWNED. size_t work_queue_set_index_ = 0; // Iff the queue isn't empty (or appearing to be empty due to a fence) then // |heap_handle_| will be valid and correspond to this queue's location within // an IntrusiveHeap inside the WorkQueueSet. base::internal::HeapHandle heap_handle_; const char* const name_; EnqueueOrder fence_; const QueueType queue_type_; DISALLOW_COPY_AND_ASSIGN(WorkQueue); }; } // namespace internal } // namespace sequence_manager } // namespace base #endif // BASE_TASK_SEQUENCE_MANAGER_WORK_QUEUE_H_
from typing import Tuple from chiavdf import prove from ecostake.consensus.constants import ConsensusConstants from ecostake.types.blockchain_format.classgroup import ClassgroupElement from ecostake.types.blockchain_format.sized_bytes import bytes32 from ecostake.types.blockchain_format.vdf import VDFInfo, VDFProof from ecostake.util.ints import uint8, uint64 def get_vdf_info_and_proof( constants: ConsensusConstants, vdf_input: ClassgroupElement, challenge_hash: bytes32, number_iters: uint64, normalized_to_identity: bool = False, ) -> Tuple[VDFInfo, VDFProof]: form_size = ClassgroupElement.get_size(constants) result: bytes = prove( bytes(challenge_hash), vdf_input.data, constants.DISCRIMINANT_SIZE_BITS, number_iters, ) output = ClassgroupElement.from_bytes(result[:form_size]) proof_bytes = result[form_size : 2 * form_size] return VDFInfo(challenge_hash, number_iters, output), VDFProof(uint8(0), proof_bytes, normalized_to_identity)
define( "dojo/cldr/nls/ko/currency", //begin v1.x content { "AUD_displayName": "호주 달러", "CAD_displayName": "캐나다 달러", "CHF_displayName": "스위스 프랑", "CNY_displayName": "중국 위안 인민폐", "EUR_displayName": "유로화", "GBP_displayName": "영국령 파운드 스털링", "HKD_displayName": "홍콩 달러", "JPY_displayName": "일본 엔화", "USD_displayName": "미국 달러" } //end v1.x content );
function Min (A, B) { let Result = A; if (B < A) { Result = B; } return Result; } function IsNewline (Char) { return ((Char == '\n') || (Char == '\r')); } function TokensEqual (ContentsFile, Index, Token) { let Start = Index; let End = Min(Index + Token.length, ContentsFile.length); let Result = true; for (let i = Start; i < End; i++) { if (ContentsFile[i] != Token[i - Start]) { Result = false; break; } } return Result; } function PutBreaksAtNewLines (String) { let Result = String; for (let i = 0; i < Result.length; i++) { if (IsNewline(Result[i])) { Result = InsertStringInString(Result, "<br /><br />", i + 1); } } return Result; } const TitleIdentifier = "title:"; const SectionIdentifier = "section_title:"; const BodyIdentifier = "section_body:"; const ImageIdentifier = "image:"; const VideoIdentifier = "video:"; const VideoURLIdentifier = "video_link:" function SafeGetTokenValueLengths (Contents, Start, Token) { let Result = {Start: Start + Token.length, End: -1}; for (let i = Result.Start; i < Contents.length; i++) { if (Contents[i] == ';') { Result.End = i; break; } } if (Result.End == -1) { Result.End = Contents.length; } return Result; } function ParseContents (ContentsFile) { let Result = { Title: "", Sections: []}; let TitleStart = -1; let TitleEnd = -1; for (let i = 0; i < ContentsFile.length; i++) { let ValueRange = {Start: -1, End: -1}; if (TokensEqual(ContentsFile, i, TitleIdentifier)) { console.log("Parsing Title"); i += TitleIdentifier.length; let TitleStart = i; while (ContentsFile[i] != ';') { i++; } let TitleEnd = i; Result.Title = ContentsFile.substring(TitleStart, TitleEnd); } else if(TokensEqual(ContentsFile, i, SectionIdentifier)) { console.log("Parsing Section"); ValueRange = SafeGetTokenValueLengths(ContentsFile, i, SectionIdentifier); let SectionTitle = ContentsFile.substring(ValueRange.Start, ValueRange.End); SectionTitle = PutBreaksAtNewLines(SectionTitle); Result.Sections.push({Title: SectionTitle, Body: ""}); } else if (TokensEqual(ContentsFile, i, BodyIdentifier)) { console.log("Parsing Body"); ValueRange = SafeGetTokenValueLengths(ContentsFile, i, BodyIdentifier); if (Result.Sections.length == 0) { Result.Sections.push({Title: "", Body: ""}); } let SectionBody = ContentsFile.substring(ValueRange.Start, ValueRange.End); SectionBody = PutBreaksAtNewLines(SectionBody); Result.Sections[Result.Sections.length - 1].Body = SectionBody; } else if (TokensEqual(ContentsFile, i, ImageIdentifier)) { console.log("Parsing Image"); ValueRange = SafeGetTokenValueLengths(ContentsFile, i, ImageIdentifier); let ImagePath = ContentsFile.substring(ValueRange.Start, ValueRange.End); Result.Sections.push({Image: ImagePath}); } else if (TokensEqual(ContentsFile, i, VideoIdentifier)) { console.log("Parsing Video"); ValueRange = SafeGetTokenValueLengths(ContentsFile, i, VideoIdentifier); let VideoPath = ContentsFile.substring(ValueRange.Start, ValueRange.End); Result.Sections.push({Video: VideoPath}); } else if (TokensEqual(ContentsFile, i, VideoURLIdentifier)) { console.log("Parsing Link"); ValueRange = SafeGetTokenValueLengths(ContentsFile, i, VideoURLIdentifier); let VideoPath = ContentsFile.substring(ValueRange.Start, ValueRange.End); Result.Sections.push({VideoLink: VideoPath}); } if (ValueRange.End >= 0) { i = ValueRange.End; } } return Result; }
from DAEpy.solvers.ocp import ocp_solver import os import argparse import numpy as np import matplotlib.pyplot as plt """ This is a simple demonstration of the proposed method for solving index 1 differential algebraic equations. In this example a first order reaction is used, for which there is an explicit solution. A + B -> C dCa/dt = -r dCb/dt = -r dCc/dt = +r r - CaCb = 0 x = c with length 3 u = r with length 1 """ def f(x,y,t): return np.array([-y[0], -y[0], y[0]], dtype=np.float64) def g(x,y,t): return np.array([y[0]-x[0]*x[1]], dtype=np.float64) def gy(x,y,t): tmp = np.array([[1.0]]) return np.repeat(tmp[...,np.newaxis],len(t),-1) def fy(x,y,t): tmp = np.array([[-1.0], [-1.0], [1.0]]) return np.repeat(tmp[...,np.newaxis],len(t),-1) def gx(x,y,t): return np.array([[-x[1], -x[0], [0]*len(t)]]) def fx(x,y,t): tmp = np.array([[0,0,0],[0,0,0],[0,0,0]]) return np.repeat(tmp[..., np.newaxis],len(t),-1) def c_exact(t): return np.array([1.0/(1.0+t), 1.0/(1.0+t), t/(1.0+t)]) def L(x,u,t): G = g(x,u,t) return np.einsum('ij...,ij...->j...', G, G) def Lx(x,u,t): G = g(x,u,t) Gx = gx(x,u,t) return 2*np.einsum('i...,i...->...', G, Gx) def Lu(x,u,t): G = g(x,u,t) Gu = gy(x,u,t) return 2*np.einsum('i...,i...->...', G, Gu) if __name__ == "__main__": """ Parse the command line arguments. """ parser = argparse.ArgumentParser(description="Parse example arguments.") parser.add_argument('--folder', default=None, type=str, dest='folder') args = parser.parse_args() """ Perform the calculations. """ numt = 500 numx = 3 numy = 1 t = np.linspace(0,1,numt, dtype=np.float64) x = np.ones((numx, numt), dtype=np.float64) y = np.ones((numy, numt), dtype=np.float64) x0 = np.array([1.0,1.0,0.0], dtype=np.float64) w = 0.5 m = 1.0e5 sol = ocp_solver(L, f, x, y, t, x0, m, Lx=Lx, Lu=Lu, fx=fx, fu=fy, verbose = 2, tol = 1e-4, max_nodes = 10000) plt.rc('text', usetex=True) f1, ax1 = plt.subplots(2,figsize=(10,7)) ax1[0].set_xlabel("t") ax1[0].set_ylabel("Concentrations") ax1[0].plot(sol.t, sol.x.T) ax1[1].set_xlabel("t") ax1[1].set_ylabel("RMS Residuals") ax1[1].plot(sol.t[1:], sol.rms_residuals) ax1[1].set_ylim([0,2e-8]) f2, ax2 = plt.subplots(2,figsize=(10,7)) ax2[0].set_xlabel("t") ax2[0].set_ylabel("Absolute Error") ax2[0].plot(sol.t, sol.x.T - c_exact(sol.t).T) ax2[1].set_xlabel("t") ax2[1].set_ylabel("Relative Error") ax2[1].plot(sol.t[1:], (sol.x.T - c_exact(sol.t).T)[1:]/c_exact(sol.t).T[1:]) f3, ax3 = plt.subplots(2,figsize=(10,7)) ax3[0].set_xlabel("t") ax3[0].set_ylabel(r"$H$") ax3[0].plot(sol.t, sol.h.T) ax3[1].set_xlabel("t") ax3[1].set_ylabel(r"$ ||\nabla H ||_{\infty}$") ax3[1].plot(sol.t, sol.hu_norm) if args.folder: f1.savefig(os.path.join(args.folder, "index_one_I_variables.png")) f2.savefig(os.path.join(args.folder, "index_one_I_errors.png")) f3.savefig(os.path.join(args.folder, "index_one_I_hamiltonian.png")) else: print("Showing") plt.show()
import logging import importlib.util from typing import Optional, Union, List, Dict logger = logging.getLogger(__name__) def is_wandb_available(): return importlib.util.find_spec("wandb") is not None class WandbLogger(object): """Weights & Biases Logger. This is a logger class that can be passed into the initialization of a KerasModel or TorchModel. It initializes and sets up a wandb logger which will log the specified metrics calculated on the specific datasets to the user's W&B dashboard. If a WandbLogger is provided to the wandb_logger flag, the metrics are logged to Weights & Biases, along with other information such as epoch number, losses, sample counts, and model configuration data. """ def __init__(self, name: Optional[str] = None, entity: Optional[str] = None, project: Optional[str] = "deepchem", mode: Optional[str] = "online", id: Optional[str] = None, resume: Optional[Union[bool, str]] = None, anonymous: Optional[str] = "never", save_run_history: Optional[bool] = False, **kwargs): """Creates a WandbLogger. Parameters ---------- name: str a display name for the run in the W&B dashboard entity: str an entity is a username or team name where you're sending the W&B run project: str the name of the project where you're sending the new W&B run mode: str W&B online or offline mode id: str a unique ID for this run, used for resuming resume: bool or str sets the resuming behavior anonymous: str controls anonymous data logging save_run_history: bool whether to save the run history to the logger at the end (for testing purposes) """ assert is_wandb_available( ), "WandbLogger requires wandb to be installed. Please run `pip install wandb --upgrade`" import wandb self._wandb = wandb if mode == "offline": logger.warning( 'Note: Model checkpoints will not be uploaded to W&B in offline mode.\n' 'Please set `mode="online"` if you need to log your model.') self.save_run_history = save_run_history # set wandb init arguments self.wandb_init_params = dict( name=name, project=project, entity=entity, mode=mode, id=id, resume=resume, anonymous=anonymous) self.wandb_init_params.update(**kwargs) self.initialized = False # Dataset ids are used to differentiate datasets seen by the logger self.dataset_ids: List[Union[int, str]] = [] def setup(self): """Initializes a W&B run and create a run object. If a pre-existing run is already initialized, use that instead. """ if self._wandb.run is None: self.wandb_run = self._wandb.init(**self.wandb_init_params) else: self.wandb_run = self._wandb.run self.initialized = True def log_data(self, data: Dict, step: int, dataset_id: Optional[Union[int, str]] = None): """Log data to W&B. Parameters ---------- data: dict the data to be logged to W&B step: int the step number at which the data is to be logged dataset_id: int or str, optional (default None) the unique id of the dataset to differentiate during logging. Typically used when there are multiple ValidationCallbacks with different datasets. """ if dataset_id is not None: if dataset_id in self.dataset_ids: for key in list(data.keys()): idx = self.dataset_ids.index(dataset_id) new_key = str(key) + "_(" + str(idx) + ")" data[new_key] = data.pop(key) else: self.dataset_ids.append(dataset_id) for key in list(data.keys()): idx = self.dataset_ids.index(dataset_id) new_key = str(key) + "_(" + str(idx) + ")" data[new_key] = data.pop(key) # log data self.wandb_run.log(data, step=step) def finish(self): """Finishes and closes the W&B run. Save run history data as field if configured to do that. """ if self.save_run_history: history = self.wandb_run.history._data self.run_history = history if self.wandb_run is not None: self.wandb_run.finish() def update_config(self, config_data): """Updates the W&B configuration. Parameters ---------- config_data: dict additional configuration data to add """ self.wandb_run.config.update(config_data)
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }());