text
stringlengths
3
1.05M
import test from '../utils/testing'; import Alert from './Alert'; test('Alert', ({ mount }) => { it('should be show by default', async () => { const wrapper = mount(Alert, {}); expect(wrapper.html()).toMatchSnapshot(); }); it('should be delete', async () => { const wrapper = mount(Alert, { propsData: { delete: true }}); const deleteBtn = wrapper.find('.mu-alert-delete-btn')[0]; const handleDelete = jest.fn(); wrapper.vm.$on('delete', handleDelete); deleteBtn.trigger('click'); expect(handleDelete).toBeCalledWith(); }); it('should be set color', async () => { const wrapper = mount(Alert, { propsData: { color: 'primary' } }); expect(wrapper.html()).toMatchSnapshot(); wrapper.setProps({ color: 'error' }); expect(wrapper.html()).toMatchSnapshot(); wrapper.setProps({ color: '#fff' }); expect(wrapper.hasStyle('background-color', '#fff')).toEqual(true); }); });
const express = require('express') const bodyParser = require('body-parser') const cookieParser = require('cookie-parser') const multipart = require('connect-multiparty') const webpack = require('webpack') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackHotMiddleware = require('webpack-hot-middleware') const WebpackConfig = require('./webpack.config') const path = require('path') const atob = require('atob') require('./server2') const app = express() const compiler = webpack(WebpackConfig) app.use(webpackDevMiddleware(compiler, { publicPath: '/__build__/', stats: { colors: true, chunks: false } })) app.use(webpackHotMiddleware(compiler)) app.use(express.static(__dirname, { setHeaders(res) { res.cookie('XSRF-TOKEN-D', '1234abc') } })) app.use(express.static(__dirname)) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(cookieParser()) app.use(multipart({ uploadDir: path.resolve(__dirname, 'upload-file') })) const router = express.Router() registerSimpleRouter() registerBaseRouter() registerErrorRouter() registerExtendRouter() registerInterceptorRouter() registerConfigRouter() registerCancelRouter() registerMoreRouter() function registerSimpleRouter() { router.get('/simple/get', function(req, res) { res.json({ msg: `hello world` }) }) } function registerBaseRouter() { router.get('/base/get', function(req, res) { res.json(req.query) }) router.post('/base/post', function(req, res) { res.json(req.body) }) router.post('/base/buffer', function(req, res) { let msg = [] req.on('data', (chunk) => { if (chunk) { msg.push(chunk) } }) req.on('end', () => { const buf = Buffer.concat(msg) res.json(buf.toJSON()) }) }) } function registerErrorRouter() { router.get('/error/get', function(req, res) { if (Math.random() > 0.5) { res.json({ msg: `hello world` }) } else { res.status(500) res.end() } }) router.get('/error/timeout', function(req, res) { setTimeout(() => { res.json({ msg: `hello world` }) }, 3000) }) } function registerExtendRouter() { router.get('/extend/get', function(req, res) { res.json({ msg: 'hello world' }) }) router.options('/extend/options', function(req, res) { res.end() }) router.delete('/extend/delete', function(req, res) { res.end() }) router.head('/extend/head', function(req, res) { res.end() }) router.post('/extend/post', function(req, res) { res.json(req.body) }) router.put('/extend/put', function(req, res) { res.json(req.body) }) router.patch('/extend/patch', function(req, res) { res.json(req.body) }) router.get('/extend/user', function(req, res) { res.json({ code: 0, message: 'ok', result: { name: 'jack', age: 18 } }) }) } function registerInterceptorRouter() { router.get('/interceptor/get', function(req, res) { res.end('hello') }) } function registerConfigRouter() { router.post('/config/post', function(req, res) { res.json(req.body) }) } function registerCancelRouter() { router.get('/cancel/get', function(req, res) { setTimeout(() => { res.json('hello') }, 1000) }) router.post('/cancel/post', function(req, res) { setTimeout(() => { res.json(req.body) }, 1000) }) } function registerMoreRouter() { router.get('/more/get', function(req, res) { res.json(req.cookies) }) router.post('/more/upload', function(req, res) { console.log(req.body, req.files) res.end('upload success!') }) router.post('/more/post', function(req, res) { const auth = req.headers.authorization const [type, credentials] = auth.split(' ') console.log(auth) console.log(atob(credentials)) const [username, password] = atob(credentials).split(':') if (type === 'Basic' && username === 'Yee' && password === '123456') { res.json(res.body) } else { res.status(401) res.end('UnAuthorization') } }) router.get('/more/304', function(req, res) { res.status(304) res.end() }) router.get('/more/A', function(req, res) { res.end('A') }) router.get('/more/B', function(req, res) { res.end('B') }) } app.use(router) const port = process.env.PORT || 8080 module.exports = app.listen(port, () => { console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`) })
module.exports={A:{A:{"2":"J D E F A B rB"},B:{"1":"L G M N O","2":"C K","257":"P Q R S V W X Y Z a b c d e f g T h H i"},C:{"1":"EB FB GB HB IB JB KB LB MB NB iB OB jB PB QB U RB SB TB UB VB WB XB YB ZB aB bB cB dB eB P Q R kB S V W X Y Z a b c d e f g T h H i","2":"sB hB I j J D E F A B C K L G M N O k l m n o p q r s t u v tB uB","194":"0 1 2 3 4 5 6 7 8 9 w x y z AB BB CB DB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 y z AB BB CB DB EB FB GB HB IB JB","2":"I j J D E F A B C K L G M N O k l m n o p q r s t u v w x","257":"KB LB MB NB iB OB jB PB QB U RB SB TB UB VB WB XB YB ZB aB bB cB dB eB P Q R S V W X Y Z a b c d e f g T h H i vB wB xB"},E:{"1":"D E F A B C K L G 1B 2B mB fB gB 3B 4B 5B nB oB 6B","2":"I j J yB lB zB 0B"},F:{"1":"0 1 2 3 4 5 6 7 8 9 s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB","2":"F B C G M N O k l m n o p q r 7B 8B 9B AC fB pB BC gB","257":"U RB SB TB UB VB WB XB YB ZB aB bB cB dB eB P Q R kB S"},G:{"1":"E FC GC HC IC JC KC LC MC NC OC PC QC RC SC TC UC VC nB oB","2":"lB CC qB DC EC"},H:{"2":"WC"},I:{"2":"hB I H XC YC ZC aC qB bC cC"},J:{"2":"D A"},K:{"2":"A B C U fB pB gB"},L:{"1":"H"},M:{"1":"T"},N:{"2":"A B"},O:{"2":"dC"},P:{"1":"eC fC gC hC iC mB jC kC lC mC nC oC","2":"I"},Q:{"1":"pC"},R:{"2":"qC"},S:{"1":"rC"}},B:7,C:"Speech Synthesis API"};
exports.onCreatePage = async ({ page, actions }) => { const { createPage } = actions // page.matchPath is a special key that's used for matching pages // only on the client. if (page.path.match(/^\/account/)) { page.matchPath = "/account/*" // Update the page. createPage(page) } } exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => { if (stage === "build-html") { /* * During the build step, `auth0-js` will break because it relies on * browser-specific APIs. Fortunately, we don’t need it during the build. * Using Webpack’s null loader, we’re able to effectively ignore `auth0-js` * during the build. (See `src/utils/auth.js` to see how we prevent this * from breaking the app.) */ actions.setWebpackConfig({ module: { rules: [ { test: /auth0-js/, use: loaders.null(), }, ], }, }) } }
import React, { Component } from 'react'; import { Header, Container } from 'semantic-ui-react'; import './HomePage.css'; class HomePage extends Component { render() { return ( <Container className="section"> <Header as="h1">Home</Header> </Container> ); } } export default HomePage;
'use strict'; /* ------------------------------------------------------------------------------------------------ CHALLENGE 1 - Review Use the characters data below for all of the challenges except challenge 2 and 3. Write a function named sortByChildren that sorts the characters below by the number of children in each house (fewest to most). If a house has the same number of children, sort alphabetically by house name. ------------------------------------------------------------------------------------------------ */ let characters = [ { name: 'Eddard', spouse: 'Catelyn', children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'], house: 'Stark' }, { name: 'Jon A.', spouse: 'Lysa', children: ['Robin'], house: 'Arryn' }, { name: 'Cersei', spouse: 'Robert', children: ['Joffrey', 'Myrcella', 'Tommen'], house: 'Lannister' }, { name: 'Daenarys', spouse: 'Khal Drogo', children: ['Drogon', 'Rhaegal', 'Viserion'], house: 'Targaryen' }, { name: 'Mace', spouse: 'Alerie', children: ['Margaery', 'Loras'], house: 'Tyrell' }, { name: 'Euron', spouse: null, children: [], house: 'Greyjoy' }, { name: 'Jon S.', spouse: null, children: [], house: 'Snow' } ]; const sortByChildren = (charArray) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 2 Write a function named containsW that takes in a string. This function should use a regular expression pattern to return true if the string contains the letter 'w' in lower case or false if it does not. ------------------------------------------------------------------------------------------------ */ const containsW = (str) => { // Solution code here... let regex = /w/; return regex.test(str); }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 3 Write a function named isNum that takes in a string or number of any length. This function should use a regular expression pattern to return true if the input contains a number, and false if the input does not contain a number. For example: 12345 returns true '12345' returns true 'h3llo world' returns true 'hello world' returns false ------------------------------------------------------------------------------------------------ */ const isNum = (input) => { // Solution code here... let regex = /[0-9]/; return regex.test(input); }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 4 Write a function named containsWorld that takes in a string or number of any length. This function should use a regular expression pattern to return true if the input contains the word 'world' all in lower-case letters, and false if the input does not. ------------------------------------------------------------------------------------------------ */ const containsWorld = (input) => { // Solution code here... let regex = /world/; return regex.test(input); }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 5 Write a function named isCapitalized that takes in a string. This function should use a regular expression pattern to match all words that begin with a capital letter. It should only match words, not punctuation. Return an array containing all the matches. ------------------------------------------------------------------------------------------------ */ const isCapitalized = (str) => { // Solution code here... let regex = /[A-Z]/g; return str.match(regex); }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 6 Write a function named citiesAtoJ that takes in an array of city names and uses a regular expression pattern to return a new array containing any cities that begin with the letters A through J, inclusive. ------------------------------------------------------------------------------------------------ */ const citiesAtoJ = (arr) => { // Solution code here... let regex = /A/g; return regex.match(arr); }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 7 - Stretch Goal You have created a game application and begin by asking users an easy question: In which month is Halloween? Write a function named matchMonth which uses a regular expression pattern to match any of these inputs: October, Oct, october, oct If the user enters any of these four inputs, return true. For any other input, return false. Do not use the vertical bar (pipe) in your pattern. ------------------------------------------------------------------------------------------------ */ const matchMonth = (input) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 8 - Stretch Goal Write a function named noPunctuation that contains a regular expression pattern to find all of the words that contain a space immediately at the end of the word. Return an array of all such words, still containing the space at the end. For example, if given the string "Hello, and have a wonderful day!", the word "Hello, " would not be returned because it is immediately followed by a comma. The word "day!" would not be returned because it is immediately followed by an exclamation point. The expected output of "Hello, and have a wonderful day!" is ["and ", "have ", "a ", "wonderful "]. ------------------------------------------------------------------------------------------------ */ const noPunctuation = str => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 9 - Stretch Goal You want to teach a friend how to play hangman and want to show them using a partially complete puzzle. Write a function named hangman which uses the replace method to remove all of the vowels (a, e, i, o, u) from the hangman string, regardless of capitalization, and replace them with an underscore. The function should return a string containing the consonants in their original positions and underscores where the vowels were previously located. For example, 'Welcome to Code 301!' will return 'W_lc_m_ t_ C_d_ 301!'. ------------------------------------------------------------------------------------------------ */ let hangman = (str) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 10 - Stretch Goal Write a function named findShells that takes in the string below and uses a regular expression pattern to find all instances of the following words: "sells", "shells", "seashells". Do not use the vertical bar (pipe) character. Hint: All of these words end with the letters "ells". ------------------------------------------------------------------------------------------------ */ const seashells = 'She sells seashells by the seashore. The shells she sells are surely seashells. So if she sells shells on the seashore, I\'m sure she sells seashore shells.'; const findShells = (str) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ TESTS All the code below will verify that your functions are working to solve the challenges. DO NOT CHANGE any of the below code. Run your tests from the console: jest challenges-04.solution.test.js ------------------------------------------------------------------------------------------------ */ describe('Testing challenge 1', () => { test('It should sort the characters by number of children', () => { expect(sortByChildren(characters)[0].name).toStrictEqual('Euron'); expect(sortByChildren(characters)[0].children.length).toStrictEqual(0); }); }); describe('Testing challenge 2', () => { test('It should return true if the input contains a lower case w', () => { expect(containsW('hello world')).toBe(true); }); test('It should return false if the input contains an upper case W', () => { expect(containsW('Hello World')).toBe(false); }); test('It should return false if the input does not contain a w', () => { expect(containsW('hello everyone')).toBe(false); }) }) describe('Testing challenge 3', () => { test('It should return true if the input is a number', () => { expect(isNum(1234567890)).toBeTruthy(); expect(isNum('12345')).toBeTruthy(); }); test('It should return true if the input contains a number', () => { expect(isNum('h3llo w0rld')).toBeTruthy(); }); test('It should return false if the input does not contain a number', () => { expect(isNum('hello world')).toBeFalsy(); expect(isNum('')).toBeFalsy(); }); }); describe('Testing challenge 4', () => { test('It should return true if the input contains the word school in lower case', () => { expect(containsWorld('hello world')).toBe(true); }); test('It should return false if the input contains the word school with any upper case letters', () => { expect(containsWorld('Hello World')).toBe(false); }); test('It should return false if the input does not contain the word school', () => { expect(containsWorld('hello everyone')).toBe(false); }); }) describe('Testing challenge 5', () => { test('It should only return words that begin with a capital letter', () => { const capitalResult = isCapitalized('We only want to Return the Words that begin With a capital Letter'); expect(capitalResult).toStrictEqual([ 'We', 'Return', 'Words', 'With', 'Letter' ]); expect(capitalResult.length).toStrictEqual(5); expect(isCapitalized('Given by our hand in the meadow that is called Runnymede, between Windsor and Staines, on the fifteenth day of June in the seventeenth year of our reign (i.e. 1215: the new regnal year began on 28 May).')).toStrictEqual(['Given', 'Runnymede', 'Windsor', 'Staines', 'June', 'May']); expect(isCapitalized('these words are all failures')).toStrictEqual([]); }); }); describe('Testing challenge 6', () => { let cities = ['Cleveland', 'San Diego', 'Birmingham', 'Seattle', 'Miami', 'New York City', 'Omaha', 'Portland', 'Austin', 'Boston', 'Newport Beach', 'Hoboken']; test('It should return the cities whose names begin with the letters A through J', () => { expect(citiesAtoJ(cities)).toContain('Cleveland', 'Birmingham', 'Austin', 'Boston', 'Hoboken'); expect(citiesAtoJ(cities).length).toStrictEqual(5); expect(citiesAtoJ([])).toStrictEqual([]); expect(citiesAtoJ(['Albuquerque', 'Chicago', 'Philadelphia', 'Newark', 'Sacramento', 'Eugene'])).toEqual(expect.arrayContaining(['Albuquerque', 'Chicago', 'Eugene'])); }); test('It should not return the cities whose names begin with the letters K through Z', () => { expect(citiesAtoJ(cities)).not.toContain('San Diego', 'Seattle', 'Miami', 'New York City', 'Omaha', 'Portland', 'Newport Beach'); }); }); xdescribe('Testing challenge 7', () => { test('It should match any of the acceptable inputs', () => { expect(matchMonth('Oct')).toBeTruthy(); expect(matchMonth('oct')).toBeTruthy(); expect(matchMonth('October')).toBeTruthy(); expect(matchMonth('october')).toBeTruthy(); }); test('It should not match anything other than the acceptable inputs', () => { expect(matchMonth('November')).toBeFalsy(); expect(matchMonth('nov')).toBeFalsy(); expect(matchMonth(123)).toBeFalsy(); expect(matchMonth('octob')).toBeFalsy(); expect(matchMonth('OCTOBER')).toBeFalsy(); expect(matchMonth('notOctober')).toBeFalsy(); }); }); xdescribe('Testing challenge 8', () => { const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras lacinia vel massa sed egestas. Nunc faucibus iaculis elit, a scelerisque enim condimentum sed. Aenean ac scelerisque sem, et pharetra diam.'; test('It should only return words that are immediately followed by a space', () => { expect(noPunctuation(lorem)).toStrictEqual([ 'Lorem ', 'ipsum ', 'dolor ', 'sit ', 'consectetur ', 'adipiscing ', 'Cras ', 'lacinia ', 'vel ', 'massa ', 'sed ', 'Nunc ', 'faucibus ', 'iaculis ', 'a ', 'scelerisque ', 'enim ', 'condimentum ', 'Aenean ', 'ac ', 'scelerisque ', 'et ', 'pharetra ' ]); expect(noPunctuation(lorem).length).toStrictEqual(23); expect(noPunctuation('Given by our hand in the meadow that is called Runnymede, between Windsor and Staines, on the fifteenth day of June in the seventeenth year of our reign (i.e. 1215: the new regnal year began on 28 May).')).toEqual(expect.arrayContaining(['Given ', 'by ', 'our ', 'hand ', 'in ', 'the ', 'meadow ', 'that ', 'is ', 'called ', 'between ', 'Windsor ', 'and ', 'on ', 'the ', 'fifteenth ', 'day ', 'of ', 'June ', 'in ', 'the ', 'seventeenth ', 'year ', 'of ', 'our ', 'reign ', 'the ', 'new ', 'regnal ', 'year ', 'began ', 'on ', '28 '])); }); test('It should not contain words that are followed by any non-space character', () => { expect(noPunctuation(lorem)).not.toContain(['amet,', 'elit.', 'egestas.', 'elit,', 'sed.', 'sem,', 'diam.', 'nibh.', 'porttitor.', 'euismod,', 'ultrices.', 'massa,', 'vel,', 'purus.', 'purus,', 'odio.', 'aliquet,', 'non,', 'sem.']); }); }); xdescribe('Testing challenge 9', () => { let startString = 'This is a regex challenge. We are trying to create a hangman phrase where all of the vowels are missing!'; test('It should remove the vowels from the hangman string and replace them with underscores', () => { expect(hangman(startString)).toStrictEqual('Th_s _s _ r_g_x ch_ll_ng_. W_ _r_ try_ng t_ cr__t_ _ h_ngm_n phr_s_ wh_r_ _ll _f th_ v_w_ls _r_ m_ss_ng!'); expect(hangman('I wAnt them all tO bE removed and replaced with Underscores.')).toStrictEqual('_ w_nt th_m _ll t_ b_ r_m_v_d _nd r_pl_c_d w_th _nd_rsc_r_s.'); }); test('It should not contain the letters "a", "e", "i", "o", or "u"', () => { expect(hangman(startString)).not.toContain('a', 'e', 'i', 'o', 'u'); }); }); xdescribe('Testing challenge 10', () => { test('It should return an array of instances of "sells", shells", and "seashells"', () => { expect(findShells(seashells)).toStrictEqual(['sells', 'seashells', 'shells', 'sells', 'seashells', 'sells', 'shells', 'sells', 'shells']); expect(findShells(seashells).length).toStrictEqual(9); }); });
// Initialize a new discord client const Discord = require('discord.js'); const client = new Discord.Client(); var mysql = require('mysql') const config = require('./config'); client.config = config; let token = config.token; var con = mysql.createConnection({ host: config.SQLhost, user: config.SQLuser, password: config.SQLpassword, database: config.SQLdatabase }) // Require dependencies const fs = require('fs'); const Enmap = require('enmap'); //const CronJob = require('cron').CronJob; const helpers = require('./Modules/helpers'); const { resourceLimits } = require('worker_threads'); // Listen to all possible events fs.readdir("./Events/", (err, files) => { if (err) return console.error(err); files.forEach(file => { const event = require(`./Events/${file}`); let eventName = file.split(".")[0]; client.on(eventName, event.bind(null, client)); }); }); client.commands = new Enmap(); // Register all available commands into the client helpers.getFiles('./Commands').forEach(file => { if (!file.endsWith(".js")) return; let props = require(file); let commandName = file.split("/"); commandName = commandName[commandName.length - 1].split('.')[0]; console.log(getTimeStamp() + `Attempting to load command ${commandName} from dir: ${file}`); client.commands.set(commandName, props); }); console.log(getTimeStamp() + 'Commands loaded'); console.log(); /*async function getServerData() { con.connect(async function(err) { if (err) throw err; console.log('connected'); con.query(`SELECT * FROM data `, async function(err, result, fields) { if (err) throw err; console.log("downloaded data"); serverData = await result; const server_id = result[0].server_id; const channel_id = result[0].channel_id; const live_role_id = result[0].live_role_id; const streamer_role_id = result[0].streamer_role_id; const notification_role_id = result[0].notification_role_id; console.log(server_id + " " + channel_id + " " + live_role_id + " " + streamer_role_id + " " + notification_role_id) }) }) }*/ function checkForActivity(presence, act) { //presence.activities.forEach(activity => { console.log(activity.type) }); return presence.activities.some(activity => activity.type == act) } function returnActivity(presence, act) { return presence.activities.find(activity => activity.type == act) } function checkForRole(member, rid) { return member.roles.cache.some(role => role.id == rid); } function checkForGuild(presence, gid) { return presence.guild.id == gid; } function getTimeStamp() { var date = new Date; return "[" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]"; } client.on('presenceUpdate', async(oldPresence, newPresence) => { const debugActivity = "STREAMING"; if (!newPresence.activities) return false; await newPresence.member.fetch(newPresence.member.id); console.log(getTimeStamp() + "Checking <" + newPresence.user.username + "> in <" + newPresence.guild.name + ">:"); console.log(); console.log(getTimeStamp() + "CheckForGuild: " + checkForGuild(newPresence, "857617077133115443")) console.log(getTimeStamp() + "CheckForRole: " + checkForRole(newPresence.member, "860232566690676758")) console.log(getTimeStamp() + "CheckForActivityNew: " + checkForActivity(newPresence, debugActivity)) console.log(getTimeStamp() + "CheckForActivityOld: " + checkForActivity(oldPresence, debugActivity)); console.log(); if (checkForActivity(newPresence, debugActivity)) console.log(getTimeStamp() + returnActivity(newPresence, debugActivity).url); if (checkForActivity(oldPresence, debugActivity)) console.log(getTimeStamp() + returnActivity(oldPresence, debugActivity).url); if (checkForGuild(newPresence, "857617077133115443") && checkForRole(newPresence.member, "860232566690676758") && (checkForActivity(newPresence, debugActivity) || checkForActivity(oldPresence, debugActivity))) { newPresence.member.roles.cache.forEach(role => console.log(getTimeStamp() + role.name)); if (checkForActivity(newPresence, debugActivity) && !checkForActivity(oldPresence, debugActivity)) { if (newPresence.user.id == "232191205700534275") { console.log("It's Comp!"); console.log(getTimeStamp() + `${newPresence.user.username} started streaming at ${returnActivity(newPresence, debugActivity).url}`); const channel = client.channels.cache.get("857650608268771408"); channel.send(`<@&860232720616259616> It is me! ${newPresence.user.username}! I am live!!! Tune in at ${returnActivity(newPresence, debugActivity).url}`).then(message => message.crosspost()); let role = newPresence.guild.roles.cache.find(role => role.id === '859934121661169674'); console.log('Adding live role'); newPresence.member.roles.add(role).catch(console.error); } else { console.log(getTimeStamp() + `${newPresence.user.username} started streaming at ${returnActivity(newPresence, debugActivity).url}`); const channel = client.channels.cache.get("857663909381144576"); channel.send(`<@&860232720616259616> ${newPresence.user.username} started streaming at ${returnActivity(newPresence, debugActivity).url}`); let role = newPresence.guild.roles.cache.find(role => role.id === '859934121661169674'); console.log('Adding live role'); newPresence.member.roles.add(role).catch(console.error); } }; if (!checkForActivity(newPresence, debugActivity) && checkForActivity(oldPresence, debugActivity)) { console.log(getTimeStamp() + `${newPresence.user.username} stopped streaming`); console.log(); let role = newPresence.guild.roles.cache.find(role => role.id === '859934121661169674'); console.log(getTimeStamp() + 'Removing live role'); console.log(); newPresence.member.roles.remove(role).catch(console.error); } } }); client.login(token); client.on('ready', async() => { let guilds = client.guilds.cache.map(guild => guild.name) console.log(getTimeStamp() + `I'm on these servers:`); console.log(getTimeStamp() + guilds); console.log(); console.log(getTimeStamp() + `I'm ready :)`); console.log(); });
define({ "group": "Назва", "openAll": "Відкрити все на одній панелі", "dropDown": "Показати у розкривному меню", "noGroup": "Групу віджетів не задано.", "groupSetLabel": "Задати властивості груп віджетів" });
# Copyright (C) 2012 Mozilla Foundation # # 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. # # APIs for building and testing OTA and FOTA updates for FxOS import argparse from cStringIO import StringIO import datetime import hashlib import os import glob import platform import re import shutil import subprocess import sys import tempfile import xml.dom.minidom as minidom import zipfile # This needs to be run from within a B2G checkout this_dir = os.path.abspath(os.path.dirname(__file__)) b2g_dir = os.path.dirname(os.path.dirname(this_dir)) bin_dir = os.path.join(this_dir, "bin") def validate_env(parser): if platform.system() not in ("Linux", "Darwin"): parser.error("This tool only runs in Linux or Mac OS X") if not which("bash"): parser.error("This tool requires bash to be on your PATH") if sys.version_info < (2, 7): parser.error("This tool requires Python 2.7 or greater") if not which("arm-linux-androideabi-readelf", path=os.environ.get("ANDROID_TOOLCHAIN")): parser.error("No readelf binary in ANDROID_TOOLCHAIN") def run_command(*args, **kwargs): try: if "input" in kwargs: input = kwargs.pop("input") if "stdin" not in kwargs: kwargs["stdin"] = subprocess.PIPE if "stdout" not in kwargs: kwargs["stdout"] = subprocess.PIPE if "stderr" not in kwargs: kwargs["stderr"] = subprocess.PIPE proc = subprocess.Popen(*args, **kwargs) out, err = proc.communicate(input) if proc.returncode != 0: raise UpdateException("Processs returned error code %d: %s" % \ (proc.returncode, err)) return out return subprocess.check_output(*args, **kwargs) except subprocess.CalledProcessError, e: raise UpdateException("Process returned error code %d: %s" % \ (e.returncode, " ".join(e.cmd))) # Copied from Lib/shutil.py in Python 3.3.0 # http://docs.python.org/3/license.html def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # Short circuit. If we're given a full path which matches the mode # and it exists, we're done here. if _access_check(cmd, mode): return cmd path = (path or os.environ.get("PATH", os.defpath)).split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = os.environ.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())] # If it does match, only test that one, otherwise we have to try # others. files = [cmd] if matches else [cmd + ext.lower() for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: dir = os.path.normcase(dir) if not dir in seen: seen.add(dir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None class UpdateException(Exception): pass class B2GConfig(object): CONFIG_VARS = ("GECKO_PATH", "GECKO_OBJDIR", "DEVICE") def __init__(self): shell = ". load-config.sh 1>&2" for var in self.CONFIG_VARS: shell += "\necho $%s" % var result = run_command(["bash", "-c", shell], cwd=b2g_dir, env={"B2G_DIR": b2g_dir}) if not result: raise UpdateException("Couldn't parse result of load-config.sh") lines = result.splitlines() if len(lines) != len(self.CONFIG_VARS): raise UpdateException("Wrong number of config vars: %d" % len(lines)) for i in range(len(self.CONFIG_VARS)): setattr(self, self.CONFIG_VARS[i].lower(), lines[i].strip()) self.init_gecko_path() if not self.gecko_objdir: self.gecko_objdir = os.path.join(self.gecko_path, "objdir-gecko") def init_gecko_path(self): if not self.gecko_path: self.gecko_path = os.path.join(b2g_dir, "gecko") if os.path.exists(self.gecko_path): return relative_gecko_path = os.path.join(b2g_dir, self.gecko_path) if os.path.exists(relative_gecko_path): self.gecko_path = relative_gecko_path return raise UpdateException("B2G gecko directory not found: %s" % self.gecko_path) def get_gecko_host_bin(self, path): return os.path.join(self.gecko_objdir, "dist", "host", "bin", path) class Tool(object): def __init__(self, path, prebuilt=False): self.tool = path self.debug = False if prebuilt: self.init_prebuilt(path) if not os.path.exists(self.tool): raise UpdateException("Couldn't find %s " % self.tool) def init_prebuilt(self, path): host_dir = "linux-x86" if platform.system() == "Darwin": host_dir = "darwin-x86" self.tool = os.path.join(bin_dir, host_dir, path) def get_tool(self): return self.tool def run(self, *args, **kwargs): command = (self.tool, ) + args if self.debug: print " ".join(['"%s"' % c for c in command]) return run_command(command, **kwargs) class AdbTool(Tool): DEVICE = ("-d") EMULATOR = ("-e") DEVICES_HEADER = "List of devices attached" def __init__(self, path=None, device=None): prebuilt = path is None if not path: path = "adb" Tool.__init__(self, path, prebuilt=prebuilt) self.adb_args = () if device in (self.DEVICE, self.EMULATOR): self.adb_args = device elif device: self.adb_args = ("-s", device) def run(self, *args): adb_args = self.adb_args + args return Tool.run(self, *adb_args) def shell(self, *args): return self.run("shell", *args) def push(self, *args): self.run("push", *args) def file_exists(self, remote_file): result = self.shell("ls %s 2>/dev/null 1>/dev/null; echo $?" % \ remote_file) return result.strip() == "0" def get_pids(self, process): result = self.shell( "toolbox ps %s | (read header; while read user pid rest; do echo $pid; done)" % \ process) return [line.strip() for line in result.splitlines()] def get_cmdline(self, pid): cmdline_path = "/proc/%s/cmdline" % pid if not self.file_exists(cmdline_path): raise UpdateException("Command line file for PID %s not found" % pid) result = self.shell("cat %s" % cmdline_path) # cmdline is null byte separated and has a trailing null byte return result.split("\x00")[:-1] def get_online_devices(self): output = self.run("devices") online = set() for line in output.split("\n"): if line.startswith(self.DEVICES_HEADER): continue tokens = line.split("\t") if len(tokens) != 2: continue device = tokens[0] state = tokens[1] if state == "device": online.add(device) return online class MarTool(Tool): def __init__(self): Tool.__init__(self, b2g_config.get_gecko_host_bin("mar")) def list_entries(self, mar_path): result = self.run("-t", mar_path) entries = [] for line in result.splitlines(): words = re.split("\s+", line) if len(words) < 3: continue if words[0] == "SIZE": continue entries.append(words[2]) return entries def create(self, mar_path, src_dir=None): if not src_dir: src_dir = os.getcwd() mar_args = ["-c", mar_path] # The MAR tool wants a listing of each file to add for root, dirs, files in os.walk(src_dir): for f in files: file_path = os.path.join(root, f) mar_args.append(os.path.relpath(file_path, src_dir)) self.run(*mar_args, cwd=src_dir) def extract(self, mar_path, dest_dir=None): self.run("-x", mar_path, cwd=dest_dir) def is_gecko_mar(self, mar_path): return not self.is_fota_mar(mar_path) def is_fota_mar(self, mar_path): entries = self.list_entries(mar_path) return "update.zip" in entries class BZip2Mar(object): def __init__(self, mar_file, verbose=False): self.mar_file = mar_file self.verbose = verbose self.mar_tool = MarTool() self.bzip2_tool = which("bzip2") if not self.bzip2_tool: raise UpdateException("Couldn't find bzip2 on the PATH") def bzip2(self, *args): bzargs = [self.bzip2_tool] if self.verbose: bzargs.append("-v") bzargs.extend(args) return run_command(bzargs) def create(self, src_dir): if not os.path.exists(src_dir): raise UpdateException("Source directory doesn't exist: %s" % src_dir) temp_dir = tempfile.mkdtemp() for root, dirs, files in os.walk(src_dir): for f in files: path = os.path.join(root, f) rel_file = os.path.relpath(path, src_dir) out_file = os.path.join(temp_dir, rel_file) out_dir = os.path.dirname(out_file) if not os.path.exists(out_dir): os.makedirs(out_dir) shutil.copy(path, out_file) self.bzip2("-z", out_file) os.rename(out_file + ".bz2", out_file) self.mar_tool.create(self.mar_file, src_dir=temp_dir) def extract(self, dest_dir): if not os.path.exists(dest_dir): os.makedirs(dest_dir) if not os.path.exists(dest_dir): raise UpdateException("Couldn't create directory: %s" % dest_dir) self.mar_tool.extract(self.mar_file, dest_dir=dest_dir) for root, dirs, files in os.walk(dest_dir): for f in files: path = os.path.join(root, f) os.rename(path, path + ".bz2") self.bzip2("-d", path + ".bz2") class FotaZip(zipfile.ZipFile): UPDATE_BINARY = "META-INF/com/google/android/update-binary" UPDATER_SCRIPT = "META-INF/com/google/android/updater-script" MANIFEST_MF = "META-INF/MANIFEST.MF" CERT_SF = "META-INF/CERT.SF" def __init__(self, path, mode="r", compression=zipfile.ZIP_DEFLATED): zipfile.ZipFile.__init__(self, path, mode, compression, True) def has_entry(self, entry): try: self.getinfo(entry) return True except: return False def validate(self, signed=False): entries = (self.UPDATE_BINARY, self.UPDATER_SCRIPT) if signed: entries += (self.MANIFEST_MF, self.CERT_SF) for entry in entries: if not self.has_entry(entry): raise UpdateException("Update zip is missing expected file: %s" % entry) def write_updater_script(self, script): self.writestr(self.UPDATER_SCRIPT, script) def write_default_update_binary(self, update_bin): self.write(update_bin, self.UPDATE_BINARY) def write_recursive(self, path, zip_path=None, filter=None): def zip_relpath(file_path): relpath = os.path.relpath(file_path, path) relpath = relpath.replace("\\", "/").lstrip("/") if zip_path: relpath = zip_path + "/" + relpath return relpath for root, dirs, files in os.walk(path): for f in files: file_path = os.path.join(root, f) relpath = zip_relpath(file_path) if not filter or filter(file_path, relpath): self.write(file_path, relpath) class FotaZipBuilder(object): def build_unsigned_zip(self, update_dir, output_zip, update_bin): if not os.path.exists(update_dir): raise UpdateException("Update dir doesn't exist: %s" % update_dir) update_binary = os.path.join(update_dir, FotaZip.UPDATE_BINARY) updater_script = os.path.join(update_dir, FotaZip.UPDATER_SCRIPT) if not os.path.exists(updater_script): raise UpdateException("updater-script not found at %s" % updater_script) update_zipfile = FotaZip(output_zip, "w") if not os.path.exists(update_binary): print "Warning: update-binary not found, using default" update_zipfile.write_default_update_binary(update_bin) update_zipfile.write_recursive(update_dir) update_zipfile.close() def sign_zip(self, unsigned_zip, public_key, private_key, output_zip): java = which("java") if java is None: raise UpdateException("java is required to be on your PATH for signing") with FotaZip(unsigned_zip) as fota_zip: fota_zip.validate() if not os.path.exists(private_key): raise UpdateException("Private key doesn't exist: %s" % private_key) if not os.path.exists(public_key): raise UpdateException("Public key doesn't exist: %s" % public_key) signapk_jar = os.path.join(bin_dir, "signapk.jar") run_command([java, "-Xmx2048m", "-jar", signapk_jar, "-w", public_key, private_key, unsigned_zip, output_zip]) class FotaMarBuilder(object): def __init__(self): self.stage_dir = tempfile.mkdtemp() def __del__(self): shutil.rmtree(self.stage_dir) def build_mar(self, signed_zip, output_mar): with FotaZip(signed_zip) as fota_zip: fota_zip.validate(signed=True) mar_tool = MarTool() make_full_update = os.path.join(b2g_config.gecko_path, "tools", "update-packaging", "make_full_update.sh") if not os.path.exists(make_full_update): raise UpdateException("Couldn't find %s " % make_full_update) mar_dir = os.path.join(self.stage_dir, "mar") os.mkdir(mar_dir) # Inside the FOTA MAR, the update needs to be called "update.zip" shutil.copy(signed_zip, os.path.join(mar_dir, "update.zip")) precomplete = os.path.join(mar_dir, "precomplete") open(precomplete, "w").write("") run_command([make_full_update, output_mar, mar_dir], env={"MAR": mar_tool.get_tool()}) class GeckoMarBuilder(object): def __init__(self): self.mar_tool = MarTool() self.mbsdiff_tool = Tool(b2g_config.get_gecko_host_bin("mbsdiff")) packaging_dir = os.path.join(b2g_config.gecko_path, "tools", "update-packaging") self.make_full_update = os.path.join(packaging_dir, "make_full_update.sh") if not os.path.exists(self.make_full_update): raise UpdateException("Couldn't find %s " % self.make_full_update) self.make_incremental_update = os.path.join(packaging_dir, "make_incremental_update.sh") if not os.path.exists(self.make_incremental_update): raise UpdateException("Couldn't find %s " % self.make_incremental_update) def build_gecko_mar(self, src_dir, output_mar, from_dir=None): if from_dir: args = [self.make_incremental_update, output_mar, from_dir, src_dir] else: args = [self.make_full_update, output_mar, src_dir] run_command(args, env={ "MAR": self.mar_tool.get_tool(), "MBSDIFF": self.mbsdiff_tool.get_tool() }) class UpdateXmlBuilder(object): DEFAULT_URL_TEMPLATE = "http://localhost/%(filename)s" DEFAULT_UPDATE_TYPE = "minor" DEFAULT_APP_VERSION = "99.0" DEFAULT_PLATFORM_VERSION = "99.0" DEFAULT_LICENSE_URL = "http://www.mozilla.com/test/sample-eula.html" DEFAULT_DETAILS_URL = "http://www.mozilla.com/test/sample-details.html" def __init__(self, complete_mar=None, partial_mar=None, url_template=None, update_type=None, app_version=None, platform_version=None, build_id=None, license_url=None, details_url=None, is_fota_update=False): if complete_mar is None and partial_mar is None: raise UpdateException("either complete_mar or partial_mar is required") self.complete_mar = complete_mar self.partial_mar = partial_mar self.url_template = url_template or self.DEFAULT_URL_TEMPLATE self.update_type = update_type or self.DEFAULT_UPDATE_TYPE self.app_version = app_version or self.DEFAULT_APP_VERSION self.platform_version = platform_version or self.DEFAULT_PLATFORM_VERSION self.build_id = build_id or self.generate_build_id() self.license_url = license_url or self.DEFAULT_LICENSE_URL self.details_url = details_url or self.DEFAULT_DETAILS_URL self.is_fota_update = is_fota_update def generate_build_id(self): return datetime.datetime.now().strftime('%Y%m%d%H%M%S') def sha512(self, patch_path): patch_hash = hashlib.sha512() with open(patch_path, "r") as patch_file: data = patch_file.read(512) while len(data) > 0: patch_hash.update(data) data = patch_file.read(512) return patch_hash.hexdigest() def build_patch(self, patch_type, patch_file): patch = self.doc.createElement("patch") patch.setAttribute("type", patch_type) template_args = self.__dict__.copy() template_args["filename"] = os.path.basename(patch_file) patch.setAttribute("URL", self.url_template % template_args) patch.setAttribute("hashFunction", "SHA512") patch.setAttribute("hashValue", self.sha512(patch_file)) patch.setAttribute("size", str(os.stat(patch_file).st_size)) return patch def build_xml(self): impl = minidom.getDOMImplementation() self.doc = impl.createDocument(None, "updates", None) updates = self.doc.documentElement update = self.doc.createElement("update") updates.appendChild(update) update.setAttribute("type", self.update_type) update.setAttribute("appVersion", self.app_version) update.setAttribute("version", self.platform_version) update.setAttribute("buildID", self.build_id) update.setAttribute("licenseURL", self.license_url) update.setAttribute("detailsURL", self.details_url) if self.is_fota_update: update.setAttribute("isOSUpdate", "true") if self.complete_mar: complete_patch = self.build_patch("complete", self.complete_mar) update.appendChild(complete_patch) if self.partial_mar: partial_patch = self.build_patch("partial", self.partial_mar) update.appendChild(partial_patch) return self.doc.toprettyxml() class UpdateXmlOptions(argparse.ArgumentParser): def __init__(self, output_arg=True): argparse.ArgumentParser.__init__(self, usage="%(prog)s [options] (update.mar)") self.add_argument("-c", "--complete-mar", dest="complete_mar", metavar="MAR", default=None, help="Path to a 'complete' MAR. This can also be " + "provided as the first argument. Either " + "--complete-mar or --partial-mar must be provided.") self.add_argument("-p", "--partial-mar", dest="partial_mar", metavar="MAR", default=None, help="Path to a 'partial' MAR") if output_arg: self.add_argument("-o", "--output", dest="output", metavar="FILE", default=None, help="Place to generate the update XML. Default: " + "print XML to stdout") self.add_argument("-u", "--url-template", dest="url_template", metavar="URL", default=None, help="A template for building URLs in the update.xml. " + "Default: http://localhost/%%(filename)s") self.add_argument("-t", "--update-type", dest="update_type", default="minor", help="The update type. Default: minor") self.add_argument("-v", "--app-version", dest="app_version", default=None, help="The application version of this update. " + "Default: 99.0") self.add_argument("-V", "--platform-version", dest="platform_version", default=None, help="The platform version of this update. Default: 99.0") self.add_argument("-i", "--build-id", dest="build_id", default=None, help="The Build ID of this update. Default: Current timestamp") self.add_argument("-l", "--license-url", dest="license_url", default=None, help="The license URL of this update. Default: " + UpdateXmlBuilder.DEFAULT_LICENSE_URL) self.add_argument("-d", "--details-url", dest="details_url", default=None, help="The details URL of this update. Default: " + UpdateXmlBuilder.DEFAULT_DETAILS_URL) self.add_argument("-O", "--fota-update", dest="fota_update", action="store_true", default=None, help="The complete MAR contains a FOTA update. " + "Default: detect.\nNote: only 'complete' MARs can be FOTA updates.") def parse_args(self): validate_env(self) options, args = argparse.ArgumentParser.parse_known_args(self) if not options.complete_mar and len(args) > 0: options.complete_mar = args[0] if not options.complete_mar and not options.partial_mar: self.print_help() print >>sys.stderr, \ "Error: At least one of --complete-mar or --partial-mar is required." sys.exit(1) fota_update = False if options.fota_update is None and options.complete_mar: if not os.path.exists(options.complete_mar): print >>sys.stderr, \ "Error: MAR doesn't exist: %s" % options.complete_mar sys.exit(1) mar_tool = MarTool() fota_update = mar_tool.is_fota_mar(options.complete_mar) elif options.fota_update: fota_update = True if not options.complete_mar: print >>sys.stderr, \ "Error: --fota-update provided without a --complete-mar" sys.exit(1) if options.partial_mar and fota_update: print >>sys.stderr, \ "Warning: --partial-mar ignored for FOTA updates" options.partial_mar = None self.is_fota_update = fota_update self.options, self.args = options, args return options, args def get_output_xml(self): return self.options.output def get_complete_mar(self): return self.options.complete_mar def get_partial_mar(self): return self.options.partial_mar def get_url_template(self): return self.options.url_template def build_xml(self): option_keys = ("complete_mar", "partial_mar", "url_template", "update_type", "app_version", "platform_version", "build_id", "license_url", "details_url") kwargs = {"is_fota_update": self.is_fota_update} for key in option_keys: kwargs[key] = getattr(self.options, key) builder = UpdateXmlBuilder(**kwargs) return builder.build_xml() class TestUpdate(object): REMOTE_BIN_DIR = "/data/local/bin" REMOTE_BUSYBOX = REMOTE_BIN_DIR + "/busybox" LOCAL_BUSYBOX = os.path.join(bin_dir, "gonk", "busybox-armv6l") REMOTE_HTTP_ROOT = "/data/local/b2g-updates" REMOTE_PROFILE_DIR = "/data/b2g/mozilla" def __init__(self, update_xml=None, complete_mar=None, partial_mar=None, url_template=None, update_dir=None, only_override=False, adb_path=None, remote_prefs_js=None): self.adb = AdbTool(path=adb_path) self.update_xml = update_xml if complete_mar is None and partial_mar is None and not only_override: raise UpdateException( "At least one of complete_mar or partial_mar is required") self.complete_mar = complete_mar self.partial_mar = partial_mar if only_override and not url_template: raise UpdateException("Update URL template required when only overriding") if update_dir and not url_template: raise UpdateException("Update URL template required with update dir") self.only_override = only_override self.is_local = update_dir is not None if not self.is_local: url_template = url_template or UpdateXmlBuilder.DEFAULT_URL_TEMPLATE self.update_url = url_template % { "filename": "update.xml" } self.stage_dir = update_dir if self.is_local else tempfile.mkdtemp() self.remote_prefs_js = remote_prefs_js def __del__(self): if not self.is_local: shutil.rmtree(self.stage_dir) def test_update(self, write_url_pref=True, restart=True): output_xml = os.path.join(self.stage_dir, "update.xml") with open(output_xml, "w") as out_file: out_file.write(self.update_xml) if not self.is_local: self.push_busybox() if not self.only_override: self.push_update_site() if not self.is_local: self.start_http_server() if write_url_pref: self.override_update_url() if restart: self.restart_b2g() def push_busybox(self): if self.adb.file_exists(self.REMOTE_BUSYBOX): print "Busybox already found at %s" % self.REMOTE_BUSYBOX return print "Busybox not found, pushing to %s" % self.REMOTE_BUSYBOX self.adb.shell("mkdir", "-p", self.REMOTE_BIN_DIR) self.adb.push(self.LOCAL_BUSYBOX, self.REMOTE_BUSYBOX) self.adb.shell("chmod", "755", self.REMOTE_BUSYBOX) def push_update_site(self): if self.complete_mar: if self.is_local: print "Copying %s to %s" % (self.complete_mar, self.stage_dir) shutil.copy(self.complete_mar, self.stage_dir) if self.partial_mar: if self.is_local: print "Copying %s to %s" % (self.partial_mar, self.stage_dir) shutil.copy(self.partial_mar, self.stage_dir) if not self.is_local: self.adb.push(self.stage_dir, self.REMOTE_HTTP_ROOT) def get_busybox_httpd_pid(self): pids = self.adb.get_pids("busybox") for pid in pids: cmdline = self.adb.get_cmdline(pid) if len(cmdline) > 1 and cmdline[1] == "httpd": return pid return None def start_http_server(self): busybox_pid = self.get_busybox_httpd_pid() if busybox_pid is not None: print "Busybox HTTP server already running, PID: %s" % busybox_pid return print "Starting Busybox HTTP server" self.adb.shell(self.REMOTE_BUSYBOX, "httpd", "-h", self.REMOTE_HTTP_ROOT) busybox_pid = self.get_busybox_httpd_pid() if busybox_pid is not None: print "Busybox HTTP server now running. Root: %s, PID: %s" % \ (self.REMOTE_HTTP_ROOT, busybox_pid) else: print >>sys.stderr, "Error: Busybox HTTP server PID not running" sys.exit(1) def override_update_url(self): if not self.remote_prefs_js: profile_dir = self.adb.shell("echo -n %s/*.default" % \ self.REMOTE_PROFILE_DIR) if "*" in profile_dir: raise UpdateException("Unable to find profile dir in %s" % \ self.REMOTE_PROFILE_DIR) self.remote_prefs_js = profile_dir + "/prefs.js" url_pref = "app.update.url.override" print "Overriding update URL in %s to %s" % (self.remote_prefs_js, self.update_url) self.adb.shell("echo 'user_pref(\"%s\", \"%s\");' >> %s" % \ (url_pref, self.update_url, self.remote_prefs_js)) def restart_b2g(self): print "Restarting B2G" self.adb.shell("stop b2g; start b2g") class Partition(object): def __init__(self, fs_type, mount_point, device, fs_size=0): self.fs_type = fs_type self.mount_point = mount_point self.device = device self.fs_size = fs_size @classmethod def create_system(cls, fs_type, device): return Partition(fs_type, "/system", device) @classmethod def create_data(cls, fs_type, device): return Partition(fs_type, "/data", device) """ Copied and adapted from AOSP (build/tools/releasetools/common.py) - fstab_version 1 is: mountpoint device fs mountoptions - fstab_version 2 is: device mountpoint fs mountflags fsoptions """ class RecoveryFSTab: def __init__(self, file): self._content = [] self._version = 0 with open(file, 'r') as f: self._content = f.readlines() for line in self._content: line = line.strip() if not line or line.startswith("#"): continue pieces = line.split() # fstab_version 1 if 3 <= len(pieces) <= 4: self._version = 1 # fstab_version 2 if len(pieces) == 5: self._version = 2 def read_v1(self): d = {} for line in self._content: line = line.strip() if not line or line.startswith("#"): continue pieces = line.split() if not (3 <= len(pieces) <= 4): raise ValueError("malformed recovery.fstab line: \"%s\"" % (line,)) p = Partition(pieces[1], pieces[0], pieces[2]) p.length = 0 options = None if len(pieces) >= 4: if pieces[3].startswith("/"): p.device2 = pieces[3] if len(pieces) >= 5: options = pieces[4] else: p.device2 = None options = pieces[3] else: p.device2 = None if options: options = options.split(",") for i in options: if i.startswith("length="): p.length = int(i[7:]) else: print "%s: unknown option \"%s\"" % (p.mount_point, i) d[p.mount_point] = p return d def read_v2(self): d = {} for line in self._content: line = line.strip() if not line or line.startswith("#"): continue pieces = line.split() if len(pieces) != 5: raise ValueError("malformed recovery.fstab line: \"%s\"" % (line,)) # Ignore entries that are managed by vold options = pieces[4] if "voldmanaged=" in options: continue # It's a good line, parse it p = Partition(pieces[2], pieces[1], pieces[0]) p.device2 = None p.length = 0 options = options.split(",") for i in options: if i.startswith("length="): p.length = int(i[7:]) else: # Ignore all unknown options in the unified fstab continue d[p.mount_point] = p return d def read(self): if self._version == 1: return self.read_v1() if self._version == 2: return self.read_v2() class FlashFotaBuilder(object): def __init__(self, fstab): self.fstab = RecoveryFSTab(fstab).read() self.symlinks = [] self.fota_check_fingerprints = [] if os.environ.get("FOTA_FINGERPRINTS"): self.fota_check_fingerprints = os.environ.get("FOTA_FINGERPRINTS").split(',') if "Item" not in globals(): self.import_releasetools() self.generator = edify_generator.EdifyGenerator(1, {"fstab": self.fstab}) def GetFilesType(self, directory): """ Compute file mime type for a directory """ cmd = ['file', '--mime-type' ] + glob.glob(os.path.join(directory, '*')) result = subprocess.check_output(cmd).split('\n') return result def AssertMountIfNeeded(self, mount_point): """ AssertMount the partition with the given mount_point if it is not already mounted. """ fstab = self.generator.info.get("fstab", None) if fstab: p = fstab[mount_point] self.generator.Print("Mounting " + mount_point) self.generator.script.append( 'ifelse(is_mounted("%s"),' \ 'ui_print("Already mounted."),' \ 'assert(mount("%s", "%s", "%s", "%s")));' % (p.mount_point, p.fs_type, common.PARTITION_TYPES[p.fs_type], p.device, p.mount_point)) self.generator.mounts.add(p.mount_point) def AssertSystemHasRwAccess(self): """ Assert that /system is mounted in rw mode """ self.generator.Print("Checking /system is writable") self.generator.script.append('assert(run_program("/system/bin/touch", "/system/bin/") == 0);') self.generator.Print("Partition is writable, we can continue") def GetDependencies(self, path): """ Find dependencies from readelf output """ so_re = re.compile(r".*\[(.*)\.so\]") readelf_android = "arm-linux-androideabi-readelf" readelf_path = os.path.join(os.environ.get("ANDROID_TOOLCHAIN"), readelf_android) result = run_command([readelf_path, "-d", path]) dependencies = [] for line in result.splitlines(): if line.find("(NEEDED)") > 0: match = so_re.match(line) if match and not (match.group(1) + ".so" in self.b2g_libs): # print "Adding dep against", match.group(1), "for", path dependencies.append(match.group(1) + ".so") return dependencies def GetSha1Values(self): """ Build a list of file/sha1 values """ b2g_bins = self.b2g_libs + self.b2g_exec b2g_exec_files = map(lambda x: os.path.join(self.out_b2g_dir, x), b2g_bins) deps_list = [] for p in b2g_exec_files: deps_list = list(set(deps_list + self.GetDependencies(p))) sha1_list = [] for root, dirs, files in os.walk(self.system_dir): for file in files: if file in deps_list: fpath = os.path.join(root, file) rpath = fpath.replace(self.system_dir, "/system") with open(fpath, 'r') as lib: hasher = hashlib.sha1() hasher.update(lib.read()) sha1_list.append({ 'file': rpath, 'sha1': hasher.hexdigest() }) return sha1_list def AssertGonkVersion(self): """ Assert that the gonk libs sha1 hashes are okay """ self.generator.Print("Checking Gonk version") for e in self.GetSha1Values(): self.generator.Print("Checking %s" % (e['file'],)) self.generator.script.append(('assert(sha1_check(read_file("%s"), "%s"));') % (e['file'], e['sha1'],)) self.generator.Print("Gonk version is okay") def AssertFingerprints(self): """ Assert that one of the fingerprints matches """ self.generator.Print("Checking build fingerprints") self.generator.AssertSomeFingerprint(*self.fota_check_fingerprints) self.generator.Print("Build is expected") def AssertDeviceOrModel(self, device): """ Assert that the device identifier is the given string. """ self.generator.Print("Checking device") cmd = ('assert(' 'getprop("ro.build.product") == "%s" || ' 'getprop("ro.product.device") == "%s" || ' 'getprop("ro.product.model") == "%s"' ');' % (device, device, device)) self.generator.script.append(cmd) self.generator.Print("Device is compatible") def CleanUpdateFiles(self): """ Cleaning all the temporary files used for update """ # delete_recursive() function in edify can handle files and # directories. staleUpdateFiles = [ os.path.join("/data", "local", "b2g-updates"), os.path.join(self.fota_sdcard, "updates", "fota") ] # sdcard will already be mounted anyway self.AssertMountIfNeeded("/data") self.generator.Print("Cleaning FOTA files") self.generator.DeleteFilesRecursive(staleUpdateFiles) self.generator.Print("FOTA files removed") def Umount(self, mount_point): """ Unmounting a mount point. We cannot do it against a device directly. """ self.generator.Print("Unmounting %s" % (mount_point)) self.generator.script.append(('unmount("%s");' % (mount_point))) def GetPartition(self, mount_point): """ Return a partition object from a mount point """ return self.fstab[mount_point] def Format(self, mount_point): """ Formatting a specific partition mounted at mount_point Edify wrapper to add format() statements. Per bug 1047350 and bug 1008239: Signature of the format() function available in Edify depends on the implementation that gets pulled as update-binary and pushed inside the zip file. Starting with AOSP SDK 16 (JB 4.1), it takes an extra mount_point argument. The rationale here is: - detect the SDK version at build time, and use the proper version - update-binary that is embedded MUST be one built from source or in sync with the source version. Using the prebuilt one from tools/update-tools/bin/gonk/ is not a good idea. """ format_statement = None if self.sdk_version < 16: format_statement = \ 'format("%(fs_type)s", "%(partition_type)s", ' \ '"%(device)s", %(size)d);' else: format_statement = \ 'format("%(fs_type)s", "%(partition_type)s", ' \ '"%(device)s", %(size)d, "%(mount_point)s");' partition = self.GetPartition(mount_point) # File system not in this will not be able to be formatted, e.g., vfat if partition.fs_type not in common.PARTITION_TYPES.keys(): return parameters = { 'fs_type': partition.fs_type, 'partition_type': common.PARTITION_TYPES[partition.fs_type], 'device': partition.device, 'size': partition.fs_size, 'mount_point': mount_point } self.generator.Print("Formatting partition %(mount_point)s, device %(device)s, as %(fs_type)s" % parameters) self.Umount(mount_point) self.generator.AppendExtra(format_statement % parameters) def FormatAll(self): """ Formatting all partitions """ didFormat = False for mount_point, partition in self.fstab.iteritems(): # We should only format what is asked for if not mount_point in self.fota_format_partitions: continue self.Format(mount_point) didFormat = True if didFormat: self.generator.Print("All partitions formatted.") def FlashPartition(self, mount_point, file): partition = self.GetPartition(mount_point) # File system not in this will not be able to be formatted, e.g., vfat if partition.fs_type not in common.PARTITION_TYPES.keys(): print >>sys.stderr, "WARNING: Unknown FS type:", partition.fs_type, \ "for", mount_point, "will continue without flashing this partition" return self.generator.Print("Flashing partition " + mount_point) params = { 'device': partition.device, 'image_file': file } self.generator.WriteRawImage(mount_point, file) def import_releasetools(self): releasetools_dir = os.path.join(b2g_dir, "build", "tools", "releasetools") sys.path.append(releasetools_dir) execfile(os.path.join(b2g_dir, "build", "tools", "releasetools", "ota_from_target_files"), globals()) sys.path.pop() def zip_filter(self, path, relpath): if self.fota_type == 'partial': if not relpath in self.fota_files: return False Item.Get(relpath, dir=os.path.isdir(path)) if not os.path.isdir(path) and os.path.islink(path): # This assumes that system always maps to /system, data to /data, etc self.symlinks.append((os.readlink(path), "/" + relpath)) return False return True def build_flash_fota(self, system_dir, public_key, private_key, output_zip, update_bin): fd, unsigned_zip = tempfile.mkstemp() os.close(fd) def custom_filter(target, files): return map(lambda x: os.path.basename(x.split(':')[0]), filter(lambda x: x.find(target) > 0, files)) self.out_b2g_dir = os.path.join(self.system_dir, "b2g") self.out_root = os.path.dirname(self.system_dir) files = self.GetFilesType(self.out_b2g_dir) self.b2g_libs = custom_filter('x-sharedlib', files) self.b2g_exec = custom_filter('x-executable', files) with FotaZip(unsigned_zip, "w") as flash_zip: if not self.fota_type == "fullimg": flash_zip.write_recursive(system_dir, "system", filter=self.zip_filter) flash_zip.write_updater_script(self.build_flash_script()) flash_zip.write_default_update_binary(update_bin) for p in self.fota_partitions: try: [ part, file ] = p.split(":") target_image = os.path.join(self.out_root, file) orig_image = os.path.join(self.out_root, file) p = self.GetPartition(part) # Expand sparse image if p.fs_type == "ext4": target_image += ".nosparse" run_command(["simg2img", orig_image, target_image]) flash_zip.write(target_image, file) # Delete expanded image if p.fs_type == "ext4": os.unlink(target_image) except ValueError as e: pass FotaZipBuilder().sign_zip(unsigned_zip, public_key, private_key, output_zip) os.unlink(unsigned_zip) def build_flash_script(self): if not hasattr(self.generator, 'DeleteFilesRecursive'): # This if block is for backwards compatibility since # mozilla-b2g/B2G is not tracked in sources.xml. # TODO: Remove after bug 1048854 has been fixed. def deprecated_DeleteFilesRecursive(objects): for o in objects: cmd = ('delete_recursive("%s");' % (o)) self.generator.script.append(self.generator._WordWrap(cmd)) self.generator.DeleteFilesRecursive = deprecated_DeleteFilesRecursive self.generator.Print("Starting B2G FOTA: " + self.fota_type) cmd = ('show_progress(1.0, 0);') self.generator.script.append(self.generator._WordWrap(cmd)) cmd = ('set_progress(0.25);') self.generator.script.append(self.generator._WordWrap(cmd)) # We do not want to check the device/model when we are checking fingerprints. if self.fota_check_device_name and not self.fota_check_fingerprints: self.AssertDeviceOrModel(self.fota_check_device_name) else: if self.fota_check_fingerprints: self.AssertFingerprints() # This method is responsible for checking the partitions we want to format self.FormatAll() # Let's handle partial/full when we extract directories/files if not self.fota_type == 'fullimg': # We need /system for unpacking the update, and /data to cleanup stale update self.AssertMountIfNeeded("/system") if self.fota_type == 'partial': # Checking fingerprint is for cases where we cannot # rely on checking sha1 of libs if self.fota_check_gonk_version and not self.fota_check_fingerprints: self.AssertGonkVersion() self.AssertSystemHasRwAccess() for f in self.fota_files: self.generator.Print("Removing " + f) self.generator.DeleteFiles(["/"+f]) for d in self.fota_dirs: self.generator.Print("Cleaning " + d) self.generator.DeleteFilesRecursive(["/"+d]) cmd = ('if greater_than_int(run_program("/system/bin/mv", "/system/b2g.bak", "/system/b2g"), 0) then') self.generator.script.append(self.generator._WordWrap(cmd)) self.generator.Print("No previous stale update.") cmd = ('set_progress(0.5);') self.generator.script.append(self.generator._WordWrap(cmd)) self.generator.Print("Remove stale libdmd.so") self.generator.DeleteFiles(["/system/b2g/libdmd.so"]) self.generator.Print("Remove stale update") self.generator.DeleteFilesRecursive(["/system/b2g/updated"]) self.generator.Print("Extracting files to /system") self.generator.UnpackPackageDir("system", "/system") cmd = ('set_progress(0.75);') self.generator.script.append(self.generator._WordWrap(cmd)) self.generator.Print("Creating symlinks") self.generator.MakeSymlinks(self.symlinks) self.generator.Print("Setting file permissions") self.build_permissions() cmd = ('set_progress(0.8);') self.generator.script.append(self.generator._WordWrap(cmd)) self.generator.Print("Cleaning update files") self.CleanUpdateFiles() if self.fota_type == 'partial': cmd = ('else ui_print("Restoring previous stale update."); endif;') self.generator.script.append(self.generator._WordWrap(cmd)) cmd = ('set_progress(0.9);') self.generator.script.append(self.generator._WordWrap(cmd)) self.generator.Print("Unmounting ...") self.generator.UnmountAll() for p in self.fota_partitions: try: [ part, file ] = p.split(":") self.FlashPartition(part, file) except ValueError as e: pass cmd = ('set_progress(1.0);') self.generator.script.append(self.generator._WordWrap(cmd)) return "\n".join(self.generator.script) + "\n" def build_permissions(self): # Put fs_config on the PATH host = "linux-x86" if platform.system() == "Darwin": host = "darwin-x86" host_bin_dir = os.path.join(b2g_dir, "out", "host", host, "bin") fs_config = Tool(os.path.join(host_bin_dir, "fs_config")) suffix = { False: "", True: "/" } paths = "\n".join([i.name + suffix[i.dir] for i in Item.ITEMS.itervalues() if i.name]) + '\n' self.fs_config_data = fs_config.run(input=paths) # see build/tools/releasetools/ota_from_target_files Item.GetMetadata(self) if not self.fota_type == 'partial': Item.Get("system").SetPermissions(self.generator) else: for f in self.fota_files: Item.Get(f).SetPermissions(self.generator) for d in self.fota_dirs: Item.Get(d).SetPermissions(self.generator) "Emulate zipfile.read so we can reuse Item.GetMetadata" def read(self, path): if path == "META/filesystem_config.txt": return self.fs_config_data raise KeyError b2g_config = B2GConfig()
import PropTypes from 'prop-types'; import { MAPBOX_TOKEN } from 'constants/map'; import PopulationMap from './PopulationMap'; import { tileLayerPixelFilter } from 'helpers/filterPixel'; class ClimateMap extends PopulationMap { constructor(props) { super(props); this.climateLayers = {}; } componentDidMount() { super.componentDidMount(); this.updateClimateLayers(); } componentDidUpdate(prevProps, prevState) { super.componentDidUpdate(prevProps, prevState); if (this.props.layers !== prevProps.layers) { this.updateClimateLayers(); } } componentWillReceiveProps(newProps) { super.componentWillReceiveProps(newProps); } updateClimateLayers() { if (!this.props.layers && this.props.layers.climate) return; const speciesId = this.props.id; const frontLayers = []; ['present', 'future', 'gains', 'losses'].forEach((time) => { ['b', 'w', 'p', 'S'].forEach((season) => { const layerId = `${time}_${speciesId}_${season}`; const layerName = `${speciesId}_${season}`; const layerPath = `https://api.mapbox.com/v4/wetlands.${layerName}/{z}/{x}/{y}.png?access_token=${MAPBOX_TOKEN}`; const layerObj = this.climateLayers[layerId] || this.createClimateLayer(layerId, layerPath, time); const varName = ['climate', time, season].join('_'); if (this.props.layers.climate && this.props.layers[varName]) { layerObj.addTo(this.map); if (time === 'gains') { frontLayers.push(layerObj); } } else { layerObj.remove(); } }); }); frontLayers.map(fl => fl.bringToFront()); } createClimateLayer(layerId, layerPath, time) { //const climateLayer = L.tileLayer(layerPath).setZIndex(1); const filterOptions = { present: time }; const climateLayer = L.tileLayerPixelFilter(layerPath, filterOptions).setZIndex(1); this.climateLayers[layerId] = climateLayer; return climateLayer; } } ClimateMap.propTypes = { ...PopulationMap.propTypes, id: PropTypes.string }; export default ClimateMap;
'use strict'; const key = 'YOURAPIKEY'; const SparkPost = require('sparkpost'); const client = new SparkPost(key); const searchParams = { events : 'click', campaign_ids : 'monday_mailshot' }; // Promise client.messageEvents.search(searchParams).then((data) => { console.log('Congrats you can use our client library!'); console.log(data); }).catch((err) => { console.log('Whoops! Something went wrong'); console.log(err); });
/* global jest, expect, describe, test, beforeEach */ const nock = require('nock'); const { Probot } = require('probot'); jest.mock('bpmn-to-image'); jest.mock('imgur'); const renderBpmnApp = require('../src'); const payload = require('./fixtures/issue_comment.created'); const xml = `<?xml version="1.0" encoding="UTF-8"?> <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="Definitions_1v7jeps" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.3.0-nightly"> <bpmn:process id="Process_1r6cnd7" isExecutable="true"> <bpmn:startEvent id="StartEvent_1"> <bpmn:outgoing>SequenceFlow_0xbi38e</bpmn:outgoing> </bpmn:startEvent> <bpmn:sequenceFlow id="SequenceFlow_0xbi38e" sourceRef="StartEvent_1" targetRef="ExclusiveGateway_0d80meh" /> <bpmn:endEvent id="EndEvent_14564ng"> <bpmn:incoming>SequenceFlow_0wetfnk</bpmn:incoming> </bpmn:endEvent> <bpmn:sequenceFlow id="SequenceFlow_087tlq4" sourceRef="IntermediateThrowEvent_0hxqe4w" targetRef="Task_1aaly1t" /> <bpmn:task id="Task_1aaly1t"> <bpmn:incoming>SequenceFlow_087tlq4</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0wetfnk</bpmn:outgoing> </bpmn:task> <bpmn:sequenceFlow id="SequenceFlow_0wetfnk" sourceRef="Task_1aaly1t" targetRef="EndEvent_14564ng" /> <bpmn:eventBasedGateway id="ExclusiveGateway_0d80meh"> <bpmn:incoming>SequenceFlow_0xbi38e</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0t7oahk</bpmn:outgoing> </bpmn:eventBasedGateway> <bpmn:intermediateCatchEvent id="IntermediateThrowEvent_0hxqe4w"> <bpmn:incoming>SequenceFlow_0t7oahk</bpmn:incoming> <bpmn:outgoing>SequenceFlow_087tlq4</bpmn:outgoing> <bpmn:messageEventDefinition /> </bpmn:intermediateCatchEvent> <bpmn:sequenceFlow id="SequenceFlow_0t7oahk" sourceRef="ExclusiveGateway_0d80meh" targetRef="IntermediateThrowEvent_0hxqe4w" /> </bpmn:process> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1r6cnd7"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1"> <dc:Bounds x="162" y="99" width="36" height="36" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0xbi38e_di" bpmnElement="SequenceFlow_0xbi38e"> <di:waypoint x="198" y="117" /> <di:waypoint x="245" y="117" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_14564ng_di" bpmnElement="EndEvent_14564ng"> <dc:Bounds x="562" y="99" width="36" height="36" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_087tlq4_di" bpmnElement="SequenceFlow_087tlq4"> <di:waypoint x="378" y="117" /> <di:waypoint x="420" y="117" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="Task_1aaly1t_di" bpmnElement="Task_1aaly1t"> <dc:Bounds x="420" y="77" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0wetfnk_di" bpmnElement="SequenceFlow_0wetfnk"> <di:waypoint x="520" y="117" /> <di:waypoint x="562" y="117" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EventBasedGateway_1mekx4f_di" bpmnElement="ExclusiveGateway_0d80meh"> <dc:Bounds x="245" y="92" width="50" height="50" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="IntermediateCatchEvent_1te0yds_di" bpmnElement="IntermediateThrowEvent_0hxqe4w"> <dc:Bounds x="342" y="99" width="36" height="36" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0t7oahk_di" bpmnElement="SequenceFlow_0t7oahk"> <di:waypoint x="295" y="117" /> <di:waypoint x="342" y="117" /> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> </bpmn:definitions> `; nock.disableNetConnect(); describe('render-bpmn', () => { let probot; // load probot beforeEach(() => { probot = new Probot({ id: 123, githubToken: 'test' }); probot.load(renderBpmnApp); }); // mock requests beforeEach(() => { nock.enableNetConnect(); nock('https://api.github.com') .post('/app/installations/2/access_tokens') .reply(200, { token: 'test' }); nock('https://github.com') .get('/pinussilvestrus/github-bpmn/files/3504544/diagram_copypaste.bpmn.txt') .reply(200, xml); nock('https://api.imgur.com') .post('/3/image') .reply(200, { data: { link: 'foo' } }); }); test('update comment after created', async () => { nock('https://api.github.com') .patch( '/repos/pinussilvestrus/github-bpmn/issues/comments/1', (body) => { // then, update #1 loading spinner expect(body).not.toBeUndefined(); expect(body.body).toContain( '![](https://github.com/pinussilvestrus/github-bpmn/blob/master/probot-app/src/misc/loading.gif?raw=true)' ); nock('https://api.github.com') .patch( '/repos/pinussilvestrus/github-bpmn/issues/comments/1', (body) => { // then, update #2 rendered diagram expect(body).not.toBeUndefined(); expect(body.body).toContain( '<img data-original=https://github.com/pinussilvestrus/github-bpmn/files/3504544/diagram_copypaste.bpmn.txt' ); return true; }) .reply(200); return true; }) .reply(200); // when await probot.receive({ name: 'issue_comment', payload }); }); });
import Taro, { Component } from '@tarojs/taro' import { View, Text, Canvas } from '@tarojs/components' import { AtButton, AtCard } from 'taro-ui' import './index.scss' import menusData from './data' export default class Location extends Component { config = { navigationBarTitleText: '网络相关API展示页' } state = { componentName: '界面', currentIndex: 0, animationObj: '', resultText: '', animationObj: { transformOrigin: 'left top 0', duration: 2000, timingFunction: 'linear', delay: 100, }, animationOprate: [ { name: '旋转', type: 'rotate' }, { name: '缩放', type: 'scale' }, { name: '移动', type: 'translate' }, { name: '展示全部', type: 'all' }, { name: '还原', type: 'reset' } ] } componentWillMount () { } componentDidMount () { } componentWillUnmount () { } componentDidShow () { } componentDidHide () { } handleMenuItem (methods, type, env, obj={}) { const nowEnv = Taro.getEnv() if (env.indexOf(nowEnv) === -1) { Taro.showToast({ icon: 'none', title: `该api暂不支持${nowEnv}环境` }) this.setState({ resultText: ` 该 api 暂不支持 ${nowEnv} 环境 ` }) return } if (type === 'animation') { this.handleAnimation('scale') } else if (type === 'selector') { let query = Taro.createSelectorQuery() switch (methods) { case 'createSelectorQuery': this.setState({ resultText: ` 成功创建了 SelectorQuery 对象实例 ` }) break case 'in': query = query.in(this.$scope) this.setState({ resultText: ` 选取范围更改为自定义组件 component 内,(注:在 h5 中不起作用)` }) break case 'select': query .select('.common_title') .boundingClientRect( rect => { this.setState({ resultText: ` 选取的是标题节点的相关信息; \n ${JSON.stringify(rect, 2)}` }) }) .exec() break case 'selectAll': query .selectAll('.common_menu_title') .boundingClientRect( rect => { this.setState({ resultText: ` 匹配出. common_menu_title 的所有节点; \n ${JSON.stringify(rect, 2)}` }) }) .exec() break case 'selectViewport': query .selectViewport() .boundingClientRect( rect => { this.setState({ resultText: ` 当前显示区域相关信息; \n ${JSON.stringify(rect, 2)}` }) }) .exec() break case 'boundingClientRect': query .select('.common_title') .boundingClientRect( rect => { this.setState({ resultText: ` 返回节点信息的位置 left、right 等字段描述; \n ${JSON.stringify(rect, 2)}` }) }) .exec() break case 'scrollOffset': query .selectViewport() .scrollOffset( rect => { this.setState({ resultText: ` 节点的滚动位置 ${rect.scrollTop}${rect.scrollLeft}` }) }) .exec() break case 'exec': query .selectViewport() .scrollOffset( rect => { this.setState({ resultText: ` 执行了 exec 方法; 获得了节点的滚动位置 ${JSON.stringify(rect, 2)}` }) }) .exec() break } } else if (type === 'canvas') { switch (methods) { case 'createCanvasContext': let context = Taro[methods]('canvasTest') context.setStrokeStyle("#00ff00") context.setLineWidth(5) context.rect(0, 0, 200, 200) context.stroke() context.setStrokeStyle("#ff0000") context.setLineWidth(2) context.moveTo(160, 100) context.arc(100, 100, 60, 0, 2 * Math.PI, true) context.moveTo(140, 100) context.arc(100, 100, 40, 0, Math.PI, false) context.moveTo(85, 80) context.arc(80, 80, 5, 0, 2 * Math.PI, true) context.moveTo(125, 80) context.arc(120, 80, 5, 0, 2 * Math.PI, true) context.stroke() context.draw() break case 'createContext': let context2 = Taro.createContext() context2.rect(10, 10, 150, 75) context2.fill() context2.stroke() Taro.drawCanvas({ canvasId: 'canvasTest', actions: context2.getActions() }) Taro.showToast({ icon: 'none', title: '不推荐使用' }) break case 'drawCanvas': Taro.showToast({ icon: 'none', title: '不推荐使用' }) let context3 = Taro.createContext() context3.rect(10, 10, 150, 75) context3.setFillStyle('red') context3.fill() context3.stroke() Taro.drawCanvas({ canvasId: 'canvasTest', actions: context3.getActions() }) break default : console.warn('type传值有误') } } else if (type === 'obj') { Taro[methods](obj) } else { Taro[methods]() } } handleMenu (index) { this.setState({ currentIndex: this.state.currentIndex === index ? -1 : index }) } goMenu = () => { Taro.navigateTo({url: '/pages/index/index'}) } handleAnimation = (type='reset') => { const nowEnv = Taro.getEnv() if (nowEnv !== 'WEAPP') { Taro.showToast({ icon: 'none', title: `该api暂不支持${nowEnv}环境` }) this.setState({ resultText: ` 该 api 暂不支持 ${nowEnv} 环境 ` }) return } let animationObj = Taro.createAnimation(this.state.animationObj) switch (type) { case 'rotate': animationObj.rotate(Math.random() * 720 - 360).step() break case 'scale': animationObj.scale(Math.random() * 2).step() break case 'translate': animationObj.translate(Math.random() * 100 - 50, Math.random() * 100 - 50).step() break case 'all': animationObj.rotate(Math.random() * 720 - 360).step() .scale(Math.random() * 2).step() .translate(Math.random() * 100 - 50, Math.random() * 100 - 50).step() .skew(Math.random() * 90, Math.random() * 90).step() break case 'reset': animationObj.rotate(0, 0) .scale(1) .translate(0, 0) .skew(0, 0) .step({ duration: 0 }) break default: console.warn('暂无该操作') } this.setState({ animationObj: animationObj.export() }) } render () { const { componentName, currentIndex, animationObj, resultText, animationOprate } = this.state return ( <View className='interface'> <View className='common_tips'> <Text className='common_tip_text'>这里展示的是Taro官方端能力,将展示基本API的调用方式及效果</Text> </View> <View className='common_header'> <Text className='common_title'>{componentName}</Text> </View> <View className='interface_menu'> { menusData.map((menu, index) => { return ( <View className={currentIndex === index ? 'menu active' : 'menu'} key={index}> <View className='menu_title' onClick={this.handleMenu.bind(this, index)} > <Text className='menu_title_name'>{menu.name}</Text> <Text className='menu_title_icon'></Text> </View> { currentIndex === index && menu.type === 'selector' && <View> <AtCard title='API 效果展示'> <View style='word-wrap: break-word'> {resultText} </View> </AtCard> </View> } { currentIndex === index && menu.type === 'canvas' && <View> <AtCard title='API 效果展示'> <View style='word-wrap: break-word'> <Canvas style='width: 300px; height: 200px;' canvas-id='canvasTest'></Canvas> </View> </AtCard> </View> } { currentIndex === index && menu.type === 'animation' && <View> <AtCard title='API 效果展示'> <View className='animation'> <View className='animation_content' animation={animationObj}>看我表演~</View> </View> </AtCard> </View> } { currentIndex === index && menu.children.map((item, ind) => { return ( <View key={ind} className='menu_item' > <AtButton type='primary' onClick={this.handleMenuItem.bind(this, item.methods, item.type, item.env, item.obj)} > {item.name} </AtButton> { item.type === 'animation' && <View className='animation_oprate'> { animationOprate.map((oprate, oprateIndex) => { return ( <View key={oprateIndex} className='animation_oprate_btn'> <AtButton type='secondary' size='small' onClick={this.handleAnimation.bind(this, oprate.type)} > {oprate.name} </AtButton> </View> ) }) } </View> } </View> ) }) } </View> ) }) } </View> <View className={Taro.getEnv() === 'H5' ? 'go_menu_btn' : 'go_menu_btn h5'} onClick={this.goMenu}> 返回首页 </View> </View> ) } }
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-1147343e"],{"04f64":function(t,e,r){"use strict";r("4ca4")},"4ca4":function(t,e,r){},c273:function(t,e,r){"use strict";r.r(e);var n=function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",{staticClass:"errPage-container"},[r("ErrorA"),r("ErrorB"),r("h3",[t._v(t._s(t.$t("errorLog.tips")))]),r("aside",[t._v(" "+t._s(t.$t("errorLog.description"))+" "),r("a",{staticClass:"link-type",attrs:{target:"_blank",href:"https://panjiachen.github.io/vue-element-admin-site/guide/advanced/error.html"}},[t._v(" "+t._s(t.$t("errorLog.documentation"))+" ")])]),t._m(0)],1)},a=[function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("a",{attrs:{href:"#"}},[r("img",{attrs:{src:"https://wpimg.wallstcn.com/360e4842-4db5-42d0-b078-f9a84a825546.gif"}})])}],s=function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",[t._v(" "+t._s(t.a.a)+" ")])},c=[],i={name:"ErrorTestA"},o=i,l=r("2877"),u=Object(l["a"])(o,s,c,!1,null,null,null),f=u.exports,_=function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div")},d=[],p={created:function(){this.b=b}},h=p,m=Object(l["a"])(h,_,d,!1,null,null,null),v=m.exports,g={name:"ErrorLog",components:{ErrorA:f,ErrorB:v}},E=g,w=(r("04f64"),Object(l["a"])(E,n,a,!1,null,"d5a4ca3c",null));e["default"]=w.exports}}]);
const signInBtn = document.getElementById("signIn"); const signUpBtn = document.getElementById("signUp"); const fistForm = document.getElementById("form1"); const secondForm = document.getElementById("form2"); const container = document.querySelector(".container"); signInBtn.addEventListener("click", () => { container.classList.remove("right-panel-active"); }); signUpBtn.addEventListener("click", () => { container.classList.add("right-panel-active"); }); fistForm.addEventListener("submit", (e) => e.preventDefault()); secondForm.addEventListener("submit", (e) => e.preventDefault());
/** * h5Validate * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Developed under the sponsorship of RootMusic, and Zumba Fitness */ /*global jQuery, window, console */ (function ($) { 'use strict'; var console = window.console || function () {}, h5 = { // Public API defaults : { debug: false, RODom: false, // HTML5-compatible validation pattern library that can be extended and/or overriden. patternLibrary : { //** TODO: Test the new regex patterns. Should I apply these to the new input types? // **TODO: password phone: /([\+][0-9]{1,3}([ \.\-])?)?([\(][0-9]{1,6}[\)])?([0-9A-Za-z \.\-]{1,32})(([A-Za-z \:]{1,11})?[0-9]{1,4}?)/, // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ email: /((([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?/, // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/iri/ url: /(https?|ftp):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?/, // Number, including positive, negative, and floating decimal. Credit: bassistance number: /-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?/, // Date in ISO format. Credit: bassistance dateISO: /\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/, alpha: /[a-zA-Z]+/, alphaNumeric: /\w+/, integer: /-?\d+/ }, // The prefix to use for dynamically-created class names. classPrefix: 'h5-', errorClass: 'ui-state-error', // No prefix for these. validClass: 'ui-state-valid', // " activeClass: 'active', // Prefix will get prepended. requiredClass: 'required', requiredAttribute: 'required', patternAttribute: 'pattern', // Attribute which stores the ID of the error container element (without the hash). errorAttribute: 'data-h5-errorid', // Events API customEvents: { 'validate': true }, // Setup KB event delegation. kbSelectors: ':input:not(:button):not(:disabled):not(.novalidate)', focusout: true, focusin: false, change: true, keyup: false, activeKeyup: true, // Setup mouse event delegation. mSelectors: '[type="range"]:not(:disabled):not(.novalidate), :radio:not(:disabled):not(.novalidate), :checkbox:not(:disabled):not(.novalidate), select:not(:disabled):not(.novalidate), option:not(:disabled):not(.novalidate)', click: true, // What do we name the required .data variable? requiredVar: 'h5-required', // What do we name the pattern .data variable? patternVar: 'h5-pattern', stripMarkup: true, // Run submit related checks and prevent form submission if any fields are invalid? submit: true, // Move focus to the first invalid field on submit? focusFirstInvalidElementOnSubmit: true, // When submitting, validate elements that haven't been validated yet? validateOnSubmit: true, // Callback stubs invalidCallback: function () {}, validCallback: function () {}, // Elements to validate with allValid (only validating visible elements) //sanljiljan: allValidSelectors: ':input:visible:not(:button):not(:disabled):not(.novalidate)', allValidSelectors: ':input:not(:button):not(:disabled):not(.novalidate)', // Mark field invalid. // ** TODO: Highlight labels // ** TODO: Implement setCustomValidity as per the spec: // http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-setcustomvalidity markInvalid: function markInvalid(options) { var $element = $(options.element), $errorID = $(options.errorID); if( $element.hasClass('cleditor') || $element.hasClass('valid_parent') ) { $element.parent().addClass(options.errorClass).removeClass(options.validClass); $element.parent().addClass(options.settings.activeClass); } else { $element.addClass(options.errorClass).removeClass(options.validClass); $element.addClass(options.settings.activeClass); } //if(!$element.closest('div.tab-pane').hasClass('active') == true && $('.'+options.errorClass).length == 1 ) if( !$element.closest('div.tab-pane').hasClass('active') == true && $('div.tab-pane.active .ui-state-error').length == 0) { //$('div.tab-pane.active').removeClass('active'); //$element.closest('div.tab-pane').addClass('active'); var attr_id = $element.closest('div.tab-pane').attr('id'); //simulate click on change langauge $('.tabbable .nav.nav-tabs li a[href=#'+attr_id+']').trigger("click"); } else { } // by sanljiljan //if($element.hasClass('cleditor') || $element.hasClass('valid_parent')) // $element.parent().addClass(options.errorClass).removeClass(options.validClass); // User needs help. Enable active validation. //if( !($element.hasClass('cleditor') || $element.hasClass('valid_parent')) ) // $element.addClass(options.settings.activeClass); if ($errorID.length) { // These ifs are technically not needed, but improve server-side performance if ($element.attr('title')) { $errorID.text($element.attr('title')); } $errorID.show(); } $element.data('valid', false); options.settings.invalidCallback.call(options.element, options.validity); return $element; }, // Mark field valid. markValid: function markValid(options) { var $element = $(options.element), $errorID = $(options.errorID); $element.addClass(options.validClass).removeClass(options.errorClass); // by sanljiljan if($element.hasClass('cleditor') || $element.hasClass('valid_parent')) { $element.parent().addClass(options.validClass).removeClass(options.errorClass); } if ($errorID.length) { $errorID.hide(); } $element.data('valid', true); options.settings.validCallback.call(options.element, options.validity); return $element; }, // Unmark field unmark: function unmark(options) { var $element = $(options.element); $element.removeClass(options.errorClass).removeClass(options.validClass); // by sanljiljan if($element.hasClass('cleditor') || $element.hasClass('valid_parent')) $element.parent().removeClass(options.errorClass).removeClass(options.validClass); $element.form.find("#" + options.element.id).removeClass(options.errorClass).removeClass(options.validClass); return $element; } } }, // Aliases defaults = h5.defaults, patternLibrary = defaults.patternLibrary, createValidity = function createValidity(validity) { return $.extend({ customError: validity.customError || false, patternMismatch: validity.patternMismatch || false, rangeOverflow: validity.rangeOverflow || false, rangeUnderflow: validity.rangeUnderflow || false, stepMismatch: validity.stepMismatch || false, tooLong: validity.tooLong || false, typeMismatch: validity.typeMismatch || false, valid: validity.valid || true, valueMissing: validity.valueMissing || false }, validity); }, methods = { /** * Check the validity of the current field * @param {object} settings instance settings * @param {object} options * .revalidate - trigger validation function first? * @return {Boolean} */ isValid: function (settings, options) { var $this = $(this); options = (settings && options) || {}; // Revalidate defaults to true if (options.revalidate !== false) { $this.trigger('validate'); } return $this.data('valid'); // get the validation result }, allValid: function (config, options) { var valid = true, formValidity = [], $this = $(this), $allFields, $filteredFields, radioNames = [], getValidity = function getValidity(e, data) { data.e = e; formValidity.push(data); }, settings = $.extend({}, config, options); // allow options to override settings options = options || {}; $this.trigger('formValidate', {settings: $.extend(true, {}, settings)}); // Make sure we're not triggering handlers more than we need to. $this.undelegate(settings.allValidSelectors, '.allValid', getValidity); $this.delegate(settings.allValidSelectors, 'validated.allValid', getValidity); $allFields = $this.find(settings.allValidSelectors); // Filter radio buttons with the same name and keep only one, // since they will be checked as a group by isValid() $filteredFields = $allFields.filter(function(index) { var name; if(this.tagName === "INPUT" && this.type === "radio") { name = this.name; if(radioNames[name] === true) { return false; } radioNames[name] = true; } return true; }); $filteredFields.each(function () { var $this = $(this); valid = $this.h5Validate('isValid', options) && valid; }); $this.trigger('formValidated', {valid: valid, elements: formValidity}); return valid; }, validate: function (settings) { // Get the HTML5 pattern attribute if it exists. // ** TODO: If a pattern class exists, grab the pattern from the patternLibrary, but the pattern attrib should override that value. var $this = $(this), pattern = $this.filter('[pattern]')[0] ? $this.attr('pattern') : false, // The pattern attribute must match the whole value, not just a subset: // "...as if it implied a ^(?: at the start of the pattern and a )$ at the end." re = new RegExp('^(?:' + pattern + ')$'), $radiosWithSameName = null, value = ($this.is('[type=checkbox]')) ? $this.is(':checked') : ($this.is('[type=radio]') ? // Cache all radio buttons (in the same form) with the same name as this one ($radiosWithSameName = $this.parents('form') // **TODO: escape the radio buttons' name before using it in the jQuery selector .find('input[name="' + $this.attr('name') + '"]')) .filter(':checked') .length > 0 : $this.val()), errorClass = settings.errorClass, validClass = settings.validClass, errorIDbare = $this.attr(settings.errorAttribute) || false, // Get the ID of the error element. errorID = errorIDbare ? '#' + errorIDbare.replace(/(:|\.|\[|\])/g,'\\$1') : false, // Add the hash for convenience. This is done in two steps to avoid two attribute lookups. required = false, validity = createValidity({element: this, valid: true}), $checkRequired = $('<input required>'), maxlength; /* If the required attribute exists, set it required to true, unless it's set 'false'. * This is a minor deviation from the spec, but it seems some browsers have falsey * required values if the attribute is empty (should be true). The more conformant * version of this failed sanity checking in the browser environment. * This plugin is meant to be practical, not ideologically married to the spec. */ // Feature fork if ($checkRequired.filter('[required]') && $checkRequired.filter('[required]').length) { required = ($this.filter('[required]').length && $this.attr('required') !== 'false'); } else { required = ($this.attr('required') !== undefined); } if (settings.debug && window.console) { console.log('Validate called on "' + value + '" with regex "' + re + '". Required: ' + required); // **DEBUG console.log('Regex test: ' + re.test(value) + ', Pattern: ' + pattern); // **DEBUG } maxlength = parseInt($this.attr('maxlength'), 10); if (!isNaN(maxlength) && value.length > maxlength) { validity.valid = false; validity.tooLong = true; } // by sanljiljan if (required && value == '<br>') { value = false; } if (required && !value) { validity.valid = false; validity.valueMissing = true; } else if (pattern && !re.test(value) && value) { validity.valid = false; validity.patternMismatch = true; } else { if (!settings.RODom) { settings.markValid({ element: this, validity: validity, errorClass: errorClass, validClass: validClass, errorID: errorID, settings: settings }); } } if (!validity.valid) { if (!settings.RODom) { settings.markInvalid({ element: this, validity: validity, errorClass: errorClass, validClass: validClass, errorID: errorID, settings: settings }); } } $this.trigger('validated', validity); // If it's a radio button, also validate the other radio buttons with the same name // (while making sure the call is not recursive) if($radiosWithSameName !== null && settings.alreadyCheckingRelatedRadioButtons !== true) { settings.alreadyCheckingRelatedRadioButtons = true; $radiosWithSameName .not($this) .trigger('validate'); settings.alreadyCheckingRelatedRadioButtons = false; } }, /** * Take the event preferences and delegate the events to selected * objects. * * @param {object} eventFlags The object containing event flags. * * @returns {element} The passed element (for method chaining). */ delegateEvents: function (selectors, eventFlags, element, settings) { var events = {}, key = 0, validate = function () { settings.validate.call(this, settings); }; $.each(eventFlags, function (key, value) { if (value) { events[key] = key; } }); // key = 0; for (key in events) { if (events.hasOwnProperty(key)) { $(element).delegate(selectors, events[key] + '.h5Validate', validate); } } return element; }, /** * Prepare for event delegation. * * @param {object} settings The full plugin state, including * options. * * @returns {object} jQuery object for chaining. */ bindDelegation: function (settings) { var $this = $(this), $forms; // Attach patterns from the library to elements. // **TODO: pattern / validation method matching should // take place inside the validate action. $.each(patternLibrary, function (key, value) { var pattern = value.toString(); pattern = pattern.substring(1, pattern.length - 1); $('.' + settings.classPrefix + key).attr('pattern', pattern); }); $forms = $this.filter('form') .add($this.find('form')) .add($this.parents('form')); $forms .attr('novalidate', 'novalidate') .submit(checkValidityOnSubmitHandler); $forms.find("input[formnovalidate][type='submit']").click(function(){ $(this).closest("form").unbind('submit', checkValidityOnSubmitHandler); }); return this.each(function () { var kbEvents = { focusout: settings.focusout, focusin: settings.focusin, change: settings.change, keyup: settings.keyup }, mEvents = { click: settings.click }, activeEvents = { keyup: settings.activeKeyup }; settings.delegateEvents(':input', settings.customEvents, this, settings); settings.delegateEvents(settings.kbSelectors, kbEvents, this, settings); settings.delegateEvents(settings.mSelectors, mEvents, this, settings); settings.delegateEvents(settings.activeClassSelector, activeEvents, this, settings); settings.delegateEvents('textarea[maxlength]', {keyup: true}, this, settings); }); } }, /** * Event handler for the form submit event. * When settings.submit is enabled: * - prevents submission if any invalid fields are found. * - Optionally validates all fields. * - Optionally moves focus to the first invalid field. * * @param {object} evt The jQuery Event object as from the submit event. * * @returns {object} undefined if no validation was done, true if validation passed, false if validation didn't. */ checkValidityOnSubmitHandler = function(evt) { var $this, settings = getInstance.call(this), allValid; if(settings.submit !== true) { return; } $this = $(this); allValid = $this.h5Validate('allValid', { revalidate: settings.validateOnSubmit === true }); if(allValid !== true) { evt.preventDefault(); if(settings.focusFirstInvalidElementOnSubmit === true){ var $invalid = $(settings.allValidSelectors, $this) .filter(function(index){ return $(this).h5Validate('isValid', { revalidate: false }) !== true; }); $invalid.first().focus(); // by sanljiljan $(window).scrollTop($invalid.first().parent().offset().top-100); //console.log($invalid.first().parent().offset().top); //console.log($invalid.first().parent()); } } return allValid; }, instances = [], buildSettings = function buildSettings(options) { // Combine defaults and options to get current settings. var settings = $.extend({}, defaults, options, methods), activeClass = settings.classPrefix + settings.activeClass; return $.extend(settings, { activeClass: activeClass, activeClassSelector: '.' + activeClass, requiredClass: settings.classPrefix + settings.requiredClass, el: this }); }, getInstance = function getInstance() { var $parent = $(this).closest('[data-h5-instanceId]'); return instances[$parent.attr('data-h5-instanceId')]; }, setInstance = function setInstance(settings) { var instanceId = instances.push(settings) - 1; if (settings.RODom !== true) { $(this).attr('data-h5-instanceId', instanceId); } $(this).trigger('instance', { 'data-h5-instanceId': instanceId }); }; $.h5Validate = { /** * Take a map of pattern names and HTML5-compatible regular * expressions, and add them to the patternLibrary. Patterns in * the library are automatically assigned to HTML element pattern * attributes for validation. * * @param {Object} patterns A map of pattern names and HTML5 compatible * regular expressions. * * @returns {Object} patternLibrary The modified pattern library */ addPatterns: function (patterns) { var patternLibrary = defaults.patternLibrary, key; for (key in patterns) { if (patterns.hasOwnProperty(key)) { patternLibrary[key] = patterns[key]; } } return patternLibrary; }, /** * Take a valid jQuery selector, and a list of valid values to * validate against. * If the user input isn't in the list, validation fails. * * @param {String} selector Any valid jQuery selector. * * @param {Array} values A list of valid values to validate selected * fields against. */ validValues: function (selector, values) { var i = 0, ln = values.length, pattern = '', re; // Build regex pattern for (i = 0; i < ln; i += 1) { pattern = pattern ? pattern + '|' + values[i] : values[i]; } re = new RegExp('^(?:' + pattern + ')$'); $(selector).data('regex', re); } }; $.fn.h5Validate = function h5Validate(options) { var action, args, settings; if (typeof options === 'string' && typeof methods[options] === 'function') { // Whoah, hold on there! First we need to get the instance: settings = getInstance.call(this); args = [].slice.call(arguments, 0); action = options; args.shift(); args = $.merge([settings], args); // Use settings here so we can plug methods into the instance dynamically? return settings[action].apply(this, args); } settings = buildSettings.call(this, options); setInstance.call(this, settings); // Returning the jQuery object allows for method chaining. return methods.bindDelegation.call(this, settings); }; }(jQuery));
const isProduction = process.env.NODE_ENV === 'production'; const path = require('path'); const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const config = require('./webpack.config'); const express = require('express'); const port = process.env.PORT || 9090; let app; const compiler = webpack(config); if (isProduction) { const gzipFiles = ['.js']; app = express(); app.get(gzipFiles, (req, res) => { res.set('Content-Encoding', 'gzip'); }); app.use('/assets', express.static(`${__dirname}/assets`)); app.get('*.js', (req, res) => { res.sendFile(path.join(__dirname, `dist/${req.url}`)); }); app.get('*.css', (req, res) => { res.sendFile(path.join(__dirname, `dist/${req.url}`)); }); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist/index.html')); }); } else { app = express(); console.log('in dev start'); app.use(require('webpack-hot-middleware')(compiler)); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'src/index.html')); }); app = new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, hotOnly: true, inline: true, historyApiFallback: true, compress: true, open: true, stats: 'minimal', }); console.log('in dev last'); } app.listen(port, (err) => { if (err) { return console.error(err); } return console.log(`Listening at http://localhost:${port}/`); });
(window["webpackJsonp_8494e7d7_6b99_47b2_a741_59873e42f16f_4_0_19"] = window["webpackJsonp_8494e7d7_6b99_47b2_a741_59873e42f16f_4_0_19"] || []).push([["vendors~sp-dialog-utils"],{ /***/ "01ek": /*!*********************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/Dialog.styles.js ***! \*********************************************************************************************************************************************************************************************************************************/ /*! exports provided: getStyles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStyles", function() { return getStyles; }); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Styling */ "4RHQ"); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Styling__WEBPACK_IMPORTED_MODULE_0__); var GlobalClassNames = { root: 'ms-Dialog' }; var getStyles = function (props) { var _a; var className = props.className, containerClassName = props.containerClassName, _b = props.dialogDefaultMinWidth, dialogDefaultMinWidth = _b === void 0 ? '288px' : _b, _c = props.dialogDefaultMaxWidth, dialogDefaultMaxWidth = _c === void 0 ? '340px' : _c, hidden = props.hidden, theme = props.theme; var classNames = Object(_Styling__WEBPACK_IMPORTED_MODULE_0__["getGlobalClassNames"])(GlobalClassNames, theme); return { root: [classNames.root, theme.fonts.medium, className], main: [ { width: dialogDefaultMinWidth, outline: '3px solid transparent', selectors: (_a = {}, _a["@media (min-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMinMedium"] + "px)"] = { width: 'auto', maxWidth: dialogDefaultMaxWidth, minWidth: dialogDefaultMinWidth }, _a) }, !hidden && { display: 'flex' }, containerClassName ] }; }; //# sourceMappingURL=Dialog.styles.js.map /***/ }), /***/ "15YF": /*!*******************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/Dialog.base.js ***! \*******************************************************************************************************************************************************************************************************************************/ /*! exports provided: DialogBase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DialogBase", function() { return DialogBase; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "tCkv"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DialogContent.types */ "F+OE"); /* harmony import */ var _Modal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Modal */ "67Sy"); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utilities/decorators/withResponsiveMode */ "jiHw"); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_5__); /* harmony import */ var _DialogContent__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./DialogContent */ "Nio4"); var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["classNamesFunction"])(); var DefaultModalProps = { isDarkOverlay: false, isBlocking: false, className: '', containerClassName: '', topOffsetFixed: false }; var DefaultDialogContentProps = { type: _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__["DialogType"].normal, className: '', topButtonsProps: [] }; var DialogBase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DialogBase, _super); function DialogBase(props) { var _this = _super.call(this, props) || this; _this._getSubTextId = function () { var _a = _this.props, ariaDescribedById = _a.ariaDescribedById, modalProps = _a.modalProps, dialogContentProps = _a.dialogContentProps, subText = _a.subText; var id = ariaDescribedById || (modalProps && modalProps.subtitleAriaId); if (!id) { id = (subText || (dialogContentProps && dialogContentProps.subText)) && _this._defaultSubTextId; } return id; }; _this._getTitleTextId = function () { var _a = _this.props, ariaLabelledById = _a.ariaLabelledById, modalProps = _a.modalProps, dialogContentProps = _a.dialogContentProps, title = _a.title; var id = ariaLabelledById || (modalProps && modalProps.titleAriaId); if (!id) { id = (title || (dialogContentProps && dialogContentProps.title)) && _this._defaultTitleTextId; } return id; }; _this._id = Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["getId"])('Dialog'); _this._defaultTitleTextId = _this._id + '-title'; _this._defaultSubTextId = _this._id + '-subText'; if (true) { Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["warnDeprecations"])('Dialog', props, { isOpen: 'hidden', type: 'dialogContentProps.type', subText: 'dialogContentProps.subText', contentClassName: 'dialogContentProps.className', topButtonsProps: 'dialogContentProps.topButtonsProps', className: 'modalProps.className', isDarkOverlay: 'modalProps.isDarkOverlay', isBlocking: 'modalProps.isBlocking', containerClassName: 'modalProps.containerClassName', onDismissed: 'modalProps.onDismissed', onLayerDidMount: 'modalProps.layerProps.onLayerDidMount', ariaDescribedById: 'modalProps.subtitleAriaId', ariaLabelledById: 'modalProps.titleAriaId' }); } return _this; } DialogBase.prototype.render = function () { var _a = this.props, className = _a.className, containerClassName = _a.containerClassName, contentClassName = _a.contentClassName, elementToFocusOnDismiss = _a.elementToFocusOnDismiss, firstFocusableSelector = _a.firstFocusableSelector, forceFocusInsideTrap = _a.forceFocusInsideTrap, styles = _a.styles, hidden = _a.hidden, ignoreExternalFocusing = _a.ignoreExternalFocusing, isBlocking = _a.isBlocking, isClickableOutsideFocusTrap = _a.isClickableOutsideFocusTrap, isDarkOverlay = _a.isDarkOverlay, isOpen = _a.isOpen, onDismiss = _a.onDismiss, onDismissed = _a.onDismissed, onLayerDidMount = _a.onLayerDidMount, responsiveMode = _a.responsiveMode, subText = _a.subText, theme = _a.theme, title = _a.title, topButtonsProps = _a.topButtonsProps, type = _a.type, minWidth = _a.minWidth, maxWidth = _a.maxWidth, modalProps = _a.modalProps; var mergedLayerProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, (modalProps ? modalProps.layerProps : { onLayerDidMount: onLayerDidMount })); if (onLayerDidMount && !mergedLayerProps.onLayerDidMount) { mergedLayerProps.onLayerDidMount = onLayerDidMount; } var dialogDraggableClassName; var dragOptions; // if we are draggable, make sure we are using the correct // draggable classname and selectors if (modalProps && modalProps.dragOptions && !modalProps.dragOptions.dragHandleSelector) { dialogDraggableClassName = 'ms-Dialog-draggable-header'; dragOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, modalProps.dragOptions, { dragHandleSelector: "." + dialogDraggableClassName }); } else { dragOptions = modalProps && modalProps.dragOptions; } var mergedModalProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, DefaultModalProps, modalProps, { layerProps: mergedLayerProps, dragOptions: dragOptions }); var dialogContentProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, DefaultDialogContentProps, this.props.dialogContentProps, { draggableHeaderClassName: dialogDraggableClassName }); var classNames = getClassNames(styles, { theme: theme, className: className || mergedModalProps.className, containerClassName: containerClassName || mergedModalProps.containerClassName, hidden: hidden, dialogDefaultMinWidth: minWidth, dialogDefaultMaxWidth: maxWidth }); return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Modal__WEBPACK_IMPORTED_MODULE_4__["Modal"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ elementToFocusOnDismiss: elementToFocusOnDismiss, firstFocusableSelector: firstFocusableSelector, forceFocusInsideTrap: forceFocusInsideTrap, ignoreExternalFocusing: ignoreExternalFocusing, isClickableOutsideFocusTrap: isClickableOutsideFocusTrap, onDismissed: onDismissed, responsiveMode: responsiveMode }, mergedModalProps, { isDarkOverlay: isDarkOverlay !== undefined ? isDarkOverlay : mergedModalProps.isDarkOverlay, isBlocking: isBlocking !== undefined ? isBlocking : mergedModalProps.isBlocking, isOpen: isOpen !== undefined ? isOpen : !hidden, className: classNames.root, containerClassName: classNames.main, onDismiss: onDismiss ? onDismiss : mergedModalProps.onDismiss, subtitleAriaId: this._getSubTextId(), titleAriaId: this._getTitleTextId() }), react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_DialogContent__WEBPACK_IMPORTED_MODULE_6__["DialogContent"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ titleId: this._defaultTitleTextId, subTextId: this._defaultSubTextId, title: title, subText: subText, showCloseButton: isBlocking !== undefined ? !isBlocking : !mergedModalProps.isBlocking, topButtonsProps: topButtonsProps ? topButtonsProps : dialogContentProps.topButtonsProps, type: type !== undefined ? type : dialogContentProps.type, onDismiss: onDismiss ? onDismiss : dialogContentProps.onDismiss, className: contentClassName || dialogContentProps.className }, dialogContentProps), this.props.children))); }; DialogBase.defaultProps = { hidden: true }; DialogBase = tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_5__["withResponsiveMode"] ], DialogBase); return DialogBase; }(react__WEBPACK_IMPORTED_MODULE_1__["Component"])); //# sourceMappingURL=Dialog.base.js.map /***/ }), /***/ "2zVY": /*!*********************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/Overlay.js ***! \*********************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Loading office-ui-fabric-react/Overlay.js var pkg = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q"); module.exports = {} for (var key in pkg) { if (pkg.hasOwnProperty(key)) { module.exports[key] = pkg[key]; } } Object.defineProperty(module.exports, "__esModule", { value: true }); /***/ }), /***/ "4azF": /*!*******************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/utilities/DraggableZone/index.js ***! \*******************************************************************************************************************************************************************************************************************************/ /*! exports provided: DraggableZone, getClassNames */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _DraggableZone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DraggableZone */ "nDaQ"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DraggableZone", function() { return _DraggableZone__WEBPACK_IMPORTED_MODULE_0__["DraggableZone"]; }); /* harmony import */ var _DraggableZone_styles__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DraggableZone.styles */ "rp3K"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getClassNames", function() { return _DraggableZone_styles__WEBPACK_IMPORTED_MODULE_1__["getClassNames"]; }); //# sourceMappingURL=index.js.map /***/ }), /***/ "67Sy": /*!*******************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/Modal.js ***! \*******************************************************************************************************************************************************************************************************/ /*! exports provided: default, Modal, ModalBase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _components_Modal_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/Modal/index */ "y2VM"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Modal", function() { return _components_Modal_index__WEBPACK_IMPORTED_MODULE_0__["Modal"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModalBase", function() { return _components_Modal_index__WEBPACK_IMPORTED_MODULE_0__["ModalBase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _components_Modal_index__WEBPACK_IMPORTED_MODULE_0__["Modal"]; }); //# sourceMappingURL=Modal.js.map /***/ }), /***/ "8S/1": /*!***************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogFooter.styles.js ***! \***************************************************************************************************************************************************************************************************************************************/ /*! exports provided: getStyles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStyles", function() { return getStyles; }); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Styling */ "4RHQ"); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Styling__WEBPACK_IMPORTED_MODULE_0__); var GlobalClassNames = { actions: 'ms-Dialog-actions', action: 'ms-Dialog-action', actionsRight: 'ms-Dialog-actionsRight' }; var getStyles = function (props) { var className = props.className, theme = props.theme; var classNames = Object(_Styling__WEBPACK_IMPORTED_MODULE_0__["getGlobalClassNames"])(GlobalClassNames, theme); return { actions: [ classNames.actions, { position: 'relative', width: '100%', minHeight: '24px', lineHeight: '24px', margin: '16px 0 0', fontSize: '0', selectors: { '.ms-Button': { lineHeight: 'normal' } } }, className ], action: [ classNames.action, { margin: '0 4px' } ], actionsRight: [ classNames.actionsRight, { textAlign: 'right', marginRight: '-4px', fontSize: '0' } ] }; }; //# sourceMappingURL=DialogFooter.styles.js.map /***/ }), /***/ "CNvk": /*!**************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogContent.base.js ***! \**************************************************************************************************************************************************************************************************************************************/ /*! exports provided: DialogContentBase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DialogContentBase", function() { return DialogContentBase; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "tCkv"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DialogContent.types */ "F+OE"); /* harmony import */ var _Button__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Button */ "xk/t"); /* harmony import */ var _Button__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_Button__WEBPACK_IMPORTED_MODULE_4__); /* harmony import */ var _DialogFooter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DialogFooter */ "T/ax"); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utilities/decorators/withResponsiveMode */ "jiHw"); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_6__); var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["classNamesFunction"])(); var DialogFooterType = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_DialogFooter__WEBPACK_IMPORTED_MODULE_5__["DialogFooter"], null).type; var DialogContentBase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DialogContentBase, _super); function DialogContentBase(props) { return _super.call(this, props) || this; } DialogContentBase.prototype.render = function () { var _a = this.props, showCloseButton = _a.showCloseButton, className = _a.className, closeButtonAriaLabel = _a.closeButtonAriaLabel, onDismiss = _a.onDismiss, subTextId = _a.subTextId, subText = _a.subText, titleId = _a.titleId, title = _a.title, type = _a.type, styles = _a.styles, theme = _a.theme, draggableHeaderClassName = _a.draggableHeaderClassName; var classNames = getClassNames(styles, { theme: theme, className: className, isLargeHeader: type === _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__["DialogType"].largeHeader, isClose: type === _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__["DialogType"].close, draggableHeaderClassName: draggableHeaderClassName }); var groupings = this._groupChildren(); var subTextContent; if (subText) { subTextContent = (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("p", { className: classNames.subText, id: subTextId }, subText)); } return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.content }, react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.header }, react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("p", { className: classNames.title, id: titleId, role: "heading", "aria-level": 2 }, title), react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.topButton }, this.props.topButtonsProps.map(function (props, index) { return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Button__WEBPACK_IMPORTED_MODULE_4__["IconButton"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ key: props.uniqueId || index }, props))); }), (type === _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__["DialogType"].close || (showCloseButton && type !== _DialogContent_types__WEBPACK_IMPORTED_MODULE_3__["DialogType"].largeHeader)) && (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Button__WEBPACK_IMPORTED_MODULE_4__["IconButton"], { className: classNames.button, iconProps: { iconName: 'Cancel' }, ariaLabel: closeButtonAriaLabel, onClick: onDismiss })))), react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.inner }, react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.innerContent }, subTextContent, groupings.contents), groupings.footers))); }; // @TODO - typing the footers as an array of DialogFooter is difficult because // casing "child as DialogFooter" causes a problem because // "Neither type 'ReactElement<any>' nor type 'DialogFooter' is assignable to the other." DialogContentBase.prototype._groupChildren = function () { var groupings = { footers: [], contents: [] }; react__WEBPACK_IMPORTED_MODULE_1__["Children"].map(this.props.children, function (child) { if (typeof child === 'object' && child !== null && child.type === DialogFooterType) { groupings.footers.push(child); } else { groupings.contents.push(child); } }); return groupings; }; DialogContentBase.defaultProps = { showCloseButton: false, className: '', topButtonsProps: [], closeButtonAriaLabel: 'Close' }; DialogContentBase = tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_6__["withResponsiveMode"] ], DialogContentBase); return DialogContentBase; }(_Utilities__WEBPACK_IMPORTED_MODULE_2__["BaseComponent"])); //# sourceMappingURL=DialogContent.base.js.map /***/ }), /***/ "F+OE": /*!***************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogContent.types.js ***! \***************************************************************************************************************************************************************************************************************************************/ /*! exports provided: ResponsiveMode, DialogType */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DialogType", function() { return DialogType; }); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utilities/decorators/withResponsiveMode */ "jiHw"); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ResponsiveMode", function() { return _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_0__["ResponsiveMode"]; }); // Exported because the type is an optional prop and not exported otherwise. /** * {@docCategory Dialog} */ var DialogType; (function (DialogType) { /** Standard dialog */ DialogType[DialogType["normal"] = 0] = "normal"; /** Dialog with large header banner */ DialogType[DialogType["largeHeader"] = 1] = "largeHeader"; /** Dialog with an 'x' close button in the upper-right corner */ DialogType[DialogType["close"] = 2] = "close"; })(DialogType || (DialogType = {})); //# sourceMappingURL=DialogContent.types.js.map /***/ }), /***/ "FI3s": /*!****************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogContent.styles.js ***! \****************************************************************************************************************************************************************************************************************************************/ /*! exports provided: getStyles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStyles", function() { return getStyles; }); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Styling */ "4RHQ"); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Styling__WEBPACK_IMPORTED_MODULE_0__); var GlobalClassNames = { contentLgHeader: 'ms-Dialog-lgHeader', close: 'ms-Dialog--close', subText: 'ms-Dialog-subText', header: 'ms-Dialog-header', headerLg: 'ms-Dialog--lgHeader', button: 'ms-Dialog-button ms-Dialog-button--close', inner: 'ms-Dialog-inner', content: 'ms-Dialog-content', title: 'ms-Dialog-title' }; var getStyles = function (props) { var _a, _b, _c; var className = props.className, theme = props.theme, isLargeHeader = props.isLargeHeader, isClose = props.isClose, hidden = props.hidden, isMultiline = props.isMultiline, draggableHeaderClassName = props.draggableHeaderClassName; var palette = theme.palette, fonts = theme.fonts, effects = theme.effects, semanticColors = theme.semanticColors; var classNames = Object(_Styling__WEBPACK_IMPORTED_MODULE_0__["getGlobalClassNames"])(GlobalClassNames, theme); return { content: [ isLargeHeader && [ classNames.contentLgHeader, { borderTop: "4px solid " + palette.themePrimary } ], isClose && classNames.close, { flexGrow: 1, overflowY: 'hidden' // required for allowScrollOnElement }, className ], subText: [ classNames.subText, fonts.medium, { margin: '0 0 24px 0', color: semanticColors.bodySubtext, lineHeight: '1.5', wordWrap: 'break-word', fontWeight: _Styling__WEBPACK_IMPORTED_MODULE_0__["FontWeights"].regular } ], header: [ classNames.header, { position: 'relative', width: '100%', boxSizing: 'border-box' }, isClose && classNames.close, draggableHeaderClassName && [ draggableHeaderClassName, { cursor: 'move' } ] ], button: [ classNames.button, hidden && { selectors: { '.ms-Icon.ms-Icon--Cancel': { color: semanticColors.buttonText, fontSize: _Styling__WEBPACK_IMPORTED_MODULE_0__["IconFontSizes"].medium } } } ], inner: [ classNames.inner, { padding: '0 24px 24px', selectors: (_a = {}, _a["@media (min-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMinSmall"] + "px) and (max-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMaxSmall"] + "px)"] = { padding: '0 16px 16px' }, _a) } ], innerContent: [ classNames.content, { position: 'relative', width: '100%' } ], title: [ classNames.title, fonts.xLarge, { color: semanticColors.bodyText, margin: '0', padding: '16px 46px 20px 24px', lineHeight: 'normal', selectors: (_b = {}, _b["@media (min-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMinSmall"] + "px) and (max-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMaxSmall"] + "px)"] = { padding: '16px 46px 16px 16px' }, _b) }, isLargeHeader && { color: semanticColors.menuHeader }, isMultiline && { fontSize: fonts.xxLarge.fontSize } ], topButton: [ { display: 'flex', flexDirection: 'row', flexWrap: 'nowrap', position: 'absolute', top: '0', right: '0', padding: '15px 15px 0 0', selectors: (_c = { '> *': { flex: '0 0 auto' }, '.ms-Dialog-button': { color: semanticColors.buttonText }, '.ms-Dialog-button:hover': { color: semanticColors.buttonTextHovered, borderRadius: effects.roundedCorner2 } }, _c["@media (min-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMinSmall"] + "px) and (max-width: " + _Styling__WEBPACK_IMPORTED_MODULE_0__["ScreenWidthMaxSmall"] + "px)"] = { padding: '15px 8px 0 0' }, _c) } ] }; }; //# sourceMappingURL=DialogContent.styles.js.map /***/ }), /***/ "Mstc": /*!*****************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Modal/Modal.base.js ***! \*****************************************************************************************************************************************************************************************************************************/ /*! exports provided: ModalBase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ModalBase", function() { return ModalBase; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "tCkv"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var _FocusTrapZone_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../FocusTrapZone/index */ "WEvm"); /* harmony import */ var _FocusTrapZone_index__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_FocusTrapZone_index__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _Modal_styles__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Modal.styles */ "fcBF"); /* harmony import */ var _Overlay__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Overlay */ "2zVY"); /* harmony import */ var _Overlay__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_Overlay__WEBPACK_IMPORTED_MODULE_5__); /* harmony import */ var _Layer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Layer */ "88pY"); /* harmony import */ var _Popup_index__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Popup/index */ "YCiU"); /* harmony import */ var _Popup_index__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_Popup_index__WEBPACK_IMPORTED_MODULE_7__); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../utilities/decorators/withResponsiveMode */ "jiHw"); /* harmony import */ var _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_8__); /* harmony import */ var _Callout_index__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Callout/index */ "UO3J"); /* harmony import */ var _Callout_index__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_Callout_index__WEBPACK_IMPORTED_MODULE_9__); /* harmony import */ var _Icon_index__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Icon/index */ "n8DK"); /* harmony import */ var _Icon_index__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_Icon_index__WEBPACK_IMPORTED_MODULE_10__); /* harmony import */ var _utilities_DraggableZone_index__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../utilities/DraggableZone/index */ "4azF"); // @TODO - need to change this to a panel whenever the breakpoint is under medium (verify the spec) var DefaultLayerProps = { eventBubblingEnabled: false }; var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["classNamesFunction"])(); var ModalBase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ModalBase, _super); function ModalBase(props) { var _this = _super.call(this, props) || this; _this._focusTrapZone = react__WEBPACK_IMPORTED_MODULE_1__["createRef"](); // Allow the user to scroll within the modal but not on the body _this._allowScrollOnModal = function (elt) { if (elt) { Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["allowScrollOnElement"])(elt, _this._events); } else { _this._events.off(_this._scrollableContent); } _this._scrollableContent = elt; }; _this._onModalContextMenuClose = function () { _this.setState({ isModalMenuOpen: false }); }; _this._onModalClose = function () { _this._lastSetX = 0; _this._lastSetY = 0; _this.setState({ isModalMenuOpen: false, isInKeyboardMoveMode: false, isOpen: false, x: 0, y: 0 }); if (_this.props.dragOptions) { _this._events.off(window, 'keyup', _this._onKeyUp, true /* useCapture */); } // Call the onDismiss callback if (_this.props.onDismissed) { _this.props.onDismissed(); } }; _this._onDragStart = function () { _this.setState({ isModalMenuOpen: false, isInKeyboardMoveMode: false }); }; _this._onDrag = function (_, ui) { var _a = _this.state, x = _a.x, y = _a.y; _this.setState({ x: x + ui.delta.x, y: y + ui.delta.y }); }; _this._onDragStop = function () { _this.focus(); }; _this._onKeyUp = function (event) { // Need to handle the CTRL + ALT + SPACE key during keyup due to FireFox bug: // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 // Otherwise it would continue to fire a click even if the event was cancelled // during mouseDown. if (event.altKey && event.ctrlKey && event.keyCode === _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].space) { // Since this is a global handler, we should make sure the target is within the dialog // before opening the dropdown if (Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["elementContains"])(_this._scrollableContent, event.target)) { _this.setState({ isModalMenuOpen: !_this.state.isModalMenuOpen }); event.preventDefault(); event.stopPropagation(); } } }; // We need a global onKeyDown event when we are in the move mode so that we can // handle the key presses and the components inside the modal do not get the events _this._onKeyDown = function (event) { if (event.altKey && event.ctrlKey && event.keyCode === _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].space) { // CTRL + ALT + SPACE is handled during keyUp event.preventDefault(); event.stopPropagation(); return; } if (_this.state.isModalMenuOpen && (event.altKey || event.keyCode === _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].escape)) { _this.setState({ isModalMenuOpen: false }); } if (_this.state.isInKeyboardMoveMode && (event.keyCode === _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].escape || event.keyCode === _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].enter)) { _this.setState({ isInKeyboardMoveMode: false }); event.preventDefault(); event.stopPropagation(); } if (_this.state.isInKeyboardMoveMode) { var handledEvent = true; var delta = _this._getMoveDelta(event); switch (event.keyCode) { case _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].escape: _this.setState({ x: _this._lastSetX, y: _this._lastSetY }); case _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].enter: { _this._lastSetX = 0; _this._lastSetY = 0; _this.setState({ isInKeyboardMoveMode: false }); break; } case _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].up: { _this.setState({ y: _this.state.y - delta }); break; } case _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].down: { _this.setState({ y: _this.state.y + delta }); break; } case _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].left: { _this.setState({ x: _this.state.x - delta }); break; } case _Utilities__WEBPACK_IMPORTED_MODULE_2__["KeyCodes"].right: { _this.setState({ x: _this.state.x + delta }); break; } default: { handledEvent = false; } } if (handledEvent) { event.preventDefault(); event.stopPropagation(); } } }; _this._onEnterKeyboardMoveMode = function () { _this._lastSetX = _this.state.x; _this._lastSetY = _this.state.y; _this.setState({ isInKeyboardMoveMode: true, isModalMenuOpen: false }); _this._events.on(window, 'keydown', _this._onKeyDown, true /* useCapture */); }; _this._onExitKeyboardMoveMode = function () { _this._lastSetX = 0; _this._lastSetY = 0; _this.setState({ isInKeyboardMoveMode: false }); _this._events.off(window, 'keydown', _this._onKeyDown, true /* useCapture */); }; _this.state = { id: Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["getId"])('Modal'), isOpen: props.isOpen, isVisible: props.isOpen, hasBeenOpened: props.isOpen, x: 0, y: 0 }; _this._lastSetX = 0; _this._lastSetY = 0; _this._warnDeprecations({ onLayerDidMount: 'layerProps.onLayerDidMount' }); return _this; } // tslint:disable-next-line function-name ModalBase.prototype.UNSAFE_componentWillReceiveProps = function (newProps) { clearTimeout(this._onModalCloseTimer); // Opening the dialog if (newProps.isOpen) { if (!this.state.isOpen) { // First Open this.setState({ isOpen: true }); // Add a keyUp handler for all key up events when the dialog is open if (newProps.dragOptions) { this._events.on(window, 'keyup', this._onKeyUp, true /* useCapture */); } } else { // Modal has been opened // Reopen during closing this.setState({ hasBeenOpened: true, isVisible: true }); if (newProps.topOffsetFixed) { var dialogMain = document.getElementsByClassName('ms-Dialog-main'); var modalRectangle = void 0; if (dialogMain.length > 0) { modalRectangle = dialogMain[0].getBoundingClientRect(); this.setState({ modalRectangleTop: modalRectangle.top }); } } } } // Closing the dialog if (!newProps.isOpen && this.state.isOpen) { this._onModalCloseTimer = this._async.setTimeout(this._onModalClose, parseFloat(_Modal_styles__WEBPACK_IMPORTED_MODULE_4__["animationDuration"]) * 1000); this.setState({ isVisible: false }); } }; ModalBase.prototype.componentDidUpdate = function (prevProps, prevState) { if (!prevProps.isOpen && !prevState.isVisible) { this.setState({ isVisible: true }); } }; ModalBase.prototype.render = function () { var _a = this.props, className = _a.className, containerClassName = _a.containerClassName, scrollableContentClassName = _a.scrollableContentClassName, elementToFocusOnDismiss = _a.elementToFocusOnDismiss, firstFocusableSelector = _a.firstFocusableSelector, forceFocusInsideTrap = _a.forceFocusInsideTrap, ignoreExternalFocusing = _a.ignoreExternalFocusing, isBlocking = _a.isBlocking, isClickableOutsideFocusTrap = _a.isClickableOutsideFocusTrap, isDarkOverlay = _a.isDarkOverlay, onDismiss = _a.onDismiss, layerProps = _a.layerProps, overlay = _a.overlay, responsiveMode = _a.responsiveMode, titleAriaId = _a.titleAriaId, styles = _a.styles, subtitleAriaId = _a.subtitleAriaId, theme = _a.theme, topOffsetFixed = _a.topOffsetFixed, onLayerDidMount = _a.onLayerDidMount, isModeless = _a.isModeless, dragOptions = _a.dragOptions; var _b = this.state, isOpen = _b.isOpen, isVisible = _b.isVisible, hasBeenOpened = _b.hasBeenOpened, modalRectangleTop = _b.modalRectangleTop, x = _b.x, y = _b.y, isInKeyboardMoveMode = _b.isInKeyboardMoveMode; if (!isOpen) { return null; } var layerClassName = layerProps === undefined ? '' : layerProps.className; var classNames = getClassNames(styles, { theme: theme, className: className, containerClassName: containerClassName, scrollableContentClassName: scrollableContentClassName, isOpen: isOpen, isVisible: isVisible, hasBeenOpened: hasBeenOpened, modalRectangleTop: modalRectangleTop, topOffsetFixed: topOffsetFixed, isModeless: isModeless, layerClassName: layerClassName, isDefaultDragHandle: dragOptions && !dragOptions.dragHandleSelector }); var mergedLayerProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, DefaultLayerProps, this.props.layerProps, { onLayerDidMount: layerProps && layerProps.onLayerDidMount ? layerProps.onLayerDidMount : onLayerDidMount, insertFirst: isModeless, className: classNames.layer }); var modalContent = (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_FocusTrapZone_index__WEBPACK_IMPORTED_MODULE_3__["FocusTrapZone"], { componentRef: this._focusTrapZone, className: classNames.main, elementToFocusOnDismiss: elementToFocusOnDismiss, isClickableOutsideFocusTrap: isModeless || isClickableOutsideFocusTrap || !isBlocking, ignoreExternalFocusing: ignoreExternalFocusing, forceFocusInsideTrap: isModeless ? !isModeless : forceFocusInsideTrap, firstFocusableSelector: firstFocusableSelector, focusPreviouslyFocusedInnerElement: true, onBlur: isInKeyboardMoveMode ? this._onExitKeyboardMoveMode : undefined }, dragOptions && isInKeyboardMoveMode && (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.keyboardMoveIconContainer }, dragOptions.keyboardMoveIconProps ? (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Icon_index__WEBPACK_IMPORTED_MODULE_10__["Icon"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, dragOptions.keyboardMoveIconProps))) : (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Icon_index__WEBPACK_IMPORTED_MODULE_10__["Icon"], { iconName: "move", className: classNames.keyboardMoveIcon })))), react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { ref: this._allowScrollOnModal, className: classNames.scrollableContent, "data-is-scrollable": true }, dragOptions && this.state.isModalMenuOpen && (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](dragOptions.menu, { items: [ { key: 'move', text: dragOptions.moveMenuItemText, onClick: this._onEnterKeyboardMoveMode }, { key: 'close', text: dragOptions.closeMenuItemText, onClick: this._onModalClose } ], onDismiss: this._onModalContextMenuClose, alignTargetEdge: true, coverTarget: true, directionalHint: _Callout_index__WEBPACK_IMPORTED_MODULE_9__["DirectionalHint"].topLeftEdge, directionalHintFixed: true, shouldFocusOnMount: true, target: this._scrollableContent })), this.props.children))); // @temp tuatology - Will adjust this to be a panel at certain breakpoints if (responsiveMode >= _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_8__["ResponsiveMode"].small) { return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Layer__WEBPACK_IMPORTED_MODULE_6__["Layer"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, mergedLayerProps), react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Popup_index__WEBPACK_IMPORTED_MODULE_7__["Popup"], { role: isModeless || !isBlocking ? 'dialog' : 'alertdialog', "aria-modal": !isModeless, ariaLabelledBy: titleAriaId, ariaDescribedBy: subtitleAriaId, onDismiss: onDismiss }, react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.root }, !isModeless && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Overlay__WEBPACK_IMPORTED_MODULE_5__["Overlay"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ isDarkThemed: isDarkOverlay, onClick: isBlocking ? undefined : onDismiss }, overlay)), dragOptions ? (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_utilities_DraggableZone_index__WEBPACK_IMPORTED_MODULE_11__["DraggableZone"], { handleSelector: dragOptions.dragHandleSelector || "." + classNames.main.split(' ')[0], preventDragSelector: "button", onStart: this._onDragStart, onDragChange: this._onDrag, onStop: this._onDragStop, position: { x: x, y: y } }, modalContent)) : (modalContent))))); } return null; }; ModalBase.prototype.focus = function () { if (this._focusTrapZone.current) { this._focusTrapZone.current.focus(); } }; ModalBase.prototype._getMoveDelta = function (event) { var delta = 10; if (event.shiftKey) { if (!event.ctrlKey) { delta = 50; } } else if (event.ctrlKey) { delta = 1; } return delta; }; ModalBase.defaultProps = { isOpen: false, isDarkOverlay: true, isBlocking: false, className: '', containerClassName: '' }; ModalBase = tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ _utilities_decorators_withResponsiveMode__WEBPACK_IMPORTED_MODULE_8__["withResponsiveMode"] ], ModalBase); return ModalBase; }(_Utilities__WEBPACK_IMPORTED_MODULE_2__["BaseComponent"])); //# sourceMappingURL=Modal.base.js.map /***/ }), /***/ "Nio4": /*!*********************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogContent.js ***! \*********************************************************************************************************************************************************************************************************************************/ /*! exports provided: DialogContent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DialogContent", function() { return DialogContent; }); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _DialogContent_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DialogContent.base */ "CNvk"); /* harmony import */ var _DialogContent_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DialogContent.styles */ "FI3s"); var DialogContent = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["styled"])(_DialogContent_base__WEBPACK_IMPORTED_MODULE_1__["DialogContentBase"], _DialogContent_styles__WEBPACK_IMPORTED_MODULE_2__["getStyles"], undefined, { scope: 'DialogContent' }); //# sourceMappingURL=DialogContent.js.map /***/ }), /***/ "OfIR": /*!**************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/Dialog.js ***! \**************************************************************************************************************************************************************************************************************************/ /*! exports provided: Dialog */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return Dialog; }); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _Dialog_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Dialog.base */ "15YF"); /* harmony import */ var _Dialog_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Dialog.styles */ "01ek"); var Dialog = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["styled"])(_Dialog_base__WEBPACK_IMPORTED_MODULE_1__["DialogBase"], _Dialog_styles__WEBPACK_IMPORTED_MODULE_2__["getStyles"], undefined, { scope: 'Dialog' }); //# sourceMappingURL=Dialog.js.map /***/ }), /***/ "T/ax": /*!********************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogFooter.js ***! \********************************************************************************************************************************************************************************************************************************/ /*! exports provided: DialogFooter */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DialogFooter", function() { return DialogFooter; }); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _DialogFooter_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DialogFooter.base */ "ugPr"); /* harmony import */ var _DialogFooter_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DialogFooter.styles */ "8S/1"); var DialogFooter = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["styled"])(_DialogFooter_base__WEBPACK_IMPORTED_MODULE_1__["DialogFooterBase"], _DialogFooter_styles__WEBPACK_IMPORTED_MODULE_2__["getStyles"], undefined, { scope: 'DialogFooter' }); //# sourceMappingURL=DialogFooter.js.map /***/ }), /***/ "UO3J": /*!**************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Callout/index.js ***! \**************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Loading office-ui-fabric-react/components/Callout/index.js var pkg = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q"); module.exports = {} for (var key in pkg) { if (pkg.hasOwnProperty(key)) { module.exports[key] = pkg[key]; } } Object.defineProperty(module.exports, "__esModule", { value: true }); /***/ }), /***/ "WEvm": /*!********************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/FocusTrapZone/index.js ***! \********************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Loading office-ui-fabric-react/components/FocusTrapZone/index.js var pkg = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q"); module.exports = {} for (var key in pkg) { if (pkg.hasOwnProperty(key)) { module.exports[key] = pkg[key]; } } Object.defineProperty(module.exports, "__esModule", { value: true }); /***/ }), /***/ "YCiU": /*!************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Popup/index.js ***! \************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Loading office-ui-fabric-react/components/Popup/index.js var pkg = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q"); module.exports = pkg.workaround_PopupIndex; /***/ }), /***/ "fcBF": /*!*******************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Modal/Modal.styles.js ***! \*******************************************************************************************************************************************************************************************************************************/ /*! exports provided: animationDuration, getStyles */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "animationDuration", function() { return animationDuration; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStyles", function() { return getStyles; }); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Styling */ "4RHQ"); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Styling__WEBPACK_IMPORTED_MODULE_0__); var animationDuration = _Styling__WEBPACK_IMPORTED_MODULE_0__["AnimationVariables"].durationValue2; var globalClassNames = { root: 'ms-Modal', main: 'ms-Dialog-main', scrollableContent: 'ms-Modal-scrollableContent', isOpen: 'is-open', layer: 'ms-Modal-Layer' }; var getStyles = function (props) { var _a; var className = props.className, containerClassName = props.containerClassName, scrollableContentClassName = props.scrollableContentClassName, isOpen = props.isOpen, isVisible = props.isVisible, hasBeenOpened = props.hasBeenOpened, modalRectangleTop = props.modalRectangleTop, theme = props.theme, topOffsetFixed = props.topOffsetFixed, isModeless = props.isModeless, layerClassName = props.layerClassName, isDefaultDragHandle = props.isDefaultDragHandle; var palette = theme.palette, effects = theme.effects, fonts = theme.fonts; var classNames = Object(_Styling__WEBPACK_IMPORTED_MODULE_0__["getGlobalClassNames"])(globalClassNames, theme); return { root: [ classNames.root, fonts.medium, { backgroundColor: 'transparent', position: isModeless ? 'absolute' : 'fixed', height: '100%', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: 0, pointerEvents: 'none', transition: "opacity " + animationDuration }, topOffsetFixed && hasBeenOpened && { alignItems: 'flex-start' }, isOpen && classNames.isOpen, isVisible && { opacity: 1, pointerEvents: 'auto' }, className ], main: [ classNames.main, { boxShadow: effects.elevation64, borderRadius: effects.roundedCorner2, backgroundColor: palette.white, boxSizing: 'border-box', position: 'relative', textAlign: 'left', outline: '3px solid transparent', maxHeight: '100%', overflowY: 'auto', zIndex: isModeless ? _Styling__WEBPACK_IMPORTED_MODULE_0__["ZIndexes"].Layer : undefined }, topOffsetFixed && hasBeenOpened && { top: modalRectangleTop }, isDefaultDragHandle && { cursor: 'move' }, containerClassName ], scrollableContent: [ classNames.scrollableContent, { overflowY: 'auto', flexGrow: 1, maxHeight: '100vh', selectors: (_a = {}, _a['@supports (-webkit-overflow-scrolling: touch)'] = { maxHeight: window.innerHeight }, _a) }, scrollableContentClassName ], layer: isModeless && [ layerClassName, classNames.layer, { position: 'static', width: 'unset', height: 'unset' } ], keyboardMoveIconContainer: { position: 'absolute', display: 'flex', justifyContent: 'center', width: '100%', padding: '3px 0px' }, keyboardMoveIcon: { fontSize: fonts.xLargePlus.fontSize, width: '24px' } }; }; //# sourceMappingURL=Modal.styles.js.map /***/ }), /***/ "glo3": /*!*************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/index.js ***! \*************************************************************************************************************************************************************************************************************************/ /*! exports provided: Dialog, DialogBase, DialogContent, DialogContentBase, DialogFooter, DialogFooterBase, ResponsiveMode, DialogType */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Dialog__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Dialog */ "OfIR"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Dialog", function() { return _Dialog__WEBPACK_IMPORTED_MODULE_0__["Dialog"]; }); /* harmony import */ var _Dialog_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Dialog.base */ "15YF"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DialogBase", function() { return _Dialog_base__WEBPACK_IMPORTED_MODULE_1__["DialogBase"]; }); /* harmony import */ var _DialogContent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DialogContent */ "Nio4"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DialogContent", function() { return _DialogContent__WEBPACK_IMPORTED_MODULE_2__["DialogContent"]; }); /* harmony import */ var _DialogContent_base__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DialogContent.base */ "CNvk"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DialogContentBase", function() { return _DialogContent_base__WEBPACK_IMPORTED_MODULE_3__["DialogContentBase"]; }); /* harmony import */ var _DialogFooter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./DialogFooter */ "T/ax"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DialogFooter", function() { return _DialogFooter__WEBPACK_IMPORTED_MODULE_4__["DialogFooter"]; }); /* harmony import */ var _DialogFooter_base__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DialogFooter.base */ "ugPr"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DialogFooterBase", function() { return _DialogFooter_base__WEBPACK_IMPORTED_MODULE_5__["DialogFooterBase"]; }); /* harmony import */ var _DialogContent_types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./DialogContent.types */ "F+OE"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ResponsiveMode", function() { return _DialogContent_types__WEBPACK_IMPORTED_MODULE_6__["ResponsiveMode"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DialogType", function() { return _DialogContent_types__WEBPACK_IMPORTED_MODULE_6__["DialogType"]; }); //# sourceMappingURL=index.js.map /***/ }), /***/ "jiHw": /*!*****************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/utilities/decorators/withResponsiveMode.js ***! \*****************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Loading office-ui-fabric-react/utilities/decorators/withResponsiveMode.js var pkg = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q"); module.exports = pkg.workaround_withResponsiveMode; /***/ }), /***/ "n8DK": /*!***********************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Icon/index.js ***! \***********************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Loading office-ui-fabric-react/components/Icon/index.js var pkg = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q"); module.exports = pkg.workaround_IconIndex; /***/ }), /***/ "nDaQ": /*!***************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/utilities/DraggableZone/DraggableZone.js ***! \***************************************************************************************************************************************************************************************************************************************/ /*! exports provided: DraggableZone */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DraggableZone", function() { return DraggableZone; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "tCkv"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _DraggableZone_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DraggableZone.styles */ "rp3K"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_3__); var eventMapping = { touch: { start: 'touchstart', move: 'touchmove', stop: 'touchend' }, mouse: { start: 'mousedown', move: 'mousemove', stop: 'mouseup' } }; var DraggableZone = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DraggableZone, _super); function DraggableZone(props) { var _this = _super.call(this, props) || this; _this._currentEventType = eventMapping.mouse; _this._events = []; _this._onMouseDown = function (event) { var onMouseDown = react__WEBPACK_IMPORTED_MODULE_1__["Children"].only(_this.props.children).props.onMouseDown; if (onMouseDown) { onMouseDown(event); } _this._currentEventType = eventMapping.mouse; return _this._onDragStart(event); }; _this._onMouseUp = function (event) { var onMouseUp = react__WEBPACK_IMPORTED_MODULE_1__["Children"].only(_this.props.children).props.onMouseUp; if (onMouseUp) { onMouseUp(event); } _this._currentEventType = eventMapping.mouse; return _this._onDragStop(event); }; _this._onTouchStart = function (event) { var onTouchStart = react__WEBPACK_IMPORTED_MODULE_1__["Children"].only(_this.props.children).props.onTouchStart; if (onTouchStart) { onTouchStart(event); } _this._currentEventType = eventMapping.touch; return _this._onDragStart(event); }; _this._onTouchEnd = function (event) { var onTouchEnd = react__WEBPACK_IMPORTED_MODULE_1__["Children"].only(_this.props.children).props.onTouchEnd; if (onTouchEnd) { onTouchEnd(event); } _this._currentEventType = eventMapping.touch; _this._onDragStop(event); }; _this._onDragStart = function (event) { // Only handle left click for dragging if (typeof event.button === 'number' && event.button !== 0) { return false; } // If the target doesn't match the handleSelector OR // if the target does match the preventDragSelector, bail out if ((_this.props.handleSelector && !_this._matchesSelector(event.target, _this.props.handleSelector)) || (_this.props.preventDragSelector && _this._matchesSelector(event.target, _this.props.preventDragSelector))) { return; } // Remember the touch identifier if this is a touch event so we can // distinguish between individual touches in multitouch scenarios // by remembering which touch point we were given _this._touchId = _this._getTouchId(event); var position = _this._getControlPosition(event); if (position === undefined) { return; } var dragData = _this._createDragDataFromPosition(position); _this.props.onStart && _this.props.onStart(event, dragData); _this.setState({ isDragging: true, lastPosition: position }); // hook up the appropriate mouse/touch events to the body to ensure // smooth dragging _this._events = [ Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["on"])(document.body, _this._currentEventType.move, _this._onDrag), Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["on"])(document.body, _this._currentEventType.stop, _this._onDragStop) ]; }; _this._onDrag = function (event) { // Prevent scrolling on mobile devices if (event.type === 'touchmove') { event.preventDefault(); } var position = _this._getControlPosition(event); if (!position) { return; } // create the updated drag data from the position data var updatedData = _this._createUpdatedDragData(_this._createDragDataFromPosition(position)); var updatedPosition = updatedData.position; _this.props.onDragChange && _this.props.onDragChange(event, updatedData); _this.setState({ position: updatedPosition, lastPosition: position }); }; _this._onDragStop = function (event) { if (!_this.state.isDragging) { return; } var position = _this._getControlPosition(event); if (!position) { return; } var baseDragData = _this._createDragDataFromPosition(position); // Set dragging to false and reset the lastPosition _this.setState({ isDragging: false, lastPosition: undefined }); _this.props.onStop && _this.props.onStop(event, baseDragData); if (_this.props.position) { _this.setState({ position: _this.props.position }); } // Remove event handlers _this._events.forEach(function (dispose) { return dispose(); }); }; _this.state = { isDragging: false, position: _this.props.position || { x: 0, y: 0 }, lastPosition: undefined }; return _this; } DraggableZone.prototype.componentDidUpdate = function (prevProps) { if (this.props.position && (!prevProps.position || this.props.position !== prevProps.position)) { this.setState({ position: this.props.position }); } }; DraggableZone.prototype.componentWillUnmount = function () { this._events.forEach(function (dispose) { return dispose(); }); }; DraggableZone.prototype.render = function () { var child = react__WEBPACK_IMPORTED_MODULE_1__["Children"].only(this.props.children); var props = child.props; var position = this.props.position; var _a = this.state, statePosition = _a.position, isDragging = _a.isDragging; var x = statePosition.x; var y = statePosition.y; if (position && !isDragging) { x = position.x; y = position.y; } return react__WEBPACK_IMPORTED_MODULE_1__["cloneElement"](child, { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props.style, { transform: "translate(" + x + "px, " + y + "px)" }), className: Object(_DraggableZone_styles__WEBPACK_IMPORTED_MODULE_2__["getClassNames"])(props.className, this.state.isDragging).root, onMouseDown: this._onMouseDown, onMouseUp: this._onMouseUp, onTouchStart: this._onTouchStart, onTouchEnd: this._onTouchEnd }); }; /** * Get the control position based off the event that fired * @param event - The event to get offsets from */ DraggableZone.prototype._getControlPosition = function (event) { var touchObj = this._getActiveTouch(event); // did we get the right touch? if (this._touchId !== undefined && !touchObj) { return undefined; } var eventToGetOffset = touchObj || event; return { x: eventToGetOffset.clientX, y: eventToGetOffset.clientY }; }; /** * Get the active touch point that we have saved from the event's TouchList * @param event - The event used to get the TouchList for the active touch point */ DraggableZone.prototype._getActiveTouch = function (event) { return ((event.targetTouches && this._findTouchInTouchList(event.targetTouches)) || (event.changedTouches && this._findTouchInTouchList(event.changedTouches))); }; /** * Get the initial touch identifier associated with the given event * @param event - The event that contains the TouchList */ DraggableZone.prototype._getTouchId = function (event) { var touch = (event.targetTouches && event.targetTouches[0]) || (event.changedTouches && event.changedTouches[0]); if (touch) { return touch.identifier; } }; /** * Returns if an element (or any of the element's parents) match the given selector */ DraggableZone.prototype._matchesSelector = function (element, selector) { if (!element || element === document.body) { return false; } /* tslint:disable-next-line:no-string-literal */ var matchesSelectorFn = element.matches || element.webkitMatchesSelector || element.msMatchesSelector /* for IE */; if (!matchesSelectorFn) { return false; } return matchesSelectorFn.call(element, selector) || this._matchesSelector(element.parentElement, selector); }; /** * Attempts to find the Touch that matches the identifier we stored in dragStart * @param touchList The TouchList to look for the stored identifier from dragStart */ DraggableZone.prototype._findTouchInTouchList = function (touchList) { if (this._touchId === undefined) { return; } for (var i = 0; i < touchList.length; i++) { if (touchList[i].identifier === this._touchId) { return touchList[i]; } } return undefined; }; /** * Create DragData based off of the last known position and the new position passed in * @param position The new position as part of the drag */ DraggableZone.prototype._createDragDataFromPosition = function (position) { var lastPosition = this.state.lastPosition; // If we have no lastPosition, use the given position // for last position if (lastPosition === undefined) { return { delta: { x: 0, y: 0 }, lastPosition: position, position: position }; } return { delta: { x: position.x - lastPosition.x, y: position.y - lastPosition.y }, lastPosition: lastPosition, position: position }; }; /** * Creates an updated DragData based off the current position and given baseDragData * @param baseDragData The base DragData (gotten from _createDragDataFromPosition) used to calculate the updated positions */ DraggableZone.prototype._createUpdatedDragData = function (baseDragData) { var position = this.state.position; return { position: { x: position.x + baseDragData.delta.x, y: position.y + baseDragData.delta.y }, delta: baseDragData.delta, lastPosition: position }; }; return DraggableZone; }(react__WEBPACK_IMPORTED_MODULE_1__["Component"])); //# sourceMappingURL=DraggableZone.js.map /***/ }), /***/ "rp3K": /*!**********************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/utilities/DraggableZone/DraggableZone.styles.js ***! \**********************************************************************************************************************************************************************************************************************************************/ /*! exports provided: getClassNames */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getClassNames", function() { return getClassNames; }); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Styling */ "4RHQ"); /* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_Styling__WEBPACK_IMPORTED_MODULE_1__); var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["memoizeFunction"])(function (className, isDragging) { return { root: Object(_Styling__WEBPACK_IMPORTED_MODULE_1__["mergeStyles"])(className, isDragging && { touchAction: 'none', selectors: { '& *': { userSelect: 'none' } } }) }; }); //# sourceMappingURL=DraggableZone.styles.js.map /***/ }), /***/ "ugPr": /*!*************************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Dialog/DialogFooter.base.js ***! \*************************************************************************************************************************************************************************************************************************************/ /*! exports provided: DialogFooterBase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DialogFooterBase", function() { return DialogFooterBase; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "tCkv"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_2__); var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_2__["classNamesFunction"])(); var DialogFooterBase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DialogFooterBase, _super); function DialogFooterBase() { return _super !== null && _super.apply(this, arguments) || this; } DialogFooterBase.prototype.render = function () { var _a = this.props, className = _a.className, styles = _a.styles, theme = _a.theme; this._classNames = getClassNames(styles, { theme: theme, className: className }); return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: this._classNames.actions }, react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: this._classNames.actionsRight }, this._renderChildrenAsActions()))); }; DialogFooterBase.prototype._renderChildrenAsActions = function () { var _this = this; return react__WEBPACK_IMPORTED_MODULE_1__["Children"].map(this.props.children, function (child) { return (child ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", { className: _this._classNames.action }, child) : null); }); }; return DialogFooterBase; }(_Utilities__WEBPACK_IMPORTED_MODULE_2__["BaseComponent"])); //# sourceMappingURL=DialogFooter.base.js.map /***/ }), /***/ "y2VM": /*!************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Modal/index.js ***! \************************************************************************************************************************************************************************************************************************/ /*! exports provided: Modal, ModalBase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Modal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Modal */ "zzdt"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Modal", function() { return _Modal__WEBPACK_IMPORTED_MODULE_0__["Modal"]; }); /* harmony import */ var _Modal_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Modal.base */ "Mstc"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModalBase", function() { return _Modal_base__WEBPACK_IMPORTED_MODULE_1__["ModalBase"]; }); //# sourceMappingURL=index.js.map /***/ }), /***/ "zzdt": /*!************************************************************************************************************************************************************************************************************************!*\ !*** /Users/runner/work/1/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/office-ui-fabric-react/7.59.0_b00af71b99b3978738e618b37212a8b6/node_modules/office-ui-fabric-react/lib/components/Modal/Modal.js ***! \************************************************************************************************************************************************************************************************************************/ /*! exports provided: Modal */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Modal", function() { return Modal; }); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Utilities */ "UJDV"); /* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Utilities__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _Modal_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Modal.base */ "Mstc"); /* harmony import */ var _Modal_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Modal.styles */ "fcBF"); var Modal = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["styled"])(_Modal_base__WEBPACK_IMPORTED_MODULE_1__["ModalBase"], _Modal_styles__WEBPACK_IMPORTED_MODULE_2__["getStyles"], undefined, { scope: 'Modal' }); //# sourceMappingURL=Modal.js.map /***/ }) }]); //# sourceMappingURL=chunk.vendors~sp-dialog-utils_38b1f7ae6797cb77c6d9.js.map
import { getCoinPaprikaRate } from './ratesAPIs/coinPaprika'; import { getAtomicExplorerBTCFees } from './btcFeesAPIs/atomicExplorer'; import { getFiatExchangeRates } from './ratesAPIs/fiatExchangeRates' import ApiException from '../../errors/apiError'; import { GENERAL } from '../../../constants/intervalConstants'; import { USD } from '../../../constants/currencies' import { CONNECTION_ERROR } from '../../errors/errorMessages'; import { GENERAL_CONNECTION_ERROR } from '../../errors/errorCodes'; import { truncateDecimal } from '../../../math'; import BigNumber from 'bignumber.js'; export const getRecommendedBTCFees = () => { //Fees are measured in satoshis per byte, slowest should //take around an hour, average should take around 30 minutes, //and fastest should take around 20 to 30 minutes let feeFunctions = [getAtomicExplorerBTCFees()] return new Promise((resolve, reject) => { Promise.all(feeFunctions) .then((fees) => { let feesFound = [] for (let i = 0; i < fees.length; i++) { if (fees[i]) { feesFound.push(fees[i]) } } if (feesFound.length > 0) { let avgFees = {slowest: 0, average: 0, fastest: 0} for (let i = 0; i < feesFound.length; i++) { avgFees.slowest += feesFound[i].slowest avgFees.average += feesFound[i].average avgFees.fastest += feesFound[i].fastest } for (let key in avgFees) { avgFees[key] = truncateDecimal((avgFees[key]/feesFound.length), 0) } resolve(avgFees) } else { resolve(false) } }) }); } export const getCoinRates = (coinObj) => { // Functions that can get rates for different coins. Due to the nature of Promise.all, // these should not reject, but instead resolve with an object that either has a // 'result' property, or an 'error' property. let rateFunctions = [getCoinPaprikaRate(coinObj)] let rateUsd = null let source = null return new Promise((resolve, reject) => { Promise.all(rateFunctions) .then(rates => { rates = rates.filter(rate => rate.error == null) if (rates.length > 0) { rateUsd = rates[0].result.rate source = rates[0].result.source return getFiatExchangeRates() } else reject( new ApiException( CONNECTION_ERROR, "No valid coin rates found", coinObj.id, GENERAL, GENERAL_CONNECTION_ERROR ) ); }) .then(exchangeRates => { let resObj = { result: { [USD]: BigNumber(rateUsd) }, source } Object.keys( exchangeRates.result == null ? {} : exchangeRates.result ).map(fiatCurr => { resObj.result[fiatCurr] = BigNumber(exchangeRates.result[fiatCurr]).multipliedBy(rateUsd).toString(); }); resolve(resObj) }) .catch(error => { reject( new ApiException( CONNECTION_ERROR, error.message || "Error connecting to rates APIs", coinObj.id, GENERAL, error.code || GENERAL_CONNECTION_ERROR ) ); }); }); }
""" Checks data once per day on a cron job to make sure data is in the database. Check late in the evening MST """ import os from datetime import datetime, timedelta import logging import boto3 import psycopg2 logger = logging.getLogger() logger.setLevel(logging.INFO) DB_CREDENTIALS = os.getenv("DB_CREDENTIALS") if not DB_CREDENTIALS: logger.error({"error": "no DB credentials env var found"}) EMAIL_TOPIC = os.getenv("EMAIL_TOPIC") if not EMAIL_TOPIC: logger.error({"error": "no SNS Topic credentials env var found"}) sns_client = boto3.client("sns") def handler(event=None, context=None): """ Check if the database is up to date """ latest_day_cases = fetch_latest_day_data("cases") latest_day_vaccines = fetch_latest_day_data("vaccines") today = datetime.utcnow() - timedelta(days=1) # sub 1 for UTC message = "Could not find current data for the following table(s): " tables = [] if latest_day_cases[0].day != today.day: tables.append(f"Cases - actual {latest_day_cases[0]} - utcnow {today}") if not latest_day_cases[ 2 ]: # check if web scraping for currently hospitalized worked tables.append("Currently Hospitalized") if latest_day_vaccines[0].day != today.day: tables.append(f"Vaccines - actual {latest_day_vaccines[0]} - utcnow {today}") if tables: message += ", ".join(tables) message += "\nGood luck!" subject = "ColoradoCovidData Missing Data" sns_client.publish( TopicArn=EMAIL_TOPIC, Message=message, Subject=subject, ) logger.error(message) return "Missing data" else: logger.info("Data looks good") return "Data looks good" def fetch_latest_day_data(table): sql = f"SELECT * FROM {table} ORDER BY reporting_date DESC LIMIT 1;" conn = psycopg2.connect(DB_CREDENTIALS) cur = conn.cursor() cur.execute(sql) data = cur.fetchone() conn.close() return data # latest date datetime object
#!/usr/bin/env python3 import logging import socket import time import requests LOGGER = logging.getLogger('mierzyciel.github') def get_github_status(org_name): users_url = f'https://api.github.com/orgs/{org_name}/members' users_j = requests.get(users_url).json() repos_url = f'https://api.github.com/orgs/{org_name}/repos' repos_j = requests.get(repos_url).json() return { 'num_repos': len(repos_j), 'num_users': len(users_j), } def upload_to_graphite(h, metric, value): s = socket.socket() try: s.connect(h) now = int(time.time()) buf = f'{metric} {value} {now}\n'.encode() LOGGER.info('Sending %r to %r', buf, h) s.send(buf) s.close() except (ConnectionRefusedError, socket.timeout) as e: LOGGER.exception(e) time.sleep(3.0) def main(): prefix = 'hakierspejs.github.' while True: h = ('graphite.hs-ldz.pl', 2003) stats = get_github_status('hakierspejs') for key, value in stats.items(): upload_to_graphite(h, prefix + key, value) time.sleep(60) if __name__ == '__main__': fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level='INFO', format=fmt) main()
new Vue({ el: '#vue', mixins: [windowMixin], data: function () { return { disclaimerDialog: { show: false, data: {} }, walletName: '', isOwner: false, adminPassword: '' } }, methods: { createWallet: function () { LNbits.href.createWallet(this.walletName, undefined, this.adminPassword) }, processing: function () { this.$q.notify({ timeout: 0, message: 'Processing...', icon: null }) } } })
const eslint = require('eslint'); const path = require('path'); const getFixtures = require('../../../utils/getFixtures'); const printIfErrors = require('../../../utils/printIfErrors'); describe('Rules', () => { const cli = new eslint.CLIEngine({ useEslintrc: false, configFile: '.eslintrc.js', parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', ecmaVersion: 2019 } }); const { valid, invalid } = getFixtures('tests/fixtures/*.ts'); describe('Valid cases', () => { valid.forEach((file) => { const fileName = path.basename(file); test(fileName, () => { const result = cli.executeOnFiles(file); printIfErrors(result); expect(result.errorCount).toEqual(0); }); }); }); describe('Invalid cases', () => { invalid.forEach((file) => { const fileName = path.basename(file); test(fileName, () => { const result = cli.executeOnFiles(file); expect(result.errorCount).toBeGreaterThan(0); }); }); }); });
AFRAME.registerComponent('menu-midsection', { schema: { active: {default: false}, selectedChallenge: {default: ''} }, update: function (oldData) { if (oldData.active && !this.data.active) { this.el.emit('hidedifficultysection', null, false); } if ((!oldData.active && this.data.active) || (this.data.selectedChallenge && oldData.selectedChallenge !== this.data.selectedChallenge)) { this.el.emit('showdifficultysection', null, false); } } });
(window.webpackJsonp=window.webpackJsonp||[]).push([[182],{255:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return i})),n.d(t,"metadata",(function(){return s})),n.d(t,"toc",(function(){return c})),n.d(t,"default",(function(){return p}));var r=n(3),a=n(8),o=(n(0),n(572)),i={id:"limitations",title:"Limitations"},s={unversionedId:"limitations",id:"version-v1.9/limitations",isDocsHomePage:!1,title:"Limitations",description:"ORY Hydra tries to solve all of OAuth 2.0 and OpenID Connect uses. There are,",source:"@site/versioned_docs/version-v1.9/limitations.md",sourceDirName:".",slug:"/limitations",permalink:"/hydra/docs/v1.9/limitations",editUrl:"https://github.com/ory/hydra/edit/master/docs/versioned_docs/version-v1.9/limitations.md",version:"v1.9",lastUpdatedBy:"aeneasr",lastUpdatedAt:1607427290,formattedLastUpdatedAt:"12/8/2020",frontMatter:{id:"limitations",title:"Limitations"},sidebar:"version-v1.9/docs",previous:{title:"JSON Web Key Sets",permalink:"/hydra/docs/v1.9/jwks"},next:{title:"Implementing the Login Endpoint",permalink:"/hydra/docs/v1.9/guides/login"}},c=[{value:"MySQL &lt;= 5.6 / MariaDB",id:"mysql--56--mariadb",children:[]},{value:"OAuth 2.0 Client Secret Length",id:"oauth-20-client-secret-length",children:[]},{value:"Resource Owner Password Credentials Grant Type (ROCP)",id:"resource-owner-password-credentials-grant-type-rocp",children:[{value:"Overview",id:"overview",children:[]},{value:"Legacy &amp; Bad Security",id:"legacy--bad-security",children:[]},{value:"What about Auth0, Okta, ...?",id:"what-about-auth0-okta-",children:[]}]}],l={toc:c};function p(e){var t=e.components,n=Object(a.a)(e,["components"]);return Object(o.b)("wrapper",Object(r.a)({},l,n,{components:t,mdxType:"MDXLayout"}),Object(o.b)("p",null,"ORY Hydra tries to solve all of OAuth 2.0 and OpenID Connect uses. There are,\nhowever, some limitations."),Object(o.b)("h2",{id:"mysql--56--mariadb"},"MySQL <= 5.6 / MariaDB"),Object(o.b)("p",null,"ORY Hydra has issues with MySQL <= 5.6 (but not MySQL 5.7+) and certain MariaDB\nversions. Read more about this ",Object(o.b)("a",{parentName:"p",href:"https://github.com/ory/hydra/issues/377"},"here"),".\nOur recommendation is to use MySQL 5.7+ or PostgreSQL."),Object(o.b)("h2",{id:"oauth-20-client-secret-length"},"OAuth 2.0 Client Secret Length"),Object(o.b)("p",null,'OAuth 2.0 Client Secrets are hashed using BCrypt. BCrypt has, by design, a\nmaximum password length. The Golang BCrypt library has a maximum password length\nof 73 bytes. Any password longer will be "truncated":'),Object(o.b)("pre",null,Object(o.b)("code",{parentName:"pre",className:"language-shell",metastring:"script",script:!0},"$ hydra clients create --id long-secret \\\n --secret 525348e77144a9cee9a7471a8b67c50ea85b9e3eb377a3c1a3a23db88f9150eefe76e6a339fdbc62b817595f53d72549d9ebe36438f8c2619846b963e9f43a94 \\\n --endpoint http://localhost:4445 \\\n --token-endpoint-auth-method client_secret_post \\\n --grant-types client_credentials\n\n$ hydra token client --client-id long-secret \\\n --client-secret 525348e77144a9cee9a7471a8b67c50ea85b9e3eb377a3c1a3a23db88f9150eefe76e6a3 \\\n --endpoint http://localhost:4444\n")),Object(o.b)("p",null,"For more information on this topic we recommend reading:"),Object(o.b)("ul",null,Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://security.stackexchange.com/questions/39849/does-bcrypt-have-a-maximum-password-length"},"https://security.stackexchange.com/questions/39849/does-bcrypt-have-a-maximum-password-length")),Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",{parentName:"li",href:"https://security.stackexchange.com/questions/6623/pre-hash-password-before-applying-bcrypt-to-avoid-restricting-password-length"},"https://security.stackexchange.com/questions/6623/pre-hash-password-before-applying-bcrypt-to-avoid-restricting-password-length"))),Object(o.b)("h2",{id:"resource-owner-password-credentials-grant-type-rocp"},"Resource Owner Password Credentials Grant Type (ROCP)"),Object(o.b)("p",null,"ORY Hydra does not and will not implement the Resource Owner Password\nCredentials Grant Type. Read on for context."),Object(o.b)("h3",{id:"overview"},"Overview"),Object(o.b)("p",null,"This grant type allows OAuth 2.0 Clients to exchange user credentials (username,\npassword) for an access token."),Object(o.b)("p",null,Object(o.b)("strong",{parentName:"p"},"Request:")),Object(o.b)("pre",null,Object(o.b)("code",{parentName:"pre"},"POST /oauth2/token HTTP/1.1\nHost: server.example.com\nAuthorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW\nContent-Type: application/x-www-form-urlencoded\n\ngrant_type=password&username=johndoe&password=A3ddj3w\n")),Object(o.b)("p",null,Object(o.b)("strong",{parentName:"p"},"Response:")),Object(o.b)("pre",null,Object(o.b)("code",{parentName:"pre"},'HTTP/1.1 200 OK\nContent-Type: application/json;charset=UTF-8\nCache-Control: no-store\nPragma: no-cache\n\n{\n "access_token":"2YotnFZFEjr1zCsicMWpAA",\n "token_type":"example",\n "expires_in":3600,\n "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",\n "example_parameter":"example_value"\n}\n')),Object(o.b)("p",null,"You might think that this is the perfect grant type for your first-party\napplication. This grant type is most commonly used in mobile authentication for\nfirst-party apps. If you plan on doing this, stop right now and read\n",Object(o.b)("a",{parentName:"p",href:"https://www.ory.sh/oauth2-for-mobile-app-spa-browser"},"this blog article"),"."),Object(o.b)("h3",{id:"legacy--bad-security"},"Legacy & Bad Security"),Object(o.b)("p",null,'The ROCP grant type is discouraged by developers, professionals, and the IETF\nitself. It was originally added because big legacy corporations (not dropping\nany names, but they are part of the IETF consortium) did not want to migrate\ntheir authentication infrastructure to the modern web but instead do what\nthey\'ve been doing all along "but OAuth 2.0" and for systems that want to\nupgrade from OAuth (1.0) to OAuth 2.0.'),Object(o.b)("p",null,"There are a ton of good reasons why this is a bad flow, they are summarized in\n",Object(o.b)("a",{parentName:"p",href:"https://www.scottbrady91.com/OAuth/Why-the-Resource-Owner-Password-Credentials-Grant-Type-is-not-Authentication-nor-Suitable-for-Modern-Applications"},"this excellent blog article as well"),"."),Object(o.b)("h3",{id:"what-about-auth0-okta-"},"What about Auth0, Okta, ...?"),Object(o.b)("p",null,"Auth0, Okta, Stormpath started early with OAuth 2.0 SaaS and adopted the ROPC\ngrant too. They since deprecated these old flows but still have them active as\nexisting apps rely on them."))}p.isMDXComponent=!0},572:function(e,t,n){"use strict";n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return b}));var r=n(0),a=n.n(r);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?i(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function c(e,t){if(null==e)return{};var n,r,a=function(e,t){if(null==e)return{};var n,r,a={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var l=a.a.createContext({}),p=function(e){var t=a.a.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):s(s({},t),e)),n},d=function(e){var t=p(e.components);return a.a.createElement(l.Provider,{value:t},e.children)},u={inlineCode:"code",wrapper:function(e){var t=e.children;return a.a.createElement(a.a.Fragment,{},t)}},h=a.a.forwardRef((function(e,t){var n=e.components,r=e.mdxType,o=e.originalType,i=e.parentName,l=c(e,["components","mdxType","originalType","parentName"]),d=p(n),h=r,b=d["".concat(i,".").concat(h)]||d[h]||u[h]||o;return n?a.a.createElement(b,s(s({ref:t},l),{},{components:n})):a.a.createElement(b,s({ref:t},l))}));function b(e,t){var n=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var o=n.length,i=new Array(o);i[0]=h;var s={};for(var c in t)hasOwnProperty.call(t,c)&&(s[c]=t[c]);s.originalType=e,s.mdxType="string"==typeof e?e:r,i[1]=s;for(var l=2;l<o;l++)i[l]=n[l];return a.a.createElement.apply(null,i)}return a.a.createElement.apply(null,n)}h.displayName="MDXCreateElement"}}]);
const Discord = require("discord.js"); const Client = require("./Client.js") /** * @template {keyof Discord.ClientEvents} K * @param {Client} client * @param {Discord.ClientEvents[K]} eventArgs */ function RunFunction(client, ...eventArgs) {} /** * @template {keyof Discord.ClientEvents} K */ class Event { /** * @param {K} event * @param {RunFunction<K>} runFunction */ constructor(event, runFunction) { this.event = event; this.run = runFunction; } } module.exports = Event;
// Muaz Khan - www.MuazKhan.com // MIT License - www.webrtc-experiment.com/licence // Documentation - github.com/streamproc/MediaStreamRecorder // ______________________ // MediaStreamRecorder.js function MediaStreamRecorder(mediaStream) { if (!mediaStream) throw 'MediaStream is mandatory.'; // void start(optional long timeSlice) // timestamp to fire "ondataavailable" this.start = function(timeSlice) { // Media Stream Recording API has not been implemented in chrome yet; // That's why using WebAudio API to record stereo audio in WAV format var Recorder = IsChrome ? window.StereoRecorder : window.MediaRecorderWrapper; // video recorder (in WebM format) if (this.mimeType.indexOf('video') != -1) { Recorder = IsChrome ? window.WhammyRecorder : window.MediaRecorderWrapper; } // video recorder (in GIF format) if (this.mimeType === 'image/gif') Recorder = window.GifRecorder; mediaRecorder = new Recorder(mediaStream); mediaRecorder.ondataavailable = this.ondataavailable; mediaRecorder.onstop = this.onstop; mediaRecorder.onStartedDrawingNonBlankFrames = this.onStartedDrawingNonBlankFrames; // Merge all data-types except "function" mediaRecorder = mergeProps(mediaRecorder, this); mediaRecorder.start(timeSlice); }; this.onStartedDrawingNonBlankFrames = function() {}; this.clearOldRecordedFrames = function() { if (!mediaRecorder) return; mediaRecorder.clearOldRecordedFrames(); }; this.stop = function() { if (mediaRecorder) mediaRecorder.stop(); }; this.ondataavailable = function(blob) { console.log('ondataavailable..', blob); }; this.onstop = function(error) { console.warn('stopped..', error); }; // Reference to "MediaRecorder.js" var mediaRecorder; } // below scripts are used to auto-load required files. function loadScript(src, onload) { var root = window.MediaStreamRecorderScriptsDir; var script = document.createElement('script'); script.src = root + src; script.onload = onload || function() {}; document.documentElement.appendChild(script); } // Muaz Khan - www.MuazKhan.com // MIT License - www.webrtc-experiment.com/licence // Documentation - github.com/streamproc/MediaStreamRecorder // _____________________________ // Cross-Browser-Declarations.js // animation-frame used in WebM recording if (!window.requestAnimationFrame) { requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; } if (!window.cancelAnimationFrame) { cancelAnimationFrame = window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame; } // WebAudio API representer if (!window.AudioContext) { window.AudioContext = window.webkitAudioContext || window.mozAudioContext; } URL = window.URL || window.webkitURL; navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (window.webkitMediaStream) window.MediaStream = window.webkitMediaStream; IsChrome = !!navigator.webkitGetUserMedia; // Merge all other data-types except "function" function mergeProps(mergein, mergeto) { mergeto = reformatProps(mergeto); for (var t in mergeto) { if (typeof mergeto[t] !== 'function') { mergein[t] = mergeto[t]; } } return mergein; } function reformatProps(obj) { var output = {}; for (var o in obj) { if (o.indexOf('-') != -1) { var splitted = o.split('-'); var name = splitted[0] + splitted[1].split('')[0].toUpperCase() + splitted[1].substr(1); output[name] = obj[o]; } else output[o] = obj[o]; } return output; } // ______________ (used to handle stuff like http://goo.gl/xmE5eg) issue #129 // ObjectStore.js var ObjectStore = { AudioContext: window.AudioContext || window.webkitAudioContext }; // ================ // MediaRecorder.js /** * Implementation of https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html * The MediaRecorder accepts a mediaStream as input source passed from UA. When recorder starts, * a MediaEncoder will be created and accept the mediaStream as input source. * Encoder will get the raw data by track data changes, encode it by selected MIME Type, then store the encoded in EncodedBufferCache object. * The encoded data will be extracted on every timeslice passed from Start function call or by RequestData function. * Thread model: * When the recorder starts, it creates a "Media Encoder" thread to read data from MediaEncoder object and store buffer in EncodedBufferCache object. * Also extract the encoded data and create blobs on every timeslice passed from start function or RequestData function called by UA. */ function MediaRecorderWrapper(mediaStream) { // if user chosen only audio option; and he tried to pass MediaStream with // both audio and video tracks; // using a dirty workaround to generate audio-only stream so that we can get audio/ogg output. if (this.type == 'audio' && mediaStream.getVideoTracks && mediaStream.getVideoTracks().length && !navigator.mozGetUserMedia) { var context = new AudioContext(); var mediaStreamSource = context.createMediaStreamSource(mediaStream); var destination = context.createMediaStreamDestination(); mediaStreamSource.connect(destination); mediaStream = destination.stream; } // void start(optional long timeSlice) // timestamp to fire "ondataavailable" // starting a recording session; which will initiate "Reading Thread" // "Reading Thread" are used to prevent main-thread blocking scenarios this.start = function(mTimeSlice) { mTimeSlice = mTimeSlice || 1000; isStopRecording = false; function startRecording() { if (isStopRecording) return; mediaRecorder = new MediaRecorder(mediaStream); mediaRecorder.ondataavailable = function(e) { console.log('ondataavailable', e.data.type, e.data.size, e.data); // mediaRecorder.state == 'recording' means that media recorder is associated with "session" // mediaRecorder.state == 'stopped' means that media recorder is detached from the "session" ... in this case; "session" will also be deleted. if (!e.data.size) { console.warn('Recording of', e.data.type, 'failed.'); return; } // at this stage, Firefox MediaRecorder API doesn't allow to choose the output mimeType format! var blob = new window.Blob([e.data], { type: e.data.type || self.mimeType || 'audio/ogg' // It specifies the container format as well as the audio and video capture formats. }); // Dispatching OnDataAvailable Handler self.ondataavailable(blob); }; mediaRecorder.onstop = function(error) { // for video recording on Firefox, it will be fired quickly. // because work on VideoFrameContainer is still in progress // https://wiki.mozilla.org/Gecko:MediaRecorder // self.onstop(error); }; // http://www.w3.org/TR/2012/WD-dom-20121206/#error-names-table // showBrowserSpecificIndicator: got neither video nor audio access // "VideoFrameContainer" can't be accessed directly; unable to find any wrapper using it. // that's why there is no video recording support on firefox // video recording fails because there is no encoder available there // http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp#317 // Maybe "Read Thread" doesn't fire video-track read notification; // that's why shutdown notification is received; and "Read Thread" is stopped. // https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html#error-handling mediaRecorder.onerror = function(error) { console.error(error); self.start(mTimeSlice); }; mediaRecorder.onwarning = function(warning) { console.warn(warning); }; // void start(optional long mTimeSlice) // The interval of passing encoded data from EncodedBufferCache to onDataAvailable // handler. "mTimeSlice < 0" means Session object does not push encoded data to // onDataAvailable, instead, it passive wait the client side pull encoded data // by calling requestData API. mediaRecorder.start(0); // Start recording. If timeSlice has been provided, mediaRecorder will // raise a dataavailable event containing the Blob of collected data on every timeSlice milliseconds. // If timeSlice isn't provided, UA should call the RequestData to obtain the Blob data, also set the mTimeSlice to zero. setTimeout(function() { mediaRecorder.stop(); startRecording(); }, mTimeSlice); } // dirty workaround to fix Firefox 2nd+ intervals startRecording(); }; var isStopRecording = false; this.stop = function() { isStopRecording = true; if (self.onstop) { self.onstop({}); } }; this.ondataavailable = this.onstop = function() {}; // Reference to itself var self = this; if (!self.mimeType && !!mediaStream.getAudioTracks) { self.mimeType = mediaStream.getAudioTracks().length && mediaStream.getVideoTracks().length ? 'video/webm' : 'audio/ogg'; } // Reference to "MediaRecorderWrapper" object var mediaRecorder; } // ================= // StereoRecorder.js function StereoRecorder(mediaStream) { // void start(optional long timeSlice) // timestamp to fire "ondataavailable" this.start = function(timeSlice) { timeSlice = timeSlice || 1000; mediaRecorder = new StereoAudioRecorder(mediaStream, this); mediaRecorder.record(); timeout = setInterval(function() { mediaRecorder.requestData(); }, timeSlice); }; this.stop = function() { if (mediaRecorder) { mediaRecorder.stop(); clearTimeout(timeout); } }; this.ondataavailable = function() {}; // Reference to "StereoAudioRecorder" object var mediaRecorder; var timeout; } // ====================== // StereoAudioRecorder.js // source code from: http://typedarray.org/wp-content/projects/WebAudioRecorder/script.js function StereoAudioRecorder(mediaStream, root) { // variables var leftchannel = []; var rightchannel = []; var scriptprocessornode; var recording = false; var recordingLength = 0; var volume; var audioInput; var sampleRate = root.sampleRate || 44100; // range: 22050 to 96000 var audioContext; var context; var numChannels = root.audioChannels || 2; this.record = function() { recording = true; // reset the buffers for the new recording leftchannel.length = rightchannel.length = 0; recordingLength = 0; }; this.requestData = function() { if (recordingLength == 0) { requestDataInvoked = false; return; } requestDataInvoked = true; // clone stuff var internal_leftchannel = leftchannel.slice(0); var internal_rightchannel = rightchannel.slice(0); var internal_recordingLength = recordingLength; // reset the buffers for the new recording leftchannel.length = rightchannel.length = []; recordingLength = 0; requestDataInvoked = false; // we flat the left and right channels down var leftBuffer = mergeBuffers(internal_leftchannel, internal_recordingLength); var rightBuffer = mergeBuffers(internal_leftchannel, internal_recordingLength); // we interleave both channels together if (numChannels === 2) { var interleaved = interleave(leftBuffer, rightBuffer); } else { var interleaved = leftBuffer; } // we create our wav file var buffer = new ArrayBuffer(44 + interleaved.length * 2); var view = new DataView(buffer); // RIFF chunk descriptor writeUTFBytes(view, 0, 'RIFF'); view.setUint32(4, 44 + interleaved.length * 2, true); writeUTFBytes(view, 8, 'WAVE'); // FMT sub-chunk writeUTFBytes(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); // stereo (2 channels) view.setUint16(22, numChannels, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 4, true); view.setUint16(32, numChannels * 2, true); view.setUint16(34, 16, true); // data sub-chunk writeUTFBytes(view, 36, 'data'); view.setUint32(40, interleaved.length * 2, true); // write the PCM samples var lng = interleaved.length; var index = 44; var volume = 1; for (var i = 0; i < lng; i++) { view.setInt16(index, interleaved[i] * (0x7FFF * volume), true); index += 2; } // our final binary blob var blob = new Blob([view], { type: 'audio/wav' }); console.debug('audio recorded blob size:', bytesToSize(blob.size)); root.ondataavailable(blob); }; this.stop = function() { // we stop recording recording = false; this.requestData(); }; function interleave(leftChannel, rightChannel) { var length = leftChannel.length + rightChannel.length; var result = new Float32Array(length); var inputIndex = 0; for (var index = 0; index < length;) { result[index++] = leftChannel[inputIndex]; result[index++] = rightChannel[inputIndex]; inputIndex++; } return result; } function mergeBuffers(channelBuffer, recordingLength) { var result = new Float32Array(recordingLength); var offset = 0; var lng = channelBuffer.length; for (var i = 0; i < lng; i++) { var buffer = channelBuffer[i]; result.set(buffer, offset); offset += buffer.length; } return result; } function writeUTFBytes(view, offset, string) { var lng = string.length; for (var i = 0; i < lng; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } } // creates the audio context // creates the audio context var audioContext = ObjectStore.AudioContext; if (!ObjectStore.AudioContextConstructor) ObjectStore.AudioContextConstructor = new audioContext(); var context = ObjectStore.AudioContextConstructor; // creates a gain node if (!ObjectStore.VolumeGainNode) ObjectStore.VolumeGainNode = context.createGain(); var volume = ObjectStore.VolumeGainNode; // creates an audio node from the microphone incoming stream var audioInput = context.createMediaStreamSource(mediaStream); // connect the stream to the gain node audioInput.connect(volume); /* From the spec: This value controls how frequently the audioprocess event is dispatched and how many sample-frames need to be processed each call. Lower values for buffer size will result in a lower (better) latency. Higher values will be necessary to avoid audio breakup and glitches Legal values are 256, 512, 1024, 2048, 4096, 8192, and 16384.*/ var bufferSize = root.bufferSize || 2048; if (root.bufferSize == 0) bufferSize = 0; if (context.createJavaScriptNode) { scriptprocessornode = context.createJavaScriptNode(bufferSize, numChannels, numChannels); } else if (context.createScriptProcessor) { scriptprocessornode = context.createScriptProcessor(bufferSize, numChannels, numChannels); } else { throw 'WebAudio API has no support on this browser.'; } bufferSize = scriptprocessornode.bufferSize; console.debug('using audio buffer-size:', bufferSize); var requestDataInvoked = false; // sometimes "scriptprocessornode" disconnects from he destination-node // and there is no exception thrown in this case. // and obviously no further "ondataavailable" events will be emitted. // below global-scope variable is added to debug such unexpected but "rare" cases. window.scriptprocessornode = scriptprocessornode; if (numChannels == 1) { console.debug('All right-channels are skipped.'); } // http://webaudio.github.io/web-audio-api/#the-scriptprocessornode-interface scriptprocessornode.onaudioprocess = function(e) { if (!recording || requestDataInvoked) return; var left = e.inputBuffer.getChannelData(0); leftchannel.push(new Float32Array(left)); if (numChannels == 2) { var right = e.inputBuffer.getChannelData(1); rightchannel.push(new Float32Array(right)); } recordingLength += bufferSize; }; volume.connect(scriptprocessornode); scriptprocessornode.connect(context.destination); } // ======================= // WhammyRecorderHelper.js function WhammyRecorderHelper(mediaStream, root) { this.record = function(timeSlice) { if (!this.width) this.width = 320; if (!this.height) this.height = 240; if (this.video && this.video instanceof HTMLVideoElement) { if (!this.width) this.width = video.videoWidth || video.clientWidth || 320; if (!this.height) this.height = video.videoHeight || video.clientHeight || 240; } if (!this.video) { this.video = { width: this.width, height: this.height }; } if (!this.canvas || !this.canvas.width || !this.canvas.height) { this.canvas = { width: this.width, height: this.height }; } canvas.width = this.canvas.width; canvas.height = this.canvas.height; // setting defaults if (this.video && this.video instanceof HTMLVideoElement) { video = this.video.cloneNode(); } else { video = document.createElement('video'); video.src = URL.createObjectURL(mediaStream); video.width = this.video.width; video.height = this.video.height; } video.muted = true; video.play(); lastTime = new Date().getTime(); whammy = new Whammy.Video(); console.log('canvas resolutions', canvas.width, '*', canvas.height); console.log('video width/height', video.width || canvas.width, '*', video.height || canvas.height); drawFrames(); }; this.clearOldRecordedFrames = function() { frames = []; }; var requestDataInvoked = false; this.requestData = function() { if (!frames.length) { requestDataInvoked = false; return; } requestDataInvoked = true; // clone stuff var internal_frames = frames.slice(0); // reset the frames for the new recording frames = []; whammy.frames = dropBlackFrames(internal_frames, -1); var WebM_Blob = whammy.compile(); root.ondataavailable(WebM_Blob); console.debug('video recorded blob size:', bytesToSize(WebM_Blob.size)); requestDataInvoked = false; }; var frames = []; var isOnStartedDrawingNonBlankFramesInvoked = false; function drawFrames() { if (isStopDrawing) return; if (requestDataInvoked) return setTimeout(drawFrames, 100); var duration = new Date().getTime() - lastTime; if (!duration) return drawFrames(); // via webrtc-experiment#206, by Jack i.e. @Seymourr lastTime = new Date().getTime(); context.drawImage(video, 0, 0, canvas.width, canvas.height); !isStopDrawing && frames.push({ duration: duration, image: canvas.toDataURL('image/webp') }); if (!isOnStartedDrawingNonBlankFramesInvoked && !isBlankFrame(frames[frames.length - 1])) { isOnStartedDrawingNonBlankFramesInvoked = true; root.onStartedDrawingNonBlankFrames(); } setTimeout(drawFrames, 10); } var isStopDrawing = false; this.stop = function() { isStopDrawing = true; this.requestData(); }; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var video; var lastTime; var whammy; var self = this; function isBlankFrame(frame, _pixTolerance, _frameTolerance) { var localCanvas = document.createElement('canvas'); localCanvas.width = canvas.width; localCanvas.height = canvas.height; var context2d = localCanvas.getContext('2d'); var sampleColor = { r: 0, g: 0, b: 0 }; var maxColorDifference = Math.sqrt( Math.pow(255, 2) + Math.pow(255, 2) + Math.pow(255, 2) ); var pixTolerance = _pixTolerance && _pixTolerance >= 0 && _pixTolerance <= 1 ? _pixTolerance : 0; var frameTolerance = _frameTolerance && _frameTolerance >= 0 && _frameTolerance <= 1 ? _frameTolerance : 0; var matchPixCount, endPixCheck, maxPixCount; var image = new Image(); image.src = frame.image; context2d.drawImage(image, 0, 0, canvas.width, canvas.height); var imageData = context2d.getImageData(0, 0, canvas.width, canvas.height); matchPixCount = 0; endPixCheck = imageData.data.length; maxPixCount = imageData.data.length / 4; for (var pix = 0; pix < endPixCheck; pix += 4) { var currentColor = { r: imageData.data[pix], g: imageData.data[pix + 1], b: imageData.data[pix + 2] }; var colorDifference = Math.sqrt( Math.pow(currentColor.r - sampleColor.r, 2) + Math.pow(currentColor.g - sampleColor.g, 2) + Math.pow(currentColor.b - sampleColor.b, 2) ); // difference in color it is difference in color vectors (r1,g1,b1) <=> (r2,g2,b2) if (colorDifference <= maxColorDifference * pixTolerance) { matchPixCount++; } } if (maxPixCount - matchPixCount <= maxPixCount * frameTolerance) { return false; } else { return true; } } function dropBlackFrames(_frames, _framesToCheck, _pixTolerance, _frameTolerance) { var localCanvas = document.createElement('canvas'); localCanvas.width = canvas.width; localCanvas.height = canvas.height; var context2d = localCanvas.getContext('2d'); var resultFrames = []; var checkUntilNotBlack = _framesToCheck === -1; var endCheckFrame = (_framesToCheck && _framesToCheck > 0 && _framesToCheck <= _frames.length) ? _framesToCheck : _frames.length; var sampleColor = { r: 0, g: 0, b: 0 }; var maxColorDifference = Math.sqrt( Math.pow(255, 2) + Math.pow(255, 2) + Math.pow(255, 2) ); var pixTolerance = _pixTolerance && _pixTolerance >= 0 && _pixTolerance <= 1 ? _pixTolerance : 0; var frameTolerance = _frameTolerance && _frameTolerance >= 0 && _frameTolerance <= 1 ? _frameTolerance : 0; var doNotCheckNext = false; for (var f = 0; f < endCheckFrame; f++) { var matchPixCount, endPixCheck, maxPixCount; if (!doNotCheckNext) { var image = new Image(); image.src = _frames[f].image; context2d.drawImage(image, 0, 0, canvas.width, canvas.height); var imageData = context2d.getImageData(0, 0, canvas.width, canvas.height); matchPixCount = 0; endPixCheck = imageData.data.length; maxPixCount = imageData.data.length / 4; for (var pix = 0; pix < endPixCheck; pix += 4) { var currentColor = { r: imageData.data[pix], g: imageData.data[pix + 1], b: imageData.data[pix + 2] }; var colorDifference = Math.sqrt( Math.pow(currentColor.r - sampleColor.r, 2) + Math.pow(currentColor.g - sampleColor.g, 2) + Math.pow(currentColor.b - sampleColor.b, 2) ); // difference in color it is difference in color vectors (r1,g1,b1) <=> (r2,g2,b2) if (colorDifference <= maxColorDifference * pixTolerance) { matchPixCount++; } } } if (!doNotCheckNext && maxPixCount - matchPixCount <= maxPixCount * frameTolerance) { // console.log('removed black frame : ' + f + ' ; frame duration ' + _frames[f].duration); } else { // console.log('frame is passed : ' + f); if (checkUntilNotBlack) { doNotCheckNext = true; } resultFrames.push(_frames[f]); } } resultFrames = resultFrames.concat(_frames.slice(endCheckFrame)); if (resultFrames.length <= 0) { // at least one last frame should be available for next manipulation // if total duration of all frames will be < 1000 than ffmpeg doesn't work well... resultFrames.push(_frames[_frames.length - 1]); } return resultFrames; } } // ================= // WhammyRecorder.js function WhammyRecorder(mediaStream) { // void start(optional long timeSlice) // timestamp to fire "ondataavailable" this.start = function(timeSlice) { timeSlice = timeSlice || 1000; mediaRecorder = new WhammyRecorderHelper(mediaStream, this); for (var prop in this) { if (typeof this[prop] !== 'function') { mediaRecorder[prop] = this[prop]; } } mediaRecorder.record(); timeout = setInterval(function() { mediaRecorder.requestData(); }, timeSlice); }; this.stop = function() { if (mediaRecorder) { mediaRecorder.stop(); clearTimeout(timeout); } }; this.clearOldRecordedFrames = function() { if (mediaRecorder) { mediaRecorder.clearOldRecordedFrames(); } }; this.ondataavailable = function() {}; // Reference to "WhammyRecorder" object var mediaRecorder; var timeout; } // Muaz Khan - https://github.com/muaz-khan // neizerth - https://github.com/neizerth // MIT License - https://www.webrtc-experiment.com/licence/ // Documentation - https://github.com/streamproc/MediaStreamRecorder // Note: // ========================================================== // whammy.js is an "external library" // and has its own copyrights. Taken from "Whammy" project. // https://github.com/antimatter15/whammy/blob/master/LICENSE // ========= // Whammy.js // todo: Firefox now supports webp for webm containers! // their MediaRecorder implementation works well! // should we provide an option to record via Whammy.js or MediaRecorder API is a better solution? var Whammy = (function() { function toWebM(frames) { var info = checkFrames(frames); var CLUSTER_MAX_DURATION = 30000; var EBML = [{ "id": 0x1a45dfa3, // EBML "data": [{ "data": 1, "id": 0x4286 // EBMLVersion }, { "data": 1, "id": 0x42f7 // EBMLReadVersion }, { "data": 4, "id": 0x42f2 // EBMLMaxIDLength }, { "data": 8, "id": 0x42f3 // EBMLMaxSizeLength }, { "data": "webm", "id": 0x4282 // DocType }, { "data": 2, "id": 0x4287 // DocTypeVersion }, { "data": 2, "id": 0x4285 // DocTypeReadVersion }] }, { "id": 0x18538067, // Segment "data": [{ "id": 0x1549a966, // Info "data": [{ "data": 1e6, //do things in millisecs (num of nanosecs for duration scale) "id": 0x2ad7b1 // TimecodeScale }, { "data": "whammy", "id": 0x4d80 // MuxingApp }, { "data": "whammy", "id": 0x5741 // WritingApp }, { "data": doubleToString(info.duration), "id": 0x4489 // Duration }] }, { "id": 0x1654ae6b, // Tracks "data": [{ "id": 0xae, // TrackEntry "data": [{ "data": 1, "id": 0xd7 // TrackNumber }, { "data": 1, "id": 0x63c5 // TrackUID }, { "data": 0, "id": 0x9c // FlagLacing }, { "data": "und", "id": 0x22b59c // Language }, { "data": "V_VP8", "id": 0x86 // CodecID }, { "data": "VP8", "id": 0x258688 // CodecName }, { "data": 1, "id": 0x83 // TrackType }, { "id": 0xe0, // Video "data": [{ "data": info.width, "id": 0xb0 // PixelWidth }, { "data": info.height, "id": 0xba // PixelHeight }] }] }] }] }]; //Generate clusters (max duration) var frameNumber = 0; var clusterTimecode = 0; while (frameNumber < frames.length) { var clusterFrames = []; var clusterDuration = 0; do { clusterFrames.push(frames[frameNumber]); clusterDuration += frames[frameNumber].duration; frameNumber++; } while (frameNumber < frames.length && clusterDuration < CLUSTER_MAX_DURATION); var clusterCounter = 0; var cluster = { "id": 0x1f43b675, // Cluster "data": [{ "data": clusterTimecode, "id": 0xe7 // Timecode }].concat(clusterFrames.map(function(webp) { var block = makeSimpleBlock({ discardable: 0, frame: webp.data.slice(4), invisible: 0, keyframe: 1, lacing: 0, trackNum: 1, timecode: Math.round(clusterCounter) }); clusterCounter += webp.duration; return { data: block, id: 0xa3 }; })) }; //Add cluster to segment EBML[1].data.push(cluster); clusterTimecode += clusterDuration; } return generateEBML(EBML); } // sums the lengths of all the frames and gets the duration function checkFrames(frames) { if (!frames[0]) { console.warn('Something went wrong. Maybe WebP format is not supported in the current browser.'); return; } var width = frames[0].width, height = frames[0].height, duration = frames[0].duration; for (var i = 1; i < frames.length; i++) { duration += frames[i].duration; } return { duration: duration, width: width, height: height }; } function numToBuffer(num) { var parts = []; while (num > 0) { parts.push(num & 0xff); num = num >> 8; } return new Uint8Array(parts.reverse()); } function strToBuffer(str) { return new Uint8Array(str.split('').map(function(e) { return e.charCodeAt(0); })); } function bitsToBuffer(bits) { var data = []; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for (var i = 0; i < bits.length; i += 8) { data.push(parseInt(bits.substr(i, 8), 2)); } return new Uint8Array(data); } function generateEBML(json) { var ebml = []; for (var i = 0; i < json.length; i++) { var data = json[i].data; if (typeof data == 'object') data = generateEBML(data); if (typeof data == 'number') data = bitsToBuffer(data.toString(2)); if (typeof data == 'string') data = strToBuffer(data); var len = data.size || data.byteLength || data.length; var zeroes = Math.ceil(Math.ceil(Math.log(len) / Math.log(2)) / 8); var size_str = len.toString(2); var padded = (new Array((zeroes * 7 + 7 + 1) - size_str.length)).join('0') + size_str; var size = (new Array(zeroes)).join('0') + '1' + padded; ebml.push(numToBuffer(json[i].id)); ebml.push(bitsToBuffer(size)); ebml.push(data); } return new Blob(ebml, { type: "video/webm" }); } function toBinStr_old(bits) { var data = ''; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for (var i = 0; i < bits.length; i += 8) { data += String.fromCharCode(parseInt(bits.substr(i, 8), 2)); } return data; } function generateEBML_old(json) { var ebml = ''; for (var i = 0; i < json.length; i++) { var data = json[i].data; if (typeof data == 'object') data = generateEBML_old(data); if (typeof data == 'number') data = toBinStr_old(data.toString(2)); var len = data.length; var zeroes = Math.ceil(Math.ceil(Math.log(len) / Math.log(2)) / 8); var size_str = len.toString(2); var padded = (new Array((zeroes * 7 + 7 + 1) - size_str.length)).join('0') + size_str; var size = (new Array(zeroes)).join('0') + '1' + padded; ebml += toBinStr_old(json[i].id.toString(2)) + toBinStr_old(size) + data; } return ebml; } function makeSimpleBlock(data) { var flags = 0; if (data.keyframe) flags |= 128; if (data.invisible) flags |= 8; if (data.lacing) flags |= (data.lacing << 1); if (data.discardable) flags |= 1; if (data.trackNum > 127) { throw "TrackNumber > 127 not supported"; } var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e) { return String.fromCharCode(e); }).join('') + data.frame; return out; } function parseWebP(riff) { var VP8 = riff.RIFF[0].WEBP[0]; var frame_start = VP8.indexOf('\x9d\x01\x2a'); // A VP8 keyframe starts with the 0x9d012a header for (var i = 0, c = []; i < 4; i++) c[i] = VP8.charCodeAt(frame_start + 3 + i); var width, height, tmp; //the code below is literally copied verbatim from the bitstream spec tmp = (c[1] << 8) | c[0]; width = tmp & 0x3FFF; tmp = (c[3] << 8) | c[2]; height = tmp & 0x3FFF; return { width: width, height: height, data: VP8, riff: riff }; } function parseRIFF(string) { var offset = 0; var chunks = {}; while (offset < string.length) { var id = string.substr(offset, 4); var len = parseInt(string.substr(offset + 4, 4).split('').map(function(i) { var unpadded = i.charCodeAt(0).toString(2); return (new Array(8 - unpadded.length + 1)).join('0') + unpadded; }).join(''), 2); var data = string.substr(offset + 4 + 4, len); offset += 4 + 4 + len; chunks[id] = chunks[id] || []; if (id == 'RIFF' || id == 'LIST') { chunks[id].push(parseRIFF(data)); } else { chunks[id].push(data); } } return chunks; } function doubleToString(num) { return [].slice.call( new Uint8Array((new Float64Array([num])).buffer), 0).map(function(e) { return String.fromCharCode(e); }).reverse().join(''); } // a more abstract-ish API function WhammyVideo(duration) { this.frames = []; this.duration = duration || 1; this.quality = 100; } WhammyVideo.prototype.add = function(frame, duration) { if ('canvas' in frame) { //CanvasRenderingContext2D frame = frame.canvas; } if ('toDataURL' in frame) { frame = frame.toDataURL('image/webp', this.quality); } if (!(/^data:image\/webp;base64,/ig).test(frame)) { throw "Input must be formatted properly as a base64 encoded DataURI of type image/webp"; } this.frames.push({ image: frame, duration: duration || this.duration }); }; WhammyVideo.prototype.compile = function() { return new toWebM(this.frames.map(function(frame) { var webp = parseWebP(parseRIFF(atob(frame.image.slice(23)))); webp.duration = frame.duration; return webp; })); }; return { Video: WhammyVideo, toWebM: toWebM }; })(); // Muaz Khan - https://github.com/muaz-khan // neizerth - https://github.com/neizerth // MIT License - https://www.webrtc-experiment.com/licence/ // Documentation - https://github.com/streamproc/MediaStreamRecorder // ========================================================== // GifRecorder.js function GifRecorder(mediaStream) { if (!window.GIFEncoder) { throw 'Please link: https://cdn.webrtc-experiment.com/gif-recorder.js'; } // void start(optional long timeSlice) // timestamp to fire "ondataavailable" this.start = function(timeSlice) { timeSlice = timeSlice || 1000; var imageWidth = this.videoWidth || 320; var imageHeight = this.videoHeight || 240; canvas.width = video.width = imageWidth; canvas.height = video.height = imageHeight; // external library to record as GIF images gifEncoder = new GIFEncoder(); // void setRepeat(int iter) // Sets the number of times the set of GIF frames should be played. // Default is 1; 0 means play indefinitely. gifEncoder.setRepeat(0); // void setFrameRate(Number fps) // Sets frame rate in frames per second. // Equivalent to setDelay(1000/fps). // Using "setDelay" instead of "setFrameRate" gifEncoder.setDelay(this.frameRate || 200); // void setQuality(int quality) // Sets quality of color quantization (conversion of images to the // maximum 256 colors allowed by the GIF specification). // Lower values (minimum = 1) produce better colors, // but slow processing significantly. 10 is the default, // and produces good color mapping at reasonable speeds. // Values greater than 20 do not yield significant improvements in speed. gifEncoder.setQuality(this.quality || 1); // Boolean start() // This writes the GIF Header and returns false if it fails. gifEncoder.start(); startTime = Date.now(); function drawVideoFrame(time) { lastAnimationFrame = requestAnimationFrame(drawVideoFrame); if (typeof lastFrameTime === undefined) { lastFrameTime = time; } // ~10 fps if (time - lastFrameTime < 90) return; context.drawImage(video, 0, 0, imageWidth, imageHeight); gifEncoder.addFrame(context); // console.log('Recording...' + Math.round((Date.now() - startTime) / 1000) + 's'); // console.log("fps: ", 1000 / (time - lastFrameTime)); lastFrameTime = time; } lastAnimationFrame = requestAnimationFrame(drawVideoFrame); timeout = setTimeout(doneRecording, timeSlice); }; function doneRecording() { endTime = Date.now(); var gifBlob = new Blob([new Uint8Array(gifEncoder.stream().bin)], { type: 'image/gif' }); self.ondataavailable(gifBlob); // todo: find a way to clear old recorded blobs gifEncoder.stream().bin = []; }; this.stop = function() { if (lastAnimationFrame) { cancelAnimationFrame(lastAnimationFrame); clearTimeout(timeout); doneRecording(); } }; this.ondataavailable = function() {}; this.onstop = function() {}; // Reference to itself var self = this; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var video = document.createElement('video'); video.muted = true; video.autoplay = true; video.src = URL.createObjectURL(mediaStream); video.play(); var lastAnimationFrame = null; var startTime, endTime, lastFrameTime; var gifEncoder; var timeout; } // ______________________ // MultiStreamRecorder.js function MultiStreamRecorder(mediaStream) { if (!mediaStream) throw 'MediaStream is mandatory.'; var self = this; var isFirefox = !!navigator.mozGetUserMedia; this.stream = mediaStream; // void start(optional long timeSlice) // timestamp to fire "ondataavailable" this.start = function(timeSlice) { audioRecorder = new MediaStreamRecorder(mediaStream); videoRecorder = new MediaStreamRecorder(mediaStream); audioRecorder.mimeType = 'audio/ogg'; videoRecorder.mimeType = 'video/webm'; for (var prop in this) { if (typeof this[prop] !== 'function') { audioRecorder[prop] = videoRecorder[prop] = this[prop]; } } audioRecorder.ondataavailable = function(blob) { if (!audioVideoBlobs[recordingInterval]) { audioVideoBlobs[recordingInterval] = {}; } audioVideoBlobs[recordingInterval].audio = blob; if (audioVideoBlobs[recordingInterval].video && !audioVideoBlobs[recordingInterval].onDataAvailableEventFired) { audioVideoBlobs[recordingInterval].onDataAvailableEventFired = true; fireOnDataAvailableEvent(audioVideoBlobs[recordingInterval]); } }; videoRecorder.ondataavailable = function(blob) { if (isFirefox) { return self.ondataavailable({ video: blob, audio: blob }); } if (!audioVideoBlobs[recordingInterval]) { audioVideoBlobs[recordingInterval] = {}; } audioVideoBlobs[recordingInterval].video = blob; if (audioVideoBlobs[recordingInterval].audio && !audioVideoBlobs[recordingInterval].onDataAvailableEventFired) { audioVideoBlobs[recordingInterval].onDataAvailableEventFired = true; fireOnDataAvailableEvent(audioVideoBlobs[recordingInterval]); } }; function fireOnDataAvailableEvent(blobs) { recordingInterval++; self.ondataavailable(blobs); } videoRecorder.onstop = audioRecorder.onstop = function(error) { self.onstop(error); }; if (!isFirefox) { audioRecorder.start(timeSlice); videoRecorder.start(timeSlice); } else { videoRecorder.start(timeSlice); } }; this.stop = function() { if (audioRecorder) audioRecorder.stop(); if (videoRecorder) videoRecorder.stop(); }; this.ondataavailable = function(blob) { console.log('ondataavailable..', blob); }; this.onstop = function(error) { console.warn('stopped..', error); }; var audioRecorder; var videoRecorder; var audioVideoBlobs = {}; var recordingInterval = 0; } function bytesToSize(bytes) { var k = 1000; var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) { return '0 Bytes'; } var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10); return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]; }
import express from 'express'; import url from 'url'; import path from 'path'; // eslint-disable-next-line import proxy from 'express-http-proxy'; const prjRoot = p => path.resolve(__dirname, '../', p); const main = async () => { const app = express(); /* app routes */ app.use('/api', proxy( 'localhost:5000', { forwardPath: (req) => { const reqUrl = url.parse(req.url).path; // eslint-disable-next-line console.log('reqUrl =', reqUrl); return `/api${reqUrl}`; }, }, )); app.use('/static', express.static(prjRoot('./dist/'))); app.get('/*', (req, res) => { res.sendFile('index.html', { root: prjRoot('./dist/') }); }); app.listen(4001, () => { // eslint-disable-next-line no-console console.log('Webpack dev server listening on port 4001...'); }); }; // eslint-disable-next-line no-console main().catch(err => console.error(err));
var kind = require('enyo/kind'); var FittableRows = require('layout/FittableRows'), BodyText = require('moonstone/BodyText'), Divider = require('moonstone/Divider'), Icon = require('moonstone/Icon'), Input = require('moonstone/Input'), InputDecorator = require('moonstone/InputDecorator'), RichText = require('moonstone/RichText'), Scroller = require('moonstone/Scroller'), TextArea = require('moonstone/TextArea'); module.exports = kind({ name: 'moon.sample.InputSample', kind: FittableRows, classes: 'moon enyo-unselectable enyo-fit moon-input-sample', components: [ {kind: Divider, content: 'Inputs'}, {kind: Scroller, horizontal: 'hidden', fit: true, components: [ {components: [ {kind: InputDecorator, components: [ {kind: Input, placeholder: 'JUST TYPE', oninput:'handleInput', onchange:'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Search term', oninput:'handleInput', onchange:'handleChange'}, {kind: Icon, icon: 'search'} ]} ]}, {components: [ {kind: InputDecorator, components: [ {kind: Input, type:'password', placeholder: 'Enter password', oninput:'handleInput', onchange:'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: Input, type:'number', placeholder: 'Enter number', oninput:'handleInput', onchange:'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Placeholder for initial value', value: 'This is the initial value', oninput:'handleInput', onchange:'handleChange'} ]} ]}, {components: [ {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Placeholder for value with ellipsis', value: 'This is the initial value that is of a certain length to display an ellipsis.', oninput:'handleInput', onchange:'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Dismiss on Enter', dismissOnEnter:true, oninput:'handleInput', onchange:'handleChange'} ]}, {kind: InputDecorator, disabled: true, components: [ {kind: Input, disabled: true, placeholder: 'Disabled input'} ]} ]}, {kind: Divider, content: 'TextAreas'}, {kind: InputDecorator, components: [ {kind: TextArea, placeholder: 'Enter text here', oninput: 'handleInput', onchange: 'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: TextArea, placeholder: 'JUST TYPE', oninput: 'handleInput', onchange: 'handleChange'} ]}, {kind: InputDecorator, disabled: true, components: [ {kind: TextArea, disabled: true, placeholder: 'Deactivated TextArea', oninput: 'handleInput', onchange: 'handleChange'} ]}, {kind: Divider, content: 'RichTexts'}, {kind: InputDecorator, components: [ {kind: RichText, oninput: 'handleInput', onchange: 'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: RichText, style: 'width: 240px;', oninput: 'handleInput', onchange: 'handleChange'}, {kind: Icon, icon: 'search'} ]}, {kind: InputDecorator, disabled: true, components: [ {kind: RichText, disabled: true, style: 'width: 240px;'} ]}, {kind: Divider, content: 'Range Inputs'}, {classes: 'range-inputs', components: [ {name: 'rangeInput', kind: InputDecorator, invalidMessage: 'Please enter a number between 25 and 100.', components: [ {kind: Input, placeholder: 'Enter a number', type: 'number', attributes: { min: 25, max: 100 }, style: 'width: 300px;', onchange:'handleChange', oninput:'handleRangeInput'} ]}, {name: 'zipCodeInput', kind: InputDecorator, invalidMessage: 'Please enter a 5 digit zip code.', components: [ {kind: Input, placeholder: 'Enter a zip code', type: 'number', style: 'width: 300px;', onchange:'handleChange', oninput:'handleZipInput'} ]}, {name: 'nameInput', kind: InputDecorator, invalid: true, invalidMessage: 'Please enter a name.', components: [ {kind: Input, style: 'width: 300px;', onchange:'handleChange', oninput:'handleNameInput'} ]} ]} ]}, {kind: Divider, content: 'Result', classes: 'moon-input-sample-result'}, {kind: BodyText, name: 'console', allowHtml: false, content: 'Input: '}, {kind: Divider, content: 'Bottom-aligned inputs', classes: 'moon-input-sample-result'}, {components: [ {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Bottom', oninput: 'handleInput', onchange: 'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Aligned', oninput: 'handleInput', onchange: 'handleChange'} ]}, {kind: InputDecorator, components: [ {kind: Input, placeholder: 'Inputs', oninput: 'handleInput', onchange: 'handleChange'} ]} ]} ], handleInput: function (sender, ev) { this.$.console.setContent('Input: ' + sender.getValue()); }, handleChange: function (sender, ev) { this.$.console.setContent('Changed: ' + sender.getValue()); }, handleRangeInput: function (sender, ev) { this.$.rangeInput.set('invalid', !ev.target.validity.valid); }, handleZipInput: function (sender, ev) { var value = ev.target.value, length = value ? value.length : 0; this.$.zipCodeInput.set('invalid', length !== 0 && length !== 5); }, handleNameInput: function (sender, ev) { var value = ev.target.value, length = value && value.length, control = this.$.nameInput; if (!value) { control.set('invalidMessage', 'Please enter a name.'); control.set('invalid', true); } else if (length < 3) { control.set('invalidMessage', 'Please enter a name that is at least 3 characters.'); control.set('invalid', true); } else { control.set('invalid', false); } } });
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/SizeOneSym/Regular/Main.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. * */ MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXSizeOneSym"] = { directory: "SizeOneSym/Regular", family: "STIXSizeOneSym", Ranges: [ [0x2b0, 0x2ff, "All"], [0x300, 0x338, "All"], [0x203e, 0x203e, "All"], [0x20d0, 0x20ef, "All"], [0x2140, 0x2140, "All"], [0x221a, 0x221c, "All"], [0x2320, 0x2321, "All"], [0x239b, 0x23b9, "All"], [0x23dc, 0x23e1, "All"], [0x2772, 0x2773, "All"], [0x27e6, 0x27eb, "All"], [0x2983, 0x2986, "All"], [0x29f8, 0x29f9, "All"], [0x2a00, 0x2a0a, "All"], [0x2afc, 0x2aff, "All"] ], 0x20: [0, 0, 250, 0, 0], // SPACE 0x28: [1066, 164, 468, 139, 382], // LEFT PARENTHESIS 0x29: [1066, 164, 468, 86, 329], // RIGHT PARENTHESIS 0x2f: [1066, 164, 579, 25, 552], // SOLIDUS 0x5b: [1066, 164, 383, 180, 363], // LEFT SQUARE BRACKET 0x5c: [1066, 164, 579, 27, 552], // REVERSE SOLIDUS 0x5d: [1066, 164, 383, 20, 203], // RIGHT SQUARE BRACKET 0x5f: [-127, 177, 1000, 0, 1000], // LOW LINE 0x7b: [1066, 164, 575, 114, 466], // LEFT CURLY BRACKET 0x7d: [1066, 164, 575, 109, 461], // RIGHT CURLY BRACKET 0xa0: [0, 0, 250, 0, 0], // NO-BREAK SPACE 0x302: [767, -554, 0, -720, -160], // COMBINING CIRCUMFLEX ACCENT 0x303: [750, -598, 0, -722, -162], // COMBINING TILDE 0x220f: [1500, -49, 1355, 50, 1305], // N-ARY PRODUCT 0x2210: [1500, -49, 1355, 50, 1305], // N-ARY COPRODUCT 0x2211: [1499, -49, 1292, 90, 1202], // N-ARY SUMMATION 0x221a: [1552, 295, 1057, 112, 1089], // SQUARE ROOT 0x22c0: [1500, -49, 1265, 60, 1205], // N-ARY LOGICAL AND 0x22c1: [1500, -49, 1265, 60, 1205], // N-ARY LOGICAL OR 0x22c2: [1510, -49, 1265, 118, 1147], // N-ARY INTERSECTION 0x22c3: [1500, -39, 1265, 118, 1147], // N-ARY UNION 0x2308: [1066, 164, 453, 180, 426], // LEFT CEILING 0x2309: [1066, 164, 453, 25, 273], // RIGHT CEILING 0x230a: [1066, 164, 453, 180, 428], // LEFT FLOOR 0x230b: [1066, 164, 453, 27, 273], // RIGHT FLOOR 0x239b: [700, 305, 450, 50, 400], // LEFT PARENTHESIS UPPER HOOK 0x239c: [705, 305, 450, 50, 174], // LEFT PARENTHESIS EXTENSION 0x239d: [705, 300, 450, 50, 400], // LEFT PARENTHESIS LOWER HOOK 0x239e: [700, 305, 450, 50, 400], // RIGHT PARENTHESIS UPPER HOOK 0x239f: [705, 305, 450, 276, 400], // RIGHT PARENTHESIS EXTENSION 0x23a0: [705, 300, 450, 50, 400], // RIGHT PARENTHESIS LOWER HOOK 0x23a1: [682, 323, 450, 50, 415], // LEFT SQUARE BRACKET UPPER CORNER 0x23a2: [687, 323, 450, 50, 150], // LEFT SQUARE BRACKET EXTENSION 0x23a3: [687, 318, 450, 50, 415], // LEFT SQUARE BRACKET LOWER CORNER 0x23a4: [682, 323, 450, 35, 400], // RIGHT SQUARE BRACKET UPPER CORNER 0x23a5: [687, 323, 450, 300, 400], // RIGHT SQUARE BRACKET EXTENSION 0x23a6: [687, 318, 450, 35, 400], // RIGHT SQUARE BRACKET LOWER CORNER 0x23a7: [700, 305, 640, 260, 600], // LEFT CURLY BRACKET UPPER HOOK 0x23a8: [705, 305, 640, 40, 380], // LEFT CURLY BRACKET MIDDLE PIECE 0x23a9: [705, 300, 640, 260, 600], // LEFT CURLY BRACKET LOWER HOOK 0x23aa: [705, 305, 640, 260, 380], // CURLY BRACKET EXTENSION 0x23ab: [700, 305, 640, 40, 380], // RIGHT CURLY BRACKET UPPER HOOK 0x23ac: [705, 305, 640, 260, 600], // RIGHT CURLY BRACKET MIDDLE PIECE 0x23ad: [705, 300, 640, 40, 380], // RIGHT CURLY BRACKET LOWER HOOK 0x23ae: [610, 25, 688, 294, 394], // INTEGRAL EXTENSION 0x23b0: [700, 301, 600, 35, 566], // UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION 0x23b1: [700, 301, 600, 35, 566], // UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION 0x23b7: [1510, 345, 1184, 112, 895], // RADICAL SYMBOL BOTTOM 0x23b8: [1566, 289, 721, 0, 66], // LEFT VERTICAL BOX LINE 0x23b9: [1566, 289, 721, 655, 721], // RIGHT VERTICAL BOX LINE 0x23de: [136, 89, 926, 0, 925], // TOP CURLY BRACKET (mathematical use) 0x23df: [789, -564, 926, 0, 925], // BOTTOM CURLY BRACKET (mathematical use) 0x27e8: [1066, 164, 578, 116, 462], // MATHEMATICAL LEFT ANGLE BRACKET 0x27e9: [1066, 164, 578, 116, 462], // MATHEMATICAL RIGHT ANGLE BRACKET 0x2a00: [1500, -49, 1555, 52, 1503], // N-ARY CIRCLED DOT OPERATOR 0x2a01: [1500, -49, 1555, 52, 1503], // N-ARY CIRCLED PLUS OPERATOR 0x2a02: [1500, -49, 1555, 52, 1503], // N-ARY CIRCLED TIMES OPERATOR 0x2a04: [1500, -39, 1265, 118, 1147], // N-ARY UNION OPERATOR WITH PLUS 0x2a05: [1500, -49, 1153, 82, 1071], // N-ARY SQUARE INTERSECTION OPERATOR 0x2a06: [1500, -49, 1153, 82, 1071] // N-ARY SQUARE UNION OPERATOR }; MathJax.OutputJax["HTML-CSS"].initFont("STIXSizeOneSym"); MathJax.Ajax.loadComplete( MathJax.OutputJax["HTML-CSS"].fontDir + "/SizeOneSym/Regular/Main.js" );
/* * Copyright (C) 2008 Apple Inc. 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 APPLE INC. ``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 APPLE INC. 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. */ import * as Common from '../common/common.js'; import * as Platform from '../platform/platform.js'; import * as UI from '../ui/ui.js'; /** * @unrestricted * @template NODE_TYPE */ export class DataGridImpl extends Common.ObjectWrapper.ObjectWrapper { /** * @param {!Parameters} dataGridParameters */ constructor(dataGridParameters) { super(); const {displayName, columns: columnsArray, editCallback, deleteCallback, refreshCallback} = dataGridParameters; this.element = document.createElement('div'); this.element.classList.add('data-grid'); UI.Utils.appendStyle(this.element, 'data_grid/dataGrid.css'); this.element.tabIndex = 0; this.element.addEventListener('keydown', this._keyDown.bind(this), false); this.element.addEventListener('contextmenu', this._contextMenu.bind(this), true); this.element.addEventListener('focusin', event => { this.updateGridAccessibleNameOnFocus(); event.consume(true); }); this.element.addEventListener('focusout', event => { this.updateGridAccessibleName(/* text */ ''); event.consume(true); }); UI.ARIAUtils.markAsApplication(this.element); this._displayName = displayName; this._editCallback = editCallback; this._deleteCallback = deleteCallback; this._refreshCallback = refreshCallback; const headerContainer = this.element.createChild('div', 'header-container'); /** @type {!Element} */ this._headerTable = headerContainer.createChild('table', 'header'); // Hide the header table from screen readers since titles are also added to data table. UI.ARIAUtils.markAsHidden(this._headerTable); /** @type {!Object.<string, !Element>} */ this._headerTableHeaders = {}; /** @type {!Element} */ this._scrollContainer = this.element.createChild('div', 'data-container'); /** @type {!Element} */ this._dataTable = this._scrollContainer.createChild('table', 'data'); /** @type {!Element} */ this._ariaLiveLabel = this.element.createChild('div', 'aria-live-label'); UI.ARIAUtils.markAsPoliteLiveRegion(this._ariaLiveLabel, false); // FIXME: Add a createCallback which is different from editCallback and has different // behavior when creating a new node. if (editCallback) { this._dataTable.addEventListener('dblclick', this._ondblclick.bind(this), false); } this._dataTable.addEventListener('mousedown', this._mouseDownInDataTable.bind(this)); this._dataTable.addEventListener('click', this._clickInDataTable.bind(this), true); /** @type {boolean} */ this._inline = false; /** @type {!Array.<!ColumnDescriptor>} */ this._columnsArray = []; /** @type {!Object.<string, !ColumnDescriptor>} */ this._columns = {}; /** @type {!Array.<!ColumnDescriptor>} */ this.visibleColumnsArray = columnsArray; columnsArray.forEach(column => this._innerAddColumn(column)); /** @type {?string} */ this._cellClass = null; /** @type {!Element} */ this._headerTableColumnGroup = this._headerTable.createChild('colgroup'); /** @type {!Element} */ this._headerTableBody = this._headerTable.createChild('tbody'); /** @type {!Element} */ this._headerRow = this._headerTableBody.createChild('tr'); /** @type {!Element} */ this._dataTableColumnGroup = this._dataTable.createChild('colgroup'); /** * @protected * @type {!Element} */ this.dataTableBody = this._dataTable.createChild('tbody'); /** @type {!Element} */ this._topFillerRow = this.dataTableBody.createChild('tr', 'data-grid-filler-row revealed'); /** @type {!Element} */ this._bottomFillerRow = this.dataTableBody.createChild('tr', 'data-grid-filler-row revealed'); this.setVerticalPadding(0, 0); this._refreshHeader(); /** @type {boolean} */ this._editing = false; /** @type {?NODE_TYPE} */ this.selectedNode = null; /** @type {boolean} */ this.expandNodesWhenArrowing = false; this.setRootNode(/** @type {!NODE_TYPE} */ (new DataGridNode())); this.setHasSelection(false); /** @type {number} */ this.indentWidth = 15; /** @type {!Array.<!Element|{__index: number, __position: number}>} */ this._resizers = []; /** @type {boolean} */ this._columnWidthsInitialized = false; /** @type {number} */ this._cornerWidth = CornerWidth; /** @type {!ResizeMethod} */ this._resizeMethod = ResizeMethod.Nearest; /** @type {?function(!UI.ContextMenu.SubMenu)} */ this._headerContextMenuCallback = null; /** @type {?function(!UI.ContextMenu.ContextMenu, !NODE_TYPE)} */ this._rowContextMenuCallback = null; } /** * @return {!NODE_TYPE} */ _firstSelectableNode() { let firstSelectableNode = this._rootNode; while (firstSelectableNode && !firstSelectableNode.selectable) { firstSelectableNode = firstSelectableNode.traverseNextNode(true); } return firstSelectableNode; } /** * @return {!NODE_TYPE} */ _lastSelectableNode() { let lastSelectableNode = this._rootNode; let iterator = this._rootNode; while (iterator) { if (iterator.selectable) { lastSelectableNode = iterator; } iterator = iterator.traverseNextNode(true); } return lastSelectableNode; } /** * @param {!Element} element * @param {*} value */ setElementContent(element, value) { const columnId = this.columnIdFromNode(element); if (!columnId) { return; } const column = this._columns[columnId]; if (column.dataType === DataGrid.DataGrid.DataType.Boolean) { DataGridImpl.setElementBoolean(element, /** @type {boolean} */ (!!value)); } else if (value !== null) { DataGridImpl.setElementText(element, /** @type {string} */ (value), !!column.longText); } } /** * @param {!Element} element * @param {string} newText * @param {boolean} longText */ static setElementText(element, newText, longText) { if (longText && newText.length > 1000) { element.textContent = newText.trimEndWithMaxLength(1000); element.title = newText; element[DataGrid._longTextSymbol] = newText; } else { element.textContent = newText; element.title = ''; element[DataGrid._longTextSymbol] = undefined; } } /** * @param {!Element} element * @param {boolean} value */ static setElementBoolean(element, value) { element.textContent = value ? '\u2713' : ''; element.title = ''; } /** * @param {boolean} isStriped */ setStriped(isStriped) { this.element.classList.toggle('striped-data-grid', isStriped); } /** * @param {boolean} focusable */ setFocusable(focusable) { this.element.tabIndex = focusable ? 0 : -1; if (focusable === false) { UI.ARIAUtils.removeRole(this.element); } } /** * @param {boolean} hasSelected */ setHasSelection(hasSelected) { // 'no-selection' class causes datagrid to have a focus-indicator border this.element.classList.toggle('no-selection', !hasSelected); } /** * @param {string=} text */ updateGridAccessibleName(text) { // Update the label with the provided text or the current selected node const accessibleText = (this.selectedNode && this.selectedNode.existingElement()) ? this.selectedNode.nodeAccessibleText : ''; this._ariaLiveLabel.textContent = text ? text : accessibleText; } updateGridAccessibleNameOnFocus() { // When a grid gets focus // 1) If an item is selected - Read the content of the row let accessibleText; if (this.selectedNode && this.selectedNode.existingElement()) { let expandText = ''; if (this.selectedNode.hasChildren()) { expandText = this.selectedNode.expanded ? ls`expanded` : ls`collapsed`; } const rowHeader = ls`${this._displayName} Row ${expandText}`; accessibleText = `${rowHeader} ${this.selectedNode.nodeAccessibleText}`; } else { // 2) If there is no selected item - Read the name of the grid and give instructions const children = this._enumerateChildren(this._rootNode, [], 1); const items = ls`Rows: ${children.length}`; accessibleText = ls`${ this._displayName} ${items}, use the up and down arrow keys to navigate and interact with the rows of the table; Use browse mode to read cell by cell.`; } this._ariaLiveLabel.textContent = accessibleText; } /** * @return {!Element} */ headerTableBody() { return this._headerTableBody; } /** * @param {!ColumnDescriptor} column * @param {number=} position */ _innerAddColumn(column, position) { column.defaultWeight = column.weight; const columnId = column.id; if (columnId in this._columns) { this._innerRemoveColumn(columnId); } if (position === undefined) { position = this._columnsArray.length; } this._columnsArray.splice(position, 0, column); this._columns[columnId] = column; if (column.disclosure) { this.disclosureColumnId = columnId; } const cell = createElement('th'); cell.className = columnId + '-column'; cell[DataGrid._columnIdSymbol] = columnId; this._headerTableHeaders[columnId] = cell; const div = createElement('div'); if (column.titleDOMFragment) { div.appendChild(column.titleDOMFragment); } else { div.textContent = column.title; } cell.appendChild(div); if (column.sort) { cell.classList.add(column.sort); this._sortColumnCell = cell; } if (column.sortable) { cell.addEventListener('click', this._clickInHeaderCell.bind(this), false); cell.classList.add('sortable'); const icon = UI.Icon.Icon.create('', 'sort-order-icon'); cell.createChild('div', 'sort-order-icon-container').appendChild(icon); cell[DataGrid._sortIconSymbol] = icon; } } /** * @param {!ColumnDescriptor} column * @param {number=} position */ addColumn(column, position) { this._innerAddColumn(column, position); } /** * @param {string} columnId */ _innerRemoveColumn(columnId) { const column = this._columns[columnId]; if (!column) { return; } delete this._columns[columnId]; const index = this._columnsArray.findIndex(columnConfig => columnConfig.id === columnId); this._columnsArray.splice(index, 1); const cell = this._headerTableHeaders[columnId]; if (cell.parentElement) { cell.parentElement.removeChild(cell); } delete this._headerTableHeaders[columnId]; } /** * @param {string} columnId */ removeColumn(columnId) { this._innerRemoveColumn(columnId); } /** * @param {string} cellClass */ setCellClass(cellClass) { this._cellClass = cellClass; } _refreshHeader() { this._headerTableColumnGroup.removeChildren(); this._dataTableColumnGroup.removeChildren(); this._headerRow.removeChildren(); this._topFillerRow.removeChildren(); this._bottomFillerRow.removeChildren(); for (let i = 0; i < this.visibleColumnsArray.length; ++i) { const column = this.visibleColumnsArray[i]; const columnId = column.id; const headerColumn = this._headerTableColumnGroup.createChild('col'); const dataColumn = this._dataTableColumnGroup.createChild('col'); if (column.width) { headerColumn.style.width = column.width; dataColumn.style.width = column.width; } this._headerRow.appendChild(this._headerTableHeaders[columnId]); const topFillerRowCell = this._topFillerRow.createChild('th', 'top-filler-td'); topFillerRowCell.textContent = column.title; topFillerRowCell.scope = 'col'; this._bottomFillerRow.createChild('td', 'bottom-filler-td')[DataGrid._columnIdSymbol] = columnId; } this._headerRow.createChild('th', 'corner'); const topFillerRowCornerCell = this._topFillerRow.createChild('th', 'corner'); topFillerRowCornerCell.classList.add('top-filler-td'); topFillerRowCornerCell.scope = 'col'; this._bottomFillerRow.createChild('td', 'corner').classList.add('bottom-filler-td'); this._headerTableColumnGroup.createChild('col', 'corner'); this._dataTableColumnGroup.createChild('col', 'corner'); } /** * @param {number} top * @param {number} bottom * @protected */ setVerticalPadding(top, bottom) { const topPx = top + 'px'; const bottomPx = (top || bottom) ? bottom + 'px' : 'auto'; if (this._topFillerRow.style.height === topPx && this._bottomFillerRow.style.height === bottomPx) { return; } this._topFillerRow.style.height = topPx; this._bottomFillerRow.style.height = bottomPx; this.dispatchEventToListeners(Events.PaddingChanged); } /** * @param {!NODE_TYPE} rootNode * @protected */ setRootNode(rootNode) { if (this._rootNode) { this._rootNode.removeChildren(); this._rootNode.dataGrid = null; this._rootNode._isRoot = false; } /** @type {!NODE_TYPE} */ this._rootNode = rootNode; rootNode._isRoot = true; rootNode.setHasChildren(false); rootNode._expanded = true; rootNode._revealed = true; rootNode.selectable = false; rootNode.dataGrid = this; } /** * @return {!NODE_TYPE} */ rootNode() { return this._rootNode; } /** * @param {!Event} event */ _ondblclick(event) { if (this._editing || this._editingNode) { return; } const columnId = this.columnIdFromNode(/** @type {!Node} */ (event.target)); if (!columnId || !this._columns[columnId].editable) { return; } this._startEditing(/** @type {!Node} */ (event.target)); } /** * @param {!DataGridNode} node * @param {number} cellIndex */ _startEditingColumnOfDataGridNode(node, cellIndex) { this._editing = true; /** @type {?DataGridNode} */ this._editingNode = node; this._editingNode.select(); const element = this._editingNode._element.children[cellIndex]; if (element[DataGrid._longTextSymbol]) { element.textContent = element[DataGrid._longTextSymbol]; } const column = this.visibleColumnsArray[cellIndex]; if (column.dataType === DataGrid.DataGrid.DataType.Boolean) { const checkboxLabel = UI.UIUtils.CheckboxLabel.create(undefined, /** @type {boolean} */ (node.data[column.id])); UI.ARIAUtils.setAccessibleName(checkboxLabel, column.title || ''); let hasChanged = false; checkboxLabel.style.height = '100%'; const checkboxElement = checkboxLabel.checkboxElement; checkboxElement.classList.add('inside-datagrid'); const initialValue = checkboxElement.checked; checkboxElement.addEventListener('change', () => { hasChanged = true; this._editingCommitted(element, checkboxElement.checked, initialValue, undefined, 'forward'); }, false); checkboxElement.addEventListener('keydown', event => { if (event.key === 'Tab') { event.consume(true); hasChanged = true; return this._editingCommitted( element, checkboxElement.checked, initialValue, undefined, event.shiftKey ? 'backward' : 'forward'); } if (event.key === ' ') { event.consume(true); checkboxElement.checked = !checkboxElement.checked; } else if (event.key === 'Enter') { event.consume(true); hasChanged = true; this._editingCommitted(element, checkboxElement.checked, initialValue, undefined, 'forward'); } }, false); checkboxElement.addEventListener('blur', () => { if (hasChanged) { return; } this._editingCommitted(element, checkboxElement.checked, checkboxElement.checked, undefined, 'next'); }, false); element.innerHTML = ''; element.appendChild(checkboxLabel); checkboxElement.focus(); } else { UI.InplaceEditor.InplaceEditor.startEditing(element, this._startEditingConfig(element)); element.getComponentSelection().selectAllChildren(element); } } /** * @param {!DataGridNode} node * @param {string} columnIdentifier */ startEditingNextEditableColumnOfDataGridNode(node, columnIdentifier) { const column = this._columns[columnIdentifier]; const cellIndex = this.visibleColumnsArray.indexOf(column); const nextEditableColumn = this._nextEditableColumn(cellIndex); if (nextEditableColumn !== -1) { this._startEditingColumnOfDataGridNode(node, nextEditableColumn); } } /** * @param {!Node} target */ _startEditing(target) { const element = /** @type {?Element} */ (target.enclosingNodeOrSelfWithNodeName('td')); if (!element) { return; } this._editingNode = this.dataGridNodeFromNode(target); if (!this._editingNode) { if (!this.creationNode) { return; } this._editingNode = this.creationNode; } // Force editing the 1st column when editing the creation node if (this._editingNode.isCreationNode) { this._startEditingColumnOfDataGridNode(this._editingNode, this._nextEditableColumn(-1)); return; } const columnId = this.columnIdFromNode(target); if (!columnId) { return; } const column = this._columns[columnId]; const cellIndex = this.visibleColumnsArray.indexOf(column); this._startEditingColumnOfDataGridNode(this._editingNode, cellIndex); } renderInline() { this.element.classList.add('inline'); this._cornerWidth = 0; this._inline = true; this.updateWidths(); } /** * @param {!Element} element * @return {!UI.InplaceEditor.Config} */ _startEditingConfig(element) { return new UI.InplaceEditor.Config(this._editingCommitted.bind(this), this._editingCancelled.bind(this)); } /** * @param {!Element} element * @param {*} newText * @param {*} oldText * @param {string|undefined} context * @param {string} moveDirection */ _editingCommitted(element, newText, oldText, context, moveDirection) { const columnId = this.columnIdFromNode(element); if (!columnId) { this._editingCancelled(element); return; } const column = this._columns[columnId]; const cellIndex = this.visibleColumnsArray.indexOf(column); const valueBeforeEditing = /** @type {string|boolean} */ ( this._editingNode.data[columnId] === null ? '' : this._editingNode.data[columnId]); const currentEditingNode = this._editingNode; /** * @param {boolean} wasChange * @this {DataGridImpl} */ function moveToNextIfNeeded(wasChange) { if (!moveDirection) { return; } if (moveDirection === 'forward') { const firstEditableColumn = this._nextEditableColumn(-1); if (currentEditingNode.isCreationNode && cellIndex === firstEditableColumn && !wasChange) { return; } const nextEditableColumn = this._nextEditableColumn(cellIndex); if (nextEditableColumn !== -1) { this._startEditingColumnOfDataGridNode(currentEditingNode, nextEditableColumn); return; } const nextDataGridNode = currentEditingNode.traverseNextNode(true, null, true); if (nextDataGridNode) { this._startEditingColumnOfDataGridNode(nextDataGridNode, firstEditableColumn); return; } if (currentEditingNode.isCreationNode && wasChange) { this.addCreationNode(false); this._startEditingColumnOfDataGridNode(this.creationNode, firstEditableColumn); return; } return; } if (moveDirection === 'backward') { const prevEditableColumn = this._nextEditableColumn(cellIndex, true); if (prevEditableColumn !== -1) { this._startEditingColumnOfDataGridNode(currentEditingNode, prevEditableColumn); return; } const lastEditableColumn = this._nextEditableColumn(this.visibleColumnsArray.length, true); const nextDataGridNode = currentEditingNode.traversePreviousNode(true, true); if (nextDataGridNode) { this._startEditingColumnOfDataGridNode(nextDataGridNode, lastEditableColumn); } return; } } // Show trimmed text after editing. this.setElementContent(element, newText); if (valueBeforeEditing === newText) { this._editingCancelled(element); moveToNextIfNeeded.call(this, false); return; } // Update the text in the datagrid that we typed this._editingNode.data[columnId] = newText; // Make the callback - expects an editing node (table row), the column number that is being edited, // the text that used to be there, and the new text. this._editCallback(this._editingNode, columnId, valueBeforeEditing, newText); if (this._editingNode.isCreationNode) { this.addCreationNode(false); } this._editingCancelled(element); moveToNextIfNeeded.call(this, true); } /** * @param {!Element} element */ _editingCancelled(element) { this._editing = false; this._editingNode = null; } /** * @param {number} cellIndex * @param {boolean=} moveBackward * @return {number} */ _nextEditableColumn(cellIndex, moveBackward) { const increment = moveBackward ? -1 : 1; const columns = this.visibleColumnsArray; for (let i = cellIndex + increment; (i >= 0) && (i < columns.length); i += increment) { if (columns[i].editable) { return i; } } return -1; } /** * @return {?string} */ sortColumnId() { if (!this._sortColumnCell) { return null; } return this._sortColumnCell[DataGrid._columnIdSymbol]; } /** * @return {?string} */ sortOrder() { if (!this._sortColumnCell || this._sortColumnCell.classList.contains(Order.Ascending)) { return Order.Ascending; } if (this._sortColumnCell.classList.contains(Order.Descending)) { return Order.Descending; } return null; } /** * @return {boolean} */ isSortOrderAscending() { return !this._sortColumnCell || this._sortColumnCell.classList.contains(Order.Ascending); } /** * @param {!Array.<number>} widths * @param {number} minPercent * @param {number=} maxPercent * @return {!Array.<number>} */ _autoSizeWidths(widths, minPercent, maxPercent) { if (minPercent) { minPercent = Math.min(minPercent, Math.floor(100 / widths.length)); } let totalWidth = 0; for (let i = 0; i < widths.length; ++i) { totalWidth += widths[i]; } let totalPercentWidth = 0; for (let i = 0; i < widths.length; ++i) { let width = Math.round(100 * widths[i] / totalWidth); if (minPercent && width < minPercent) { width = minPercent; } else if (maxPercent && width > maxPercent) { width = maxPercent; } totalPercentWidth += width; widths[i] = width; } let recoupPercent = totalPercentWidth - 100; while (minPercent && recoupPercent > 0) { for (let i = 0; i < widths.length; ++i) { if (widths[i] > minPercent) { --widths[i]; --recoupPercent; if (!recoupPercent) { break; } } } } while (maxPercent && recoupPercent < 0) { for (let i = 0; i < widths.length; ++i) { if (widths[i] < maxPercent) { ++widths[i]; ++recoupPercent; if (!recoupPercent) { break; } } } } return widths; } /** * The range of |minPercent| and |maxPercent| is [0, 100]. * @param {number} minPercent * @param {number=} maxPercent * @param {number=} maxDescentLevel */ autoSizeColumns(minPercent, maxPercent, maxDescentLevel) { let widths = []; for (let i = 0; i < this._columnsArray.length; ++i) { widths.push((this._columnsArray[i].title || '').length); } maxDescentLevel = maxDescentLevel || 0; const children = this._enumerateChildren(this._rootNode, [], maxDescentLevel + 1); for (let i = 0; i < children.length; ++i) { const node = children[i]; for (let j = 0; j < this._columnsArray.length; ++j) { const text = String(node.data[this._columnsArray[j].id]); if (text.length > widths[j]) { widths[j] = text.length; } } } widths = this._autoSizeWidths(widths, minPercent, maxPercent); for (let i = 0; i < this._columnsArray.length; ++i) { this._columnsArray[i].weight = widths[i]; } this._columnWidthsInitialized = false; this.updateWidths(); } /** * @param {!DataGridNode} rootNode * @param {!Array<!DataGridNode>} result * @param {number} maxLevel * @return {!Array<!NODE_TYPE>} */ _enumerateChildren(rootNode, result, maxLevel) { if (!rootNode._isRoot) { result.push(rootNode); } if (!maxLevel) { return []; } for (let i = 0; i < rootNode.children.length; ++i) { this._enumerateChildren(rootNode.children[i], result, maxLevel - 1); } return result; } onResize() { this.updateWidths(); } // Updates the widths of the table, including the positions of the column // resizers. // // IMPORTANT: This function MUST be called once after the element of the // DataGrid is attached to its parent element and every subsequent time the // width of the parent element is changed in order to make it possible to // resize the columns. // // If this function is not called after the DataGrid is attached to its // parent element, then the DataGrid's columns will not be resizable. updateWidths() { // Do not attempt to use offsetes if we're not attached to the document tree yet. if (!this._columnWidthsInitialized && this.element.offsetWidth) { // Give all the columns initial widths now so that during a resize, // when the two columns that get resized get a percent value for // their widths, all the other columns already have percent values // for their widths. // Use container size to avoid changes of table width caused by change of column widths. const tableWidth = this.element.offsetWidth - this._cornerWidth; const cells = this._headerTableBody.rows[0].cells; const numColumns = cells.length - 1; // Do not process corner column. for (let i = 0; i < numColumns; i++) { const column = this.visibleColumnsArray[i]; if (!column.weight) { column.weight = 100 * cells[i].offsetWidth / tableWidth || 10; } } this._columnWidthsInitialized = true; } this._applyColumnWeights(); } /** * @param {string} columnId * @returns {number} */ indexOfVisibleColumn(columnId) { return this.visibleColumnsArray.findIndex(column => column.id === columnId); } /** * @param {string} name */ setName(name) { this._columnWeightsSetting = Common.Settings.Settings.instance().createSetting('dataGrid-' + name + '-columnWeights', {}); this._loadColumnWeights(); } _resetColumnWeights() { for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; column.weight = column.defaultWeight; } this._applyColumnWeights(); this._saveColumnWeights(); } _loadColumnWeights() { if (!this._columnWeightsSetting) { return; } const weights = this._columnWeightsSetting.get(); for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; const weight = weights[column.id]; if (weight) { column.weight = weight; } } this._applyColumnWeights(); } _saveColumnWeights() { if (!this._columnWeightsSetting) { return; } const weights = {}; for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; weights[column.id] = column.weight; } this._columnWeightsSetting.set(weights); } wasShown() { this._loadColumnWeights(); } willHide() { } _applyColumnWeights() { let tableWidth = this.element.offsetWidth - this._cornerWidth; if (tableWidth <= 0) { return; } let sumOfWeights = 0.0; const fixedColumnWidths = []; for (let i = 0; i < this.visibleColumnsArray.length; ++i) { const column = this.visibleColumnsArray[i]; if (column.fixedWidth) { const width = this._headerTableColumnGroup.children[i][DataGrid._preferredWidthSymbol] || this._headerTableBody.rows[0].cells[i].offsetWidth; fixedColumnWidths[i] = width; tableWidth -= width; } else { sumOfWeights += this.visibleColumnsArray[i].weight; } } let sum = 0; let lastOffset = 0; const minColumnWidth = 14; // px for (let i = 0; i < this.visibleColumnsArray.length; ++i) { const column = this.visibleColumnsArray[i]; let width; if (column.fixedWidth) { width = fixedColumnWidths[i]; } else { sum += column.weight; const offset = (sum * tableWidth / sumOfWeights) | 0; width = Math.max(offset - lastOffset, minColumnWidth); lastOffset = offset; } this._setPreferredWidth(i, width); } this._positionResizers(); } /** * @param {!Object.<string, boolean>} columnsVisibility */ setColumnsVisiblity(columnsVisibility) { this.visibleColumnsArray = []; for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; if (columnsVisibility[column.id]) { this.visibleColumnsArray.push(column); } } this._refreshHeader(); this._applyColumnWeights(); const nodes = this._enumerateChildren(this.rootNode(), [], -1); for (let i = 0; i < nodes.length; ++i) { nodes[i].refresh(); } } get scrollContainer() { return this._scrollContainer; } _positionResizers() { const headerTableColumns = this._headerTableColumnGroup.children; const numColumns = headerTableColumns.length - 1; // Do not process corner column. const left = []; const resizers = this._resizers; while (resizers.length > numColumns - 1) { resizers.pop().remove(); } for (let i = 0; i < numColumns - 1; i++) { // Get the width of the cell in the first (and only) row of the // header table in order to determine the width of the column, since // it is not possible to query a column for its width. left[i] = (left[i - 1] || 0) + this._headerTableBody.rows[0].cells[i].offsetWidth; } // Make n - 1 resizers for n columns. for (let i = 0; i < numColumns - 1; i++) { let resizer = resizers[i]; if (!resizer) { // This is the first call to updateWidth, so the resizers need // to be created. resizer = createElement('div'); resizer.__index = i; resizer.classList.add('data-grid-resizer'); // This resizer is associated with the column to its right. UI.UIUtils.installDragHandle( resizer, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), 'col-resize'); this.element.appendChild(resizer); resizers.push(resizer); } if (resizer.__position !== left[i]) { resizer.__position = left[i]; resizer.style.left = left[i] + 'px'; } } } addCreationNode(hasChildren) { if (this.creationNode) { this.creationNode.makeNormal(); } const emptyData = {}; for (const column in this._columns) { emptyData[column] = null; } this.creationNode = new CreationDataGridNode(emptyData, hasChildren); this.rootNode().appendChild(this.creationNode); } /** * @param {!Event} event * @suppressGlobalPropertiesCheck */ _keyDown(event) { if (event.shiftKey || event.metaKey || event.ctrlKey || this._editing || UI.UIUtils.isEditing()) { return; } let handled = false; let nextSelectedNode; if (!this.selectedNode) { // Select the first or last node based on the arrow key direction if (event.key === 'ArrowUp' && !event.altKey) { nextSelectedNode = this._lastSelectableNode(); } else if (event.key === 'ArrowDown' && !event.altKey) { nextSelectedNode = this._firstSelectableNode(); } handled = nextSelectedNode ? true : false; } else if (event.key === 'ArrowUp' && !event.altKey) { nextSelectedNode = this.selectedNode.traversePreviousNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traversePreviousNode(true); } handled = nextSelectedNode ? true : false; } else if (event.key === 'ArrowDown' && !event.altKey) { nextSelectedNode = this.selectedNode.traverseNextNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traverseNextNode(true); } handled = nextSelectedNode ? true : false; } else if (event.key === 'ArrowLeft') { if (this.selectedNode.expanded) { if (event.altKey) { this.selectedNode.collapseRecursively(); } else { this.selectedNode.collapse(); } handled = true; } else if (this.selectedNode.parent && !this.selectedNode.parent._isRoot) { handled = true; if (this.selectedNode.parent.selectable) { nextSelectedNode = this.selectedNode.parent; handled = nextSelectedNode ? true : false; } else if (this.selectedNode.parent) { this.selectedNode.parent.collapse(); } } } else if (event.key === 'ArrowRight') { if (!this.selectedNode.revealed) { this.selectedNode.reveal(); handled = true; } else if (this.selectedNode.hasChildren()) { handled = true; if (this.selectedNode.expanded) { nextSelectedNode = this.selectedNode.children[0]; handled = nextSelectedNode ? true : false; } else { if (event.altKey) { this.selectedNode.expandRecursively(); } else { this.selectedNode.expand(); } } } } else if (event.keyCode === 8 || event.keyCode === 46) { if (this._deleteCallback) { handled = true; this._deleteCallback(this.selectedNode); } } else if (isEnterKey(event)) { if (this._editCallback) { handled = true; this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]); } else { this.dispatchEventToListeners(Events.OpenedNode, this.selectedNode); } } if (nextSelectedNode) { nextSelectedNode.reveal(); nextSelectedNode.select(); } if ((event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'ArrowLeft' || event.key === 'ArrowRight') && document.activeElement !== this.element) { // crbug.com/1005449 // navigational keys pressed but current DataGrid panel has lost focus; // re-focus to ensure subsequent keydowns can be registered within this DataGrid this.element.focus(); } if (handled) { event.consume(true); } } /** * @param {?NODE_TYPE} root * @param {boolean} onlyAffectsSubtree */ updateSelectionBeforeRemoval(root, onlyAffectsSubtree) { let ancestor = this.selectedNode; while (ancestor && ancestor !== root) { ancestor = ancestor.parent; } // Selection is not in the subtree being deleted. if (!ancestor) { return; } let nextSelectedNode; // Skip subtree being deleted when looking for the next selectable node. for (ancestor = root; ancestor && !ancestor.nextSibling; ancestor = ancestor.parent) { } if (ancestor) { nextSelectedNode = ancestor.nextSibling; } while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traverseNextNode(true); } if (!nextSelectedNode || nextSelectedNode.isCreationNode) { nextSelectedNode = root.traversePreviousNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traversePreviousNode(true); } } if (nextSelectedNode) { nextSelectedNode.reveal(); nextSelectedNode.select(); } else { this.selectedNode.deselect(); } } /** * @param {!Node} target * @return {?NODE_TYPE} */ dataGridNodeFromNode(target) { const rowElement = target.enclosingNodeOrSelfWithNodeName('tr'); return rowElement && rowElement._dataGridNode; } /** * @param {!Node} target * @return {?string} */ columnIdFromNode(target) { const cellElement = target.enclosingNodeOrSelfWithNodeName('td'); return cellElement && cellElement[DataGrid._columnIdSymbol]; } /** * @param {!Event} event */ _clickInHeaderCell(event) { const cell = event.target.enclosingNodeOrSelfWithNodeName('th'); if (!cell) { return; } this._sortByColumnHeaderCell(cell); } /** * @param {!Node} cell */ _sortByColumnHeaderCell(cell) { if ((cell[DataGrid._columnIdSymbol] === undefined) || !cell.classList.contains('sortable')) { return; } let sortOrder = Order.Ascending; if ((cell === this._sortColumnCell) && this.isSortOrderAscending()) { sortOrder = Order.Descending; } if (this._sortColumnCell) { this._sortColumnCell.classList.remove(Order.Ascending, Order.Descending); } this._sortColumnCell = cell; cell.classList.add(sortOrder); const icon = cell[DataGrid._sortIconSymbol]; icon.setIconType(sortOrder === Order.Ascending ? 'smallicon-triangle-up' : 'smallicon-triangle-down'); this.dispatchEventToListeners(Events.SortingChanged); } /** * @param {string} columnId * @param {!Order} sortOrder */ markColumnAsSortedBy(columnId, sortOrder) { if (this._sortColumnCell) { this._sortColumnCell.classList.remove(Order.Ascending, Order.Descending); } this._sortColumnCell = this._headerTableHeaders[columnId]; this._sortColumnCell.classList.add(sortOrder); } /** * @param {string} columnId * @return {!Element} */ headerTableHeader(columnId) { return this._headerTableHeaders[columnId]; } /** * @param {!Event} event */ _mouseDownInDataTable(event) { const target = /** @type {!Node} */ (event.target); const gridNode = this.dataGridNodeFromNode(target); if (!gridNode || !gridNode.selectable || gridNode.isEventWithinDisclosureTriangle(event)) { return; } const columnId = this.columnIdFromNode(target); if (columnId && this._columns[columnId].nonSelectable) { return; } if (event.metaKey) { if (gridNode.selected) { gridNode.deselect(); } else { gridNode.select(); } } else { gridNode.select(); this.dispatchEventToListeners(Events.OpenedNode, gridNode); } } /** * @param {?function(!UI.ContextMenu.SubMenu)} callback */ setHeaderContextMenuCallback(callback) { this._headerContextMenuCallback = callback; } /** * @param {?function(!UI.ContextMenu.ContextMenu, !NODE_TYPE)} callback */ setRowContextMenuCallback(callback) { this._rowContextMenuCallback = callback; } /** * @param {!Event} event */ _contextMenu(event) { const contextMenu = new UI.ContextMenu.ContextMenu(event); const target = /** @type {!Node} */ (event.target); const sortableVisibleColumns = this.visibleColumnsArray.filter(column => { return (column.sortable && column.title); }); const sortableHiddenColumns = this._columnsArray.filter( column => sortableVisibleColumns.indexOf(column) === -1 && column.allowInSortByEvenWhenHidden); const sortableColumns = [...sortableVisibleColumns, ...sortableHiddenColumns]; if (sortableColumns.length > 0) { const sortMenu = contextMenu.defaultSection().appendSubMenuItem(ls`Sort By`); for (const column of sortableColumns) { const headerCell = this._headerTableHeaders[column.id]; sortMenu.defaultSection().appendItem( /** @type {string} */ (column.title), this._sortByColumnHeaderCell.bind(this, headerCell)); } } if (target.isSelfOrDescendant(this._headerTableBody)) { if (this._headerContextMenuCallback) { this._headerContextMenuCallback(contextMenu); } contextMenu.defaultSection().appendItem( Common.UIString.UIString('Reset Columns'), this._resetColumnWeights.bind(this)); contextMenu.show(); return; } // Add header context menu to a subsection available from the body const headerSubMenu = contextMenu.defaultSection().appendSubMenuItem(ls`Header Options`); if (this._headerContextMenuCallback) { this._headerContextMenuCallback(headerSubMenu); } headerSubMenu.defaultSection().appendItem( Common.UIString.UIString('Reset Columns'), this._resetColumnWeights.bind(this)); const isContextMenuKey = (event.button === 0); const gridNode = isContextMenuKey ? this.selectedNode : this.dataGridNodeFromNode(target); if (isContextMenuKey && this.selectedNode) { const boundingRowRect = this.selectedNode.existingElement().getBoundingClientRect(); if (boundingRowRect) { const x = (boundingRowRect.right + boundingRowRect.left) / 2; const y = (boundingRowRect.bottom + boundingRowRect.top) / 2; contextMenu.setX(x); contextMenu.setY(y); } } if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode)) { contextMenu.defaultSection().appendItem(Common.UIString.UIString('Refresh'), this._refreshCallback.bind(this)); } if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) { if (this._editCallback) { if (gridNode === this.creationNode) { contextMenu.defaultSection().appendItem( Common.UIString.UIString('Add new'), this._startEditing.bind(this, target)); } else if (isContextMenuKey) { const firstEditColumnIndex = this._nextEditableColumn(-1); if (firstEditColumnIndex > -1) { const firstColumn = this.visibleColumnsArray[firstEditColumnIndex]; if (firstColumn && firstColumn.editable) { contextMenu.defaultSection().appendItem( ls`Edit "${firstColumn.title}"`, this._startEditingColumnOfDataGridNode.bind(this, gridNode, firstEditColumnIndex)); } } } else { const columnId = this.columnIdFromNode(target); if (columnId && this._columns[columnId].editable) { contextMenu.defaultSection().appendItem( Common.UIString.UIString('Edit "%s"', this._columns[columnId].title), this._startEditing.bind(this, target)); } } } if (this._deleteCallback && gridNode !== this.creationNode) { contextMenu.defaultSection().appendItem( Common.UIString.UIString('Delete'), this._deleteCallback.bind(this, gridNode)); } if (this._rowContextMenuCallback) { this._rowContextMenuCallback(contextMenu, gridNode); } } contextMenu.show(); } /** * @param {!Event} event */ _clickInDataTable(event) { const gridNode = this.dataGridNodeFromNode(/** @type {!Node} */ (event.target)); if (!gridNode || !gridNode.hasChildren() || !gridNode.isEventWithinDisclosureTriangle(event)) { return; } if (gridNode.expanded) { if (event.altKey) { gridNode.collapseRecursively(); } else { gridNode.collapse(); } } else { if (event.altKey) { gridNode.expandRecursively(); } else { gridNode.expand(); } } } /** * @param {!ResizeMethod} method */ setResizeMethod(method) { this._resizeMethod = method; } /** * @param {!Event} event * @return {boolean} */ _startResizerDragging(event) { this._currentResizer = event.target; return true; } _endResizerDragging() { this._currentResizer = null; this._saveColumnWeights(); } /** * @param {!Event} event */ _resizerDragging(event) { const resizer = this._currentResizer; if (!resizer) { return; } // Constrain the dragpoint to be within the containing div of the // datagrid. let dragPoint = event.clientX - this.element.totalOffsetLeft(); const firstRowCells = this._headerTableBody.rows[0].cells; let leftEdgeOfPreviousColumn = 0; // Constrain the dragpoint to be within the space made up by the // column directly to the left and the column directly to the right. let leftCellIndex = resizer.__index; let rightCellIndex = leftCellIndex + 1; for (let i = 0; i < leftCellIndex; i++) { leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth; } // Differences for other resize methods if (this._resizeMethod === ResizeMethod.Last) { rightCellIndex = this._resizers.length; } else if (this._resizeMethod === ResizeMethod.First) { leftEdgeOfPreviousColumn += firstRowCells[leftCellIndex].offsetWidth - firstRowCells[0].offsetWidth; leftCellIndex = 0; } const rightEdgeOfNextColumn = leftEdgeOfPreviousColumn + firstRowCells[leftCellIndex].offsetWidth + firstRowCells[rightCellIndex].offsetWidth; // Give each column some padding so that they don't disappear. const leftMinimum = leftEdgeOfPreviousColumn + ColumnResizePadding; const rightMaximum = rightEdgeOfNextColumn - ColumnResizePadding; if (leftMinimum > rightMaximum) { return; } dragPoint = Platform.NumberUtilities.clamp(dragPoint, leftMinimum, rightMaximum); const position = (dragPoint - CenterResizerOverBorderAdjustment); resizer.__position = position; resizer.style.left = position + 'px'; this._setPreferredWidth(leftCellIndex, dragPoint - leftEdgeOfPreviousColumn); this._setPreferredWidth(rightCellIndex, rightEdgeOfNextColumn - dragPoint); const leftColumn = this.visibleColumnsArray[leftCellIndex]; const rightColumn = this.visibleColumnsArray[rightCellIndex]; if (leftColumn.weight || rightColumn.weight) { const sumOfWeights = leftColumn.weight + rightColumn.weight; const delta = rightEdgeOfNextColumn - leftEdgeOfPreviousColumn; leftColumn.weight = (dragPoint - leftEdgeOfPreviousColumn) * sumOfWeights / delta; rightColumn.weight = (rightEdgeOfNextColumn - dragPoint) * sumOfWeights / delta; } this._positionResizers(); event.preventDefault(); } /** * @param {number} columnIndex * @param {number} width */ _setPreferredWidth(columnIndex, width) { const pxWidth = width + 'px'; this._headerTableColumnGroup.children[columnIndex][DataGrid._preferredWidthSymbol] = width; this._headerTableColumnGroup.children[columnIndex].style.width = pxWidth; this._dataTableColumnGroup.children[columnIndex].style.width = pxWidth; } /** * @param {string} columnId * @return {number} */ columnOffset(columnId) { if (!this.element.offsetWidth) { return 0; } for (let i = 1; i < this.visibleColumnsArray.length; ++i) { if (columnId === this.visibleColumnsArray[i].id) { if (this._resizers[i - 1]) { return this._resizers[i - 1].__position; } } } return 0; } /** * @return {!DataGridWidget} */ asWidget() { if (!this._dataGridWidget) { this._dataGridWidget = new DataGridWidget(this); } return this._dataGridWidget; } topFillerRowElement() { return this._topFillerRow; } } // Keep in sync with .data-grid col.corner style rule. export const CornerWidth = 14; /** @enum {symbol} */ export const Events = { SelectedNode: Symbol('SelectedNode'), DeselectedNode: Symbol('DeselectedNode'), OpenedNode: Symbol('OpenedNode'), SortingChanged: Symbol('SortingChanged'), PaddingChanged: Symbol('PaddingChanged'), }; /** @enum {string} */ export const Order = { Ascending: 'sort-ascending', Descending: 'sort-descending' }; /** @enum {string} */ export const Align = { Center: 'center', Right: 'right' }; /** @enum {symbol} */ export const DataType = { String: Symbol('String'), Boolean: Symbol('Boolean'), }; export const ColumnResizePadding = 24; export const CenterResizerOverBorderAdjustment = 3; /** @enum {string} */ export const ResizeMethod = { Nearest: 'nearest', First: 'first', Last: 'last' }; /** * @unrestricted * @template NODE_TYPE */ export class DataGridNode extends Common.ObjectWrapper.ObjectWrapper { /** * @param {?Object.<string, *>=} data * @param {boolean=} hasChildren */ constructor(data, hasChildren) { super(); /** @type {?Element} */ this._element = null; /** @protected @type {boolean} @suppress {accessControls} */ this._expanded = false; /** @type {boolean} */ this._selected = false; /** @type {boolean} */ this._dirty = false; /** @type {boolean} */ this._inactive = false; /** @type {string} */ this.key; /** @type {number|undefined} */ this._depth; /** @type {boolean|undefined} */ this._revealed; /** @type {boolean} */ this._attached = false; /** @type {?{parent: !NODE_TYPE, index: number}} */ this._savedPosition = null; /** @type {boolean} */ this._shouldRefreshChildren = true; /** @type {!Object.<string, *>} */ this._data = data || {}; /** @type {boolean} */ this._hasChildren = hasChildren || false; /** @type {!Array.<!NODE_TYPE>} */ this.children = []; /** @type {?DataGridImpl} */ this.dataGrid = null; /** @type {?NODE_TYPE} */ this.parent = null; /** @type {?NODE_TYPE} */ this.previousSibling = null; /** @type {?NODE_TYPE} */ this.nextSibling = null; /** @type {number} */ this.disclosureToggleWidth = 10; /** @type {boolean} */ this.selectable = true; /** @type {boolean} */ this._isRoot = false; /** @type {string} */ this.nodeAccessibleText = ''; /** @type {!Map<string, string>}} */ this.cellAccessibleTextMap = new Map(); } /** * @return {!Element} */ element() { if (!this._element) { const element = this.createElement(); this.createCells(element); } return /** @type {!Element} */ (this._element); } /** * @protected * @return {!Element} */ createElement() { this._element = document.createElement('tr'); this._element.classList.add('data-grid-data-grid-node'); this._element._dataGridNode = this; if (this._hasChildren) { this._element.classList.add('parent'); } if (this.expanded) { this._element.classList.add('expanded'); } if (this.selected) { this._element.classList.add('selected'); } if (this.revealed) { this._element.classList.add('revealed'); } if (this.dirty) { this._element.classList.add('dirty'); } if (this.inactive) { this._element.classList.add('inactive'); } return this._element; } /** * @return {?Element} */ existingElement() { return this._element || null; } /** * @protected */ resetElement() { this._element = null; } /** * @param {!Element} element * @protected */ createCells(element) { element.removeChildren(); const columnsArray = this.dataGrid.visibleColumnsArray; const accessibleTextArray = []; // Add depth if node is part of a tree if (this._hasChildren || !this.parent._isRoot) { accessibleTextArray.push(ls`level ${this.depth + 1}`); } for (let i = 0; i < columnsArray.length; ++i) { const column = columnsArray[i]; const cell = element.appendChild(this.createCell(column.id)); // Add each visibile cell to the node's accessible text by gathering 'Column Title: content' const localizedTitle = ls`${column.title}`; accessibleTextArray.push(`${localizedTitle}: ${this.cellAccessibleTextMap.get(column.id) || cell.textContent}`); } this.nodeAccessibleText = accessibleTextArray.join(', '); element.appendChild(this._createTDWithClass('corner')); } /** * @return {!Object.<string, *>} */ get data() { return this._data; } /** * @param {!Object.<string, *>} x */ set data(x) { this._data = x || {}; this.refresh(); } /** * @return {boolean} */ get revealed() { if (this._revealed !== undefined) { return this._revealed; } let currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { if (!currentAncestor.expanded) { this._revealed = false; return false; } currentAncestor = currentAncestor.parent; } this.revealed = true; return true; } /** * @param {boolean} x */ set revealed(x) { if (this._revealed === x) { return; } this._revealed = x; if (this._element) { this._element.classList.toggle('revealed', this._revealed); } for (let i = 0; i < this.children.length; ++i) { this.children[i].revealed = x && this.expanded; } } /** * @return {boolean} */ isDirty() { return this._dirty; } /** * @param {boolean} dirty */ setDirty(dirty) { if (this._dirty === dirty) { return; } this._dirty = dirty; if (!this._element) { return; } if (dirty) { this._element.classList.add('dirty'); } else { this._element.classList.remove('dirty'); } } /** * @return {boolean} */ isInactive() { return this._inactive; } /** * @param {boolean} inactive */ setInactive(inactive) { if (this._inactive === inactive) { return; } this._inactive = inactive; if (!this._element) { return; } if (inactive) { this._element.classList.add('inactive'); } else { this._element.classList.remove('inactive'); } } /** * @return {boolean} */ hasChildren() { return this._hasChildren; } /** * @param {boolean} x */ setHasChildren(x) { if (this._hasChildren === x) { return; } this._hasChildren = x; if (!this._element) { return; } this._element.classList.toggle('parent', this._hasChildren); this._element.classList.toggle('expanded', this._hasChildren && this.expanded); } /** * @return {number} */ get depth() { if (this._depth !== undefined) { return this._depth; } if (this.parent && !this.parent._isRoot) { this._depth = this.parent.depth + 1; } else { this._depth = 0; } return this._depth; } /** * @return {number} */ get leftPadding() { return this.depth * this.dataGrid.indentWidth; } /** * @return {boolean} */ get shouldRefreshChildren() { return this._shouldRefreshChildren; } /** * @param {boolean} x */ set shouldRefreshChildren(x) { this._shouldRefreshChildren = x; if (x && this.expanded) { this.expand(); } } /** * @return {boolean} */ get selected() { return this._selected; } /** * @param {boolean} x */ set selected(x) { if (x) { this.select(); } else { this.deselect(); } } /** * @return {boolean} */ get expanded() { return this._expanded; } /** * @param {boolean} x */ set expanded(x) { if (x) { this.expand(); } else { this.collapse(); } } refresh() { if (!this.dataGrid) { this._element = null; } if (!this._element) { return; } this.createCells(this._element); } /** * @param {string} className * @return {!Element} */ _createTDWithClass(className) { const cell = document.createElement('td'); if (className) { cell.className = className; } const cellClass = this.dataGrid._cellClass; if (cellClass) { cell.classList.add(cellClass); } return cell; } /** * @param {string} columnId * @return {!Element} */ createTD(columnId) { const cell = this._createTDWithClass(columnId + '-column'); cell[DataGrid._columnIdSymbol] = columnId; const alignment = this.dataGrid._columns[columnId].align; if (alignment) { cell.classList.add(alignment); } if (columnId === this.dataGrid.disclosureColumnId) { cell.classList.add('disclosure'); if (this.leftPadding) { cell.style.setProperty('padding-left', this.leftPadding + 'px'); } } return cell; } /** * @param {string} columnId * @return {!Element} */ createCell(columnId) { const cell = this.createTD(columnId); const data = this.data[columnId]; if (data instanceof Node) { cell.appendChild(data); } else if (data !== null) { this.dataGrid.setElementContent(cell, /** @type {string} */ (data)); } return cell; } /** * @param {string} name * @param {!Element} cell * @param {string} columnId */ setCellAccessibleName(name, cell, columnId) { this.cellAccessibleTextMap.set(columnId, name); // Mark all direct children of cell as hidden so cell name is properly announced for (let i = 0; i < cell.children.length; i++) { UI.ARIAUtils.markAsHidden(cell.children[i]); } UI.ARIAUtils.setAccessibleName(cell, name); } /** * @return {number} */ nodeSelfHeight() { return 20; } /** * @param {!NODE_TYPE} child */ appendChild(child) { this.insertChild(child, this.children.length); } /** * @param {boolean=} onlyCaches */ resetNode(onlyCaches) { // @TODO(allada) This is a hack to make sure ViewportDataGrid can clean up these caches. Try Not To Use. delete this._depth; delete this._revealed; if (onlyCaches) { return; } if (this.previousSibling) { this.previousSibling.nextSibling = this.nextSibling; } if (this.nextSibling) { this.nextSibling.previousSibling = this.previousSibling; } this.dataGrid = null; this.parent = null; this.nextSibling = null; this.previousSibling = null; this._attached = false; } /** * @param {!NODE_TYPE} child * @param {number} index */ insertChild(child, index) { if (!child) { throw 'insertChild: Node can\'t be undefined or null.'; } if (child.parent === this) { const currentIndex = this.children.indexOf(child); if (currentIndex < 0) { console.assert(false, 'Inconsistent DataGrid state'); } if (currentIndex === index) { return; } if (currentIndex < index) { --index; } } child.remove(); this.children.splice(index, 0, child); this.setHasChildren(true); child.parent = this; child.dataGrid = this.dataGrid; child.recalculateSiblings(index); child._shouldRefreshChildren = true; let current = child.children[0]; while (current) { current.resetNode(true); current.dataGrid = this.dataGrid; current._attached = false; current._shouldRefreshChildren = true; current = current.traverseNextNode(false, child, true); } if (this.expanded) { child._attach(); } if (!this.revealed) { child.revealed = false; } } remove() { if (this.parent) { this.parent.removeChild(this); } } /** * @param {!NODE_TYPE} child */ removeChild(child) { if (!child) { throw 'removeChild: Node can\'t be undefined or null.'; } if (child.parent !== this) { throw 'removeChild: Node is not a child of this node.'; } if (this.dataGrid) { this.dataGrid.updateSelectionBeforeRemoval(child, false); } child._detach(); child.resetNode(); Platform.ArrayUtilities.removeElement(this.children, child, true); if (this.children.length <= 0) { this.setHasChildren(false); } } removeChildren() { if (this.dataGrid) { this.dataGrid.updateSelectionBeforeRemoval(this, true); } for (let i = 0; i < this.children.length; ++i) { const child = this.children[i]; child._detach(); child.resetNode(); } this.children = []; this.setHasChildren(false); } /** * @param {number} myIndex */ recalculateSiblings(myIndex) { if (!this.parent) { return; } const previousChild = this.parent.children[myIndex - 1] || null; if (previousChild) { previousChild.nextSibling = this; } this.previousSibling = previousChild; const nextChild = this.parent.children[myIndex + 1] || null; if (nextChild) { nextChild.previousSibling = this; } this.nextSibling = nextChild; } collapse() { if (this._isRoot) { return; } if (this._element) { this._element.classList.remove('expanded'); } this._expanded = false; if (this.selected) { this.dataGrid.updateGridAccessibleName(/* text */ ls`collapsed`); } for (let i = 0; i < this.children.length; ++i) { this.children[i].revealed = false; } } collapseRecursively() { let item = this; while (item) { if (item.expanded) { item.collapse(); } item = item.traverseNextNode(false, this, true); } } populate() { } expand() { if (!this._hasChildren || this.expanded) { return; } if (this._isRoot) { return; } if (this.revealed && !this._shouldRefreshChildren) { for (let i = 0; i < this.children.length; ++i) { this.children[i].revealed = true; } } if (this._shouldRefreshChildren) { for (let i = 0; i < this.children.length; ++i) { this.children[i]._detach(); } this.populate(); if (this._attached) { for (let i = 0; i < this.children.length; ++i) { const child = this.children[i]; if (this.revealed) { child.revealed = true; } child._attach(); } } this._shouldRefreshChildren = false; } if (this._element) { this._element.classList.add('expanded'); } if (this.selected) { this.dataGrid.updateGridAccessibleName(/* text */ ls`expanded`); } this._expanded = true; } expandRecursively() { let item = this; while (item) { item.expand(); item = item.traverseNextNode(false, this); } } reveal() { if (this._isRoot) { return; } let currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { if (!currentAncestor.expanded) { currentAncestor.expand(); } currentAncestor = currentAncestor.parent; } this.element().scrollIntoViewIfNeeded(false); } /** * @param {boolean=} supressSelectedEvent */ select(supressSelectedEvent) { if (!this.dataGrid || !this.selectable || this.selected) { return; } if (this.dataGrid.selectedNode) { this.dataGrid.selectedNode.deselect(); } this._selected = true; this.dataGrid.selectedNode = this; if (this._element) { this._element.classList.add('selected'); this.dataGrid.setHasSelection(true); this.dataGrid.updateGridAccessibleName(); } if (!supressSelectedEvent) { this.dataGrid.dispatchEventToListeners(Events.SelectedNode, this); } } revealAndSelect() { if (this._isRoot) { return; } this.reveal(); this.select(); } /** * @param {boolean=} supressDeselectedEvent */ deselect(supressDeselectedEvent) { if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected) { return; } this._selected = false; this.dataGrid.selectedNode = null; if (this._element) { this._element.classList.remove('selected'); this.dataGrid.setHasSelection(false); this.dataGrid.updateGridAccessibleName(''); } if (!supressDeselectedEvent) { this.dataGrid.dispatchEventToListeners(Events.DeselectedNode); } } /** * @param {boolean} skipHidden * @param {?NODE_TYPE=} stayWithin * @param {boolean=} dontPopulate * @param {!Object=} info * @return {?NODE_TYPE} */ traverseNextNode(skipHidden, stayWithin, dontPopulate, info) { if (!dontPopulate && this._hasChildren) { this.populate(); } if (info) { info.depthChange = 0; } let node = (!skipHidden || this.revealed) ? this.children[0] : null; if (node && (!skipHidden || this.expanded)) { if (info) { info.depthChange = 1; } return node; } if (this === stayWithin) { return null; } node = (!skipHidden || this.revealed) ? this.nextSibling : null; if (node) { return node; } node = this; while (node && !node._isRoot && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) { if (info) { info.depthChange -= 1; } node = node.parent; } if (!node) { return null; } return (!skipHidden || node.revealed) ? node.nextSibling : null; } /** * @param {boolean} skipHidden * @param {boolean=} dontPopulate * @return {?NODE_TYPE} */ traversePreviousNode(skipHidden, dontPopulate) { let node = (!skipHidden || this.revealed) ? this.previousSibling : null; if (!dontPopulate && node && node._hasChildren) { node.populate(); } while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null)) { if (!dontPopulate && node._hasChildren) { node.populate(); } node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null); } if (node) { return node; } if (!this.parent || this.parent._isRoot) { return null; } return this.parent; } /** * @param {!Event} event * @return {boolean} */ isEventWithinDisclosureTriangle(event) { if (!this._hasChildren) { return false; } const cell = event.target.enclosingNodeOrSelfWithNodeName('td'); if (!cell || !cell.classList.contains('disclosure')) { return false; } const left = cell.totalOffsetLeft() + this.leftPadding; return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth; } _attach() { if (!this.dataGrid || this._attached) { return; } this._attached = true; const previousNode = this.traversePreviousNode(true, true); const previousElement = previousNode ? previousNode.element() : this.dataGrid._topFillerRow; this.dataGrid.dataTableBody.insertBefore(this.element(), previousElement.nextSibling); if (this.expanded) { for (let i = 0; i < this.children.length; ++i) { this.children[i]._attach(); } } } _detach() { if (!this._attached) { return; } this._attached = false; if (this._element) { this._element.remove(); } for (let i = 0; i < this.children.length; ++i) { this.children[i]._detach(); } } savePosition() { if (this._savedPosition) { return; } if (!this.parent) { throw 'savePosition: Node must have a parent.'; } this._savedPosition = {parent: this.parent, index: this.parent.children.indexOf(this)}; } restorePosition() { if (!this._savedPosition) { return; } if (this.parent !== this._savedPosition.parent) { this._savedPosition.parent.insertChild(this, this._savedPosition.index); } this._savedPosition = null; } } /** * @unrestricted * @extends {DataGridNode<!NODE_TYPE>} * @template NODE_TYPE */ export class CreationDataGridNode extends DataGridNode { constructor(data, hasChildren) { super(data, hasChildren); /** @type {boolean} */ this.isCreationNode = true; } makeNormal() { this.isCreationNode = false; } } /** * @unrestricted */ export class DataGridWidget extends UI.Widget.VBox { /** * @param {!DataGridImpl} dataGrid */ constructor(dataGrid) { super(); this._dataGrid = dataGrid; this.element.appendChild(dataGrid.element); this.setDefaultFocusedElement(dataGrid.element); } /** * @override */ wasShown() { this._dataGrid.wasShown(); } /** * @override */ willHide() { this._dataGrid.willHide(); } /** * @override */ onResize() { this._dataGrid.onResize(); } /** * @override * @return {!Array.<!Element>} */ elementsToRestoreScrollPositionsFor() { return [this._dataGrid._scrollContainer]; } /** * @override */ detachChildWidgets() { super.detachChildWidgets(); for (const dataGrid of this._dataGrids) { this.element.removeChild(dataGrid.element); } this._dataGrids = []; } } /** * @typedef {{ * displayName: string, * columns: !Array.<!ColumnDescriptor>, * editCallback: (function(!Object, string, *, *)|undefined), * deleteCallback: (function(!Object)|undefined|function(string)), * refreshCallback: (function()|undefined) * }} */ export let Parameters; /** * @typedef {{ * id: string, * title: (string|undefined), * titleDOMFragment: (?DocumentFragment|undefined), * sortable: boolean, * sort: (?Order|undefined), * align: (?Align|undefined), * fixedWidth: (boolean|undefined), * editable: (boolean|undefined), * nonSelectable: (boolean|undefined), * longText: (boolean|undefined), * disclosure: (boolean|undefined), * weight: (number|undefined), * allowInSortByEvenWhenHidden: (boolean|undefined), * dataType: (?DataType|undefined) * }} */ export let ColumnDescriptor;
const mongoose = require('mongoose'); mongoose.Promise = global.Promise; async function connect(url) { mongoose.set('useCreateIndex', true); await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }); console.log('[db] succesfully connected'); } module.exports = connect;
/** * Intersect a set of points against the user's locally stored points. * * v1 - Unencrypted, simpleminded (minimal optimization). */ import dayjs from 'dayjs'; import duration from 'dayjs/plugin/duration'; import { NativeModules } from 'react-native'; import PushNotification from 'react-native-push-notification'; import { isPlatformiOS } from './../Util'; import { CONCERN_TIME_WINDOW_MINUTES, DEFAULT_EXPOSURE_PERIOD_MINUTES, MAX_EXPOSURE_WINDOW_DAYS, MIN_CHECK_INTERSECT_INTERVAL, } from '../constants/history'; import { AUTHORITY_NEWS, AUTHORITY_SOURCE_SETTINGS, CROSSED_PATHS, LAST_CHECKED, } from '../constants/storage'; import { DEBUG_MODE } from '../constants/storage'; import { GetStoreData, SetStoreData } from '../helpers/General'; import languages from '../locales/languages'; /** * Intersects the locationArray with the concernLocationArray, returning the results * as a dayBin array. * * @param {array} localArray - array of the local locations. Assumed to have been sorted and normalized * @param {array} concernArray - superset array of all concerning points from health authorities. Assumed to have been sorted and normalized * @param {int} numDayBins - (optional) number of bins in the array returned * @param {int} concernTimeWindowMS - (optional) window of time to use when determining an exposure * @param {int} defaultExposurePeriodMS - (optional) the default exposure period to use when necessary when an exposure is found */ export function intersectSetIntoBins( localArray, concernArray, numDayBins = MAX_EXPOSURE_WINDOW_DAYS, concernTimeWindowMS = 1000 * 60 * CONCERN_TIME_WINDOW_MINUTES, defaultExposurePeriodMS = DEFAULT_EXPOSURE_PERIOD_MINUTES * 60 * 1000, ) { // useful for time calcs dayjs.extend(duration); // generate an array with the asked for number of day bins const dayBins = getEmptyLocationBins(numDayBins); //for (let loc of localArray) { for (let i = 0; i < localArray.length; i++) { let currentLocation = localArray[i]; // The current day is 0 days ago (in otherwords, bin 0). // Figure out how many days ago the current location was. // Note that we're basing this off midnight in the user's current timezone. // Also using the dayjs subtract method, which should take timezone and // daylight savings into account. let midnight = dayjs().startOf('day'); let daysAgo = 0; while (currentLocation.time < midnight.valueOf() && daysAgo < numDayBins) { midnight = midnight.subtract(1, 'day'); daysAgo++; } // if this location's date is earlier than the number of days to bin, we can skip it if (daysAgo >= numDayBins) continue; // Check to see if this is the first exposure for this bin. If so, reset the exposure time to 0 // to indicate that we do actually have some data for this day if (dayBins[daysAgo] < 0) dayBins[daysAgo] = 0; // timeMin and timeMax set from the concern time window // These define the window of time that is considered an intersection of concern. // The idea is that if this location (lat,lon) is in the concernLocationArray from // the time starting from this location's recorded minus the concernTimeWindow time up // to this locations recorded time, then it is a location of concern. let timeMin = currentLocation.time - concernTimeWindowMS; let timeMax = currentLocation.time; // now find the index in the concernArray that starts with timeMin (if one exists) // // TODO: There's probably an optimization that could be done if the locationArray // increased in time only a small amount, since the index we found // in the concernArray is probably already close to where we want to be. let j = binarySearchForTime(concernArray, timeMin); // we don't really if the exact timestamp wasn't found, so just take the j value as the index to start if (j < 0) j = -(j + 1); // starting at the now known index that corresponds to the beginning of the // location time window, go through all of the concernArray's time-locations // to see if there are actually any intersections of concern. Stop when // we get past the timewindow. while (j < concernArray.length && concernArray[j].time <= timeMax) { if ( areLocationsNearby( concernArray[j].latitude, concernArray[j].longitude, currentLocation.latitude, currentLocation.longitude, ) ) { // Crossed path. Add the exposure time to the appropriate day bin. // How long was the possible concern time? // = the amount of time from the current locations time to the next location time // or = if that calculated time is not possible or too large, use the defaultExposurePeriodMS let exposurePeriod = defaultExposurePeriodMS; if (i < localArray.length - 1) { let timeWindow = localArray[i + 1].time - currentLocation.time; if (timeWindow < defaultExposurePeriodMS * 2) { // not over 2x the default, so should be OK exposurePeriod = timeWindow; } } // now add the exposure period to the bin dayBins[daysAgo] += exposurePeriod; // Since we've counted the current location time period, we can now break the loop for // this time period and go on to the next location break; } j++; } } return dayBins; } /** * Function to determine if two location points are "nearby". * Uses shortcuts when possible, then the exact calculation. * * @param {number} lat1 - location 1 latitude * @param {number} lon1 - location 1 longitude * @param {number} lat2 - location 2 latitude * @param {number} lon2 - location 2 longitude * @return {boolean} true if the two locations meet the criteria for nearby */ export function areLocationsNearby(lat1, lon1, lat2, lon2) { let nearbyDistance = 20; // in meters, anything closer is "nearby" // these numbers from https://en.wikipedia.org/wiki/Decimal_degrees let notNearbyInLatitude = 0.00017966; // = nearbyDistance / 111320 let notNearbyInLongitude_23Lat = 0.00019518; // = nearbyDistance / 102470 let notNearbyInLongitude_45Lat = 0.0002541; // = nearbyDistance / 78710 let notNearbyInLongitude_67Lat = 0.00045981; // = nearbyDistance / 43496 let deltaLon = lon2 - lon1; // Initial checks we can do quickly. The idea is to filter out any cases where the // difference in latitude or the difference in longitude must be larger than the // nearby distance, since this can be calculated trivially. if (Math.abs(lat2 - lat1) > notNearbyInLatitude) return false; if (Math.abs(lat1) < 23) { if (Math.abs(deltaLon) > notNearbyInLongitude_23Lat) return false; } else if (Math.abs(lat1) < 45) { if (Math.abs(deltaLon) > notNearbyInLongitude_45Lat) return false; } else if (Math.abs(lat1) < 67) { if (Math.abs(deltaLon) > notNearbyInLongitude_67Lat) return false; } // Close enough to do a detailed calculation. Using the the Spherical Law of Cosines method. // https://www.movable-type.co.uk/scripts/latlong.html // https://en.wikipedia.org/wiki/Spherical_law_of_cosines // // Calculates the distance in meters let p1 = (lat1 * Math.PI) / 180; let p2 = (lat2 * Math.PI) / 180; let deltaLambda = (deltaLon * Math.PI) / 180; let R = 6371e3; // gives d in metres let d = Math.acos( Math.sin(p1) * Math.sin(p2) + Math.cos(p1) * Math.cos(p2) * Math.cos(deltaLambda), ) * R; // closer than the "nearby" distance? if (d < nearbyDistance) return true; // nope return false; } /** * Performs "safety" cleanup of the data, to help ensure that we actually have location * data in the array. Also fixes cases with extra info or values coming in as strings. * * @param {array} arr - array of locations in JSON format */ export function normalizeAndSortLocations(arr) { // This fixes several issues that I found in different input data: // * Values stored as strings instead of numbers // * Extra info in the input // * Improperly sorted data (can happen after an Import) let result = []; if (arr) { for (let i = 0; i < arr.length; i++) { let elem = arr[i]; if ('time' in elem && 'latitude' in elem && 'longitude' in elem) { result.push({ time: Number(elem.time), latitude: Number(elem.latitude), longitude: Number(elem.longitude), }); } } result.sort((a, b) => a.time - b.time); } return result; } // Basic binary search. Assumes a sorted array. function binarySearchForTime(array, targetTime) { // Binary search: // array = sorted array // target = search target // Returns: // value >= 0, index of found item // value < 0, i where -(i+1) is the insertion point let i = 0; let n = array.length - 1; while (i <= n) { let k = (n + i) >> 1; let cmp = targetTime - array[k].time; if (cmp > 0) { i = k + 1; } else if (cmp < 0) { n = k - 1; } else { // Found exact match! // NOTE: Could be one of several if array has duplicates return k; } } return -i - 1; } /** * Kicks off the intersection process. Immediately returns after starting the * background intersection. Typically would be run about every 12 hours, but * but might get run more frequently, e.g. when the user changes authority settings * * TODO: This call kicks off the intersection, as well as getting basic info * from the authority (e.g. the news url) since we get that in the same call. * Ideally those should probably be broken up better, but for now leaving it alone. */ export function checkIntersect() { console.log( 'Intersect tick entering on', isPlatformiOS() ? 'iOS' : 'Android', ); asyncCheckIntersect().then(result => { if (result === null) { console.log('[intersect] skipped'); } else { console.log('[intersect] completed: ', result); } }); } /** * Async run of the intersection. Also saves off the news sources that the authories specified, * since that comes from the authorities in the same download. * * Returns the array of day bins (mostly for debugging purposes) */ async function asyncCheckIntersect() { // first things first ... is it time to actually try the intersection? let lastCheckedMs = Number(await GetStoreData(LAST_CHECKED)); if ( lastCheckedMs + MIN_CHECK_INTERSECT_INTERVAL * 60 * 1000 > dayjs().valueOf() ) return null; // Set up the empty set of dayBins for intersections, and the array for the news urls let dayBins = getEmptyLocationBins(); let name_news = []; // get the saved set of locations for the user, already sorted let locationArray = await NativeModules.SecureStorageManager.getLocations(); // get the health authorities let authority_list = await GetStoreData(AUTHORITY_SOURCE_SETTINGS); if (authority_list) { // Parse the registered health authorities authority_list = JSON.parse(authority_list); for (const authority of authority_list) { try { let responseJson = await retrieveUrlAsJson(authority.url); // Update the news array with the info from the authority name_news.push({ name: responseJson.authority_name, news_url: responseJson.info_website, }); // intersect the users location with the locations from the authority let tempDayBin = intersectSetIntoBins( locationArray, normalizeAndSortLocations(responseJson.concern_points), ); // Update each day's bin with the result from the intersection. To keep the // difference between no data (==-1) and exposure data (>=0), there // are a total of 3 cases to consider. dayBins = dayBins.map((currentValue, i) => { if (currentValue < 0) return tempDayBin[i]; if (tempDayBin[i] < 0) return currentValue; return currentValue + tempDayBin[i]; }); } catch (error) { // TODO: We silently fail. Could be a JSON parsing issue, could be a network issue, etc. // Should do better than this. console.log('[authority] fetch/parse error :', error); } } } // Store the news arary for the authorities found. SetStoreData(AUTHORITY_NEWS, name_news); // if any of the bins are > 0, tell the user if (dayBins.some(a => a > 0)) notifyUserOfRisk(); // store the results SetStoreData(CROSSED_PATHS, dayBins); // TODO: Store per authority? // save off the current time as the last checked time let unixtimeUTC = dayjs().valueOf(); SetStoreData(LAST_CHECKED, unixtimeUTC); return dayBins; } export function getEmptyLocationBins( exposureWindowDays = MAX_EXPOSURE_WINDOW_DAYS, ) { return new Array(exposureWindowDays).fill(-1); } /** * Notify the user that they are possibly at risk */ function notifyUserOfRisk() { PushNotification.localNotification({ title: languages.t('label.push_at_risk_title'), message: languages.t('label.push_at_risk_message'), }); } /** * Return Json retrieved from a URL * * @param {*} url */ async function retrieveUrlAsJson(url) { let response = await fetch(url); let responseJson = await response.json(); return responseJson; } /** Set the app into debug mode */ export function enableDebugMode() { SetStoreData(DEBUG_MODE, 'true'); // Create faux intersection data let pseudoBin = []; for (let i = 0; i < MAX_EXPOSURE_WINDOW_DAYS; i++) { let intersections = Math.max(0, Math.floor(Math.random() * 50 - 20)) * 60 * 1000; // in millis if (intersections == 0 && Math.random() < 0.3) intersections = -1; // about 30% of negative will be set as no data pseudoBin.push(intersections); } let dayBin = JSON.stringify(pseudoBin); console.log(dayBin); SetStoreData(CROSSED_PATHS, dayBin); } /** Restore the app from debug mode */ export function disableDebugMode() { // Wipe faux intersection data let pseudoBin = []; for (let i = 0; i < MAX_EXPOSURE_WINDOW_DAYS; i++) { pseudoBin.push(0); } let dayBin = JSON.stringify(pseudoBin); SetStoreData(CROSSED_PATHS, dayBin); SetStoreData(DEBUG_MODE, 'false'); // Kick off intersection calculations to restore data checkIntersect(); }
var title = "Manor Mystery"; var desc = "Something is not quite right at the Manor on <a href=\"event:location|75#LHV36AG0LO2208L\">Hauki Seeks<\/a>."; var offer = "Have you heard of Hauki Seeks Manor? That place has always been kind of creepy, but lately it seems some really strange things have been occurring. I won't blame you if you don't want to check it out, but that person you're trying to impress might think you're pretty brave if you do."; var completion = "Hey! you found my note! I lost it somewhere in this Manor and have been scaring people from coming in here in case someone picked it up before I could."; var button_accept = "I'm brave!"; var auto_complete = 0; var familiar_turnin = 0; var is_tracked = 0; var show_alert = 0; var silent_complete = 0; var progress = [ ]; var giver_progress = [ ]; var no_progress = "null"; var prereq_quests = []; var prerequisites = []; var end_npcs = ["npc_juju_black"]; var locations = {}; var requirements = { "r468" : { "type" : "flag", "name" : "quest_manor_mystery_done", "class_id" : "note", "desc" : "Brave the Manor" } }; function onComplete(pc){ // generated from rewards var xp=0; var currants=0; var mood=0; var energy=0; var favor=0; var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_quest_modifier(); xp = pc.stats_add_xp(round_to_5(10 * multiplier), true, {type: 'quest_complete', quest: this.class_tsid}); apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } this.onComplete_custom(pc); } var rewards = { "xp" : 10 }; function doProvided(pc){ // generated from provided pc.createItemFromFamiliar('note_manor_mystery', 1); } function onAccepted(pc){ pc.mmquest_flag1=true; pc.mmquest_flag2=false; pc.mmquest_flag3=false; pc.mmquest_flag4=false; pc.mmquest_flag5=false; pc.mmquest_flag6=false; pc.mmquest_flag7=false; } function onComplete_custom(pc){ delete pc.mmquest_flag1; delete pc.mmquest_flag2; delete pc.mmquest_flag3; delete pc.mmquest_flag4; delete pc.mmquest_flag5; delete pc.mmquest_flag6; delete pc.mmquest_flag7; delete pc.quest_manor_mystery_done; } //log.info("manor_mystery.js LOADED"); // generated ok (NO DATE)
from django.contrib import admin from .models import Post, Group class PostAdmin(admin.ModelAdmin): list_display = ("pk", "text", "pub_date", "author") search_fields = ("text",) list_filter = ("pub_date",) empty_value_display = '-пусто-' class GroupAdmin(admin.ModelAdmin): list_display = ("title", "slug", "description") search_fields = ("text",) admin.site.register(Post, PostAdmin) admin.site.register(Group, GroupAdmin)
import React from "react" export default () => ( <div style={{ color: `gray` }}> <div style={{backgroundColor: 'red', width:"500px", margin: "auto"}}>About Gatsby is very very wonderful indonesia</div> <p style={{display: `hidden`}}>Such wow. Very React.</p> <p>Next</p> </div> )
import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import App from '../shared/App'; const Root = () => ( <BrowserRouter> <App /> </BrowserRouter> ); export default Root;
var language_index = 1; var navbar_menu_active = false; var classes_to_hide = new Set(); window.onload = function () { switchLanguage(); hide_class("mh-ride-cond"); hide_class("mh-invalid-meat"); hide_class("mh-invalid-part"); hide_class("mh-no-preset"); } function refresh_visibility(c) { for (element of document.getElementsByClassName(c)) { matched = false; for (let c of classes_to_hide) { if (element.classList.contains(c)) { matched = true; break; } } if (matched) { element.classList.add("mh-hidden"); } else { element.classList.remove("mh-hidden"); } } } function hide_class(c) { classes_to_hide.add(c); refresh_visibility(c); } function show_class(c) { classes_to_hide.delete(c); refresh_visibility(c); } function selectLanguage(language) { language_index = language; switchLanguage(); } function switchLanguage() { for (var i = 0; i < 32; ++i) { var c = "mh-lang-" + i; if (i === language_index) { show_class(c); } else { hide_class(c); } var c = "mh-lang-menu-" + i; for (element of document.getElementsByClassName(c)) { if (i === language_index) { element.classList.add("has-text-weight-bold"); } else { element.classList.remove("has-text-weight-bold"); } } } } function onCheckDisplay(checkbox, class_to_show, class_to_hide) { if (checkbox.checked) { show_class(class_to_show) if (class_to_hide != null) { hide_class(class_to_hide) } } else { hide_class(class_to_show) if (class_to_hide != null) { show_class(class_to_hide) } } } function onToggleNavbarMenu() { navbar_menu_active = !navbar_menu_active; if (navbar_menu_active) { document.getElementById("navbarBurger").classList.add("is-active"); document.getElementById("navbarMenu").classList.add("is-active"); } else { document.getElementById("navbarBurger").classList.remove("is-active"); document.getElementById("navbarMenu").classList.remove("is-active"); } }
require("dotenv").config({ path: `.env.${process.env.NODE_ENV}`, }) module.exports = { siteMetadata: { title: "Anablock", description: "We provide Salesforce consulting and system integration services.", author: "Anastasia Technology LLC", twitterUsername: "@VukDukic", image: "/favicon.png", siteUrl: "https://www.anablock.com" }, plugins: [ `gatsby-plugin-react-helmet`, `gatsby-plugin-sass`, `gatsby-plugin-styled-components`, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, `gatsby-plugin-transition-link`, `gatsby-plugin-playground`, `gatsby-plugin-sitemap`, 'gatsby-plugin-robots-txt', `gatsby-plugin-fontawesome-css`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images/`, ignore: [`**/\.*`], // ignore files starting with a dot } }, { resolve: `gatsby-source-filesystem`, options: { name: `careers`, path: `${__dirname}/src/careers/`, ignore: [`**/\.*`], // ignore files starting with a dot } }, { resolve: `gatsby-source-contentful`, options: { spaceId: process.env.CONTENTFUL_SPACE_ID, // Learn about environment variables: https://gatsby.dev/env-vars accessToken: process.env.CONTENTFUL_ACCESS_TOKEN, }, }, { resolve: 'gatsby-plugin-robots-txt', options: { host: 'https://www.anablock.com', sitemap: 'hhttps://www.anablock.com/sitemap.xml', policy: [{ userAgent: '*', allow: '/' }] } }, { resolve: `gatsby-plugin-manifest`, options: { name: `Anablock`, short_name: `Anablock`, start_url: `/`, background_color: `#f7f0eb`, theme_color: `#a2466c`, display: `standalone`, icon: `static/favicon.png`, }, }, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: "UA-148391227-1", }, }, { resolve: `gatsby-plugin-facebook-pixel`, options: { pixelId: '1726109470873000', }, }, { resolve: `gatsby-plugin-google-fonts`, options: { fonts: [ `limelight`, `source sans pro\:300,400,400i,700` // you can also specify font weights and styles ], display: 'swap' } }, ], }
/** * PageController * * @description :: Server-side logic for managing pages * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { showSignupPage: function (req, res) { if (req.session.userId) { return res.redirect('/'); } return res.view('signup', { me: null }); }, showRestorePage: function (req, res) { if (req.session.userId) { return res.redirect('/'); } return res.view('restore', { me: null }); }, showEditProfilePage: function (req, res) { if (!req.session.userId) { return res.redirect('/'); } User.findOne(req.session.userId, function (err, user){ if (err) { console.log('error: ', error); return res.negotiate(err); } if (!user) { sails.log.verbose('Session refers to a user who no longer exists- did you delete a user, then try to refresh the page with an open tab logged-in as that user?'); return res.view('homepage'); } return res.view('edit-profile', { me: { id: user.id, email: user.email, username: user.username, gravatarURL: user.gravatarURL, admin: user.admin } }); }); }, showProfilePage: function (req, res) { if (!req.session.userId) { return res.redirect('/'); } User.findOne(req.session.userId, function (err, user){ if (err) { console.log('error: ', error); return res.negotiate(err); } if (!user) { sails.log.verbose('Session refers to a user who no longer exists- did you delete a user, then try to refresh the page with an open tab logged-in as that user?'); return res.view('homepage'); } return res.view('profile', { me: { id: user.id, email: user.email, gravatarURL: user.gravatarURL, admin: user.admin } }); }); }, showAdminPage: function(req, res) { if (!req.session.userId) { return res.redirect('/'); } User.findOne(req.session.userId, function(err, user) { if (err) { return res.negotiate(err); } if (!user) { sails.log.verbose('Session refers to a user who no longer exists- did you delete a user, then try to refresh the page with an open tab logged-in as that user?'); return res.view('homepage'); } if (user.admin) { return res.view('adminUsers', { me: { id: user.id, email: user.email, username: user.username, gravatarURL: user.gravatarURL, admin: user.admin } }); } else { //E return res.view('homepage', { me: { id: user.id, email: user.email, username: user.username, gravatarURL: user.gravatarURL, admin: user.admin } }); } }); }, showHomePage: function(req, res) { console.log(); console.log('showHomePage'); console.log('================================================'); console.log('req.session.userId is:',req.session.userId); console.log('req.session is:',req.session); console.log('req.session.id is:',req.session.id); if (!req.session.userId) { return res.view('homepage', { me: null }); } User.findOne(req.session.userId, function(err, user) { if (err) { return res.negotiate(err); } if (!user) { sails.log.verbose('Session refers to a user who no longer exists- did you delete a user, then try to refresh the page with an open tab logged-in as that user?'); return res.view('homepage', { me: null }); } return res.view('homepage', { me: { id: user.id, email: user.email, gravatarURL: user.gravatarURL, admin: user.admin } }); }); }, showVideosPage: function(req, res) { console.log(); console.log('showVideosPage'); console.log('================================================'); console.log('req.session.userId is:',req.session.userId); console.log('req.session.someDictionary is:',req.session.someDictionary); console.log('req.session is:',req.session); console.log('req.session.id is:',req.session.id); if (!req.session.userId) { return res.view('videos', { me: null }); } User.findOne(req.session.userId, function(err, user) { if (err) { return res.negotiate(err); } if (!user) { sails.log.verbose('Session refers to a user who no longer exists- did you delete a user, then try to refresh the page with an open tab logged-in as that user?'); return res.view('videos', { me: null }); } return res.view('videos', { me: { id: user.id, email: user.email, gravatarURL: user.gravatarURL, admin: user.admin } }); }); } };
# -*- coding: utf-8 -*- class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: if not graph: return True colors = [0] * len(graph) def dfs(node, parent_color): # 判断从当前节点出发是可构成二分图 if colors[node] != 0: return colors[node] != parent_color colors[node] = 1 if parent_color == 2 else 2 for j in range(len(graph[node])): if not dfs(graph[node][j], colors[node]): return False return True for i in range(len(colors)): if colors[i] == 0: if not dfs(i, 1): return False return True
var GUI = (window["webpackJsonpGUI"] = window["webpackJsonpGUI"] || []).push([["gui"],{ /***/ "./node_modules/css-loader/index.js?!./node_modules/postcss-loader/src/index.js?!./src/playground/index.css": /*!*****************************************************************************************************************!*\ !*** ./node_modules/css-loader??ref--5-1!./node_modules/postcss-loader/src??postcss!./src/playground/index.css ***! \*****************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! ../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false); // imports // module exports.push([module.i, "html,\nbody,\n.index_app_3Qs6X {\n /* probably unecessary, transitional until layout is refactored */\n width: 100%; \n height: 100%;\n margin: 0;\n\n /* Setting min height/width makes the UI scroll below those sizes */\n min-width: 1024px;\n min-height: 640px; /* Min height to fit sprite/backdrop button */\n}\n\n/* @todo: move globally? Safe / side FX, for blocks particularly? */\n\n* { -webkit-box-sizing: border-box; box-sizing: border-box; }\n", ""]); // exports exports.locals = { "app": "index_app_3Qs6X" }; /***/ }), /***/ "./src/playground/index.css": /*!**********************************!*\ !*** ./src/playground/index.css ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var content = __webpack_require__(/*! !../../node_modules/css-loader??ref--5-1!../../node_modules/postcss-loader/src??postcss!./index.css */ "./node_modules/css-loader/index.js?!./node_modules/postcss-loader/src/index.js?!./src/playground/index.css"); if(typeof content === 'string') content = [[module.i, content, '']]; var transform; var insertInto; var options = {"hmr":true} options.transform = transform options.insertInto = undefined; var update = __webpack_require__(/*! ../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options); if(content.locals) module.exports = content.locals; if(false) {} /***/ }), /***/ "./src/playground/index.jsx": /*!**********************************!*\ !*** ./src/playground/index.jsx ***! \**********************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var es6_object_assign_auto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! es6-object-assign/auto */ "./node_modules/es6-object-assign/auto.js"); /* harmony import */ var es6_object_assign_auto__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(es6_object_assign_auto__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var core_js_fn_array_includes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! core-js/fn/array/includes */ "./node_modules/core-js/fn/array/includes.js"); /* harmony import */ var core_js_fn_array_includes__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(core_js_fn_array_includes__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var core_js_fn_promise_finally__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! core-js/fn/promise/finally */ "./node_modules/core-js/fn/promise/finally.js"); /* harmony import */ var core_js_fn_promise_finally__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(core_js_fn_promise_finally__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var intl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! intl */ "./node_modules/intl/index.js"); /* harmony import */ var intl__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(intl__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__); /* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); /* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_5__); /* harmony import */ var _lib_analytics__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../lib/analytics */ "./src/lib/analytics.js"); /* harmony import */ var _lib_app_state_hoc_jsx__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../lib/app-state-hoc.jsx */ "./src/lib/app-state-hoc.jsx"); /* harmony import */ var _components_browser_modal_browser_modal_jsx__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../components/browser-modal/browser-modal.jsx */ "./src/components/browser-modal/browser-modal.jsx"); /* harmony import */ var _lib_supported_browser__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../lib/supported-browser */ "./src/lib/supported-browser.js"); /* harmony import */ var _index_css__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./index.css */ "./src/playground/index.css"); /* harmony import */ var _index_css__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_index_css__WEBPACK_IMPORTED_MODULE_10__); // Polyfills // For Safari 9 // Register "base" page view _lib_analytics__WEBPACK_IMPORTED_MODULE_6__["default"].pageview('/'); var appTarget = document.createElement('div'); appTarget.className = _index_css__WEBPACK_IMPORTED_MODULE_10___default.a.app; document.body.appendChild(appTarget); if (Object(_lib_supported_browser__WEBPACK_IMPORTED_MODULE_9__["default"])()) { // require needed here to avoid importing unsupported browser-crashing code // at the top level __webpack_require__(/*! ./render-gui.jsx */ "./src/playground/render-gui.jsx").default(appTarget); } else { _components_browser_modal_browser_modal_jsx__WEBPACK_IMPORTED_MODULE_8__["default"].setAppElement(appTarget); var WrappedBrowserModalComponent = Object(_lib_app_state_hoc_jsx__WEBPACK_IMPORTED_MODULE_7__["default"])(_components_browser_modal_browser_modal_jsx__WEBPACK_IMPORTED_MODULE_8__["default"], true /* localesOnly */ ); var handleBack = function handleBack() {}; // eslint-disable-next-line react/jsx-no-bind react_dom__WEBPACK_IMPORTED_MODULE_5___default.a.render( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(WrappedBrowserModalComponent, { onBack: handleBack }), appTarget); } /***/ }), /***/ "./src/playground/render-gui.jsx": /*!***************************************!*\ !*** ./src/playground/render-gui.jsx ***! \***************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); /* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! redux */ "./node_modules/redux/es/index.js"); /* harmony import */ var _lib_app_state_hoc_jsx__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../lib/app-state-hoc.jsx */ "./src/lib/app-state-hoc.jsx"); /* harmony import */ var _containers_gui_jsx__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../containers/gui.jsx */ "./src/containers/gui.jsx"); /* harmony import */ var _lib_hash_parser_hoc_jsx__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../lib/hash-parser-hoc.jsx */ "./src/lib/hash-parser-hoc.jsx"); /* harmony import */ var _lib_log_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../lib/log.js */ "./src/lib/log.js"); function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var onClickLogo = function onClickLogo() { window.location = 'https://scratch.mit.edu'; }; var handleTelemetryModalCancel = function handleTelemetryModalCancel() { Object(_lib_log_js__WEBPACK_IMPORTED_MODULE_6__["default"])('User canceled telemetry modal'); }; var handleTelemetryModalOptIn = function handleTelemetryModalOptIn() { Object(_lib_log_js__WEBPACK_IMPORTED_MODULE_6__["default"])('User opted into telemetry'); }; var handleTelemetryModalOptOut = function handleTelemetryModalOptOut() { Object(_lib_log_js__WEBPACK_IMPORTED_MODULE_6__["default"])('User opted out of telemetry'); }; /* * Render the GUI playground. This is a separate function because importing anything * that instantiates the VM causes unsupported browsers to crash * {object} appTarget - the DOM element to render to */ /* harmony default export */ __webpack_exports__["default"] = (function (appTarget) { _containers_gui_jsx__WEBPACK_IMPORTED_MODULE_4__["default"].setAppElement(appTarget); // note that redux's 'compose' function is just being used as a general utility to make // the hierarchy of HOC constructor calls clearer here; it has nothing to do with redux's // ability to compose reducers. var WrappedGui = Object(redux__WEBPACK_IMPORTED_MODULE_2__["compose"])(_lib_app_state_hoc_jsx__WEBPACK_IMPORTED_MODULE_3__["default"], _lib_hash_parser_hoc_jsx__WEBPACK_IMPORTED_MODULE_5__["default"])(_containers_gui_jsx__WEBPACK_IMPORTED_MODULE_4__["default"]); // TODO a hack for testing the backpack, allow backpack host to be set by url param var backpackHostMatches = window.location.href.match(/[?&]backpack_host=([^&]*)&?/); var backpackHost = backpackHostMatches ? backpackHostMatches[1] : null; var scratchDesktopMatches = window.location.href.match(/[?&]isScratchDesktop=([^&]+)/); var simulateScratchDesktop; if (scratchDesktopMatches) { try { // parse 'true' into `true`, 'false' into `false`, etc. simulateScratchDesktop = JSON.parse(scratchDesktopMatches[1]); } catch (_unused) { // it's not JSON so just use the string // note that a typo like "falsy" will be treated as true simulateScratchDesktop = scratchDesktopMatches[1]; } } if (false) {} react_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render( // important: this is checking whether `simulateScratchDesktop` is truthy, not just defined! simulateScratchDesktop ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(WrappedGui, { canEditTitle: true, isScratchDesktop: true, showTelemetryModal: true, canSave: false, onTelemetryModalCancel: handleTelemetryModalCancel, onTelemetryModalOptIn: handleTelemetryModalOptIn, onTelemetryModalOptOut: handleTelemetryModalOptOut }) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(WrappedGui, { canEditTitle: true, backpackVisible: true, showComingSoon: true, backpackHost: backpackHost, canSave: false, onClickLogo: onClickLogo }), appTarget); }); /***/ }), /***/ 1: /*!*******************************************!*\ !*** ./locale-data/complete.js (ignored) ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports) { /* (ignored) */ /***/ }) },[["./src/playground/index.jsx","lib.min"]]]); //# sourceMappingURL=gui.js.map
/*! * Bootstrap-select v1.5.4 (http://silviomoreto.github.io/bootstrap-select/) * * Copyright 2013-2014 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Nic není vybráno', noneResultsText: 'Žádné výsledky', countSelectedText: 'Označeno {0} z {1}', maxOptionsText: ['Limit překročen ({n} {var} max)', 'Limit skupiny překročen ({n} {var} max)', ['položek', 'položka']], multipleSeparator: ', ' }; }(jQuery));
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup import json import os chromedriver = "/home/mars/Desktop/WebScrapingCoruse/scrapingWithSelenium/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver chrome_option = Options() chrome_option.add_argument("--start-maximized") driver = webdriver.Chrome(chromedriver, chrome_options=chrome_option) actions = ActionChains(driver) def save_object( file_name , saved_object , writing_method): saved_object = json.dumps(saved_object, indent=3 , ensure_ascii=False) with open(file_name, writing_method) as handler: handler.writelines(saved_object + ',') def main(): timeout = 30 i = 0 all_links = [] with open('car_links.json' , 'r') as file: car_links = json.load(file) while i <= 4 : for link in car_links[i]['links']: all_links.append(link) i += 1 for car in all_links: car_data = {} driver.get(car) try : show_phone_number_button = driver.find_element_by_css_selector('#phone-open') show_phone_number_button.click() WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, '//*[contains(concat( " ", @class, " " ), concat( " ", "addetail-single-phone-number", " " ))]'))) phone_number = driver.find_element_by_css_selector('.addetail-single-phone-number').text WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.XPATH, '//p[(((count(preceding-sibling::*) + 1) = 3) and parent::*)]'))) car_data = { 'announcement_time ' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 3) and parent::*)]').text , 'kilometer' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 4) and parent::*)]').text , 'gear_box_type' : driver.find_element_by_xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "inforight", " " ))]//p[(((count(preceding-sibling::*) + 1) = 5) and parent::*)]').text , 'fuel_type' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 6) and parent::*)]').text , 'body' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 7) and parent::*)]').text , 'color' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 8) and parent::*)]').text , 'state' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 9) and parent::*)]').text , 'city' : driver.find_element_by_xpath('//p[(((count(preceding-sibling::*) + 1) = 10) and parent::*)]').text , 'phone_number' : phone_number } save_object('data.json' , car_data , 'a') except: car_data = { 'announcement_time ' : None , 'kilometer' : None , 'gear_box_type' : None , 'fuel_type' : None , 'body' : None, 'color' : None , 'state' : None , 'city' : None , 'phone_number' : None } save_object('data.json' , car_data , 'a') if __name__ == "__main__": main()
//Importing Packages const Discord = require("discord.js") var CronJob = require('cron').CronJob; //starting the module module.exports = client => { //Loop through every setupped guild every single minute and call the dailyfact command client.JobTimesMessages = new CronJob('10 * * * * *', function() { //get all guilds which are setupped var currentMinute = new Date().getMinutes() var currentHour = new Date().getHours(); var Days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] var currentDay = Days[new Date().getDay()]; var guilds = client.settings.filter(v => v.timedmessages && v.timedmessages.length > 0 && v.timedmessages.filter(msg => msg.days.includes(currentDay) && Number(msg.minute) == Number(currentMinute) && Number(msg.hour) == Number(currentHour)).length > 0 ).keyArray(); //Loop through all guilds and send a random auto-generated-nsfw setup for(const guildid of guilds){ timedmessage(guildid) } }, null, true, 'Europe/Berlin'); client.JobTimesMessages.start(); //function for sending automatic nsfw async function timedmessage(guildid){ try{ //get all guilds which are setupped var currentMinute = new Date().getMinutes() var currentHour = new Date().getHours(); var Days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] var currentDay = Days[new Date().getDay()]; //get the Guild var guild = client.guilds.cache.get(guildid) //if no guild, return if(!guild) return; //get the settings let timedmessages = client.settings.get(guild.id, "timedmessages") //If no settings found, or defined on "no" return if(!timedmessage || timedmessage.length == 0) return let timedmessages_to_send = timedmessages.filter(msg => msg.days.includes(currentDay) && Number(msg.minute) == Number(currentMinute) && Number(msg.hour) == Number(currentHour)); if(timedmessages_to_send.length > 0){ for(const msg of timedmessages_to_send){ let channel = guild.channels.cache.get(msg.channel) || await guild.channels.fetch(msg.channel).catch(() => {}) || false; if(!channel) return if(msg.embed){ var es = client.settings.get(guild.id, "embed"); channel.send({embeds : [ new Discord.MessageEmbed() .setColor(es.color) .setFooter(client.getFooter(es)) .setThumbnail(es.thumb ? es.footericon && (es.footericon.includes("http://") || es.footericon.includes("https://")) ? es.footericon : client.user.displayAvatarURL() : null) .setDescription(msg.content.substring(0, 2000)) ]}).catch((e) => { console.log(e) }) } else { channel.send({content : msg.content.substring(0, 2000)}).catch(() => {}) } } } } catch (e){ console.log(String(e).grey) } } }
"use strict"; var __generator = (this && this.__generator)/* istanbul ignore next */ || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __values = (this && this.__values)/* istanbul ignore next */ || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; }; var __read = (this && this.__read)/* istanbul ignore next */ || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread)/* istanbul ignore next */ || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; Object.defineProperty(exports, "__esModule", { value: true }); var errors = require("../errors"); var utils_1 = require("../utils"); var VirtualFileSystemHost = /** @class */ (function () { function VirtualFileSystemHost() { this.directories = new utils_1.KeyValueCache(); this.getOrCreateDir("/"); } VirtualFileSystemHost.prototype.delete = function (path) { try { this.deleteSync(path); return Promise.resolve(); } catch (err) { return Promise.reject(err); } }; VirtualFileSystemHost.prototype.deleteSync = function (path) { path = utils_1.FileUtils.getStandardizedAbsolutePath(this, path); if (this.directories.has(path)) { try { // remove descendant dirs for (var _a = __values(utils_1.ArrayUtils.from(this.directories.getKeys())), _b = _a.next(); !_b.done; _b = _a.next()) { var directoryPath = _b.value; if (utils_1.StringUtils.startsWith(directoryPath, path)) this.directories.removeByKey(directoryPath); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_b && !_b.done && (_c = _a.return)) _c.call(_a); } finally { if (e_1) throw e_1.error; } } // remove this dir this.directories.removeByKey(path); return; } var parentDir = this.directories.get(utils_1.FileUtils.getDirPath(path)); if (parentDir == null || !parentDir.files.has(path)) throw new errors.FileNotFoundError(path); parentDir.files.removeByKey(path); var e_1, _c; }; VirtualFileSystemHost.prototype.readDirSync = function (dirPath) { dirPath = utils_1.FileUtils.getStandardizedAbsolutePath(this, dirPath); var dir = this.directories.get(dirPath); if (dir == null) throw new errors.DirectoryNotFoundError(dirPath); return __spread(getDirectories(this.directories.getKeys()), dir.files.getKeys()); function getDirectories(dirPaths) { var dirPaths_1, dirPaths_1_1, path, parentDir, e_2_1, e_2, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 5, 6, 7]); dirPaths_1 = __values(dirPaths), dirPaths_1_1 = dirPaths_1.next(); _b.label = 1; case 1: if (!!dirPaths_1_1.done) return [3 /*break*/, 4]; path = dirPaths_1_1.value; parentDir = utils_1.FileUtils.getDirPath(path); if (!(parentDir === dirPath && parentDir !== path)) return [3 /*break*/, 3]; return [4 /*yield*/, path]; case 2: _b.sent(); _b.label = 3; case 3: dirPaths_1_1 = dirPaths_1.next(); return [3 /*break*/, 1]; case 4: return [3 /*break*/, 7]; case 5: e_2_1 = _b.sent(); e_2 = { error: e_2_1 }; return [3 /*break*/, 7]; case 6: try { if (dirPaths_1_1 && !dirPaths_1_1.done && (_a = dirPaths_1.return)) _a.call(dirPaths_1); } finally { if (e_2) throw e_2.error; } return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); } }; VirtualFileSystemHost.prototype.readFile = function (filePath, encoding) { if (encoding === void 0) { encoding = "utf-8"; } try { return Promise.resolve(this.readFileSync(filePath, encoding)); } catch (err) { return Promise.reject(err); } }; VirtualFileSystemHost.prototype.readFileSync = function (filePath, encoding) { if (encoding === void 0) { encoding = "utf-8"; } filePath = utils_1.FileUtils.getStandardizedAbsolutePath(this, filePath); var parentDir = this.directories.get(utils_1.FileUtils.getDirPath(filePath)); if (parentDir == null) throw new errors.FileNotFoundError(filePath); var fileText = parentDir.files.get(filePath); if (fileText === undefined) throw new errors.FileNotFoundError(filePath); return fileText; }; VirtualFileSystemHost.prototype.writeFile = function (filePath, fileText) { this.writeFileSync(filePath, fileText); return Promise.resolve(); }; VirtualFileSystemHost.prototype.writeFileSync = function (filePath, fileText) { filePath = utils_1.FileUtils.getStandardizedAbsolutePath(this, filePath); var dirPath = utils_1.FileUtils.getDirPath(filePath); this.getOrCreateDir(dirPath).files.set(filePath, fileText); }; VirtualFileSystemHost.prototype.mkdir = function (dirPath) { this.mkdirSync(dirPath); return Promise.resolve(); }; VirtualFileSystemHost.prototype.mkdirSync = function (dirPath) { dirPath = utils_1.FileUtils.getStandardizedAbsolutePath(this, dirPath); this.getOrCreateDir(dirPath); }; VirtualFileSystemHost.prototype.fileExists = function (filePath) { return Promise.resolve(this.fileExistsSync(filePath)); }; VirtualFileSystemHost.prototype.fileExistsSync = function (filePath) { filePath = utils_1.FileUtils.getStandardizedAbsolutePath(this, filePath); var dirPath = utils_1.FileUtils.getDirPath(filePath); var dir = this.directories.get(dirPath); if (dir == null) return false; return dir.files.has(filePath); }; VirtualFileSystemHost.prototype.directoryExists = function (dirPath) { return Promise.resolve(this.directoryExistsSync(dirPath)); }; VirtualFileSystemHost.prototype.directoryExistsSync = function (dirPath) { dirPath = utils_1.FileUtils.getStandardizedAbsolutePath(this, dirPath); return this.directories.has(dirPath); }; VirtualFileSystemHost.prototype.getCurrentDirectory = function () { return "/"; }; VirtualFileSystemHost.prototype.glob = function (patterns) { var filePaths = []; var allFilePaths = utils_1.ArrayUtils.from(getAllFilePaths(this.directories.getValues())); return utils_1.matchGlobs(allFilePaths, patterns, this.getCurrentDirectory()); function getAllFilePaths(directories) { var directories_1, directories_1_1, dir, e_3_1, e_3, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 5, 6, 7]); directories_1 = __values(directories), directories_1_1 = directories_1.next(); _b.label = 1; case 1: if (!!directories_1_1.done) return [3 /*break*/, 4]; dir = directories_1_1.value; return [5 /*yield**/, __values(dir.files.getKeys())]; case 2: _b.sent(); _b.label = 3; case 3: directories_1_1 = directories_1.next(); return [3 /*break*/, 1]; case 4: return [3 /*break*/, 7]; case 5: e_3_1 = _b.sent(); e_3 = { error: e_3_1 }; return [3 /*break*/, 7]; case 6: try { if (directories_1_1 && !directories_1_1.done && (_a = directories_1.return)) _a.call(directories_1); } finally { if (e_3) throw e_3.error; } return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); } }; VirtualFileSystemHost.prototype.getOrCreateDir = function (dirPath) { var dir = this.directories.get(dirPath); if (dir == null) { dir = { path: dirPath, files: new utils_1.KeyValueCache() }; this.directories.set(dirPath, dir); var parentDirPath = utils_1.FileUtils.getDirPath(dirPath); if (parentDirPath !== dirPath) this.getOrCreateDir(parentDirPath); } return dir; }; return VirtualFileSystemHost; }()); exports.VirtualFileSystemHost = VirtualFileSystemHost;
from util import exec_remote_command_host from base import BaseInstanceStep from dbaas_credentials.models import CredentialType from util import get_credentials_for import json import logging LOG = logging.getLogger(__name__) class SSLFiles(object): @property def ssl_path(self): return '/data/ssl' def conf_file(self, basename): return basename + '.conf' def csr_file(self, basename): return basename + '-cert.csr' def key_file(self, basename): return basename + "-key.pem " def json_file(self, basename): return basename + '-cert.json' def ca_file(self, basename): return basename + "-ca.pem " def cert_file(self, basename): return basename + "-cert.pem " def crt_file(self, basename): return basename + "-cert.crt " class SSL(BaseInstanceStep): def __init__(self, instance): super(SSL, self).__init__(instance) self.credential = get_credentials_for( self.environment, CredentialType.PKI) self.certificate_allowed = self.credential.get_parameter_by_name( 'certificate_allowed') self.master_ssl_ca = self.credential.get_parameter_by_name( 'master_ssl_ca') self.certificate_type = self.credential.get_parameter_by_name( 'certificate_type') self.ssl_files = SSLFiles() @property def ssl_path(self): return self.ssl_files.ssl_path @property def ssl_file_basename(self): raise NotImplementedError @property def conf_file(self): return self.ssl_files.conf_file(self.ssl_file_basename) @property def csr_file(self): return self.ssl_files.csr_file(self.ssl_file_basename) @property def key_file(self): return self.ssl_files.key_file(self.ssl_file_basename) @property def json_file(self): return self.ssl_files.json_file(self.ssl_file_basename) @property def ca_file(self): return self.ssl_files.ca_file(self.ssl_file_basename) @property def cert_file(self): return self.ssl_files.cert_file(self.ssl_file_basename) @property def crt_file(self): return self.ssl_files.crt_file(self.ssl_file_basename) @property def conf_file_path(self): return self.ssl_path + '/' + self.conf_file @property def csr_file_path(self): return self.ssl_path + '/' + self.csr_file @property def key_file_path(self): return self.ssl_path + '/' + self.key_file @property def json_file_path(self): return self.ssl_path + '/' + self.json_file @property def ca_file_path(self): return self.ssl_path + '/' + self.ca_file @property def cert_file_path(self): return self.ssl_path + '/' + self.cert_file @property def crt_file_path(self): return self.ssl_path + '/' + self.crt_file @property def ssl_dns(self): raise NotImplementedError @property def is_valid(self): return ( str(self.certificate_allowed).lower() == 'true' and self.plan.replication_topology.can_setup_ssl ) def do(self): raise NotImplementedError def undo(self): pass def exec_script(self, script): output = {} return_code = exec_remote_command_host(self.host, script, output) if return_code != 0: raise EnvironmentError(str(output)) LOG.info("output: {}".format(output)) return output class IfConguredSSLValidator(SSL): @property def is_valid(self): return self.infra.ssl_configured class UpdateOpenSSlLib(SSL): def __unicode__(self): return "Updating OpenSSL Lib..." def do(self): if not self.is_valid: return script = """yum update -y openssl local err=$? if [ "$err" != "0" ]; then yum clean all yum update -y openssl fi """ self.exec_script(script) class UpdateOpenSSlLibIfConfigured(UpdateOpenSSlLib, IfConguredSSLValidator): pass class MongoDBUpdateCertificates(SSL): def __unicode__(self): return "Updating Certificates libraries..." def do(self): if not self.is_valid: return script = """yum update globoi-ca-certificates yum update ca-certificates """ self.exec_script(script) class MongoDBUpdateCertificatesIfConfigured(MongoDBUpdateCertificates, IfConguredSSLValidator): pass class CreateSSLFolder(SSL): def __unicode__(self): return "Creating SSL Folder..." def do(self): if not self.is_valid: return script = "mkdir -p {}".format(self.ssl_path) self.exec_script(script) def undo(self): pass class CreateSSLFolderRollbackIfRunning(CreateSSLFolder): def undo(self): if self.vm_is_up(attempts=2): super(CreateSSLFolderRollbackIfRunning, self).undo() class CreateSSLFolderIfConfigured(CreateSSLFolder, IfConguredSSLValidator): pass class InstanceSSLBaseName(SSL): @property def ssl_file_basename(self): return self.host.hostname.split('.')[0] class InfraSSLBaseName(SSL): @property def ssl_file_basename(self): return self.infra.name class InstanceSSLDNS(SSL): @property def ssl_dns(self): if self.certificate_type == 'IP': return self.host.address else: return self.instance.dns class InstanceSSLDNSIp(SSL): @property def ssl_dns(self): return self.host.address class InfraSSLDNS(SSL): @property def ssl_dns(self): if self.certificate_type == 'IP': return self.infra.endpoint.split(':')[0] else: return self.infra.endpoint_dns.split(':')[0] class CreateSSLConfigFile(SSL): def __unicode__(self): return "Creating SSL Config File..." def create_ssl_config_file(self): script = """(cat <<EOF_SSL [req] distinguished_name = req_distinguished_name req_extensions = v3_req prompt = no [req_distinguished_name] C = BR ST = RJ L = Rio de Janeiro O = Globo Comunicacao e Participacoes SA OU = Data Center-Globo.com emailAddress = dns-tech\@corp.globo.com CN = {dns} [v3_req] keyUsage = keyEncipherment, dataEncipherment extendedKeyUsage = serverAuth subjectAltName = @alt_names [alt_names] DNS.1 = {dns} EOF_SSL ) > {file_path}""".format(dns=self.ssl_dns, file_path=self.conf_file_path) self.exec_script(script) def do(self): if not self.is_valid: return self.create_ssl_config_file() class MongoDBCreateSSLConfigFile(SSL): def __unicode__(self): return "Creating SSL Config File..." def create_ssl_config_file(self): script = """(cat <<EOF_SSL [req] distinguished_name = req_distinguished_name req_extensions = v3_req prompt = no [req_distinguished_name] C = BR ST = RJ L = Rio de Janeiro O = Globo Comunicacao e Participacoes SA OU = Data Center-Globo.com emailAddress = dns-tech\@corp.globo.com CN = {dns} [v3_req] keyUsage = keyEncipherment, dataEncipherment extendedKeyUsage = serverAuth, clientAuth subjectAltName = @alt_names [alt_names] DNS.1 = {dns} IP.1 = {ip} EOF_SSL ) > {file_path}""".format( dns=self.ssl_dns, file_path=self.conf_file_path, ip=self.host.address ) self.exec_script(script) def do(self): if not self.is_valid: return self.create_ssl_config_file() class CreateSSLConfForInstanceDNS(CreateSSLConfigFile, InstanceSSLBaseName, InstanceSSLDNS): pass class CreateSSLConfForInstanceIP(CreateSSLConfigFile, InstanceSSLBaseName, InstanceSSLDNSIp): pass class CreateSSLConfForInfraEndPoint(CreateSSLConfigFile, InfraSSLBaseName, InfraSSLDNS): pass class CreateSSLConfForInfraEndPointIfConfigured(CreateSSLConfForInfraEndPoint, IfConguredSSLValidator): pass class MongoDBCreateSSLConfForInstanceDNS(MongoDBCreateSSLConfigFile, InstanceSSLBaseName, InstanceSSLDNS): pass class MongoDBCreateSSLConfForInfraEndPoint(MongoDBCreateSSLConfigFile, InfraSSLBaseName, InfraSSLDNS): pass class MongoDBCreateSSLConfForInfra(MongoDBCreateSSLConfigFile, InfraSSLBaseName, InstanceSSLDNS): pass class MongoDBCreateSSLConfForInfraIfConfigured(MongoDBCreateSSLConfForInfra, IfConguredSSLValidator): pass class MongoDBCreateSSLConfForInfraIP(MongoDBCreateSSLConfigFile, InfraSSLBaseName, InstanceSSLDNSIp): pass class MongoDBCreateSSLConfForInfraIPIfConfigured( MongoDBCreateSSLConfForInfraIP, IfConguredSSLValidator): pass class CreateSSLConfForInstanceIPIfConfigured(CreateSSLConfForInstanceIP, IfConguredSSLValidator): pass class RequestSSL(SSL): def __unicode__(self): return "Requesting SSL..." def request_ssl_certificate(self): script = "cd {ssl_path}\n" script += "openssl req -new -out {csr} -newkey rsa:2048 " script += "-nodes -sha256 -keyout {key} -config {conf}" script = script.format( ssl_path=self.ssl_path, csr=self.csr_file, key=self.key_file, conf=self.conf_file) self.exec_script(script) def do(self): if not self.is_valid: return self.request_ssl_certificate() class RequestSSLForInstance(RequestSSL, InstanceSSLBaseName): pass class RequestSSLForInstanceIfConfigured(RequestSSLForInstance, IfConguredSSLValidator): pass class RequestSSLForInfra(RequestSSL, InfraSSLBaseName): pass class RequestSSLForInfraIfConfigured(RequestSSLForInfra, IfConguredSSLValidator): pass class UpdateSSLForInfra(RequestSSLForInfra): def request_ssl_certificate(self): script = "cd {ssl_path}\n" script += "openssl req -new -out {csr}" script += "-sha256 -key {key} -config {conf}" script = script.format( ssl_path=self.ssl_path, csr=self.csr_file, key=self.key_file, conf=self.conf_file) self.exec_script(script) class UpdateSSLForInstance(RequestSSLForInstance): def request_ssl_certificate(self): script = "cd {ssl_path}\n" script += "openssl req -new -out {csr}" script += "-sha256 -key {key} -config {conf}" script = script.format( ssl_path=self.ssl_path, csr=self.csr_file, key=self.key_file, conf=self.conf_file) self.exec_script(script) class CreateJsonRequestFile(SSL): def __unicode__(self): return "Creating JSON SSL File..." def read_csr_file(self): script = "cat {}".format(self.csr_file_path) output = self.exec_script(script) csr_content = '' for line in output['stdout']: csr_content += line return csr_content.rstrip('\n').replace('\n', '\\n') def create_json_request(self, csr_content): script = """(cat <<EOF_SSL {{"certificate": {{"ttl": "8760", "csr": "{csr_content}"}} }} EOF_SSL ) > {file_path}""" script = script.format( csr_content=csr_content, file_path=self.json_file_path) self.exec_script(script) def do(self): if not self.is_valid: return csr_content = self.read_csr_file() self.create_json_request(csr_content) class CreateJsonRequestFileInstance(CreateJsonRequestFile, InstanceSSLBaseName): pass class CreateJsonRequestFileInstanceIfConfigured(CreateJsonRequestFileInstance, IfConguredSSLValidator): pass class CreateJsonRequestFileInfra(CreateJsonRequestFile, InfraSSLBaseName): pass class CreateJsonRequestFileInfraIfConfigured(CreateJsonRequestFileInfra, IfConguredSSLValidator): pass class CreateCertificate(SSL): def __unicode__(self): return "Creating certificate..." def create_certificate_script(self): script = 'curl -d @{json} -H "X-Pki: 42" -H "Content-type: ' script += 'application/json" {endpoint}' script = script.format( json=self.json_file_path, endpoint=self.credential.endpoint) return script def save_certificate_file(self, certificate, filepath): script = "echo '{}' > {}".format(certificate, filepath) self.exec_script(script) def do(self): if not self.is_valid: return script = self.create_certificate_script() output = self.exec_script(script) certificates = json.loads(output['stdout'][0]) ca_chain = certificates['ca_chain'][0] self.save_certificate_file(ca_chain, self.ca_file_path) certificate = certificates['certificate'] self.save_certificate_file(certificate, self.cert_file_path) class CreateCertificateMongoDB(CreateCertificate): def save_mongodb_certificate(self, key_file, crt_file, ca_file, cert_file): script = "cd {}\n".format(self.ssl_path) script += 'cat {key_file} {crt_file} {ca_file} > {cert_file}' script = script.format( key_file=key_file, crt_file=crt_file, ca_file=ca_file, cert_file=cert_file ) self.exec_script(script) def do(self): if not self.is_valid: return script = self.create_certificate_script() output = self.exec_script(script) certificates = json.loads(output['stdout'][0]) ca_chain = certificates['ca_chain'][0] self.save_certificate_file(ca_chain, self.ca_file_path) certificate = certificates['certificate'] self.save_certificate_file(certificate, self.crt_file_path) self.save_mongodb_certificate( self.key_file_path, self.crt_file_path, self.ca_file_path, self.cert_file_path) class CreateCertificateInstance(CreateCertificate, InstanceSSLBaseName): pass class CreateCertificateInstanceMongoDB(CreateCertificateMongoDB, InstanceSSLBaseName): pass class CreateCertificateInfraMongoDB(CreateCertificateMongoDB, InfraSSLBaseName): pass class CreateCertificateInstanceIfConfigured(CreateCertificateInstance, IfConguredSSLValidator): pass class CreateCertificateInfraMongoDBIfConfigured(CreateCertificateInfraMongoDB, IfConguredSSLValidator): pass class CreateCertificateInfra(CreateCertificate, InfraSSLBaseName): pass class CreateCertificateInfraIfConfigured(CreateCertificateInfra, IfConguredSSLValidator): pass class SetSSLFilesAccessMySQL(SSL): def __unicode__(self): return "Setting SSL Files Access..." def sll_file_access_script(self): script = "cd {}\n".format(self.ssl_path) script += "chown mysql:mysql *\n" script += "chown mysql:mysql .\n" script += "chmod 400 *key*.pem\n" script += "chmod 444 *cert*.pem\n" script += "chmod 755 ." self.exec_script(script) def do(self): if not self.is_valid: return self.sll_file_access_script() class SetSSLFilesAccessMySQLIfConfigured(SetSSLFilesAccessMySQL, IfConguredSSLValidator): pass class SetSSLFilesAccessMongoDB(SSL): def __unicode__(self): return "Setting SSL Files Access..." def sll_file_access_script(self): script = "cd {}\n".format(self.ssl_path) script += "chown mongodb:mongodb *.pem\n" script += "chmod 755 ." self.exec_script(script) def do(self): if not self.is_valid: return self.sll_file_access_script() class SetSSLFilesAccessMongoDBIfConfigured(SetSSLFilesAccessMongoDB, IfConguredSSLValidator): pass class SetInfraConfiguredSSL(SSL): def __unicode__(self): return "Setting infra as SSL configured..." def do(self): if not self.is_valid: return infra = self.infra infra.ssl_configured = True infra.save() def undo(self): if not self.is_valid: return infra = self.infra infra.ssl_configured = False infra.save() class SetInfraSSLModeAllowTLS(SSL): def __unicode__(self): return "Setting infra SSL Mode to allow TLS..." def do(self): if not self.is_valid: return infra = self.infra infra.ssl_mode = infra.ALLOWTLS infra.save() class SetInfraSSLModePreferTLS(SSL): def __unicode__(self): return "Setting infra SSL Mode to prefer TLS..." def do(self): if not self.is_valid: return infra = self.infra infra.ssl_mode = infra.PREFERTLS infra.save() class SetInfraSSLModeRequireTLS(SSL): def __unicode__(self): return "Setting infra SSL Mode to require TLS..." def do(self): if not self.is_valid: return infra = self.infra infra.ssl_mode = infra.REQUIRETLS infra.save() class UpdateExpireAtDate(SSL): def __unicode__(self): return "Updating expire_at date..." @property def is_valid(self): return self.infra.ssl_configured def do(self): if not self.is_valid: return output = self.exec_script( ('date --date="$(openssl x509 -in /data/ssl/{}-cert.pem ' '-noout -enddate | cut -d= -f 2)" --iso-8601'.format( self.infra.name)) ) try: expire_at = output['stdout'][0] except (IndexError, KeyError) as err: raise Exception("Error get expire SSL date. {}".format(err)) host = self.host host.ssl_expire_at = expire_at.strip() host.save() def undo(self): pass class UpdateExpireAtDateRollback(UpdateExpireAtDate): def __unicode__(self): return "Update expire_at date if Rollback..." def do(self): pass def undo(self): return super(UpdateExpireAtDateRollback, self).do() class SetReplicationUserRequireSSL(SSL): def __unicode__(self): return "Setting replication user to require SSL..." @property def is_valid(self): if not self.plan.is_ha: return False return super(SetReplicationUserRequireSSL, self).is_valid def do(self): if not self.is_valid: return driver = self.infra.get_driver() driver.set_replication_require_ssl( instance=self.instance, ca_path=self.master_ssl_ca) driver.set_replication_user_require_ssl() def undo(self): if not self.is_valid: return driver = self.infra.get_driver() driver.set_replication_user_not_require_ssl() driver.set_replication_not_require_ssl(instance=self.instance) class SetReplicationUserRequireSSLRollbackIfRunning(SetReplicationUserRequireSSL): # noqa def undo(self): if self.database_is_up(attempts=2): super(SetReplicationUserRequireSSLRollbackIfRunning, self).undo() class UnSetReplicationUserRequireSSL(SetReplicationUserRequireSSL): def __unicode__(self): return "Removing replication user to require SSL..." def do(self): super(UnSetReplicationUserRequireSSL, self).undo() def undo(self): super(UnSetReplicationUserRequireSSL, self).do() class BackupSSLFolder(SSL): source_ssl_dir = '/data/ssl' backup_ssl_dir = '/data/ssl-BKP' def __unicode__(self): return "Doing backup of SSL folder..." def do(self): script = 'cp -rp {} {}'.format( self.source_ssl_dir, self.backup_ssl_dir ) return self.run_script(script) def undo(self): script = ('[ -d {1} ] ' '&& cp -rp {1}/* {0} ' '&& rm -rf {1} ' '|| exit 0'.format(self.source_ssl_dir, self.backup_ssl_dir)) return self.run_script(script) class RestoreSSLFolder4Rollback(BackupSSLFolder): def __unicode__(self): return "Restore SSL folder if doing rollback..." def do(self): pass class SetMongoDBTSLParameter(SSL): @property def is_valid(self): return self.instance.instance_type == self.instance.MONGODB @property def client(self): return self.driver.get_client(self.instance) class SetMongoDBPreferTLSParameter(SetMongoDBTSLParameter): def __unicode__(self): return "Setting MongoDB parameters to preffer TSL..." def do(self): if not self.is_valid: return self.client.admin.command('setParameter', 1, tlsMode='preferTLS') if self.plan.is_ha: self.client.admin.command( 'setParameter', 1, clusterAuthMode='sendX509') class SetMongoDBRequireTLSParameter(SetMongoDBTSLParameter): def __unicode__(self): return "Setting MongoDB parameters to require TSL..." def do(self): if not self.is_valid: return self.client.admin.command('setParameter', 1, tlsMode='requireTLS') if self.plan.is_ha: self.client.admin.command( 'setParameter', 1, clusterAuthMode='x509')
# _ __ # | |/ /___ ___ _ __ ___ _ _ ® # | ' </ -_) -_) '_ \/ -_) '_| # |_|\_\___\___| .__/\___|_| # |_| # # Keeper Commander # Copyright 2018 Keeper Security Inc. # Contact: [email protected] # def get_folder_path(params, folder_uid, delimiter='/'): uid = folder_uid path = '' while uid in params.folder_cache: f = params.folder_cache[uid] name = f.name name = name.replace(delimiter, 2*delimiter) if len(path) > 0: path = name + delimiter + path else: path = name uid = f.parent_uid return path def find_folders(params, record_uid): for fuid in params.subfolder_record_cache: if record_uid in params.subfolder_record_cache[fuid]: if fuid: yield fuid def try_resolve_path(params, path): if type(path) is not str: path = '' folder = params.folder_cache[params.current_folder] if params.current_folder in params.folder_cache else params.root_folder if len(path) > 0: if path[0] == '/': folder = params.root_folder path = path[1:] start = 0 while True: idx = path.find('/', start) path_component = '' if idx < 0: if len(path) > 0: path_component = path.strip() elif idx > 0 and path[idx - 1] == '\\': start = idx + 1 continue else: path_component = path[:idx].strip() if len(path_component) == 0: break folder_uid = '' if path_component == '.': folder_uid = folder.uid elif path_component == '..': folder_uid = folder.parent_uid or '/' else: for uid in folder.subfolders: sf = params.folder_cache[uid] if sf.name.strip() == path_component: folder_uid = uid if folder_uid: folder = params.folder_cache[folder_uid] if folder_uid in params.folder_cache else params.root_folder else: break if idx < 0: path = '' break path = path[idx+1:] start = 0 return folder, path class BaseFolderNode: RootFolderType = '/' UserFolderType = 'user_folder' SharedFolderType = 'shared_folder' SharedFolderFolderType = 'shared_folder_folder' """ Folder Common Fields""" def __init__(self, type): self.type = type self.uid = None self.parent_uid = None self.name = None self.subfolders = [] def get_folder_type(self): if self.type == BaseFolderNode.RootFolderType: return 'Root' elif self.type == BaseFolderNode.UserFolderType: return 'Regular Folder' elif self.type == BaseFolderNode.SharedFolderType: return 'Shared Folder' elif self.type == BaseFolderNode.SharedFolderFolderType: return 'Subfolder in Shared Folder' return '' def display(self, **kwargs): print('') print('{0:>20s}: {1:<20s}'.format('Folder UID', self.uid)) print('{0:>20s}: {1:<20s}'.format('Folder Type', self.get_folder_type())) print('{0:>20s}: {1}'.format('Name', self.name)) class UserFolderNode(BaseFolderNode): def __init__(self): BaseFolderNode.__init__(self, BaseFolderNode.UserFolderType) class SharedFolderFolderNode(BaseFolderNode): def __init__(self): BaseFolderNode.__init__(self, BaseFolderNode.SharedFolderFolderType) self.shared_folder_uid = None class SharedFolderNode(BaseFolderNode): def __init__(self): BaseFolderNode.__init__(self, BaseFolderNode.SharedFolderType) class RootFolderNode(BaseFolderNode): def __init__(self): BaseFolderNode.__init__(self, BaseFolderNode.RootFolderType) self.name = 'My Vault'
let start = (config)=>{ let hConfig = __handle_config(config) __send_message( __TYPE.BIOMETRICS.CHECK.START, hConfig ) } export default { start }
from Configure.configure import * class MyButton(QtWidgets.QPushButton): def __init__(self, text, styleNo=1): super().__init__() self.setText(text) self.setStyle(styleNo) self.setSizePolicy( QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding ) def setStyle(self, styleNo): if styleNo == 1: self.fileName = "resources/css/button/button1.css" elif styleNo == 2: self.fileName = "resources/css/button/button2.css" elif styleNo == 3: self.fileName = "resources/css/button/button3.css" elif styleNo == 4: self.fileName = "resources/css/button/button4.css" elif styleNo == 5: self.fileName = "resources/css/button/button5.css" btn_css = Global.readCSS(self.fileName) self.setStyleSheet(btn_css)
# postgresql/json.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from __future__ import absolute_import import json from .base import ischema_names from ... import types as sqltypes from ...sql.operators import custom_op from ... import sql from ...sql import elements, default_comparator from ... import util __all__ = ('JSON', 'JSONElement', 'JSONB') class JSONElement(elements.BinaryExpression): """Represents accessing an element of a :class:`.JSON` value. The :class:`.JSONElement` is produced whenever using the Python index operator on an expression that has the type :class:`.JSON`:: expr = mytable.c.json_data['some_key'] The expression typically compiles to a JSON access such as ``col -> key``. Modifiers are then available for typing behavior, including :meth:`.JSONElement.cast` and :attr:`.JSONElement.astext`. """ def __init__(self, left, right, astext=False, opstring=None, result_type=None): self._astext = astext if opstring is None: if hasattr(right, '__iter__') and \ not isinstance(right, util.string_types): opstring = "#>" right = "{%s}" % ( ", ".join(util.text_type(elem) for elem in right)) else: opstring = "->" self._json_opstring = opstring operator = custom_op(opstring, precedence=5) right = default_comparator._check_literal( left, operator, right) super(JSONElement, self).__init__( left, right, operator, type_=result_type) @property def astext(self): """Convert this :class:`.JSONElement` to use the 'astext' operator when evaluated. E.g.:: select([data_table.c.data['some key'].astext]) .. seealso:: :meth:`.JSONElement.cast` """ if self._astext: return self else: return JSONElement( self.left, self.right, astext=True, opstring=self._json_opstring + ">", result_type=sqltypes.String(convert_unicode=True) ) def cast(self, type_): """Convert this :class:`.JSONElement` to apply both the 'astext' operator as well as an explicit type cast when evaluated. E.g.:: select([data_table.c.data['some key'].cast(Integer)]) .. seealso:: :attr:`.JSONElement.astext` """ if not self._astext: return self.astext.cast(type_) else: return sql.cast(self, type_) class JSON(sqltypes.TypeEngine): """Represent the Postgresql JSON type. The :class:`.JSON` type stores arbitrary JSON format data, e.g.:: data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), Column('data', JSON) ) with engine.connect() as conn: conn.execute( data_table.insert(), data = {"key1": "value1", "key2": "value2"} ) :class:`.JSON` provides several operations: * Index operations:: data_table.c.data['some key'] * Index operations returning text (required for text comparison):: data_table.c.data['some key'].astext == 'some value' * Index operations with a built-in CAST call:: data_table.c.data['some key'].cast(Integer) == 5 * Path index operations:: data_table.c.data[('key_1', 'key_2', ..., 'key_n')] * Path index operations returning text (required for text comparison):: data_table.c.data[('key_1', 'key_2', ..., 'key_n')].astext == \\ 'some value' Index operations return an instance of :class:`.JSONElement`, which represents an expression such as ``column -> index``. This element then defines methods such as :attr:`.JSONElement.astext` and :meth:`.JSONElement.cast` for setting up type behavior. The :class:`.JSON` type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the :mod:`sqlalchemy.ext.mutable` extension must be used. This extension will allow "in-place" changes to the datastructure to produce events which will be detected by the unit of work. See the example at :class:`.HSTORE` for a simple example involving a dictionary. Custom serializers and deserializers are specified at the dialect level, that is using :func:`.create_engine`. The reason for this is that when using psycopg2, the DBAPI only allows serializers at the per-cursor or per-connection level. E.g.:: engine = create_engine("postgresql://scott:tiger@localhost/test", json_serializer=my_serialize_fn, json_deserializer=my_deserialize_fn ) When using the psycopg2 dialect, the json_deserializer is registered against the database using ``psycopg2.extras.register_default_json``. .. versionadded:: 0.9 """ __visit_name__ = 'JSON' def __init__(self, none_as_null=False): """Construct a :class:`.JSON` type. :param none_as_null: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that when this flag is False, the :func:`.null` construct can still be used to persist a NULL value:: from sqlalchemy import null conn.execute(table.insert(), data=null()) .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null` is now supported in order to persist a NULL value. """ self.none_as_null = none_as_null class comparator_factory(sqltypes.Concatenable.Comparator): """Define comparison operations for :class:`.JSON`.""" def __getitem__(self, other): """Get the value at a given key.""" return JSONElement(self.expr, other) def _adapt_expression(self, op, other_comparator): if isinstance(op, custom_op): if op.opstring == '->': return op, sqltypes.Text return sqltypes.Concatenable.Comparator.\ _adapt_expression(self, op, other_comparator) def bind_processor(self, dialect): json_serializer = dialect._json_serializer or json.dumps if util.py2k: encoding = dialect.encoding def process(value): if isinstance(value, elements.Null) or ( value is None and self.none_as_null ): return None return json_serializer(value).encode(encoding) else: def process(value): if isinstance(value, elements.Null) or ( value is None and self.none_as_null ): return None return json_serializer(value) return process def result_processor(self, dialect, coltype): json_deserializer = dialect._json_deserializer or json.loads if util.py2k: encoding = dialect.encoding def process(value): if value is None: return None return json_deserializer(value.decode(encoding)) else: def process(value): if value is None: return None return json_deserializer(value) return process ischema_names['json'] = JSON class JSONB(JSON): """Represent the Postgresql JSONB type. The :class:`.JSONB` type stores arbitrary JSONB format data, e.g.:: data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), Column('data', JSONB) ) with engine.connect() as conn: conn.execute( data_table.insert(), data = {"key1": "value1", "key2": "value2"} ) :class:`.JSONB` provides several operations: * Index operations:: data_table.c.data['some key'] * Index operations returning text (required for text comparison):: data_table.c.data['some key'].astext == 'some value' * Index operations with a built-in CAST call:: data_table.c.data['some key'].cast(Integer) == 5 * Path index operations:: data_table.c.data[('key_1', 'key_2', ..., 'key_n')] * Path index operations returning text (required for text comparison):: data_table.c.data[('key_1', 'key_2', ..., 'key_n')].astext == \\ 'some value' Index operations return an instance of :class:`.JSONElement`, which represents an expression such as ``column -> index``. This element then defines methods such as :attr:`.JSONElement.astext` and :meth:`.JSONElement.cast` for setting up type behavior. The :class:`.JSON` type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the :mod:`sqlalchemy.ext.mutable` extension must be used. This extension will allow "in-place" changes to the datastructure to produce events which will be detected by the unit of work. See the example at :class:`.HSTORE` for a simple example involving a dictionary. Custom serializers and deserializers are specified at the dialect level, that is using :func:`.create_engine`. The reason for this is that when using psycopg2, the DBAPI only allows serializers at the per-cursor or per-connection level. E.g.:: engine = create_engine("postgresql://scott:tiger@localhost/test", json_serializer=my_serialize_fn, json_deserializer=my_deserialize_fn ) When using the psycopg2 dialect, the json_deserializer is registered against the database using ``psycopg2.extras.register_default_json``. .. versionadded:: 0.9.7 """ __visit_name__ = 'JSONB' hashable = False class comparator_factory(sqltypes.Concatenable.Comparator): """Define comparison operations for :class:`.JSON`.""" def __getitem__(self, other): """Get the value at a given key.""" return JSONElement(self.expr, other) def _adapt_expression(self, op, other_comparator): # How does one do equality?? jsonb also has "=" eg. # '[1,2,3]'::jsonb = '[1,2,3]'::jsonb if isinstance(op, custom_op): if op.opstring in ['?', '?&', '?|', '@>', '<@']: return op, sqltypes.Boolean if op.opstring == '->': return op, sqltypes.Text return sqltypes.Concatenable.Comparator.\ _adapt_expression(self, op, other_comparator) def has_key(self, other): """Boolean expression. Test for presence of a key. Note that the key may be a SQLA expression. """ return self.expr.op('?')(other) def has_all(self, other): """Boolean expression. Test for presence of all keys in jsonb """ return self.expr.op('?&')(other) def has_any(self, other): """Boolean expression. Test for presence of any key in jsonb """ return self.expr.op('?|')(other) def contains(self, other, **kwargs): """Boolean expression. Test if keys (or array) are a superset of/contained the keys of the argument jsonb expression. """ return self.expr.op('@>')(other) def contained_by(self, other): """Boolean expression. Test if keys are a proper subset of the keys of the argument jsonb expression. """ return self.expr.op('<@')(other) ischema_names['jsonb'] = JSONB
import debugpy from os import environ as env def attach_debugger_if_dev(): if "DEBUG" in env and env["DEBUG"] == "True": debugpy.listen(("0.0.0.0", 5678)) print("⏳ VS Code debugger can now be attached ⏳", flush=True) debugpy.wait_for_client() print("🎉 VS Code debugger attached, enjoy debugging 🎉", flush=True)
""" Render a depth image ~~~~~~~~~~~~~~~~~~~~ Plot a depth image as viewed from a camera overlooking the "hills" example mesh. """ # sphinx_gallery_thumbnail_number = 2 import pyvista as pv import matplotlib.pyplot as plt from pyvista import examples # Load an interesting example of geometry mesh = examples.load_random_hills() # Establish geometry within a pv.Plotter() p = pv.Plotter() p.add_mesh(mesh, color=True) p.store_image = True # permit image caching after plotter is closed p.show() ############################################################################### # Record depth image without and with a custom fill value zval = p.get_image_depth() zval_filled_by_42s = p.get_image_depth(fill_value=42.0) ############################################################################### # Visualize depth images plt.figure() plt.imshow(zval) plt.colorbar(label='Distance to Camera') plt.title('Depth image') plt.xlabel('X Pixel') plt.ylabel('Y Pixel') plt.show() ############################################################################### plt.figure() plt.imshow(zval_filled_by_42s) plt.title('Depth image (custom fill_value)') plt.colorbar(label='Distance to Camera') plt.xlabel('X Pixel') plt.ylabel('Y Pixel') plt.show()
const autoprefixer = require('autoprefixer') const path = require('path') const config = require('./config') const webpack = require('webpack') const ExtractTextPlugin = require('extract-text-webpack-plugin') const StringReplacePlugin = require('string-replace-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'eval-source-map', entry: { app: [ './src/app.js' ] }, output: { path: path.join(__dirname, 'public'), filename: '[name].js', publicPath: '/' }, devServer: { contentBase: './public', noInfo: true, hot: true, inline: true, historyApiFallback: true, host: '0.0.0.0', watchOptions: { aggregateTimeout: 300, poll: 1000 }, port: 8000 }, plugins: [ new webpack.HotModuleReplacementPlugin(), new ExtractTextPlugin('[name].css'), new HtmlWebpackPlugin({ template: './src/index.html' }), new StringReplacePlugin() ], postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], resolve: { extensions: ['', '.js'] }, standard: { // config options to be passed through to standard e.g. parser: 'babel-eslint' }, module: { preLoaders: [ { // set up standard-loader as a preloader test: /\.js?$/, loader: 'standard', exclude: /node_modules/ } ], loaders: [{ test: /\.js?$/, loaders: ['babel'], exclude: /node_modules/ }, { test: /config.js$/, loader: StringReplacePlugin.replace({ replacements: [{ pattern: /@@(\w*?)@@/ig, replacement: function (match, p1, offset, string) { return config.get(p1) } }] }) }, { test: /\.scss$/, loader: ExtractTextPlugin.extract('css!postcss!sass?includePaths[]=' +(path.resolve(__dirname, './node_modules'))) }, { test: /\.scss$/, loader: ExtractTextPlugin.extract('css!postcss!sass?includePaths[]=' + (path.resolve(__dirname, './node_modules'))) }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader' }] } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. const fs = require("fs"); function haveISSUESID(title) { if (!title) { return false; } return /^\[ML-\d+\]/.test(title); } async function commentOpenISSUESIssue(github, context, pullRequestNumber) { const {data: comments} = await github.issues.listComments({ owner: context.repo.owner, repo: context.repo.repo, issue_number: pullRequestNumber, per_page: 1 }); if (comments.length > 0) { return; } const commentPath = ".github/workflows/dev_cron/title_check.md"; const comment = fs.readFileSync(commentPath).toString(); await github.issues.createComment({ owner: context.repo.owner, repo: context.repo.repo, issue_number: pullRequestNumber, body: comment }); } module.exports = async ({github, context}) => { const pullRequestNumber = context.payload.number; const title = context.payload.pull_request.title; if (!haveISSUESID(title)) { await commentOpenISSUESIssue(github, context, pullRequestNumber); } };
import matplotlib matplotlib.use('Agg') from model import Generator import torch from torch.autograd import Variable from torch.utils.trainer.plugins.plugin import Plugin from torch.utils.trainer.plugins.monitor import Monitor from torch.utils.trainer.plugins import LossMonitor from librosa.output import write_wav from matplotlib import pyplot from glob import glob import os import pickle import time class TrainingLossMonitor(LossMonitor): stat_name = 'training_loss' class ValidationPlugin(Plugin): def __init__(self, val_dataset, test_dataset): super().__init__([(1, 'epoch')]) self.val_dataset = val_dataset self.test_dataset = test_dataset def register(self, trainer): self.trainer = trainer val_stats = self.trainer.stats.setdefault('validation_loss', {}) val_stats['log_epoch_fields'] = ['{last:.4f}'] test_stats = self.trainer.stats.setdefault('test_loss', {}) test_stats['log_epoch_fields'] = ['{last:.4f}'] def epoch(self, idx): self.trainer.model.eval() val_stats = self.trainer.stats.setdefault('validation_loss', {}) val_stats['last'] = self._evaluate(self.val_dataset) test_stats = self.trainer.stats.setdefault('test_loss', {}) test_stats['last'] = self._evaluate(self.test_dataset) self.trainer.model.train() def _evaluate(self, dataset): loss_sum = 0 n_examples = 0 for data in dataset: batch_inputs = data[: -1] batch_target = data[-1] batch_size = batch_target.size()[0] def wrap(input): if torch.is_tensor(input): input = Variable(input, volatile=True) if self.trainer.cuda: input = input.cuda() return input batch_inputs = list(map(wrap, batch_inputs)) batch_target = Variable(batch_target, volatile=True) if self.trainer.cuda: batch_target = batch_target.cuda() batch_output = self.trainer.model(*batch_inputs) loss_sum += self.trainer.criterion(batch_output, batch_target) \ .data[0] * batch_size n_examples += batch_size return loss_sum / n_examples class AbsoluteTimeMonitor(Monitor): stat_name = 'time' def __init__(self, *args, **kwargs): kwargs.setdefault('unit', 's') kwargs.setdefault('precision', 0) kwargs.setdefault('running_average', False) kwargs.setdefault('epoch_average', False) super(AbsoluteTimeMonitor, self).__init__(*args, **kwargs) self.start_time = None def _get_value(self, *args): if self.start_time is None: self.start_time = time.time() return time.time() - self.start_time class SaverPlugin(Plugin): last_pattern = 'ep{}-it{}' best_pattern = 'best-ep{}-it{}' def __init__(self, checkpoints_path, keep_old_checkpoints): super().__init__([(1, 'epoch')]) self.checkpoints_path = checkpoints_path self.keep_old_checkpoints = keep_old_checkpoints self._best_val_loss = float('+inf') def register(self, trainer): self.trainer = trainer def epoch(self, epoch_index): if not self.keep_old_checkpoints: self._clear(self.last_pattern.format('*', '*')) torch.save( self.trainer.model.state_dict(), os.path.join( self.checkpoints_path, self.last_pattern.format(epoch_index, self.trainer.iterations) ) ) cur_val_loss = self.trainer.stats['validation_loss']['last'] if cur_val_loss < self._best_val_loss: self._clear(self.best_pattern.format('*', '*')) torch.save( self.trainer.model.state_dict(), os.path.join( self.checkpoints_path, self.best_pattern.format( epoch_index, self.trainer.iterations ) ) ) self._best_val_loss = cur_val_loss def _clear(self, pattern): pattern = os.path.join(self.checkpoints_path, pattern) for file_name in glob(pattern): os.remove(file_name) class GeneratorPlugin(Plugin): pattern = 'ep{}-s{}.wav' def __init__(self, samples_path, n_samples, sample_length, sample_rate, sampling_temperature): super().__init__([(1, 'epoch')]) self.samples_path = samples_path self.n_samples = n_samples self.sample_length = sample_length self.sample_rate = sample_rate self.sampling_temperature = sampling_temperature def register(self, trainer): self.generate = Generator(trainer.model.model, trainer.cuda) # New register to accept model and cuda setting (which tells whether we should use GPU or not) -> audio generation after training def register_generate(self, model, cuda): self.generate = Generator(model, cuda) def epoch(self, epoch_index, initial_seq=None): samples = self.generate(self.n_samples, self.sample_length, self.sampling_temperature, initial_seq=initial_seq) \ .cpu().float().numpy() for i in range(self.n_samples): write_wav( os.path.join( self.samples_path, self.pattern.format(epoch_index, i + 1) ), samples[i, :], sr=self.sample_rate, norm=True ) class StatsPlugin(Plugin): data_file_name = 'stats.pkl' plot_pattern = '{}.svg' def __init__(self, results_path, iteration_fields, epoch_fields, plots): super().__init__([(1, 'iteration'), (1, 'epoch')]) self.results_path = results_path self.iteration_fields = self._fields_to_pairs(iteration_fields) self.epoch_fields = self._fields_to_pairs(epoch_fields) self.plots = plots self.data = { 'iterations': { field: [] for field in self.iteration_fields + [('iteration', 'last')] }, 'epochs': { field: [] for field in self.epoch_fields + [('iteration', 'last')] } } def register(self, trainer): self.trainer = trainer def iteration(self, *args): for (field, stat) in self.iteration_fields: self.data['iterations'][field, stat].append( self.trainer.stats[field][stat] ) self.data['iterations']['iteration', 'last'].append( self.trainer.iterations ) def epoch(self, epoch_index): for (field, stat) in self.epoch_fields: self.data['epochs'][field, stat].append( self.trainer.stats[field][stat] ) self.data['epochs']['iteration', 'last'].append( self.trainer.iterations ) data_file_path = os.path.join(self.results_path, self.data_file_name) with open(data_file_path, 'wb') as f: pickle.dump(self.data, f) for (name, info) in self.plots.items(): x_field = self._field_to_pair(info['x']) try: y_fields = info['ys'] except KeyError: y_fields = [info['y']] labels = list(map( lambda x: ' '.join(x) if type(x) is tuple else x, y_fields )) y_fields = self._fields_to_pairs(y_fields) try: formats = info['formats'] except KeyError: formats = [''] * len(y_fields) pyplot.gcf().clear() for (y_field, format, label) in zip(y_fields, formats, labels): if y_field in self.iteration_fields: part_name = 'iterations' else: part_name = 'epochs' xs = self.data[part_name][x_field] ys = self.data[part_name][y_field] pyplot.plot(xs, ys, format, label=label) if 'log_y' in info and info['log_y']: pyplot.yscale('log') pyplot.legend() pyplot.savefig( os.path.join(self.results_path, self.plot_pattern.format(name)) ) @staticmethod def _field_to_pair(field): if type(field) is tuple: return field else: return (field, 'last') @classmethod def _fields_to_pairs(cls, fields): return list(map(cls._field_to_pair, fields)) class CometPlugin(Plugin): def __init__(self, experiment, fields): super().__init__([(1, 'epoch')]) self.experiment = experiment self.fields = [ field if type(field) is tuple else (field, 'last') for field in fields ] def register(self, trainer): self.trainer = trainer def epoch(self, epoch_index): for (field, stat) in self.fields: self.experiment.log_metric(field, self.trainer.stats[field][stat]) self.experiment.log_epoch_end(epoch_index)
import pytest import torch from torch.autograd import gradcheck from torch.testing import assert_allclose from kornia.morphology import top_hat class TestTopHat: def test_smoke(self, device, dtype): kernel = torch.rand(3, 3, device=device, dtype=dtype) assert kernel is not None @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)]) @pytest.mark.parametrize("kernel", [(3, 3), (5, 5)]) def test_cardinality(self, device, dtype, shape, kernel): img = torch.ones(shape, device=device, dtype=dtype) krnl = torch.ones(kernel, device=device, dtype=dtype) assert top_hat(img, krnl).shape == shape def test_kernel(self, device, dtype): tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[ None, None, :, : ] kernel = torch.tensor([[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype) expected = torch.tensor([[0.0, 0.5, 0.0], [0.2, 0.0, 0.5], [0.0, 0.5, 0.0]], device=device, dtype=dtype)[ None, None, :, : ] assert_allclose(top_hat(tensor, kernel), expected, atol=1e-3, rtol=1e-3) def test_structural_element(self, device, dtype): tensor = torch.tensor([[0.5, 1.0, 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[ None, None, :, : ] structural_element = torch.tensor( [[-1.0, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], device=device, dtype=dtype ) expected = torch.tensor([[0.0, 0.5, 0.0], [0.2, 0.0, 0.5], [0.0, 0.5, 0.0]], device=device, dtype=dtype)[ None, None, :, : ] assert_allclose( top_hat(tensor, torch.ones_like(structural_element), structuring_element=structural_element), expected, atol=1e-3, rtol=1e-3 ) def test_exception(self, device, dtype): input = torch.ones(1, 1, 3, 4, device=device, dtype=dtype) kernel = torch.ones(3, 3, device=device, dtype=dtype) with pytest.raises(TypeError): assert top_hat([0.0], kernel) with pytest.raises(TypeError): assert top_hat(input, [0.0]) with pytest.raises(ValueError): test = torch.ones(2, 3, 4, device=device, dtype=dtype) assert top_hat(test, kernel) with pytest.raises(ValueError): test = torch.ones(2, 3, 4, device=device, dtype=dtype) assert top_hat(input, test) @pytest.mark.grad def test_gradcheck(self, device, dtype): input = torch.rand(2, 3, 4, 4, requires_grad=True, device=device, dtype=torch.float64) kernel = torch.rand(3, 3, requires_grad=True, device=device, dtype=torch.float64) assert gradcheck(top_hat, (input, kernel), raise_exception=True) @pytest.mark.jit def test_jit(self, device, dtype): op = top_hat op_script = torch.jit.script(op) input = torch.rand(1, 2, 7, 7, device=device, dtype=dtype) kernel = torch.ones(3, 3, device=device, dtype=dtype) actual = op_script(input, kernel) expected = op(input, kernel) assert_allclose(actual, expected)
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); 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 _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames2 = require('classnames'); var _classnames3 = _interopRequireDefault(_classnames2); var _FormattedMessage = require('../../../components/FormattedMessage'); var _FormattedMessage2 = _interopRequireDefault(_FormattedMessage); var _CSSClassnames = require('../../../utils/CSSClassnames'); var _CSSClassnames2 = _interopRequireDefault(_CSSClassnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP var CLASS_ROOT = _CSSClassnames2.default.CONTROL_ICON; var COLOR_INDEX = _CSSClassnames2.default.COLOR_INDEX; var Icon = function (_Component) { (0, _inherits3.default)(Icon, _Component); function Icon() { (0, _classCallCheck3.default)(this, Icon); return (0, _possibleConstructorReturn3.default)(this, (Icon.__proto__ || (0, _getPrototypeOf2.default)(Icon)).apply(this, arguments)); } (0, _createClass3.default)(Icon, [{ key: 'render', value: function render() { var _classnames; var _props = this.props; var a11yTitleId = _props.a11yTitleId; var className = _props.className; var colorIndex = _props.colorIndex; var _props2 = this.props; var a11yTitle = _props2.a11yTitle; var size = _props2.size; var classes = (0, _classnames3.default)(CLASS_ROOT, CLASS_ROOT + '-folder', className, (_classnames = {}, (0, _defineProperty3.default)(_classnames, CLASS_ROOT + '--' + size, size), (0, _defineProperty3.default)(_classnames, COLOR_INDEX + '-' + colorIndex, colorIndex), _classnames)); a11yTitle = a11yTitle || _react2.default.createElement(_FormattedMessage2.default, { id: 'folder', defaultMessage: 'folder' }); return _react2.default.createElement( 'svg', { version: '1.1', viewBox: '0 0 24.0001 24', width: '24px', height: '24px', role: 'img', className: classes, 'aria-labelledby': a11yTitleId }, _react2.default.createElement( 'title', { id: a11yTitleId }, a11yTitle ), _react2.default.createElement( 'g', null, _react2.default.createElement('rect', { x: '0', y: '0', fill: 'none', width: '24', height: '24' }), _react2.default.createElement('path', { fill: 'none', stroke: '#000000', strokeWidth: '2', strokeMiterlimit: '10', d: 'M23.0001,22h-22V6l0-4h8l3,4h11V22z M1.0001,10h22' }) ) ); } }]); return Icon; }(_react.Component); Icon.displayName = 'Icon'; exports.default = Icon; ; Icon.propTypes = { a11yTitle: _react.PropTypes.string, a11yTitleId: _react.PropTypes.string, colorIndex: _react.PropTypes.string, size: _react.PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']) }; Icon.defaultProps = { a11yTitleId: 'folder-title' }; Icon.icon = true; Icon.displayName = 'Folder'; module.exports = exports['default'];
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016, 2017, 2018 Guenter Bartsch # # 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 very simple console chatbot zamia ai demo # import os import sys import traceback import logging import datetime import codecs import readline from builtins import input from optparse import OptionParser from zamiaai.ai_kernal import AIKernal, AIContext, USER_PREFIX, LANGUAGES from nltools import misc from nltools.tokenizer import tokenize PROC_TITLE = 'chatbot' # # init # misc.init_app(PROC_TITLE) # # command line # parser = OptionParser("usage: %prog [options])") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="enable debug output") (options, args) = parser.parse_args() # # logger # if options.verbose: logging.getLogger().setLevel(logging.DEBUG) logging.getLogger("requests").setLevel(logging.WARNING) else: logging.basicConfig(level=logging.INFO) # # setup AI DB, Kernal and Context # kernal = AIKernal.from_ini_file() for skill in kernal.all_skills: kernal.consult_skill (skill) kernal.setup_nlp_model() ctx = kernal.create_context() logging.debug ('AI kernal initialized.') # # main loop # print(chr(27) + "[2J") while True: user_utt = input ('> ') ai_utt, score, action = kernal.process_input(ctx, user_utt) print('AI : %s' % ai_utt) if action: print(' %s' % repr(action)) print
import torch def kaiming_init(module): classname = module.__class__.__name__ if classname.find('Conv') != -1: torch.nn.init.kaiming_normal_(module.weight, nonlinearity='relu') def weights_init(m): classname = m.__class__.__name__ if "Conv" in classname: try: m.weight.data.normal_(0.0, 0.02) except: pass elif "BatchNorm" in classname: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) def load_checkpoint(net, checkpoint): from collections import OrderedDict temp = OrderedDict() if 'state_dict' in checkpoint: checkpoint = dict(checkpoint['state_dict']) for k in checkpoint: k2 = 'module.'+k if not k.startswith('module.') else k temp[k2] = checkpoint[k] net.load_state_dict(temp, strict=True)
 CKEDITOR.lang['is']={"editor":"Rich Text Editor","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"Press ALT 0 for help","browseServer":"Fletta í skjalasafni","url":"Vefslóð","protocol":"Samskiptastaðall","upload":"Senda upp","uploadSubmit":"Hlaða upp","image":"Setja inn mynd","flash":"Flash","form":"Setja inn innsláttarform","checkbox":"Setja inn hökunarreit","radio":"Setja inn valhnapp","textField":"Setja inn textareit","textarea":"Setja inn textasvæði","hiddenField":"Setja inn falið svæði","button":"Setja inn hnapp","select":"Setja inn lista","imageButton":"Setja inn myndahnapp","notSet":"<ekkert valið>","id":"Auðkenni","name":"Nafn","langDir":"Lesstefna","langDirLtr":"Frá vinstri til hægri (LTR)","langDirRtl":"Frá hægri til vinstri (RTL)","langCode":"Tungumálakóði","longDescr":"Nánari lýsing","cssClass":"Stílsniðsflokkur","advisoryTitle":"Titill","cssStyle":"Stíll","ok":"Í lagi","cancel":"Hætta við","close":"Close","preview":"Forskoða","resize":"Resize","generalTab":"Almennt","advancedTab":"Tæknilegt","validateNumberFailed":"This value is not a number.","confirmNewPage":"Any unsaved changes to this content will be lost. Are you sure you want to load new page?","confirmCancel":"You have changed some options. Are you sure you want to close the dialog window?","options":"Options","target":"Mark","targetNew":"New Window (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Same Window (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"Frá vinstri til hægri (LTR)","langDirRTL":"Frá hægri til vinstri (RTL)","styles":"Stíll","cssClasses":"Stílsniðsflokkur","width":"Breidd","height":"Hæð","align":"Jöfnun","alignLeft":"Vinstri","alignRight":"Hægri","alignCenter":"Miðjað","alignJustify":"Jafna báðum megin","alignTop":"Efst","alignMiddle":"Miðjuð","alignBottom":"Neðst","alignNone":"None","invalidValue":"Invalid value.","invalidHeight":"Height must be a number.","invalidWidth":"Width must be a number.","invalidCssLength":"Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, unavailable</span>"},"about":{"copy":"Copyright &copy; $1. All rights reserved.","dlgTitle":"About CKEditor","help":"Check $1 for help.","moreInfo":"For licensing information please visit our web site:","title":"About CKEditor","userGuide":"CKEditor User's Guide"},"basicstyles":{"bold":"Feitletrað","italic":"Skáletrað","strike":"Yfirstrikað","subscript":"Niðurskrifað","superscript":"Uppskrifað","underline":"Undirstrikað"},"blockquote":{"toolbar":"Inndráttur"},"clipboard":{"copy":"Afrita","copyError":"Öryggisstillingar vafrans þíns leyfa ekki afritun texta með músaraðgerð. Notaðu lyklaborðið í afrita (Ctrl/Cmd+C).","cut":"Klippa","cutError":"Öryggisstillingar vafrans þíns leyfa ekki klippingu texta með músaraðgerð. Notaðu lyklaborðið í klippa (Ctrl/Cmd+X).","paste":"Líma","pasteArea":"Paste Area","pasteMsg":"Límdu í svæðið hér að neðan og (<STRONG>Ctrl/Cmd+V</STRONG>) og smelltu á <STRONG>OK</STRONG>.","securityMsg":"Vegna öryggisstillinga í vafranum þínum fær ritillinn ekki beinan aðgang að klippuborðinu. Þú verður að líma innihaldið aftur inn í þennan glugga.","title":"Líma"},"contextmenu":{"options":"Context Menu Options"},"button":{"selectedLabel":"%1 (Selected)"},"toolbar":{"toolbarCollapse":"Collapse Toolbar","toolbarExpand":"Expand Toolbar","toolbarGroups":{"document":"Document","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"Editor toolbars"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"format":{"label":"Stílsnið","panelTitle":"Stílsnið","tag_address":"Vistfang","tag_div":"Venjulegt (DIV)","tag_h1":"Fyrirsögn 1","tag_h2":"Fyrirsögn 2","tag_h3":"Fyrirsögn 3","tag_h4":"Fyrirsögn 4","tag_h5":"Fyrirsögn 5","tag_h6":"Fyrirsögn 6","tag_p":"Venjulegt letur","tag_pre":"Forsniðið"},"horizontalrule":{"toolbar":"Lóðrétt lína"},"image":{"alt":"Baklægur texti","border":"Rammi","btnUpload":"Hlaða upp","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"Vinstri bil","img2Button":"Do you want to transform the selected image on a image button?","infoTab":"Almennt","linkTab":"Stikla","lockRatio":"Festa stærðarhlutfall","menu":"Eigindi myndar","resetSize":"Reikna stærð","title":"Eigindi myndar","titleButton":"Eigindi myndahnapps","upload":"Hlaða upp","urlMissing":"Image source URL is missing.","vSpace":"Hægri bil","validateBorder":"Border must be a whole number.","validateHSpace":"HSpace must be a whole number.","validateVSpace":"VSpace must be a whole number."},"indent":{"indent":"Minnka inndrátt","outdent":"Auka inndrátt"},"fakeobjects":{"anchor":"Anchor","flash":"Flash Animation","hiddenfield":"Hidden Field","iframe":"IFrame","unknown":"Unknown Object"},"link":{"acccessKey":"Skammvalshnappur","advanced":"Tæknilegt","advisoryContentType":"Tegund innihalds","advisoryTitle":"Titill","anchor":{"toolbar":"Stofna/breyta kaflamerki","menu":"Eigindi kaflamerkis","title":"Eigindi kaflamerkis","name":"Nafn bókamerkis","errorName":"Sláðu inn nafn bókamerkis!","remove":"Remove Anchor"},"anchorId":"Eftir auðkenni einingar","anchorName":"Eftir akkerisnafni","charset":"Táknróf","cssClasses":"Stílsniðsflokkur","emailAddress":"Netfang","emailBody":"Meginmál","emailSubject":"Efni","id":"Auðkenni","info":"Almennt","langCode":"Lesstefna","langDir":"Lesstefna","langDirLTR":"Frá vinstri til hægri (LTR)","langDirRTL":"Frá hægri til vinstri (RTL)","menu":"Breyta stiklu","name":"Nafn","noAnchors":"<Engin bókamerki á skrá>","noEmail":"Sláðu inn netfang!","noUrl":"Sláðu inn veffang stiklunnar!","other":"<annar>","popupDependent":"Háð venslum (Netscape)","popupFeatures":"Eigindi sprettiglugga","popupFullScreen":"Heilskjár (IE)","popupLeft":"Fjarlægð frá vinstri","popupLocationBar":"Fanglína","popupMenuBar":"Vallína","popupResizable":"Resizable","popupScrollBars":"Skrunstikur","popupStatusBar":"Stöðustika","popupToolbar":"Verkfærastika","popupTop":"Fjarlægð frá efri brún","rel":"Relationship","selectAnchor":"Veldu akkeri","styles":"Stíll","tabIndex":"Raðnúmer innsláttarreits","target":"Mark","targetFrame":"<rammi>","targetFrameName":"Nafn markglugga","targetPopup":"<sprettigluggi>","targetPopupName":"Nafn sprettiglugga","title":"Stikla","toAnchor":"Bókamerki á þessari síðu","toEmail":"Netfang","toUrl":"Vefslóð","toolbar":"Stofna/breyta stiklu","type":"Stikluflokkur","unlink":"Fjarlægja stiklu","upload":"Senda upp"},"list":{"bulletedlist":"Punktalisti","numberedlist":"Númeraður listi"},"magicline":{"title":"Insert paragraph here"},"maximize":{"maximize":"Maximize","minimize":"Minimize"},"pastetext":{"button":"Líma sem ósniðinn texta","title":"Líma sem ósniðinn texta"},"pastefromword":{"confirmCleanup":"The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?","error":"It was not possible to clean up the pasted data due to an internal error","title":"Líma úr Word","toolbar":"Líma úr Word"},"removeformat":{"toolbar":"Fjarlægja snið"},"sourcearea":{"toolbar":"Kóði"},"specialchar":{"options":"Special Character Options","title":"Velja tákn","toolbar":"Setja inn merki"},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"stylescombo":{"label":"Stílflokkur","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"Breidd ramma","caption":"Titill","cell":{"menu":"Reitur","insertBefore":"Skjóta inn reiti fyrir aftan","insertAfter":"Skjóta inn reiti fyrir framan","deleteCell":"Fella reit","merge":"Sameina reiti","mergeRight":"Sameina til hægri","mergeDown":"Sameina niður á við","splitHorizontal":"Kljúfa reit lárétt","splitVertical":"Kljúfa reit lóðrétt","title":"Cell Properties","cellType":"Cell Type","rowSpan":"Rows Span","colSpan":"Columns Span","wordWrap":"Word Wrap","hAlign":"Horizontal Alignment","vAlign":"Vertical Alignment","alignBaseline":"Baseline","bgColor":"Background Color","borderColor":"Border Color","data":"Data","header":"Header","yes":"Yes","no":"No","invalidWidth":"Cell width must be a number.","invalidHeight":"Cell height must be a number.","invalidRowSpan":"Rows span must be a whole number.","invalidColSpan":"Columns span must be a whole number.","chooseColor":"Choose"},"cellPad":"Reitaspássía","cellSpace":"Bil milli reita","column":{"menu":"Dálkur","insertBefore":"Skjóta inn dálki vinstra megin","insertAfter":"Skjóta inn dálki hægra megin","deleteColumn":"Fella dálk"},"columns":"Dálkar","deleteTable":"Fella töflu","headers":"Fyrirsagnir","headersBoth":"Hvort tveggja","headersColumn":"Fyrsti dálkur","headersNone":"Engar","headersRow":"Fyrsta röð","invalidBorder":"Border size must be a number.","invalidCellPadding":"Cell padding must be a positive number.","invalidCellSpacing":"Cell spacing must be a positive number.","invalidCols":"Number of columns must be a number greater than 0.","invalidHeight":"Table height must be a number.","invalidRows":"Number of rows must be a number greater than 0.","invalidWidth":"Table width must be a number.","menu":"Eigindi töflu","row":{"menu":"Röð","insertBefore":"Skjóta inn röð fyrir ofan","insertAfter":"Skjóta inn röð fyrir neðan","deleteRow":"Eyða röð"},"rows":"Raðir","summary":"Áfram","title":"Eigindi töflu","toolbar":"Tafla","widthPc":"prósent","widthPx":"myndeindir","widthUnit":"width unit"},"undo":{"redo":"Hætta við afturköllun","undo":"Afturkalla"},"wsc":{"btnIgnore":"Hunsa","btnIgnoreAll":"Hunsa allt","btnReplace":"Skipta","btnReplaceAll":"Skipta öllu","btnUndo":"Til baka","changeTo":"Tillaga","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Villuleit ekki sett upp.<br>Viltu setja hana upp?","manyChanges":"Villuleit lokið: %1 orðum breytt","noChanges":"Villuleit lokið: Engu orði breytt","noMispell":"Villuleit lokið: Engin villa fannst","noSuggestions":"- engar tillögur -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Ekki í orðabókinni","oneChange":"Villuleit lokið: Einu orði breytt","progress":"Villuleit í gangi...","title":"Spell Checker","toolbar":"Villuleit"}};
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { HotTableComponent, HotColumnComponent, HotTableRegisterer, HotSettingsResolver, HotTableModule } from './public_api'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGFuZHNvbnRhYmxlLWFuZ3VsYXIuanMiLCJzb3VyY2VSb290Ijoibmc6Ly9AaGFuZHNvbnRhYmxlL2FuZ3VsYXIvIiwic291cmNlcyI6WyJoYW5kc29udGFibGUtYW5ndWxhci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBSUEsK0dBQWMsY0FBYyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBHZW5lcmF0ZWQgYnVuZGxlIGluZGV4LiBEbyBub3QgZWRpdC5cbiAqL1xuXG5leHBvcnQgKiBmcm9tICcuL3B1YmxpY19hcGknO1xuIl19
const c = {} if(process.env.NODE_ENV === 'production'){ c.protocol = '' c.host = '/api/courier' c.port = '' } if(process.env.NODE_ENV === 'development'){ c.protocol = 'http://' c.host = '192.168.0.41/api/courier' c.port = '' } const baseUrl = `${c.protocol}${c.host}${c.port}` export const apiMachinesUrl = `${baseUrl}` export const apiMenuUrl = `${baseUrl}` export const apiUserUrl = `${baseUrl}` export const apiAuthUrl = `${baseUrl}` export const apiConfigAppUrl = `infotoria:`
const { Project, Writers } = require('ts-morph'); const fetch = require('node-fetch'); const { endpoints } = require('pokedex-promise-v2/src/endpoints'); const { rootEndpoints } = require('pokedex-promise-v2/src/rootEndpoints'); const docList = [ 'berries', 'contests', 'encounters', 'evolution', 'games', 'items', 'locations', 'machines', 'moves', 'pokemon', 'resource-lists', 'utility', ]; const skips = ['APIResource', 'APIResourceList', 'NamedAPIResource', 'NamedAPIResourceList']; const apiList = []; function convertType(type) { let result; if (type.type === 'list') { result = `${convertType(type.of)}[]`; } else if (type.type) { result = `${type.type}<${convertType(type.of)}>`; } else if (type === 'integer') { result = 'number'; } else { result = type; } return result; } // find nullable (based on examples, not accurate) function findNullable(response, model, api) { if (!response) { return; } if (Array.isArray(response) && response.length > 0) { return findNullable(response[0], model, api); } for (const [key, data] of Object.entries(response)) { const field = model.fields.find(field => field.name === key); if (!field) { console.warn(`field: ${key} not found in api ${api.name}`); continue; } if (data === null) { field.nullable = true; continue; } if (Array.isArray(data) && data.length > 0) { const model = api.responseModels.find(model => model.name === field.type.of); if (model) { findNullable(data[0], model, api); } } if (typeof data === 'object') { const model = api.responseModels.find(model => model.name === field.type); if (model) { findNullable(data, model, api); } } } } async function loadDocument(namespace, docName) { const response = await fetch(`https://raw.githubusercontent.com/PokeAPI/pokeapi.co/master/src/docs/${docName}.json`); const apis = await response.json(); for (const api of apis) { findNullable(api.exampleResponse, api.responseModels[0], api); for (const [index, model] of api.responseModels.entries()) { if (skips.includes(model.name)) { continue; } const interface = namespace.addInterface({ name: model.name, }); if (index === 0) { interface.addJsDoc({ description: api.description, }); } for (const field of model.fields) { interface.addProperty({ name: field.name, type: field.nullable ? Writers.unionType(convertType(field.type), 'null') : convertType(field.type), }).addJsDoc({ description: field.description, }); } } } apiList.push(...apis); } async function produceDefinition() { const project = new Project(); const file = project.createSourceFile('index.d.ts', `// Type definitions for pokedex-promise-v2 v3.x // Project: https://github.com/PokeAPI/pokedex-promise-v2 // Definitions by: Mudkip <https://github.com/mudkipme/> // Definitions: https://github.com/mudkipme/pokeapi-v2-typescript`, { overwrite: true, }); const module = file.addNamespace({ name: '"pokedex-promise-v2"', }); module.addInterface({ name: 'APIResourceURL', extends: 'String', typeParameters: 'T' }); const namespace = module.addNamespace({ name: 'PokeAPI', }); namespace.addInterface({ name: 'APIResource', typeParameters: 'T', properties: [{ name: 'url', type: 'APIResourceURL<T>', }], }); namespace.addInterface({ name: 'NamedAPIResource', typeParameters: 'T', properties: [{ name: 'name', type: 'string', }, { name: 'url', type: 'APIResourceURL<T>', }], }); namespace.addInterface({ name: 'APIResourceList', typeParameters: 'T', properties: [{ name: 'count', type: 'number', }, { name: 'next', type: Writers.unionType('APIResourceURL<APIResourceList<T>>', 'null'), }, { name: 'previous', type: Writers.unionType('APIResourceURL<APIResourceList<T>>', 'null'), }, { name: 'results', type: 'APIResource<T>[]', }], }); namespace.addInterface({ name: 'NamedAPIResourceList', typeParameters: 'T', properties: [{ name: 'count', type: 'number', }, { name: 'next', type: Writers.unionType('APIResourceURL<NamedAPIResourceList<T>>', 'null'), }, { name: 'previous', type: Writers.unionType('APIResourceURL<NamedAPIResourceList<T>>', 'null'), }, { name: 'results', type: 'NamedAPIResource<T>[]', }], }); for (const docName of docList) { await loadDocument(namespace, docName); } module.addInterface({ name: 'PokeAPIOptions', properties: [{ name: 'protocol', type: Writers.unionType('"https"', '"http"'), hasQuestionToken: true, }, { name: 'hostName', type: 'string', hasQuestionToken: true, }, { name: 'versionPath', type: 'string', hasQuestionToken: true, }, { name: 'cacheLimit', type: 'number', hasQuestionToken: true, }, { name: 'timeout', type: 'number', hasQuestionToken: true, }], }); module.addInterface({ name: 'RootEndPointInterval', properties: [{ name: 'limit', type: 'number', hasQuestionToken: true, },{ name: 'offset', type: 'number', hasQuestionToken: true, }], }); const apiMap = {}; for (const api of apiList) { if (api.exampleRequest?.match(/^\/v2\/([\w-]+)\/\{[\w\s]+\}\/$/)) { apiMap[api.exampleRequest.match(/^\/v2\/([\w-]+)/)[1]] = api; } } module.addInterface({ name: 'EndPointResult', properties: endpoints.map(([_, apiName]) => ({ name: `"${apiName}"`, type: `APIResourceURL<PokeAPI.${Object.keys(apiMap[apiName].exampleResponse).includes('name') ? 'NamedAPIResourceList' : 'APIResourceList'}<PokeAPI.${apiMap[apiName].responseModels[0].name}>>`, })), }); const cls = module.addClass({ name: 'PokeAPI', }); cls.addConstructor({ parameters: [{ name: 'options', type: 'PokeAPIOptions', hasQuestionToken: true, }], }); cls.addMethod({ name: 'resource', parameters: [{ name: 'path', type: 'string', }], returnType: 'Promise<unknown>', }); cls.addMethod({ name: 'resource', parameters: [{ name: 'paths', type: 'string[]', }], returnType: 'Promise<unknown[]>', }); cls.addMethod({ name: 'resource', typeParameters: 'T', parameters: [{ name: 'path', type: 'APIResourceURL<T>', }], returnType: 'Promise<T>', }); cls.addMethod({ name: 'resource', typeParameters: 'T', parameters: [{ name: 'paths', type: 'APIResourceURL<T>[]', }], returnType: 'Promise<T[]>', }); for (const [method, apiName] of endpoints) { cls.addMethod({ name: method, parameters: [{ name: method.match(/ByName$/) ? 'nameOrId' : 'id', type: method.match(/ByName$/) ? Writers.unionType('string', 'number') : 'number', }], returnType: `Promise<PokeAPI.${apiMap[apiName].responseModels[0].name}>`, }); cls.addMethod({ name: method, parameters: [{ name: method.match(/ByName$/) ? 'nameOrIds' : 'ids', type: method.match(/ByName$/) ? 'Array<string | number>' : 'number[]', }], returnType: `Promise<PokeAPI.${apiMap[apiName].responseModels[0].name}[]>`, }); } cls.addMethod({ name: 'getEndpointsList', returnType: 'EndPointResult', }); for (const [method, path] of rootEndpoints) { const apiName = path.replace(/\/$/, ''); if (!apiMap[apiName]) { continue; } cls.addMethod({ name: method, parameters: [{ name: 'interval', type: 'RootEndPointInterval', hasQuestionToken: true, }], returnType: `Promise<PokeAPI.${Object.keys(apiMap[apiName].exampleResponse).includes('name') ? 'NamedAPIResourceList' : 'APIResourceList'}<PokeAPI.${apiMap[apiName].responseModels[0].name}>>`, }); } module.addExportAssignment({ expression: 'PokeAPI', }); await file.save(); } produceDefinition().catch(e => console.warn(e));
const path = require('path'); const webpack = require('webpack'); const merge = require('webpack-merge'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const TARGET = process.env.npm_lifecycle_event; const PATHS = { app: path.join(__dirname, 'app'), build: path.join(__dirname, 'build'), vendor: path.join(__dirname, 'app/vendor') }; const common = { entry: { index: ['babel-polyfill', './app/app.jsx'], vendor: [ 'react', 'react-dom', 'react-router-dom', 'react-redux', 'react-intl', 'redux', 'redux-promise', 'redux-thunk', 'redux-logger' ], custom_elements_vendor: [ `${PATHS.vendor}/custom-elements-es5-adapter.js` ] }, resolve: { extensions: ['.js', '.jsx'] }, output: { path: PATHS.build, filename: '[name].js' }, devtool: 'source-map', module: { rules: [ { test: /\.js$/, use: 'babel-loader', // TODO: for own project replace to /node_modules/ // Exclude app.jsx for npm as we use a module in node_modules that is JSX. // babel-loader is excluding it so it doesn't read it, // we make an exception for that package in that regex (whitelist or blacklist) // For more details please see issues - https://github.com/babel/babel-loader/issues/530 exclude: /node_modules\/(?!(app)\/).*/, include: PATHS.app }, { test: /\.jsx$/, use: 'babel-loader', exclude: /node_modules\/(?!(app)\/).*/, include: PATHS.app } ] }, externals: { 'jquery': 'jQuery' } }; if (TARGET === 'dev' || TARGET === 'fast-start' || !TARGET) { module.exports = common; } if (TARGET === 'prod' || TARGET === 'staging') { module.exports = merge(common, { optimization: { minimize: true, minimizer: [ new UglifyJsPlugin({ sourceMap: false }) ], splitChunks: { cacheGroups: { vendor: { chunks: 'initial', name: 'vendor', test: 'vendor', enforce: true } } } }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }) ] }); }
const schema = require('../../mongoose/prefix'); // Defining the schema module.exports = { name: 'setprefix', aliases: [], description: 'This will allow you to set the prefix for the message guild, this will update the prefix so all commands work with that prefix instead of \`>\`.', category: 'config', dmOnly: false, // Boolean guildOnly: true, // Boolean args: true, // Boolean usage: '{prefix}setprefix <prefix>', cooldown: 10, //seconds(s) guarded: false, // Boolean permissions: ['ADMINISTRATOR'], run: async ({ message, args, prefix }) => { const newPrefix = args[0]; if (!newPrefix || newPrefix === prefix) return message.channel.send('Please make sure you provide a **new** prefix!'); // If they don't provide a prefix or they try use the same prefix then this will be sent. try { await schema.findOneAndUpdate({ GuildID: message.guild.id }, { GuildID: message.guild.id, GuildName: message.guild.name, Prefix: newPrefix }, { upsert: true }); // Saving the data to the database, we use upsert: true for incase there is no data. } catch (err) { console.log(err); return message.channel.send('An error occured whilst saving the prefix, please try again!'); } message.channel.send(`${guild.name}'s prefix has now been set to \`${newPrefix}\``); } }
import argparse import os import os.path as osp import shutil import tempfile import mmcv import torch import torch.distributed as dist from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, load_checkpoint from mmdet.apis import init_dist from mmdet.core import coco_eval, results2json, wrap_fp16_model from mmdet.datasets import build_dataloader, build_dataset from mmdet.models import build_detector def single_gpu_test(model, data_loader, show=False): model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=not show, **data) results.append(result) if show: model.module.show_result(data, result, dataset.img_norm_cfg) batch_size = data['img'][0].size(0) for _ in range(batch_size): prog_bar.update() return results def multi_gpu_test(model, data_loader, tmpdir=None): model.eval() results = [] dataset = data_loader.dataset rank, world_size = get_dist_info() if rank == 0: prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) results.append(result) if rank == 0: batch_size = data['img'][0].size(0) for _ in range(batch_size * world_size): prog_bar.update() # collect results from all ranks results = collect_results(results, len(dataset), tmpdir) return results def collect_results(result_part, size, tmpdir=None): rank, world_size = get_dist_info() # create a tmp dir if it is not specified if tmpdir is None: MAX_LEN = 512 # 32 is whitespace dir_tensor = torch.full((MAX_LEN, ), 32, dtype=torch.uint8, device='cuda') if rank == 0: tmpdir = tempfile.mkdtemp() tmpdir = torch.tensor( bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda') dir_tensor[:len(tmpdir)] = tmpdir dist.broadcast(dir_tensor, 0) tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip() else: mmcv.mkdir_or_exist(tmpdir) # dump the part result to the dir mmcv.dump(result_part, osp.join(tmpdir, 'part_{}.pkl'.format(rank))) dist.barrier() # collect all parts if rank != 0: return None else: # load results of all parts from tmp dir part_list = [] for i in range(world_size): part_file = osp.join(tmpdir, 'part_{}.pkl'.format(i)) part_list.append(mmcv.load(part_file)) # sort the results ordered_results = [] for res in zip(*part_list): ordered_results.extend(list(res)) # the dataloader may pad some samples ordered_results = ordered_results[:size] # remove tmp dir shutil.rmtree(tmpdir) return ordered_results def parse_args(): parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', default='./result.pkl',help='output result file') parser.add_argument( '--json_out', default='./result.pkl.bbox', help='output result file name without extension', type=str) parser.add_argument( '--eval', type=str, nargs='+', choices=['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'], default=['bbox'], help='eval types') parser.add_argument('--show', action='store_true', help='show results') parser.add_argument('--tmpdir', help='tmp dir for writing some results') parser.add_argument( '--launcher', choices=['none', 'pytorch', 'slurm', 'mpi'], default='none', help='job launcher') parser.add_argument('--local_rank', type=int, default=0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def main(): args = parse_args() assert args.out or args.show or args.json_out, \ ('Please specify at least one operation (save or show the results) ' 'with the argument "--out" or "--show" or "--json_out"') if args.out is not None and not args.out.endswith(('.pkl', '.pickle')): raise ValueError('The output file must be a pkl file.') if args.json_out is not None and args.json_out.endswith('.json'): args.json_out = args.json_out[:-5] cfg = mmcv.Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None cfg.data.test.test_mode = True # init distributed env first, since logger depends on the dist info. if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) # build the dataloader # TODO: support multiple images per gpu (only minor changes are needed) dataset = build_dataset(cfg.data.test) data_loader = build_dataloader( dataset, imgs_per_gpu=1, workers_per_gpu=cfg.data.workers_per_gpu, dist=distributed, shuffle=False) # build the model and load checkpoint model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg) fp16_cfg = cfg.get('fp16', None) if fp16_cfg is not None: wrap_fp16_model(model) checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu') # old versions did not save class info in checkpoints, this walkaround is # for backward compatibility if 'CLASSES' in checkpoint['meta']: model.CLASSES = checkpoint['meta']['CLASSES'] else: model.CLASSES = dataset.CLASSES if not distributed: model = MMDataParallel(model, device_ids=[0]) outputs = single_gpu_test(model, data_loader, args.show) else: model = MMDistributedDataParallel(model.cuda()) outputs = multi_gpu_test(model, data_loader, args.tmpdir) rank, _ = get_dist_info() if args.out and rank == 0: print('\nwriting results to {}'.format(args.out)) mmcv.dump(outputs, args.out) eval_types = args.eval if eval_types: print('Starting evaluate {}'.format(' and '.join(eval_types))) if eval_types == ['proposal_fast']: result_file = args.out coco_eval(result_file, eval_types, dataset.coco) else: if not isinstance(outputs[0], dict): result_files = results2json(dataset, outputs, args.out) coco_eval(result_files, eval_types, dataset.coco) else: for name in outputs[0]: print('\nEvaluating {}'.format(name)) outputs_ = [out[name] for out in outputs] result_file = args.out + '.{}'.format(name) result_files = results2json(dataset, outputs_, result_file) coco_eval(result_files, eval_types, dataset.coco) # Save predictions in the COCO json format if args.json_out and rank == 0: if not isinstance(outputs[0], dict): results2json(dataset, outputs, args.json_out) else: for name in outputs[0]: outputs_ = [out[name] for out in outputs] result_file = args.json_out + '.{}'.format(name) results2json(dataset, outputs_, result_file) if __name__ == '__main__': main()
import json import sys def read_arguments(): l = len(sys.argv) if (l != 4): raise Exception("There must be three of arguments \ \"python FNdwithjson.py input.json output.json words_len\"" + "\n ther are " + str(l) + " of arguments.") input_file_name = sys.argv[1] output_file_name = sys.argv[2] try: words_len = int(sys.argv[3]) except: raise Exception("Third argument must be a integer.") return input_file_name, output_file_name, words_len if __name__ == "__main__": print("This is core mock program") input_file_name, output_file_name, words_len = read_arguments() output = { 'TF': "mock-tf", 'Score': 13, 'Words': ["mock-words"], 'Weights': [1.23, 1.4233] } with open(output_file_name, "w", encoding="utf-8") as f: json.dump(output, f)
'use strict'; const _ = require('lodash'); const proxyquire = require('proxyquire'); const App = require('lib/gui/app'); const {stubTool} = require('../../utils'); describe('lib/gui/server', () => { const sandbox = sinon.createSandbox(); let server; let expressStub; let bodyParserStub; let staticMiddleware; const mkExpressApp_ = () => ({ use: sandbox.stub(), get: sandbox.stub(), post: sandbox.stub(), listen: sandbox.stub().callsArg(2), static: sandbox.stub() }); const mkApi_ = () => ({initServer: sandbox.stub()}); const startServer = (opts = {}) => { opts = _.defaults(opts, { paths: [], tool: stubTool(), guiApi: mkApi_(), configs: {options: {}, pluginConfig: {path: 'default-path'}} }); return server.start(opts); }; beforeEach(() => { sandbox.stub(App, 'create').returns(Object.create(App.prototype)); sandbox.stub(App.prototype, 'initialize').resolves(); sandbox.stub(App.prototype, 'findEqualDiffs').resolves(); sandbox.stub(App.prototype, 'finalize'); expressStub = mkExpressApp_(); staticMiddleware = sandbox.stub(); bodyParserStub = {json: sandbox.stub()}; server = proxyquire('lib/gui/server', { express: Object.assign(() => expressStub, {static: staticMiddleware}), 'body-parser': bodyParserStub, 'signal-exit': sandbox.stub().yields(), '../server-utils': {logger: {log: sandbox.stub()}} }); }); afterEach(() => sandbox.restore()); it('should init server from api', () => { const guiApi = mkApi_(); return startServer({guiApi}) .then(() => assert.calledOnceWith(guiApi.initServer, expressStub)); }); it('should init server only after body is parsed', () => { const guiApi = mkApi_(); return startServer({guiApi}) .then(() => assert.callOrder(bodyParserStub.json, guiApi.initServer)); }); it('should init server before any static middleware starts', () => { const guiApi = mkApi_(); return startServer({guiApi}) .then(() => assert.callOrder(guiApi.initServer, staticMiddleware)); }); it('should properly complete app working', () => { sandbox.stub(process, 'kill'); return startServer() .then(() => { process.emit('SIGTERM'); assert.calledOnce(App.prototype.finalize); }); }); });
$(function(){ var current = window.location.href; $('ul.navbar-nav li a').each(function(){ var $this = $(this); if($this.attr('href') == current) { $this.parents('li').addClass('active'); } }); });
const express = require('express'); const app = express(); const port = 3000; app.use(express.static('public')); app.use(express.json()); app.set('view engine', 'pug'); app.get('/', (req, res) => { res.render('index') }) app.listen(3000, () => { console.log(`Listening to Port ${port}`); })
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class MultiSelect extends Component { constructor(props) { super(props); this.state = { data: this.props.options, checkedItems: {}, }; } componentDidMount() { this.props.onFocus(); } static getDerivedStateFromProps(nextProps) { let valuesPart = nextProps.selectedItems !== null ? nextProps.selectedItems.values : null; let selected = nextProps.selectedItems && Array.isArray(nextProps.selectedItems) ? nextProps.selectedItems : valuesPart; if (selected !== null && typeof selected !== 'undefined') { let updatedCheckedItems = {}; selected.map((item) => { if (item) { updatedCheckedItems[item.key] = { key: item.key, caption: item.caption, value: true, }; } return item; }); return { checkedItems: updatedCheckedItems, }; } return null; } selectItem = (key, caption) => { let selected = null; let newCheckedItems = JSON.parse(JSON.stringify(this.state.checkedItems)); if (typeof this.state.checkedItems[key] === 'undefined') { newCheckedItems[key] = { key, caption, value: true }; } else { newCheckedItems[key].value = !this.state.checkedItems[key].value; } this.setState({ checkedItems: newCheckedItems }); selected = Object.keys(newCheckedItems).map((item) => { if (newCheckedItems[item].value === true) { return { key: newCheckedItems[item].key, caption: newCheckedItems[item].caption, }; } }); this.props.onSelect(selected.filter((el) => typeof el !== 'undefined')); }; render() { const { data, checkedItems } = this.state; const dataSource = data.size > 0 ? data : this.props.options; return ( <div className="filter-multiselect"> <div> {dataSource.map((item) => ( <div className="form-group" key={item.key}> <div key={item.key} className="row"> <div className=" col-sm-6 float-left"> <label className="form-control-label" title={item.caption}> {item.caption} </label> </div> <div className="col-sm-6 float-right"> <label className="input-checkbox"> <input type="checkbox" onChange={() => this.selectItem(item.key, item.caption)} checked={ checkedItems[item.key] ? checkedItems[item.key].value : false } /> <span className="input-checkbox-tick" /> </label> </div> </div> </div> ))} </div> </div> ); } } MultiSelect.propTypes = { options: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), onFocus: PropTypes.func, onSelect: PropTypes.func, selectedItems: PropTypes.any, }; export default MultiSelect;
(function () { $.atoms.create_vm = [ { tag_code: "host", type: "input", attrs: { name: gettext("VC地址"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "username", type: "input", attrs: { name: gettext("VC账号"), placeholder: gettext("必填,VC账号"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "password", type: "input", attrs: { name: gettext("VC密码"), placeholder: gettext("必填,VC密码"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "state", type: "input", attrs: { name: gettext("群集模式"), placeholder: gettext("False/True"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "dc_moId", type: "input", attrs: { name: gettext("dc_moId"), placeholder: gettext("必填,datacenter moId"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "hc_moId", type: "input", attrs: { name: gettext("hc_moId"), placeholder: gettext("必填,独立主机/集群MoId"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "ds_moId", type: "input", attrs: { name: gettext("ds_moId"), placeholder: gettext("必填,存储MoId"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "vs_moId", type: "input", attrs: { name: gettext("vs_moId"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "rp_moId", type: "input", attrs: { name: gettext("资源池"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "vmtemplate_moId", type: "input", attrs: { name: gettext("teme_moId"), placeholder: gettext("必填,模板MoId"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "vm_name", type: "input", attrs: { name: gettext("vm_name"), placeholder: gettext("必填, VC上的机器名称"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "vmtemplate_os", type: "input", attrs: { name: gettext("系统类型"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "cpu", type: "input", attrs: { name: gettext("cpu"), placeholder: gettext("必填,cpu大小"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "mem", type: "input", attrs: { name: gettext("内存"), placeholder: gettext("必填,内存大小"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "mem_re", type: "input", attrs: { name: gettext("预置内存"), placeholder: gettext("必填,内存大小"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "disk_type", type: "input", attrs: { name: gettext("数据盘"), placeholder: gettext("磁盘类型:thin/eager/thick"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "disk_size", type: "input", attrs: { name: gettext("数据盘大小"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "disk_spbm", type: "input", attrs: { name: gettext("存储策略"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "computer_name", type: "input", attrs: { name: gettext("计算机名"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "ip", type: "input", attrs: { name: gettext("ip"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "mask", type: "input", attrs: { name: gettext("子网掩码"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "gateway", type: "input", attrs: { name: gettext("网关"), placeholder: gettext("必填"), hookable: true }, validation: [ { type: "required" } ] }, { tag_code: "dns", type: "input", attrs: { name: gettext("DNS列表"), placeholder: gettext("必填,多个以逗号分割"), hookable: true }, validation: [ { type: "required" } ] } ] })();
const crypto = require('crypto') const jwt = require('jsonwebtoken'); const mail = require('../libs/mail'); const user = require('../models/user'); const dbUser = require('../db/user.db'); const validation = require('../middleware/validation'); const uploadFile = require('../middleware/uploadFile'); async function createNewUser(req, res) { let validate = await validation.createUser(req, res) if (validate) return res.status(400).json({ 'error': validate }) let userFromDataBase = await dbUser.getUserDataBase(req.body); if (userFromDataBase) return res.status(403).json({ 'error': 'user already exists' }) let mailToken = crypto.createHmac('sha256', JSON.stringify(req.body)).digest('hex') let sendMail = await mail.sendMailTo(req.body.email, `http://localhost:3000/api/user/confirm/${mailToken}`) if (!sendMail) return res.status(500).json({ 'error': 'Mail system not working' }) req.body.pw = await user.encryptPassword(req.body.pw) let newUser = new user(Object.assign(req.body, { verificationToken: mailToken })) return res.status(201).json(await newUser.save()) } async function confirmMail(req, res) { let edit = await user.findOneAndUpdate({ verificationToken: req.params.tokenConfirm }, { verificatedUser: true }) if (!edit) return res.status(500).json({ 'error': 'database problems.' }) return res.status(200).json({ 'message': 'user confirmed' }) } async function login(req, res) { let userFromDataBase = await dbUser.getUserDataBase(req.body); if (!userFromDataBase) return res.status(401).json({ 'error': 'user not exists' }) let comparePassword = await user.comparePassword(req.body.pw, userFromDataBase.pw) if (!comparePassword) return res.status(401).json({ 'error': 'wrong password' }) let token = jwt.sign({ 'data': req.body }, process.env.API_KEY || 'algosupersecreto1') if (!token) return res.status(401).json({ 'error': 'wrong auth' }) if (!userFromDataBase.verificatedUser) return res.status(401).json({ 'error': 'need to confirm via mail' }) if (!userFromDataBase.activeProfile) return res.status(401).json({ 'error': 'Banned' }) let cookieData = JSON.stringify({ screenName: userFromDataBase.screenName, email: req.body.email }) res.cookie('userData', cookieData, { expires: new Date(Date.now() + 9000000), httpOnly: true }) req.session.token = token req.session.userInfo = { email: req.body.email, _id: userFromDataBase._id, soundPath: userFromDataBase.soundPath, isAdmin: userFromDataBase.isAdmin } return res.status(200).json({ 'message': 'user acess granted' }) } async function editUser(req, res) { uploadFile.upload(req, res, async (err) => { let validate = await validation.editUser(req, res) if (validate) return res.status(400).json({ 'error': validate }) if (err) return res.status(500).json({ 'error': err.toString().split('Error: ')[1] }) let currentPath = req.file ? `${req.file.destination}/${req.file.filename}` : req.session.userInfo.soundPath let edit = await dbUser.editUserDataBase(req.session.userInfo.email, Object.assign({ 'soundPath': currentPath }, req.body)) if (!edit) return res.status(500).json({ 'error': 'database problems.' }) req.session.userInfo.soundPath = currentPath return res.status(200).json({ 'message': 'data edited' }) }) } async function feed(req, res) { let getFeed = await dbUser.getFeedDataBase('screenName soundPath activeProfile updatedAt -_id', req.session.userInfo.isAdmin) if (!getFeed) return res.status(404).json({ 'error': 'feed could not be found' }) return res.status(200).json(getFeed) } async function me(req, res) { let userFromDataBase = await dbUser.getUserDataBase(req.session.userInfo, 'screenName email soundPath -_id') if (!userFromDataBase) return res.status(500).json({ 'error': 'Something went wrong' }) return res.status(200).json(userFromDataBase) } async function getUser(req, res) { let userFromDataBase = await dbUser.getUserDataBase(req.params, 'screenName activeProfile soundPath -_id') if (!userFromDataBase) return res.status(401).json({ 'error': 'user no exists' }) if (!userFromDataBase.activeProfile) return res.status(200).json({ 'error': 'user banned' }) return res.status(200).json(userFromDataBase) } async function logOut(req, res) { req.session.destroy() res.clearCookie('userData') } module.exports = { createNewUser, login, editUser, feed, confirmMail, me, getUser, logOut }
(function(e){const i=e["hr"]=e["hr"]||{};i.dictionary=Object.assign(i.dictionary||{},{"%0 of %1":"%0 od %1",Aquamarine:"Akvamarin",Big:"Veliki",Black:"Crna","Block quote":"Blok citat",Blue:"Plava",Bold:"Podebljano","Break text":"","Bulleted List":"Obična lista",Cancel:"Poništi","Cannot upload file:":"Datoteku nije moguće poslati:","Centered image":"Centrirana slika","Change image text alternative":"Promijeni alternativni tekst slike","Choose heading":"Odaberite naslov",Code:"Kod",Column:"Kolona","Could not insert image at the current position.":"Nije moguće umetnuti sliku na trenutnu poziciju","Could not obtain resized image URL.":"Nije moguće dohvatiti URL slike s promijenjenom veličinom","Decrease indent":"Umanji uvlačenje",Default:"Podrazumijevano","Delete column":"Obriši kolonu","Delete row":"Obriši red","Dim grey":"Tamnosiva",Downloadable:"Moguće preuzeti","Dropdown toolbar":"Traka padajućeg izbornika","Edit block":"Uredi blok","Edit link":"Uredi vezu","Editor toolbar":"Traka uređivača","Enter image caption":"Unesite naslov slike","Font Size":"Veličina fonta","Full size image":"Slika pune veličine",Green:"Zelena",Grey:"Siva","Header column":"Kolona zaglavlja","Header row":"Red zaglavlja",Heading:"Naslov","Heading 1":"Naslov 1","Heading 2":"Naslov 2","Heading 3":"Naslov 3","Heading 4":"Naslov 4","Heading 5":"Naslov 5","Heading 6":"Naslov 6","Horizontal line":"Vodoravna linija",Huge:"Ogroman","Image toolbar":"Traka za slike","image widget":"Slika widget","In line":"","Increase indent":"Povećaj uvlačenje","Insert column left":"Umetni stupac lijevo","Insert column right":"Umetni stupac desno","Insert image":"Umetni sliku","Insert image or file":"Umetni sliku ili datoteku","Insert media":"Ubaci medij","Insert paragraph after block":"","Insert paragraph before block":"","Insert row above":"Ubaci red iznad","Insert row below":"Ubaci red ispod","Insert table":"Ubaci tablicu","Inserting image failed":"Umetanje slike nije uspjelo",Italic:"Ukošeno","Left aligned image":"Lijevo poravnata slika","Light blue":"Svijetloplava","Light green":"Svijetlozelena","Light grey":"Svijetlosiva",Link:"Veza","Link URL":"URL veze","Media URL":"URL medija","media widget":"dodatak za medije","Merge cell down":"Spoji ćelije prema dolje","Merge cell left":"Spoji ćelije prema lijevo","Merge cell right":"Spoji ćelije prema desno","Merge cell up":"Spoji ćelije prema gore","Merge cells":"Spoji ćelije",Next:"Sljedeći","Numbered List":"Brojčana lista","Open in a new tab":"Otvori u novoj kartici","Open link in new tab":"Otvori vezu u novoj kartici",Orange:"Narančasta",Paragraph:"Paragraf","Paste the media URL in the input.":"Zalijepi URL medija u ulaz.",Previous:"Prethodni",Purple:"Ljubičasta",Red:"Crvena",Redo:"Ponovi","Rich Text Editor":"Rich Text Editor","Rich Text Editor, %0":"Rich Text Editor, %0","Right aligned image":"Slika poravnata desno",Row:"Red",Save:"Snimi","Select all":"Odaberi sve","Select column":"Odaberi stupac","Select row":"Odaberi redak","Selecting resized image failed":"Odabir slike s promijenjenom veličinom nije uspjelo","Show more items":"Prikaži više stavaka","Side image":"Slika sa strane",Small:"Mali","Split cell horizontally":"Razdvoji ćeliju vodoravno","Split cell vertically":"Razdvoji ćeliju okomito","Table toolbar":"Traka za tablice","Text alternative":"Alternativni tekst","The URL must not be empty.":"URL ne smije biti prazan.","This link has no URL":"Ova veza nema URL","This media URL is not supported.":"URL nije podržan.",Tiny:"Sićušan","Tip: Paste the URL into the content to embed faster.":"Natuknica: Za brže ugrađivanje zalijepite URL u sadržaj.","Toggle caption off":"","Toggle caption on":"",Turquoise:"Tirkizna",Underline:"Podcrtavanje",Undo:"Poništi",Unlink:"Ukloni vezu","Upload failed":"Slanje nije uspjelo","Upload in progress":"Slanje u tijeku",White:"Bijela","Widget toolbar":"Traka sa spravicama","Wrap text":"",Yellow:"Žuta"});i.getPluralForm=function(e){return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2}})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
from setuptools import setup import codecs import os.path __dir__ = os.path.dirname(os.path.abspath(__file__)) setup( name='Crowd', license='BSD', py_modules=['crowd'], version='2.0.0', install_requires=['requests', 'lxml'], description='A python client to the Atlassian Crowd REST API', long_description=codecs.open(os.path.join(__dir__, 'README.rst'), encoding='utf-8').read(), author='Alexander Else', author_email='[email protected]', url='https://github.com/pycontribs/python-crowd', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Systems Administration :: Authentication/Directory", ] )
import { fetchUserById, fetchAllProjectUsers, fetchUserProjects, } from "../../src/data-access/api-calls/calls.js"; import ProjectComponent from "/components/project-component.js"; const userProfileProjectsComponent = { components: { ProjectComponent, }, template: ` <div class="user-profile-projects" v-if="projects.length>0"> <h1 class="user-profile-projects-title">My projects</h1> <div class="user-profile-projects-cards"> <template v-for="project in showingProjects"> <project-component :project="project"/> </template> <nav class="projects-nav" aria-label="Page navigation example"> <ul class="projects-pagination"> <li class="projects-pagination--item"> <button class="projects-pagination--item__btn" v-on:click="previousPage" v-bind:disabled="disablePrevious"> Previous</button> </li> {{ pageCount }} <li class="projects-pagination--item"> <button class="projects-pagination--item__btn" v-on:click="nextPage" v-bind:disabled="disableNext"> Next </button> </li> </ul> </nav> </div> </div> `, computed: { showingProjects: function () { // `this` points to the vm instance const startingPosition = (this.pageCount - 1) * 3; return this.projects.slice(startingPosition, startingPosition + 3); }, disablePrevious: function () { return this.pageCount === 1; }, disableNext: function () { const limit = Math.ceil(this.projects.length / 3); return this.pageCount === limit; }, }, data() { return { projects: [], pageCount: 1, }; }, methods: { async getDataOnLoad() { const id = this.getMemberId(); const user = await fetchUserById(id); const result = await fetchUserProjects(id); for (let i = 0; i < result.length; i++) { this.projects.push({ thumbnail: result[i].Thumbnail, github_url: result[i].GithubURL, website_url: result[i].WebsiteURL, title: result[i].Title, description: result[i].Description, members: await fetchAllProjectUsers(result[i].ProjectID), }); } }, getMemberId() { const queryPart = window.location.search; const parts = queryPart.replace("?", "").split("&"); for (let part of parts) { if (part.split("=")[0] === "memberId") { return part.split("=")[1]; } } }, nextPage() { this.pageCount++; }, previousPage() { this.pageCount--; }, }, mounted: function () { this.getDataOnLoad(); }, }; export default userProfileProjectsComponent;
broker_url = 'redis://127.0.0.1:6379/0' broker_pool_limit = 1000 timezone = 'Asia/Shanghai' accept_content = ['pickle', 'json'] task_serializer = 'pickle' result_backend = 'redis://127.0.0.1:6379/0' result_serializer = 'pickle' result_cache_max = 10000 result_expires = 3600 # 任务过期时间 worker_redirect_stdouts_level = 'INFO'
import { MockedProvider } from "@apollo/react-testing"; import { fireEvent, render, wait } from "@testing-library/react"; import React from "react"; import apolloMock from "./apolloMock"; import App from "./App"; import authorsQuery from "./authors.graphql"; import createAuthorMutation from "./createAuthor.graphql"; test("adds author", async () => { const mocks = [ apolloMock(authorsQuery, {}, { data: { authors: [] } }), apolloMock( createAuthorMutation, { input: { name: "Foo", books: [{ title: "Bar" }] } }, { data: { createAuthor: { name: "Foo", books: [{ title: "Bar" }] } } } ), apolloMock( authorsQuery, {}, { data: { authors: [{ name: "Foo", books: [{ title: "Bar" }] }] } } ), ]; const { getByText } = render( <MockedProvider mocks={mocks}> <App /> </MockedProvider> ); fireEvent.click(getByText("Add")); await wait(() => { expect(getByText("Foo")).toBeInTheDocument(); }); });
import React from "react"; import { useDispatch } from "react-redux"; import Filters from "../components/Filters"; import LaunchList from "../components/LaunchList"; import getPosts from "../Api/Api"; const Home = () => { const [filters, setFilters] = React.useState({ launchDate: "", launchStatus: "", upcoming: false, }); const [rocketName, setRocketName] = React.useState(""); const dispatch = useDispatch(); const searchByRocketName = (e) => { e.preventDefault(); dispatch(getPosts(rocketName)); }; React.useEffect(() => { dispatch(getPosts()); }, [dispatch]); return ( <div className="container d-flex flex-column align-items-center justify-content-center mt-4 mb-4"> <Filters filters={filters} setFilters={setFilters} setRocketName={setRocketName} searchByRocketName={searchByRocketName} /> <LaunchList filters={filters} /> </div> ); }; export default Home;
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy.types import String, Integer, Boolean, Text, Date from webapp.libs.mediahelper import MediaHelper Base = declarative_base() class Schedule(Base): __tablename__ = "schedule" schedule_id = Column(Integer, primary_key=True) date = Column("dt", Date, nullable=False) content = Column(Text, nullable=False) enabled = Column(Boolean) def __init__(self, schedule_id=None, date=None, content=None, enabled=None): Base.__init__(self) self.schedule_id = schedule_id self.date = date self.content = content self.enabled = enabled
# Copyright The PyTorch Lightning team. # # 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. import pickle from argparse import ArgumentParser from unittest.mock import MagicMock from typing import Optional import pytest import torch from torch.utils.data import DataLoader, random_split from pytorch_lightning import LightningDataModule, Trainer, seed_everything from tests.base import EvalModelTemplate from tests.base.datasets import TrialMNIST from tests.base.datamodules import TrialMNISTDataModule from tests.base.develop_utils import reset_seed from pytorch_lightning.utilities.model_utils import is_overridden from pytorch_lightning.accelerators.gpu_accelerator import GPUAccelerator from pytorch_lightning.callbacks import ModelCheckpoint def test_can_prepare_data(tmpdir): dm = TrialMNISTDataModule() trainer = Trainer() trainer.datamodule = dm # 1 no DM # prepare_data_per_node = True # local rank = 0 (True) trainer.prepare_data_per_node = True trainer.local_rank = 0 assert trainer.data_connector.can_prepare_data() # local rank = 1 (False) trainer.local_rank = 1 assert not trainer.data_connector.can_prepare_data() # prepare_data_per_node = False (prepare across all nodes) # global rank = 0 (True) trainer.prepare_data_per_node = False trainer.node_rank = 0 trainer.local_rank = 0 assert trainer.data_connector.can_prepare_data() # global rank = 1 (False) trainer.node_rank = 1 trainer.local_rank = 0 assert not trainer.data_connector.can_prepare_data() trainer.node_rank = 0 trainer.local_rank = 1 assert not trainer.data_connector.can_prepare_data() # 2 dm # prepar per node = True # local rank = 0 (True) trainer.prepare_data_per_node = True trainer.local_rank = 0 # is_overridden prepare data = True # has been called # False dm._has_prepared_data = True assert not trainer.data_connector.can_prepare_data() # has not been called # True dm._has_prepared_data = False assert trainer.data_connector.can_prepare_data() # is_overridden prepare data = False # True dm.prepare_data = None assert trainer.data_connector.can_prepare_data() def test_hooks_no_recursion_error(tmpdir): # hooks were appended in cascade every tine a new data module was instantiated leading to a recursion error. # See https://github.com/PyTorchLightning/pytorch-lightning/issues/3652 class DummyDM(LightningDataModule): def setup(self, *args, **kwargs): pass def prepare_data(self, *args, **kwargs): pass for i in range(1005): dm = DummyDM() dm.setup() dm.prepare_data() def test_base_datamodule(tmpdir): dm = TrialMNISTDataModule() dm.prepare_data() dm.setup() def test_base_datamodule_with_verbose_setup(tmpdir): dm = TrialMNISTDataModule() dm.prepare_data() dm.setup('fit') dm.setup('test') def test_data_hooks_called(tmpdir): dm = TrialMNISTDataModule() assert dm.has_prepared_data is False assert dm.has_setup_fit is False assert dm.has_setup_test is False dm.prepare_data() assert dm.has_prepared_data is True assert dm.has_setup_fit is False assert dm.has_setup_test is False dm.setup() assert dm.has_prepared_data is True assert dm.has_setup_fit is True assert dm.has_setup_test is True def test_data_hooks_called_verbose(tmpdir): dm = TrialMNISTDataModule() assert dm.has_prepared_data is False assert dm.has_setup_fit is False assert dm.has_setup_test is False dm.prepare_data() assert dm.has_prepared_data is True assert dm.has_setup_fit is False assert dm.has_setup_test is False dm.setup('fit') assert dm.has_prepared_data is True assert dm.has_setup_fit is True assert dm.has_setup_test is False dm.setup('test') assert dm.has_prepared_data is True assert dm.has_setup_fit is True assert dm.has_setup_test is True def test_data_hooks_called_with_stage_kwarg(tmpdir): dm = TrialMNISTDataModule() dm.prepare_data() assert dm.has_prepared_data is True dm.setup(stage='fit') assert dm.has_setup_fit is True assert dm.has_setup_test is False dm.setup(stage='test') assert dm.has_setup_fit is True assert dm.has_setup_test is True def test_dm_add_argparse_args(tmpdir): parser = ArgumentParser() parser = TrialMNISTDataModule.add_argparse_args(parser) args = parser.parse_args(['--data_dir', './my_data']) assert args.data_dir == './my_data' def test_dm_init_from_argparse_args(tmpdir): parser = ArgumentParser() parser = TrialMNISTDataModule.add_argparse_args(parser) args = parser.parse_args(['--data_dir', './my_data']) dm = TrialMNISTDataModule.from_argparse_args(args) dm.prepare_data() dm.setup() def test_dm_pickle_after_init(tmpdir): dm = TrialMNISTDataModule() pickle.dumps(dm) def test_train_loop_only(tmpdir): dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, ) # fit model result = trainer.fit(model, dm) assert result == 1 assert trainer.logger_connector.callback_metrics['loss'] < 0.6 def test_train_val_loop_only(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, ) # fit model result = trainer.fit(model, dm) assert result == 1 assert trainer.logger_connector.callback_metrics['loss'] < 0.6 def test_dm_checkpoint_save(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, callbacks=[ModelCheckpoint(dirpath=tmpdir, monitor='early_stop_on')], ) # fit model result = trainer.fit(model, dm) checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0] checkpoint = torch.load(checkpoint_path) assert dm.__class__.__name__ in checkpoint assert checkpoint[dm.__class__.__name__] == dm.__class__.__name__ def test_test_loop_only(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, ) trainer.test(model, datamodule=dm) def test_full_loop(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, deterministic=True, ) # fit model result = trainer.fit(model, dm) assert result == 1 # test result = trainer.test(datamodule=dm) result = result[0] assert result['test_acc'] > 0.8 def test_trainer_attached_to_dm(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, deterministic=True, ) # fit model result = trainer.fit(model, dm) assert result == 1 assert dm.trainer is not None # test result = trainer.test(datamodule=dm) result = result[0] assert dm.trainer is not None @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="test requires multi-GPU machine") def test_full_loop_single_gpu(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, gpus=1, deterministic=True, ) # fit model result = trainer.fit(model, dm) assert result == 1 # test result = trainer.test(datamodule=dm) result = result[0] assert result['test_acc'] > 0.8 @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") def test_full_loop_dp(tmpdir): reset_seed() dm = TrialMNISTDataModule(tmpdir) model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=3, weights_summary=None, accelerator='dp', gpus=2, deterministic=True, ) # fit model result = trainer.fit(model, dm) assert result == 1 # test result = trainer.test(datamodule=dm) result = result[0] assert result['test_acc'] > 0.8 @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="test requires multi-GPU machine") def test_dm_transfer_batch_to_device(tmpdir): class CustomBatch: def __init__(self, data): self.samples = data[0] self.targets = data[1] class CurrentTestDM(LightningDataModule): hook_called = False def transfer_batch_to_device(self, data, device): self.hook_called = True if isinstance(data, CustomBatch): data.samples = data.samples.to(device) data.targets = data.targets.to(device) else: data = super().transfer_batch_to_device(data, device) return data model = EvalModelTemplate() dm = CurrentTestDM() batch = CustomBatch((torch.zeros(5, 28), torch.ones(5, 1, dtype=torch.long))) trainer = Trainer(gpus=1) # running .fit() would require us to implement custom data loaders, we mock the model reference instead trainer.get_model = MagicMock(return_value=model) if is_overridden('transfer_batch_to_device', dm): model.transfer_batch_to_device = dm.transfer_batch_to_device trainer.accelerator_backend = GPUAccelerator(trainer) batch_gpu = trainer.accelerator_backend.batch_to_device(batch, torch.device('cuda:0')) expected = torch.device('cuda', 0) assert dm.hook_called assert batch_gpu.samples.device == batch_gpu.targets.device == expected class CustomMNISTDataModule(LightningDataModule): def __init__(self, data_dir: str = "./"): super().__init__() self.data_dir = data_dir self._epochs_called_for = [] def prepare_data(self): TrialMNIST(self.data_dir, train=True, download=True) def setup(self, stage: Optional[str] = None): mnist_full = TrialMNIST( root=self.data_dir, train=True, num_samples=64, download=True ) self.mnist_train, self.mnist_val = random_split(mnist_full, [128, 64]) self.dims = self.mnist_train[0][0].shape def train_dataloader(self): assert self.trainer.current_epoch not in self._epochs_called_for self._epochs_called_for.append(self.trainer.current_epoch) return DataLoader(self.mnist_train, batch_size=4) def test_dm_reload_dataloaders_every_epoch(tmpdir): """Test datamodule, where trainer argument reload_dataloaders_every_epoch is set to True/False""" dm = CustomMNISTDataModule(tmpdir) model = EvalModelTemplate() model.validation_step = None model.validation_step_end = None model.validation_epoch_end = None model.test_step = None model.test_step_end = None model.test_epoch_end = None trainer = Trainer( default_root_dir=tmpdir, max_epochs=2, limit_train_batches=0.01, reload_dataloaders_every_epoch=True, ) trainer.fit(model, dm)
/* * @Author: czy0729 * @Date: 2019-04-29 16:44:35 * @Last Modified by: czy0729 * @Last Modified time: 2019-10-20 18:51:54 */ import React from 'react' import { observer } from 'mobx-react' import { Tabs as CompTabs } from '@components' import TabBarRight from './tab-bar-right' import { tabs } from './store' function Tabs({ $, children, ...other }) { const { page, _page } = $.state return ( <CompTabs tabs={tabs} initialPage={page} page={children ? page : _page} prerenderingSiblingsNumber={1} renderTabBarRight={<TabBarRight $={$} />} onTabClick={$.onTabClick} onChange={$.onChange} {...other} > {children} </CompTabs> ) } export default observer(Tabs)
# ------------------------------------------------------------------------ # Copyright (c) 2021 4669 (for eccv submission only). All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # ------------------------------------------------------------------------ """ MOT dataset which returns image_id for evaluation. """ from pathlib import Path import cv2 import numpy as np import torch import torch.utils.data import os.path as osp from PIL import Image, ImageDraw import copy import datasets.transforms as T from models.structures import Instances class DetMOTDetection: def __init__(self, args, data_txt_path: str, seqs_folder, transforms): self.args = args self._transforms = transforms self.num_frames_per_batch = max(args.sampler_lengths) self.sample_mode = args.sample_mode self.sample_interval = args.sample_interval self.vis = args.vis self.video_dict = {} with open(data_txt_path, 'r') as file: self.img_files = file.readlines() self.img_files = [osp.join(seqs_folder, x.split(',')[0].strip()) for x in self.img_files] self.img_files = list(filter(lambda x: len(x) > 0, self.img_files)) self.label_files = [(x.replace('images', 'labels_with_ids').replace('.png', '.txt').replace('.jpg', '.txt')) for x in self.img_files] # The number of images per sample: 1 + (num_frames - 1) * interval. # The number of valid samples: num_images - num_image_per_sample + 1. self.item_num = len(self.img_files) - (self.num_frames_per_batch - 1) * self.sample_interval self._register_videos() # video sampler. self.sampler_steps: list = args.sampler_steps self.lengths: list = args.sampler_lengths print("sampler_steps={} lenghts={}".format(self.sampler_steps, self.lengths)) if self.sampler_steps is not None and len(self.sampler_steps) > 0: # Enable sampling length adjustment. assert len(self.lengths) > 0 assert len(self.lengths) == len(self.sampler_steps) + 1 for i in range(len(self.sampler_steps) - 1): assert self.sampler_steps[i] < self.sampler_steps[i + 1] self.item_num = len(self.img_files) - (self.lengths[-1] - 1) * self.sample_interval self.period_idx = 0 self.num_frames_per_batch = self.lengths[0] self.current_epoch = 0 def _register_videos(self): for label_name in self.label_files: video_name = '/'.join(label_name.split('/')[:-1]) if video_name not in self.video_dict: print("register {}-th video: {} ".format(len(self.video_dict) + 1, video_name)) self.video_dict[video_name] = len(self.video_dict) assert len(self.video_dict) <= 300 def set_epoch(self, epoch): self.current_epoch = epoch if self.sampler_steps is None or len(self.sampler_steps) == 0: # fixed sampling length. return for i in range(len(self.sampler_steps)): if epoch >= self.sampler_steps[i]: self.period_idx = i + 1 print("set epoch: epoch {} period_idx={}".format(epoch, self.period_idx)) self.num_frames_per_batch = self.lengths[self.period_idx] def step_epoch(self): # one epoch finishes. print("Dataset: epoch {} finishes".format(self.current_epoch)) self.set_epoch(self.current_epoch + 1) @staticmethod def _targets_to_instances(targets: dict, img_shape) -> Instances: gt_instances = Instances(tuple(img_shape)) gt_instances.boxes = targets['boxes'] gt_instances.labels = targets['labels'] gt_instances.obj_ids = targets['obj_ids'] gt_instances.area = targets['area'] return gt_instances def _pre_single_frame(self, idx: int): img_path = self.img_files[idx] label_path = self.label_files[idx] img = Image.open(img_path) targets = {} w, h = img._size assert w > 0 and h > 0, "invalid image {} with shape {} {}".format(img_path, w, h) if osp.isfile(label_path): labels0 = np.loadtxt(label_path, dtype=np.float32).reshape(-1, 6) # normalized cewh to pixel xyxy format labels = labels0.copy() labels[:, 2] = w * (labels0[:, 2] - labels0[:, 4] / 2) labels[:, 3] = h * (labels0[:, 3] - labels0[:, 5] / 2) labels[:, 4] = w * (labels0[:, 2] + labels0[:, 4] / 2) labels[:, 5] = h * (labels0[:, 3] + labels0[:, 5] / 2) else: raise ValueError('invalid label path: {}'.format(label_path)) video_name = '/'.join(label_path.split('/')[:-1]) obj_idx_offset = self.video_dict[video_name] * 100000 # 100000 unique ids is enough for a video. targets['boxes'] = [] targets['area'] = [] targets['iscrowd'] = [] targets['labels'] = [] targets['obj_ids'] = [] targets['image_id'] = torch.as_tensor(idx) targets['size'] = torch.as_tensor([h, w]) targets['orig_size'] = torch.as_tensor([h, w]) for label in labels: targets['boxes'].append(label[2:6].tolist()) targets['area'].append(label[4] * label[5]) targets['iscrowd'].append(0) targets['labels'].append(0) obj_id = label[1] + obj_idx_offset if label[1] >= 0 else label[1] targets['obj_ids'].append(obj_id) # relative id targets['area'] = torch.as_tensor(targets['area']) targets['iscrowd'] = torch.as_tensor(targets['iscrowd']) targets['labels'] = torch.as_tensor(targets['labels']) targets['obj_ids'] = torch.as_tensor(targets['obj_ids']) targets['boxes'] = torch.as_tensor(targets['boxes'], dtype=torch.float32).reshape(-1, 4) targets['boxes'][:, 0::2].clamp_(min=0, max=w) targets['boxes'][:, 1::2].clamp_(min=0, max=h) return img, targets def _get_sample_range(self, start_idx): # take default sampling method for normal dataset. assert self.sample_mode in ['fixed_interval', 'random_interval'], 'invalid sample mode: {}'.format(self.sample_mode) if self.sample_mode == 'fixed_interval': sample_interval = self.sample_interval elif self.sample_mode == 'random_interval': sample_interval = np.random.randint(1, self.sample_interval + 1) default_range = start_idx, start_idx + (self.num_frames_per_batch - 1) * sample_interval + 1, sample_interval return default_range def pre_continuous_frames(self, start, end, interval=1): targets = [] images = [] for i in range(start, end, interval): img_i, targets_i = self._pre_single_frame(i) images.append(img_i) targets.append(targets_i) return images, targets def __getitem__(self, idx): sample_start, sample_end, sample_interval = self._get_sample_range(idx) images, targets = self.pre_continuous_frames(sample_start, sample_end, sample_interval) data = {} if self._transforms is not None: images, targets = self._transforms(images, targets) gt_instances = [] for img_i, targets_i in zip(images, targets): gt_instances_i = self._targets_to_instances(targets_i, img_i.shape[1:3]) gt_instances.append(gt_instances_i) data.update({ 'imgs': images, 'gt_instances': gt_instances, }) if self.args.vis: data['ori_img'] = [target_i['ori_img'] for target_i in targets] return data def __len__(self): return self.item_num class DetMOTDetectionValidation(DetMOTDetection): def __init__(self, args, seqs_folder, transforms): args.data_txt_path = args.val_data_txt_path super().__init__(args, seqs_folder, transforms) def make_detmot_transforms(image_set, args=None): normalize = T.MotCompose([ T.MotToTensor(), T.MotNormalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800] if image_set == 'train': color_transforms = [] scale_transforms = [ T.MotRandomHorizontalFlip(), T.MotRandomResize(scales, max_size=1333), normalize, ] return T.MotCompose(color_transforms + scale_transforms) if image_set == 'val': return T.MotCompose([ T.MotRandomResize([800], max_size=1333), normalize, ]) raise ValueError(f'unknown {image_set}') def build(image_set, args): root = Path(args.mot_path) assert root.exists(), f'provided MOT path {root} does not exist' transforms = make_detmot_transforms(image_set, args) if image_set == 'train': data_txt_path = args.data_txt_path_train dataset = DetMOTDetection(args, data_txt_path=data_txt_path, seqs_folder=root, transforms=transforms) if image_set == 'val': data_txt_path = args.data_txt_path_val dataset = DetMOTDetection(args, data_txt_path=data_txt_path, seqs_folder=root, transforms=transforms) return dataset
var map = L.map('mapa').setView([-28.455693, -65.786256], 16); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); L.marker([-28.455693, -65.786256]).addTo(map) .bindPopup('GDLWebCamp 2021<br> Boletos ya disponibles!.') .openPopup() .bindTooltip('Ubicación.') .openTooltip();
'use strict'; var mark = 0; function myInfo(){ var Name = prompt("what is your name??") alert("welcome " + Name) alert("i am not going to ask you to guess my name because you already know it so i will ask you to guess something you don't know"); var myAge = prompt("guess what is my age"); console.log(myAge); var mycolor = prompt("guess what is my favorite color"); console.log(mycolor); var spacialty = prompt("guess what is my spacialty"); console.log(spacialty); var result = document.getElementById("gis"); result.innerHTML = myAge + " " + '<br>' + mycolor + " " + '<br>' + spacialty ; } function qSky(){ var sky = prompt("do i love science answer(yes/no) or (y/n)"); switch (sky.toLowerCase()) { case 'yes': case 'y': alert('you are right i love it so much'); mark = mark + 1; break; case 'no': case 'n': alert("you are wrong for sure!!"); break; default: alert("you didn't type a correct answer!"); } } function favSub(){ var phi = prompt("Is phisics what i love the most in science? answer(yes/no) or (y/n)"); switch (phi.toLowerCase()) { case "yes": alert('you are right '); mark = mark + 1; break; case "no": alert("you are wrong!!"); break; case "y": alert('you are right '); mark = mark + 1; break; case "n": alert("you are wrong!!"); break; default: alert("you didn't type a correct answer!"); } } function myGame(){ var zero = prompt("do i play pes now ? answer(yes/no) or (y/n)"); switch (zero.toLowerCase()) { case "yes": alert('you are wrong i was playing it sadly i can not now '); break; case "no": alert("you are right!!"); mark = mark + 1; break; case "y": alert('you are wrong i was playing it sadly i can not now'); break; case "n": alert("you are right!!"); mark = mark + 1; break; default: alert("you didn't type a correct answer!"); } } function myFood(){ var hungry = prompt("am i hungry? answer(yes/no) or (y/n)"); switch (hungry.toLowerCase()) { case "yes": alert("you are right!!"); mark = mark + 1; break; case "no": alert("you are wrong!!"); break; case "y": alert("you are right!!"); mark = mark + 1; break; case "n": alert("you are wrong!!"); break; default: alert("you didn't type a correct answer!"); } } function myLife(){ var life = prompt("do i love mansaf? answer(yes/no) or (y/n)"); switch (life.toLowerCase()) { case "yes": alert("you are right!! who hates mansaf"); mark = mark + 1; break; case "no": alert(" sure you are wrong ! "); break; case "y": alert("you are right!! who hates mansaf"); mark = mark + 1; break; case "n": alert("sure you are wrong ! "); break; default: alert("you didn't type a correct answer!"); } } function evenNum(){ var myNumber = 8; var guessNumber = prompt("guess an even number from 0 to 10 (you have only 4 attempts)"); for (var i = 0; i < 4; i++) { if (myNumber == guessNumber) { mark = mark + 1; alert("your answer " + guessNumber + " is right"); break; } if(i == 3){ break; } else if (guessNumber < myNumber) { alert('your answer too low ') guessNumber = prompt("guess an even number from 0 to 10 (try ahain)"); } else if (guessNumber > myNumber) { alert('your answer too high ') guessNumber = prompt("guess an even number from 0 to 10 (try again"); } else { alert('your answer is wrong '); guessNumber = prompt("guess an even number from 0 to 10 (try again"); } } } function favInst(){ var guessFav = ['razan', 'shihab', 'baraa', 'samer', 'bashar', 'riham', 'all']; var userfav = prompt("guess my favourit instructor (you have only 6 attepts) "); for (var i = 0; i < 6; i++) { for (var x = 0; x < guessFav.length; x++) { if (userfav == guessFav[x]) { mark = mark + 1 alert("yes but she/he is not the only one"); var test = "y"; } } x = 0; if (test == "y") { break; } if(i == 5){ break; } userfav = prompt("guess my favourit instructor try again!"); } } myInfo(); qSky(); favSub(); myGame(); myFood(); myLife(); evenNum(); favInst(); alert("thank you to vist my website " + Name + " and you have " + mark + " out of 7 ")
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread")); var _react = _interopRequireDefault(require("react")); var _icons = require("@filou/icons"); var _reactFela = require("react-fela"); var _recompose = require("recompose"); var _slugify = _interopRequireDefault(require("slugify")); var _get = _interopRequireDefault(require("lodash/get")); var _nav = _interopRequireDefault(require("../nav")); // import Img from 'gatsby-image'; var _default = (0, _recompose.withState)('open', 'setOpen', false)((0, _reactFela.createComponent)(function (_ref) { var theme = _ref.theme, styles = _ref.styles, top = _ref.top; return (0, _objectSpread2.default)({}, styles, { zIndex: 13, top: top, overflow: 'hidden', height: 0, paddingY: 0, paddingLeft: 40, paddingRight: 10, display: 'flex', transition: theme.transition, backgroundColor: 'rgb(85, 85, 85)', color: 'white', textAlign: 'center', cursor: 'pointer', boxShadow: styles.position === 'fixed' ? theme.boxShadow : undefined, '> h2': (0, _objectSpread2.default)({ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: 'white', flex: 1, margin: 0 }, (0, _get.default)(theme, 'filou/static/ChaptersLink', {})), ifMediumDown: { paddingY: 10, height: 'initial' } }); }, function (_ref2) { var headings = _ref2.headings, className = _ref2.className, open = _ref2.open, setOpen = _ref2.setOpen, element = _ref2.element; return _react.default.createElement("div", { onClick: function onClick() { return setOpen(!open); }, className: className }, _react.default.createElement("h2", null, element ? element.innerText : 'Kapitel zeigen'), _react.default.createElement(_icons.FaHashtag, { size: 30, color: "white" }), _react.default.createElement(_nav.default, { inverted: true, open: open, onClose: function onClose() { return setOpen(false); } }, headings.filter(function (x) { return x.value; }).map(function (_ref3, i) { var value = _ref3.value; return _react.default.createElement(_nav.default.Item, { key: value + i, active: element && value === element.innerText, to: "#".concat((0, _slugify.default)(value)) }, value); }))); }, function (p) { return Object.keys(p); })); exports.default = _default;
#def gp(a,q): #k = 0 #while True: #result = a * q**k #if result <=10000: #yield result #else: #return #print(k) #k += 1 #a, q = input().strip().split(' ') #[a, q] = map(int, [a,q]) #gps = gp(a,q) ##print(list(gp(a,q)) ) ##print(gp(a,q)) #print(gps.__next__()) #print(gps.__next__()) #print(gps.__next__()) def counter(start=0): n = start while True: result = yield n # A print(type(result), result) # B if result == 'Q': break n += 1 c = counter() print(next(c)) # C print(c.send('Wow!')) # D print(next(c)) # E print(c.send('Q')) # F
import React from 'react' import ReactDOM from 'react-dom' import { BarChart } from 'react-d3' import Loading from '../loading' import getData from '../../lib/get-data' import config from '../../config' export default class Results extends React.Component { constructor (props) { super(props) this.state = { results: [], loading: true, innerHeight: 300, innerWidth: 1200, stats: [ { values: [] } ] } this.readMore = this.readMore.bind(this) this.fitToParentSize = this.fitToParentSize.bind(this) } async componentDidMount () { this.fitToParentSize() window.addEventListener('resize', this.fitToParentSize) const data = await getData(`${config.generatorUrl}?id=${this.props.urlId}`) const stats = [ { values: Object.assign(data.map(s => ({ x: `${s.title} (${s.score})`, y: s.score }))) } ] this.setState({ results: data, stats: stats, loading: false }) } fitToParentSize () { const elem = ReactDOM.findDOMNode(this) const w = elem.parentNode.offsetWidth - 20 this.setState({ innerWidth: w }) } readMore (e) { const name = e.currentTarget.getAttribute('name') if (!this.state[name] || this.state[name] === 'none') { this.setState({ [name]: 'block' }) } else { this.setState({ [name]: 'none' }) } } render () { return ( <div> <Loading loading={this.state.loading} /> <div style={{display: this.state.loading ? 'none' : 'block'}}> <p className='question'>Test results</p> <p className='title2'>Domains</p> <div> <BarChart data={this.state.stats} width={this.state.innerWidth} height={this.state.innerHeigth} hoverAnimation={false} /> </div> { this.state.results.map(d => <div key={d.title} id={'domain-' + d.domain}> <p className='question'>{d.title}</p> <p> <span dangerouslySetInnerHTML={{__html: d.shortDescription}} /> <br /> <br /> <div style={{display: this.state[d.domain] || 'none'}}><span dangerouslySetInnerHTML={{__html: d.description}} /></div> <span name={d.domain} onClick={this.readMore} style={{textTransform: 'lowercase', color: '#5991ff'}}> {this.state[d.domain] === 'block' ? '...read less' : `... read more (${d.description.split(' ').length} words)`} </span> </p> <p><span dangerouslySetInnerHTML={{__html: d.text}} /> </p> <p>Your level of <i>{d.title.toLowerCase()}</i> is <b>{d.scoreText} ({d.score}/{d.count * 5})</b></p> <div style={{ display: d.facets.length > 1 ? 'block' : 'none' }} > <BarChart data={[{values: Object.assign(d.facets.map(s => ({x: `${s.title} (${s.score})`, y: s.score})))}]} width={this.state.innerWidth} hoverAnimation={false} height={this.state.innerHeight} /> </div> { d.facets.map(f => <span key={f.title}> <p className='title2'>{f.title}</p> <p><span dangerouslySetInnerHTML={{__html: f.text}} /></p> <p>Your level of <i>{f.title.toLowerCase()}</i> is <b>{f.scoreText} ({f.score}/{f.count * 5})</b></p> </span> ) } </div> ) } <style> {` .title2 { font-size: 23px; margin-bottom: 10px; } .rd3-barchart-bar:nth-child(1) { fill: #ff8888; } .rd3-barchart-bar:nth-child(2) { fill: #88d6ff; } .rd3-barchart-bar:nth-child(3) { fill: #fff188; } .rd3-barchart-bar:nth-child(4) { fill: #98ff88; } .rd3-barchart-bar:nth-child(5) { fill: #ee88ff; box-shadow: 7px 10px 5px 0px rgba(0,0,0,0.75); } .rd3-barchart-bar:nth-child(6) { fill: #a988ff; } @media (min-width:681px) and (max-width:1300px) { .rd3-barchart-xaxis text { text-anchor: start; transform: rotate(50deg); alignment-baseline: hanging; } .rd3-chart { padding-bottom: 190px; } .rd3-barchart-xaxis line { transform: scaleY(4); } } @media (max-width: 680px) { .rd3-barchart-xaxis text { writing-mode: tb; text-anchor: start; } .rd3-barchart-xaxis line { transform: scaleY(0); } .rd3-chart { padding-bottom: 200px; } } `} </style> </div> </div> ) } }
import React from 'react'; const CollegeLutheran = () => ( <div className="elevation2 project"> <h4>College Lutheran Church</h4> <img alt="College Lutheran Church Homepage" src="https://dl.dropboxusercontent.com/s/354maifx0dkzt9s/Screenshot%20from%202019-02-22%2016-01-50.png?dl=0" /> <br /> <a href="https://www.collegelutheran.org" target="_blank" rel="noreferrer noopener" > Collegeluthean.org </a> </div> ); export default CollegeLutheran;
#coding=utf-8 import tensorflow as tf import sys import os import numpy as np from collections import OrderedDict from semantic.visualization_utils import STANDARD_COLORS from object_detection2.standard_names import * import semantic.toolkit as smt import wml_tfutils as wmlt import time from iotoolkit.coco_toolkit import * import wml_utils as wmlu import logging import glob from collections import Iterable from object_detection2.data.transforms.transform import WTransformList slim = tf.contrib.slim slim_example_decoder = tf.contrib.slim.tfexample_decoder def __parse_func(example_proto): keys_to_features = { 'image/encoded':tf.FixedLenFeature((), tf.string, default_value=''), #[H,W,C] 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/height': tf.FixedLenFeature((), tf.int64,1), 'image/width': tf.FixedLenFeature((), tf.int64,1), 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/label': tf.VarLenFeature(dtype=tf.int64), 'image/object/bbox/difficult': tf.VarLenFeature(dtype=tf.int64), 'image/object/bbox/truncated': tf.VarLenFeature(dtype=tf.int64), } example_proto = tf.parse_single_example(example_proto,keys_to_features) image = tf.image.decode_jpeg(example_proto['image/encoded'],channels=3) xmin = tf.sparse_tensor_to_dense(example_proto['image/object/bbox/xmin']) ymin = tf.sparse_tensor_to_dense(example_proto['image/object/bbox/ymin']) xmax = tf.sparse_tensor_to_dense(example_proto['image/object/bbox/xmax']) ymax = tf.sparse_tensor_to_dense(example_proto['image/object/bbox/ymax']) xmin = tf.reshape(xmin,[-1,1]) ymin = tf.reshape(ymin,[-1,1]) xmax = tf.reshape(xmax,[-1,1]) ymax = tf.reshape(ymax,[-1,1]) boxes = tf.concat([ymin,xmin,ymax,xmax],axis=1) keys_to_res = { 'image':image, 'height':'image/height', 'width':'image/width', 'gt_boxes':boxes, 'gt_labels':'image/object/bbox/label', 'gt_difficult':'image/object/bbox/difficult', } res = {} for k,v in keys_to_res.items(): if isinstance(v,str): if isinstance(example_proto[v],tf.SparseTensor): res[k] = tf.sparse_tensor_to_dense(example_proto[v]) else: res[k] = example_proto[v] else: res[k] = v return res ''' file_pattern类似于 'voc_2012_%s_*.tfrecord' split_to_sizes:所有文件中样本的数量 items_to_descriptions:解码的数据项的描述 num_classes:类别数,不包含背景 ''' def get_database(dataset_dir,num_parallel=1,file_pattern='*_train.record'): file_pattern = os.path.join(dataset_dir,file_pattern) files = glob.glob(file_pattern) if len(files) == 0: logging.error(f'No files found in {file_pattern}') a = input(f"No files found in {file_pattern}, continue?(y/n)") if a != 'y': exit(-1) else: wmlu.show_list(files) dataset = tf.data.TFRecordDataset(files,num_parallel_reads=num_parallel) dataset = dataset.map(__parse_func,num_parallel_calls=num_parallel) return dataset def get_from_dataset(data_item,keys): res = [] for k in keys: res.append(data_item[k]) return res ''' return: image:[H,W,C] labels:[X] bboxes:[X,4] mask:[X,H,W] ''' def get_data(data_dir,num_parallel=8,log_summary=True,file_pattern="*.tfrecord",id_to_label={},transforms=None,has_file_index=True,filter_func=None,filter_empty=True): ''' id_to_label:first id is the category_id in coco, second label is the label id for model ''' dataset = get_database(dataset_dir=data_dir,num_parallel=num_parallel,file_pattern=file_pattern) def filter_func_empty(x): return tf.greater(tf.shape(x[GT_BOXES])[0],0) if filter_empty: dataset = dataset.filter(filter_func_empty) if filter_func is not None: dataset = dataset.filter(filter_func) if transforms is not None: if isinstance(transforms,Iterable): transforms = WTransformList(list(transforms)) dataset = dataset.map(transforms,num_parallel_calls=num_parallel) if filter_empty: #处理后有的bbox可能消失了 dataset = dataset.filter(filter_func_empty) with tf.name_scope('data_provider'): pass ''' [image, glabels, bboxes] = get_from_dataset(provider,["image", "object/label", "object/bbox"]) if log_summary: odu.tf_summary_image_with_box(image, bboxes, "input_data") label = 1 if len(id_to_label) == 0: for i in range(1, 80): id_to_label[i] = label label += 1 table = tf.contrib.lookup.HashTable( tf.contrib.lookup.KeyValueTensorInitializer(np.array(list(id_to_label.keys()), dtype=np.int64), np.array(list(id_to_label.values()), dtype=np.int64)), -1) glabels = table.lookup(glabels) wmlt.add_to_hash_table_collection(table.init) image = tf.Print(image,[tf.shape(image),tf.shape(glabels),tf.shape(bboxes)]) return image, glabels, bboxes''' return dataset
# -*- coding: utf-8 -*- # Copyright 2020 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. # from typing import ( Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, ) from google.cloud.dialogflowcx_v3beta1.types import session_entity_type class ListSessionEntityTypesPager: """A pager for iterating through ``list_session_entity_types`` requests. This class thinly wraps an initial :class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse` object, and provides an ``__iter__`` method to iterate through its ``session_entity_types`` field. If there are more pages, the ``__iter__`` method will make additional ``ListSessionEntityTypes`` requests and continue to iterate through the ``session_entity_types`` field on the corresponding responses. All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[..., session_entity_type.ListSessionEntityTypesResponse], request: session_entity_type.ListSessionEntityTypesRequest, response: session_entity_type.ListSessionEntityTypesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): The initial request object. response (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = session_entity_type.ListSessionEntityTypesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]: for page in self.pages: yield from page.session_entity_types def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListSessionEntityTypesAsyncPager: """A pager for iterating through ``list_session_entity_types`` requests. This class thinly wraps an initial :class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse` object, and provides an ``__aiter__`` method to iterate through its ``session_entity_types`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListSessionEntityTypes`` requests and continue to iterate through the ``session_entity_types`` field on the corresponding responses. All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, method: Callable[ ..., Awaitable[session_entity_type.ListSessionEntityTypesResponse] ], request: session_entity_type.ListSessionEntityTypesRequest, response: session_entity_type.ListSessionEntityTypesResponse, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): The initial request object. response (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = session_entity_type.ListSessionEntityTypesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages( self, ) -> AsyncIterator[session_entity_type.ListSessionEntityTypesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]: async def async_generator(): async for page in self.pages: for response in page.session_entity_types: yield response return async_generator() def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
import pytest from vyper.compiler import compile_code from vyper.opcodes import EVM_VERSIONS code = """ @public def _bitwise_and(x: uint256, y: uint256) -> uint256: return bitwise_and(x, y) @public def _bitwise_or(x: uint256, y: uint256) -> uint256: return bitwise_or(x, y) @public def _bitwise_xor(x: uint256, y: uint256) -> uint256: return bitwise_xor(x, y) @public def _bitwise_not(x: uint256) -> uint256: return bitwise_not(x) @public def _shift(x: uint256, y: int128) -> uint256: return shift(x, y) """ @pytest.mark.parametrize('evm_version', list(EVM_VERSIONS)) def test_bitwise_opcodes(evm_version): opcodes = compile_code(code, ['opcodes'], evm_version=evm_version)['opcodes'] if evm_version in ("byzantium", "atlantis"): assert "SHL" not in opcodes assert "SHR" not in opcodes else: assert "SHL" in opcodes assert "SHR" in opcodes @pytest.mark.parametrize('evm_version', list(EVM_VERSIONS)) def test_test_bitwise(get_contract_with_gas_estimation, evm_version): c = get_contract_with_gas_estimation(code, evm_version=evm_version) x = 126416208461208640982146408124 y = 7128468721412412459 assert c._bitwise_and(x, y) == (x & y) assert c._bitwise_or(x, y) == (x | y) assert c._bitwise_xor(x, y) == (x ^ y) assert c._bitwise_not(x) == 2**256 - 1 - x assert c._shift(x, 3) == x * 8 assert c._shift(x, 255) == 0 assert c._shift(y, 255) == 2**255 assert c._shift(x, 256) == 0 assert c._shift(x, 0) == x assert c._shift(x, -1) == x // 2 assert c._shift(x, -3) == x // 8 assert c._shift(x, -256) == 0 @pytest.mark.parametrize('evm_version', list(EVM_VERSIONS)) def test_literals(get_contract, evm_version): code = """ @public def left(x: uint256) -> uint256: return shift(x, -3) @public def right(x: uint256) -> uint256: return shift(x, 3) """ c = get_contract(code, evm_version=evm_version) assert c.left(80) == 10 assert c.right(80) == 640
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @record */ export function Action() { } if (false) { /** @type {?} */ Action.prototype.type; } /** * @record * @template T, V */ export function ActionReducer() { } /** * @record * @template T, V */ export function ActionReducerFactory() { } /** * @record * @template T, V */ export function StoreFeature() { } if (false) { /** @type {?} */ StoreFeature.prototype.key; /** @type {?} */ StoreFeature.prototype.reducers; /** @type {?} */ StoreFeature.prototype.reducerFactory; /** @type {?|undefined} */ StoreFeature.prototype.initialState; /** @type {?|undefined} */ StoreFeature.prototype.metaReducers; } /** @type {?} */ export const typePropertyIsNotAllowedMsg = 'type property is not allowed in action creators'; /** * @record */ export function RuntimeChecks() { } if (false) { /** @type {?} */ RuntimeChecks.prototype.strictStateSerializability; /** @type {?} */ RuntimeChecks.prototype.strictActionSerializability; /** @type {?} */ RuntimeChecks.prototype.strictStateImmutability; /** @type {?} */ RuntimeChecks.prototype.strictActionImmutability; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vbW9kdWxlcy9zdG9yZS9zcmMvbW9kZWxzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFBQSw0QkFFQzs7O0lBREMsc0JBQWE7Ozs7OztBQWdCZixtQ0FFQzs7Ozs7QUFNRCwwQ0FLQzs7Ozs7QUFNRCxrQ0FNQzs7O0lBTEMsMkJBQVk7O0lBQ1osZ0NBQXVEOztJQUN2RCxzQ0FBMkM7O0lBQzNDLG9DQUErQjs7SUFDL0Isb0NBQW1DOzs7QUFjckMsTUFBTSxPQUFPLDJCQUEyQixHQUN0QyxpREFBaUQ7Ozs7QUEyQm5ELG1DQUtDOzs7SUFKQyxtREFBb0M7O0lBQ3BDLG9EQUFxQzs7SUFDckMsZ0RBQWlDOztJQUNqQyxpREFBa0MiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgaW50ZXJmYWNlIEFjdGlvbiB7XG4gIHR5cGU6IHN0cmluZztcbn1cblxuLy8gZGVjbGFyZSB0byBtYWtlIGl0IHByb3BlcnR5LXJlbmFtaW5nIHNhZmVcbmV4cG9ydCBkZWNsYXJlIGludGVyZmFjZSBUeXBlZEFjdGlvbjxUIGV4dGVuZHMgc3RyaW5nPiBleHRlbmRzIEFjdGlvbiB7XG4gIHJlYWRvbmx5IHR5cGU6IFQ7XG59XG5cbmV4cG9ydCB0eXBlIEFjdGlvblR5cGU8QT4gPSBBIGV4dGVuZHMgQWN0aW9uQ3JlYXRvcjxpbmZlciBULCBpbmZlciBDPlxuICA/IFJldHVyblR5cGU8Qz4gJiB7IHR5cGU6IFQgfVxuICA6IG5ldmVyO1xuXG5leHBvcnQgdHlwZSBUeXBlSWQ8VD4gPSAoKSA9PiBUO1xuXG5leHBvcnQgdHlwZSBJbml0aWFsU3RhdGU8VD4gPSBQYXJ0aWFsPFQ+IHwgVHlwZUlkPFBhcnRpYWw8VD4+IHwgdm9pZDtcblxuZXhwb3J0IGludGVyZmFjZSBBY3Rpb25SZWR1Y2VyPFQsIFYgZXh0ZW5kcyBBY3Rpb24gPSBBY3Rpb24+IHtcbiAgKHN0YXRlOiBUIHwgdW5kZWZpbmVkLCBhY3Rpb246IFYpOiBUO1xufVxuXG5leHBvcnQgdHlwZSBBY3Rpb25SZWR1Y2VyTWFwPFQsIFYgZXh0ZW5kcyBBY3Rpb24gPSBBY3Rpb24+ID0ge1xuICBbcCBpbiBrZXlvZiBUXTogQWN0aW9uUmVkdWNlcjxUW3BdLCBWPlxufTtcblxuZXhwb3J0IGludGVyZmFjZSBBY3Rpb25SZWR1Y2VyRmFjdG9yeTxULCBWIGV4dGVuZHMgQWN0aW9uID0gQWN0aW9uPiB7XG4gIChcbiAgICByZWR1Y2VyTWFwOiBBY3Rpb25SZWR1Y2VyTWFwPFQsIFY+LFxuICAgIGluaXRpYWxTdGF0ZT86IEluaXRpYWxTdGF0ZTxUPlxuICApOiBBY3Rpb25SZWR1Y2VyPFQsIFY+O1xufVxuXG5leHBvcnQgdHlwZSBNZXRhUmVkdWNlcjxUID0gYW55LCBWIGV4dGVuZHMgQWN0aW9uID0gQWN0aW9uPiA9IChcbiAgcmVkdWNlcjogQWN0aW9uUmVkdWNlcjxULCBWPlxuKSA9PiBBY3Rpb25SZWR1Y2VyPFQsIFY+O1xuXG5leHBvcnQgaW50ZXJmYWNlIFN0b3JlRmVhdHVyZTxULCBWIGV4dGVuZHMgQWN0aW9uID0gQWN0aW9uPiB7XG4gIGtleTogc3RyaW5nO1xuICByZWR1Y2VyczogQWN0aW9uUmVkdWNlck1hcDxULCBWPiB8IEFjdGlvblJlZHVjZXI8VCwgVj47XG4gIHJlZHVjZXJGYWN0b3J5OiBBY3Rpb25SZWR1Y2VyRmFjdG9yeTxULCBWPjtcbiAgaW5pdGlhbFN0YXRlPzogSW5pdGlhbFN0YXRlPFQ+O1xuICBtZXRhUmVkdWNlcnM/OiBNZXRhUmVkdWNlcjxULCBWPltdO1xufVxuXG5leHBvcnQgdHlwZSBTZWxlY3RvcjxULCBWPiA9IChzdGF0ZTogVCkgPT4gVjtcblxuZXhwb3J0IHR5cGUgU2VsZWN0b3JXaXRoUHJvcHM8U3RhdGUsIFByb3BzLCBSZXN1bHQ+ID0gKFxuICBzdGF0ZTogU3RhdGUsXG4gIHByb3BzOiBQcm9wc1xuKSA9PiBSZXN1bHQ7XG5cbmV4cG9ydCB0eXBlIERpc2FsbG93VHlwZVByb3BlcnR5PFQ+ID0gVCBleHRlbmRzIHsgdHlwZTogYW55IH1cbiAgPyBUeXBlUHJvcGVydHlJc05vdEFsbG93ZWRcbiAgOiBUO1xuXG5leHBvcnQgY29uc3QgdHlwZVByb3BlcnR5SXNOb3RBbGxvd2VkTXNnID1cbiAgJ3R5cGUgcHJvcGVydHkgaXMgbm90IGFsbG93ZWQgaW4gYWN0aW9uIGNyZWF0b3JzJztcbnR5cGUgVHlwZVByb3BlcnR5SXNOb3RBbGxvd2VkID0gdHlwZW9mIHR5cGVQcm9wZXJ0eUlzTm90QWxsb3dlZE1zZztcblxuZXhwb3J0IHR5cGUgQ3JlYXRvcjxcbiAgUCBleHRlbmRzIGFueVtdID0gYW55W10sXG4gIFIgZXh0ZW5kcyBvYmplY3QgPSBvYmplY3Rcbj4gPSBSIGV4dGVuZHMgeyB0eXBlOiBhbnkgfVxuICA/IFR5cGVQcm9wZXJ0eUlzTm90QWxsb3dlZFxuICA6IEZ1bmN0aW9uV2l0aFBhcmFtZXRlcnNUeXBlPFAsIFI+O1xuXG5leHBvcnQgdHlwZSBQcm9wc1JldHVyblR5cGU8VCBleHRlbmRzIG9iamVjdD4gPSBUIGV4dGVuZHMgeyB0eXBlOiBhbnkgfVxuICA/IFR5cGVQcm9wZXJ0eUlzTm90QWxsb3dlZFxuICA6IHsgX2FzOiAncHJvcHMnOyBfcDogVCB9O1xuXG5leHBvcnQgdHlwZSBBY3Rpb25DcmVhdG9yPFxuICBUIGV4dGVuZHMgc3RyaW5nID0gc3RyaW5nLFxuICBDIGV4dGVuZHMgQ3JlYXRvciA9IENyZWF0b3Jcbj4gPSBDICYgVHlwZWRBY3Rpb248VD47XG5cbmV4cG9ydCB0eXBlIEZ1bmN0aW9uV2l0aFBhcmFtZXRlcnNUeXBlPFAgZXh0ZW5kcyB1bmtub3duW10sIFIgPSB2b2lkPiA9IChcbiAgLi4uYXJnczogUFxuKSA9PiBSO1xuXG5leHBvcnQgdHlwZSBQYXJhbWV0ZXJzVHlwZTxUPiA9IFQgZXh0ZW5kcyAoLi4uYXJnczogaW5mZXIgVSkgPT4gdW5rbm93blxuICA/IFVcbiAgOiBuZXZlcjtcblxuZXhwb3J0IGludGVyZmFjZSBSdW50aW1lQ2hlY2tzIHtcbiAgc3RyaWN0U3RhdGVTZXJpYWxpemFiaWxpdHk6IGJvb2xlYW47XG4gIHN0cmljdEFjdGlvblNlcmlhbGl6YWJpbGl0eTogYm9vbGVhbjtcbiAgc3RyaWN0U3RhdGVJbW11dGFiaWxpdHk6IGJvb2xlYW47XG4gIHN0cmljdEFjdGlvbkltbXV0YWJpbGl0eTogYm9vbGVhbjtcbn1cbiJdfQ==
export const RightCircleOutline = { name: 'right-circle', theme: 'outline', icon: '<svg viewBox="64 64 896 896" focusable="false"><path d="M666.7 505.5l-246-178A8 8 0 00408 334v46.9c0 10.2 4.9 19.9 13.2 25.9L566.6 512 421.2 617.2c-8.3 6-13.2 15.6-13.2 25.9V690c0 6.5 7.4 10.3 12.7 6.5l246-178c4.4-3.2 4.4-9.8 0-13z" /><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z" /></svg>' }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiUmlnaHRDaXJjbGVPdXRsaW5lLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2ljb25zL291dGxpbmUvUmlnaHRDaXJjbGVPdXRsaW5lLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUVBLE1BQU0sQ0FBQyxNQUFNLGtCQUFrQixHQUFtQjtJQUM5QyxJQUFJLEVBQUUsY0FBYztJQUNwQixLQUFLLEVBQUUsU0FBUztJQUNoQixJQUFJLEVBQUUsNmFBQTZhO0NBQ3RiLENBQUEiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBJY29uRGVmaW5pdGlvbiB9IGZyb20gJ0BhbnQtZGVzaWduL2ljb25zLWFuZ3VsYXInO1xuXG5leHBvcnQgY29uc3QgUmlnaHRDaXJjbGVPdXRsaW5lOiBJY29uRGVmaW5pdGlvbiA9IHtcbiAgICBuYW1lOiAncmlnaHQtY2lyY2xlJyxcbiAgICB0aGVtZTogJ291dGxpbmUnLFxuICAgIGljb246ICc8c3ZnIHZpZXdCb3g9XCI2NCA2NCA4OTYgODk2XCIgZm9jdXNhYmxlPVwiZmFsc2VcIj48cGF0aCBkPVwiTTY2Ni43IDUwNS41bC0yNDYtMTc4QTggOCAwIDAwNDA4IDMzNHY0Ni45YzAgMTAuMiA0LjkgMTkuOSAxMy4yIDI1LjlMNTY2LjYgNTEyIDQyMS4yIDYxNy4yYy04LjMgNi0xMy4yIDE1LjYtMTMuMiAyNS45VjY5MGMwIDYuNSA3LjQgMTAuMyAxMi43IDYuNWwyNDYtMTc4YzQuNC0zLjIgNC40LTkuOCAwLTEzelwiIC8+PHBhdGggZD1cIk01MTIgNjRDMjY0LjYgNjQgNjQgMjY0LjYgNjQgNTEyczIwMC42IDQ0OCA0NDggNDQ4IDQ0OC0yMDAuNiA0NDgtNDQ4Uzc1OS40IDY0IDUxMiA2NHptMCA4MjBjLTIwNS40IDAtMzcyLTE2Ni42LTM3Mi0zNzJzMTY2LjYtMzcyIDM3Mi0zNzIgMzcyIDE2Ni42IDM3MiAzNzItMTY2LjYgMzcyLTM3MiAzNzJ6XCIgLz48L3N2Zz4nXG59Il19
<?xml version="1.0" encoding="utf-8"?> <project path="" name="Ext - JS Lib" author="Ext JS, LLC" version="2.1" copyright="Ext JS Library $version&#xD;&#xA;Copyright(c) 2006-2008, $author.&#xD;&#xA;[email protected]&#xD;&#xA;&#xD;&#xA;http://extjs.com/license" output="C:\apps\www\deploy\ext-2.1\" source="True" source-dir="$output\source" minify="True" min-dir="$output\build" doc="False" doc-dir="$output\docs" min-dair="$output\build"> <directory name="" /> <target name="Core" file="$output\ext-core.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="core\DomHelper.js" /> <include name="core\Template.js" /> <include name="core\DomQuery.js" /> <include name="util\Observable.js" /> <include name="core\EventManager.js" /> <include name="core\Element.js" /> <include name="core\Fx.js" /> <include name="core\CompositeElement.js" /> <include name="data\Connection.js" /> <include name="core\UpdateManager.js" /> <include name="util\DelayedTask.js" /> </target> <target name="Everything" file="$output\ext-all.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="core\DomHelper.js" /> <include name="core\Template.js" /> <include name="core\DomQuery.js" /> <include name="util\Observable.js" /> <include name="core\EventManager.js" /> <include name="core\Element.js" /> <include name="core\Fx.js" /> <include name="core\CompositeElement.js" /> <include name="data\Connection.js" /> <include name="core\UpdateManager.js" /> <include name="util\Date.js" /> <include name="util\DelayedTask.js" /> <include name="util\TaskMgr.js" /> <include name="util\MixedCollection.js" /> <include name="util\JSON.js" /> <include name="util\Format.js" /> <include name="util\XTemplate.js" /> <include name="util\CSS.js" /> <include name="util\ClickRepeater.js" /> <include name="util\KeyNav.js" /> <include name="util\KeyMap.js" /> <include name="util\TextMetrics.js" /> <include name="dd\DDCore.js" /> <include name="dd\DragTracker.js" /> <include name="dd\ScrollManager.js" /> <include name="dd\Registry.js" /> <include name="dd\StatusProxy.js" /> <include name="dd\DragSource.js" /> <include name="dd\DropTarget.js" /> <include name="dd\DragZone.js" /> <include name="dd\DropZone.js" /> <include name="data\SortTypes.js" /> <include name="data\Record.js" /> <include name="data\StoreMgr.js" /> <include name="data\Store.js" /> <include name="data\SimpleStore.js" /> <include name="data\JsonStore.js" /> <include name="data\DataField.js" /> <include name="data\DataReader.js" /> <include name="data\DataProxy.js" /> <include name="data\MemoryProxy.js" /> <include name="data\HttpProxy.js" /> <include name="data\ScriptTagProxy.js" /> <include name="data\JsonReader.js" /> <include name="data\XmlReader.js" /> <include name="data\ArrayReader.js" /> <include name="data\Tree.js" /> <include name="data\GroupingStore.js" /> <include name="widgets\ComponentMgr.js" /> <include name="widgets\Component.js" /> <include name="widgets\Action.js" /> <include name="widgets\Layer.js" /> <include name="widgets\Shadow.js" /> <include name="widgets\BoxComponent.js" /> <include name="widgets\SplitBar.js" /> <include name="widgets\Container.js" /> <include name="widgets\layout\ContainerLayout.js" /> <include name="widgets\layout\FitLayout.js" /> <include name="widgets\layout\CardLayout.js" /> <include name="widgets\layout\AnchorLayout.js" /> <include name="widgets\layout\ColumnLayout.js" /> <include name="widgets\layout\BorderLayout.js" /> <include name="widgets\layout\FormLayout.js" /> <include name="widgets\layout\AccordionLayout.js" /> <include name="widgets\layout\TableLayout.js" /> <include name="widgets\layout\AbsoluteLayout.js" /> <include name="widgets\Viewport.js" /> <include name="widgets\Panel.js" /> <include name="widgets\Window.js" /> <include name="widgets\WindowManager.js" /> <include name="widgets\PanelDD.js" /> <include name="state\Provider.js" /> <include name="state\StateManager.js" /> <include name="state\CookieProvider.js" /> <include name="widgets\DataView.js" /> <include name="widgets\ColorPalette.js" /> <include name="widgets\DatePicker.js" /> <include name="widgets\TabPanel.js" /> <include name="widgets\Button.js" /> <include name="widgets\SplitButton.js" /> <include name="widgets\CycleButton.js" /> <include name="widgets\Toolbar.js" /> <include name="widgets\PagingToolbar.js" /> <include name="widgets\Resizable.js" /> <include name="widgets\Editor.js" /> <include name="widgets\MessageBox.js" /> <include name="widgets\tips\Tip.js" /> <include name="widgets\tips\ToolTip.js" /> <include name="widgets\tips\QuickTip.js" /> <include name="widgets\tips\QuickTips.js" /> <include name="widgets\tree\TreePanel.js" /> <include name="widgets\tree\TreeEventModel.js" /> <include name="widgets\tree\TreeSelectionModel.js" /> <include name="widgets\tree\TreeNode.js" /> <include name="widgets\tree\AsyncTreeNode.js" /> <include name="widgets\tree\TreeNodeUI.js" /> <include name="widgets\tree\TreeLoader.js" /> <include name="widgets\tree\TreeFilter.js" /> <include name="widgets\tree\TreeSorter.js" /> <include name="widgets\tree\TreeDropZone.js" /> <include name="widgets\tree\TreeDragZone.js" /> <include name="widgets\tree\TreeEditor.js" /> <include name="widgets\menu\Menu.js" /> <include name="widgets\menu\MenuMgr.js" /> <include name="widgets\menu\BaseItem.js" /> <include name="widgets\menu\TextItem.js" /> <include name="widgets\menu\Separator.js" /> <include name="widgets\menu\Item.js" /> <include name="widgets\menu\CheckItem.js" /> <include name="widgets\menu\Adapter.js" /> <include name="widgets\menu\DateItem.js" /> <include name="widgets\menu\ColorItem.js" /> <include name="widgets\menu\DateMenu.js" /> <include name="widgets\menu\ColorMenu.js" /> <include name="widgets\form\Field.js" /> <include name="widgets\form\TextField.js" /> <include name="widgets\form\TriggerField.js" /> <include name="widgets\form\TextArea.js" /> <include name="widgets\form\NumberField.js" /> <include name="widgets\form\DateField.js" /> <include name="widgets\form\Combo.js" /> <include name="widgets\form\Checkbox.js" /> <include name="widgets\form\Radio.js" /> <include name="widgets\form\Hidden.js" /> <include name="widgets\form\BasicForm.js" /> <include name="widgets\form\Form.js" /> <include name="widgets\form\FieldSet.js" /> <include name="widgets\form\HtmlEditor.js" /> <include name="widgets\form\TimeField.js" /> <include name="widgets\form\Label.js" /> <include name="widgets\form\Action.js" /> <include name="widgets\form\VTypes.js" /> <include name="widgets\grid\GridPanel.js" /> <include name="widgets\grid\GridView.js" /> <include name="widgets\grid\GroupingView.js" /> <include name="widgets\grid\ColumnDD.js" /> <include name="widgets\grid\ColumnSplitDD.js" /> <include name="widgets\grid\GridDD.js" /> <include name="widgets\grid\ColumnModel.js" /> <include name="widgets\grid\AbstractSelectionModel.js" /> <include name="widgets\grid\RowSelectionModel.js" /> <include name="widgets\grid\CellSelectionModel.js" /> <include name="widgets\grid\EditorGrid.js" /> <include name="widgets\grid\GridEditor.js" /> <include name="widgets\grid\PropertyGrid.js" /> <include name="widgets\grid\RowNumberer.js" /> <include name="widgets\grid\CheckboxSelectionModel.js" /> <include name="widgets\LoadMask.js" /> <include name="widgets\ProgressBar.js" /> <include name="widgets\Slider.js" /> <include name="widgets\StatusBar.js" /> <include name="debug.js" /> </target> <file name="layout\LayoutRegionLite.js" path="layout" /> <file name="DDScrollManager.js" path="" /> <file name="grid\AbstractColumnModel.js" path="grid" /> <file name="data\ArrayAdapter.js" path="data" /> <file name="data\DataAdapter.js" path="data" /> <file name="data\HttpAdapter.js" path="data" /> <file name="data\JsonAdapter.js" path="data" /> <file name="data\ArrayProxy.js" path="data" /> <file name="widgets\SimpleMenu.js" path="widgets" /> <file name="CSS.js" path="" /> <file name="CustomTagReader.js" path="" /> <file name="Format.js" path="" /> <file name="JSON.js" path="" /> <file name="MixedCollection.js" path="" /> <file name="data\DataSource.js" path="data" /> <file name="license.txt" path="" /> <file name="yui-ext-dl.jsb" path="" /> <file name="yui-ext.jsb" path="" /> <file name="form\FloatingEditor.js" path="form" /> <file name="anim\Actor.js" path="anim" /> <file name="anim\Animator.js" path="anim" /> <file name="data\AbstractDataModel.js" path="data" /> <file name="data\DataModel.js" path="data" /> <file name="data\DataSet.js" path="data" /> <file name="data\DataStore.js" path="data" /> <file name="data\DefaultDataModel.js" path="data" /> <file name="data\JSONDataModel.js" path="data" /> <file name="data\LoadableDataModel.js" path="data" /> <file name="data\Set.js" path="data" /> <file name="data\TableModel.js" path="data" /> <file name="data\XMLDataModel.js" path="data" /> <file name="form\DateField.js" path="form" /> <file name="form\Field.js" path="form" /> <file name="form\FieldGroup.js" path="form" /> <file name="form\Form.js" path="form" /> <file name="form\NumberField.js" path="form" /> <file name="form\Select.js" path="form" /> <file name="form\TextArea.js" path="form" /> <file name="form\TextField.js" path="form" /> <file name="grid\editor\CellEditor.js" path="grid\editor" /> <file name="grid\editor\CheckboxEditor.js" path="grid\editor" /> <file name="grid\editor\DateEditor.js" path="grid\editor" /> <file name="grid\editor\NumberEditor.js" path="grid\editor" /> <file name="grid\editor\SelectEditor.js" path="grid\editor" /> <file name="grid\editor\TextEditor.js" path="grid\editor" /> <file name="grid\AbstractGridView.js" path="grid" /> <file name="grid\AbstractSelectionModel.js" path="grid" /> <file name="grid\CellSelectionModel.js" path="grid" /> <file name="grid\DefaultColumnModel.js" path="grid" /> <file name="grid\EditorGrid.js" path="grid" /> <file name="grid\EditorSelectionModel.js" path="grid" /> <file name="grid\Grid.js" path="grid" /> <file name="grid\GridDD.js" path="grid" /> <file name="grid\GridEditor.js" path="grid" /> <file name="grid\GridView.js" path="grid" /> <file name="grid\GridViewLite.js" path="grid" /> <file name="grid\PagedGridView.js" path="grid" /> <file name="grid\RowSelectionModel.js" path="grid" /> <file name="grid\SelectionModel.js" path="grid" /> <file name="layout\BasicLayoutRegion.js" path="layout" /> <file name="layout\BorderLayout.js" path="layout" /> <file name="layout\BorderLayoutRegions.js" path="layout" /> <file name="layout\ContentPanels.js" path="layout" /> <file name="layout\LayoutManager.js" path="layout" /> <file name="layout\LayoutRegion.js" path="layout" /> <file name="layout\LayoutStateManager.js" path="layout" /> <file name="layout\SplitLayoutRegion.js" path="layout" /> <file name="menu\Adapter.js" path="menu" /> <file name="menu\BaseItem.js" path="menu" /> <file name="menu\CheckItem.js" path="menu" /> <file name="menu\ColorItem.js" path="menu" /> <file name="menu\DateItem.js" path="menu" /> <file name="menu\DateMenu.js" path="menu" /> <file name="menu\Item.js" path="menu" /> <file name="menu\Menu.js" path="menu" /> <file name="menu\MenuMgr.js" path="menu" /> <file name="menu\Separator.js" path="menu" /> <file name="menu\TextItem.js" path="menu" /> <file name="tree\AsyncTreeNode.js" path="tree" /> <file name="tree\TreeDragZone.js" path="tree" /> <file name="tree\TreeDropZone.js" path="tree" /> <file name="tree\TreeFilter.js" path="tree" /> <file name="tree\TreeLoader.js" path="tree" /> <file name="tree\TreeNode.js" path="tree" /> <file name="tree\TreeNodeUI.js" path="tree" /> <file name="tree\TreePanel.js" path="tree" /> <file name="tree\TreeSelectionModel.js" path="tree" /> <file name="tree\TreeSorter.js" path="tree" /> <file name="widgets\BasicDialog2.js" path="widgets" /> <file name="widgets\InlineEditor.js" path="widgets" /> <file name="widgets\TaskPanel.js" path="widgets" /> <file name="widgets\TemplateView.js" path="widgets" /> <file name="Anims.js" path="" /> <file name="Bench.js" path="" /> <file name="compat.js" path="" /> <file name="CompositeElement.js" path="" /> <file name="Date.js" path="" /> <file name="DomHelper.js" path="" /> <file name="DomQuery.js" path="" /> <file name="Element.js" path="" /> <file name="EventManager.js" path="" /> <file name="Ext.js" path="" /> <file name="Fx.js" path="" /> <file name="KeyMap.js" path="" /> <file name="KeyNav.js" path="" /> <file name="Layer.js" path="" /> <file name="State.js" path="" /> <file name="Template.js" path="" /> <file name="UpdateManager.js" path="" /> <file name="yutil.js" path="" /> <file name=".DS_Store" path="" /> <file name="widgets\form\Select.js" path="widgets\form" /> <file name="widgets\Notifier.js" path="widgets" /> <file name="yui\dragdrop.js" path="yui" /> <file name="yui-overrides.js" path="" /> <target name="YUI" file="$output\adapter\yui\ext-yui-adapter.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="core\Ext.js" /> <include name="adapter\yui-bridge.js" /> </target> <target name="Menus" file="$output\package\menu\menus.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\menu\Menu.js" /> <include name="widgets\menu\MenuMgr.js" /> <include name="widgets\menu\BaseItem.js" /> <include name="widgets\menu\TextItem.js" /> <include name="widgets\menu\Separator.js" /> <include name="widgets\menu\Item.js" /> <include name="widgets\menu\CheckItem.js" /> <include name="widgets\menu\Adapter.js" /> <include name="widgets\menu\DateItem.js" /> <include name="widgets\menu\ColorItem.js" /> <include name="widgets\menu\DateMenu.js" /> <include name="widgets\menu\ColorMenu.js" /> </target> <target name="Tree" file="$output\package\tree\tree.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="data\Tree.js" /> <include name="widgets\tree\TreeEventModel.js" /> <include name="widgets\tree\TreePanel.js" /> <include name="widgets\tree\TreeSelectionModel.js" /> <include name="widgets\tree\TreeNode.js" /> <include name="widgets\tree\AsyncTreeNode.js" /> <include name="widgets\tree\TreeNodeUI.js" /> <include name="widgets\tree\TreeLoader.js" /> <include name="widgets\tree\TreeFilter.js" /> <include name="widgets\tree\TreeSorter.js" /> <include name="widgets\tree\TreeDropZone.js" /> <include name="widgets\tree\TreeDragZone.js" /> <include name="widgets\tree\TreeEditor.js" /> </target> <target name="Grid" file="$output\package\grid\grid.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\grid\Grid.js" /> <include name="widgets\grid\AbstractGridView.js" /> <include name="widgets\grid\GridView.js" /> <include name="widgets\grid\ColumnModel.js" /> <include name="widgets\grid\AbstractSelectionModel.js" /> <include name="widgets\grid\RowSelectionModel.js" /> <include name="widgets\grid\CellSelectionModel.js" /> <include name="widgets\grid\ColumnDD.js" /> <include name="widgets\grid\ColumnSplitDD.js" /> <include name="widgets\grid\GridDD.js" /> </target> <target name="Dialog" file="$output\package\dialog\dialogs.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\BasicDialog.js" /> <include name="widgets\MessageBox.js" /> </target> <target name="Form" file="$output\package\form\form.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\form\Field.js" /> <include name="widgets\form\TextField.js" /> <include name="widgets\form\TriggerField.js" /> <include name="widgets\form\TextArea.js" /> <include name="widgets\form\NumberField.js" /> <include name="widgets\form\Label.js" /> <include name="widgets\form\DateField.js" /> <include name="widgets\form\Checkbox.js" /> <include name="widgets\form\Radio.js" /> <include name="widgets\form\Combo.js" /> <include name="widgets\Editor.js" /> <include name="widgets\form\BasicForm.js" /> <include name="widgets\form\Form.js" /> <include name="widgets\form\Action.js" /> <include name="widgets\form\VTypes.js" /> </target> <target name="Button" file="$output\package\button\button.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\Button.js" /> <include name="widgets\SplitButton.js" /> </target> <target name="Grid - Edit" file="$output\package\grid\edit-grid.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\grid\EditorGrid.js" /> <include name="widgets\grid\GridEditor.js" /> <include name="widgets\grid\PropertyGrid.js" /> </target> <target name="JQUERY" file="$output\adapter\jquery\ext-jquery-adapter.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="core\Ext.js" /> <include name="adapter\jquery-bridge.js" /> </target> <target name="Utilities" file="$output\package\util.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="util\DelayedTask.js" /> <include name="util\MixedCollection.js" /> <include name="util\JSON.js" /> <include name="util\Format.js" /> <include name="util\CSS.js" /> <include name="util\ClickRepeater.js" /> <include name="util\KeyNav.js" /> <include name="util\KeyMap.js" /> <include name="util\TextMetrics.js" /> </target> <target name="Drag Drop" file="$output\package\dragdrop\dragdrop.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="dd\DDCore.js" /> <include name="dd\ScrollManager.js" /> <include name="dd\Registry.js" /> <include name="dd\StatusProxy.js" /> <include name="dd\DragSource.js" /> <include name="dd\DropTarget.js" /> <include name="dd\DragZone.js" /> <include name="dd\DropZone.js" /> </target> <target name="Data" file="$output\package\data\data.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="data\SortTypes.js" /> <include name="data\Record.js" /> <include name="data\StoreMgr.js" /> <include name="data\Store.js" /> <include name="data\SimpleStore.js" /> <include name="data\Connection.js" /> <include name="data\DataField.js" /> <include name="data\DataReader.js" /> <include name="data\DataProxy.js" /> <include name="data\MemoryProxy.js" /> <include name="data\HttpProxy.js" /> <include name="data\ScriptTagProxy.js" /> <include name="data\JsonReader.js" /> <include name="data\XmlReader.js" /> <include name="data\ArrayReader.js" /> </target> <target name="Widget Core" file="$output\package\widget-core.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\ComponentMgr.js" /> <include name="widgets\Component.js" /> <include name="widgets\BoxComponent.js" /> <include name="widgets\Layer.js" /> <include name="widgets\Shadow.js" /> </target> <target name="color-palette" file="$output\package\color-palette.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\ColorPalette.js" /> </target> <target name="Date Picker" file="$output\package\datepicker\datepicker.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\DatePicker.js" /> </target> <target name="Tabs" file="$output\package\tabs\tabs.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\TabPanel.js" /> </target> <target name="Toolbar" file="$output\package\toolbar\toolbar.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\Toolbar.js" /> <include name="widgets\PagingToolbar.js" /> </target> <target name="Resizable" file="$output\package\resizable.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\Resizable.js" /> </target> <target name="SplitBar" file="$output\package\splitbar.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\SplitBar.js" /> </target> <target name="QTips" file="$output\package\qtips\qtips.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="widgets\tips\Tip.js" /> <include name="widgets\tips\ToolTip.js" /> <include name="widgets\tips\QuickTip.js" /> <include name="widgets\tips\QuickTips.js" /> </target> <file name="util\CustomTagReader.js" path="util" /> <target name="Date" file="$output\package\date.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="util\Date.js" /> </target> <file name="widgets\Combo.js" path="widgets" /> <target name="Prototype" file="$output\adapter\prototype\ext-prototype-adapter.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="core\Ext.js" /> <include name="adapter\prototype-bridge.js" /> </target> <file name="widgets\form\Validators.js" path="widgets\form" /> <file name="experimental\ext-lang-en.js" path="experimental" /> <file name="experimental\jquery-bridge.js" path="experimental" /> <file name="experimental\prototype-bridge.js" path="experimental" /> <file name="experimental\yui-bridge.js" path="experimental" /> <file name="widgets\Frame.js" path="widgets" /> <file name="widgets\.DS_Store" path="widgets" /> <file name="widgets\layout\AutoLayout.js" path="widgets\layout" /> <file name="widgets\TabPanel2.js" path="widgets" /> <file name="widgets\panel\ButtonPanel.js" path="widgets\panel" /> <file name="widgets\._.DS_Store" path="widgets" /> <file name="._.DS_Store" path="" /> <file name="experimental\Ajax.js" path="experimental" /> <file name="experimental\Anims.js" path="experimental" /> <file name="experimental\BasicDialog2.js" path="experimental" /> <file name="experimental\BasicGridView.js" path="experimental" /> <file name="experimental\GridView3.js" path="experimental" /> <file name="experimental\GridViewUI.js" path="experimental" /> <file name="experimental\ModelEventHandler.js" path="experimental" /> <file name="experimental\TaskPanel.js" path="experimental" /> <file name="experimental\UIEventHandler.js" path="experimental" /> <file name="legacy\Actor.js" path="legacy" /> <file name="legacy\Animator.js" path="legacy" /> <file name="legacy\compat.js" path="legacy" /> <file name="legacy\InlineEditor.js" path="legacy" /> <file name="widgets\grid\Grid.js" path="widgets\grid" /> <file name="widgets\panel\AutoLayout.js" path="widgets\panel" /> <file name="widgets\panel\BorderLayout.js" path="widgets\panel" /> <file name="widgets\panel\Container.js" path="widgets\panel" /> <file name="widgets\panel\ContainerLayout.js" path="widgets\panel" /> <file name="widgets\panel\Grid.js" path="widgets\panel" /> <file name="widgets\panel\Panel.js" path="widgets\panel" /> <file name="widgets\panel\TabPanel.js" path="widgets\panel" /> <file name="widgets\panel\TreePanel.js" path="widgets\panel" /> <file name="widgets\panel\Viewport.js" path="widgets\panel" /> <file name="widgets\panel\Window.js" path="widgets\panel" /> <file name="widgets\panel\WindowManager.js" path="widgets\panel" /> <file name="widgets\BasicDialog.js" path="widgets" /> <file name="experimental\GridExtensions.js" path="experimental" /> <file name="widgets\layout\BasicLayoutRegion.js" path="widgets\layout" /> <file name="widgets\layout\BorderLayoutRegions.js" path="widgets\layout" /> <file name="widgets\layout\ContentPanels.js" path="widgets\layout" /> <file name="widgets\layout\LayoutManager.js" path="widgets\layout" /> <file name="widgets\layout\LayoutRegion.js" path="widgets\layout" /> <file name="widgets\layout\LayoutStateManager.js" path="widgets\layout" /> <file name="widgets\layout\ReaderLayout.js" path="widgets\layout" /> <file name="widgets\layout\SplitLayoutRegion.js" path="widgets\layout" /> <target name="Ext Base" file="$output\adapter\ext\ext-base.js" debug="False" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event"> <include name="core\Ext.js" /> <include name="adapter\ext-base.js" /> </target> <file name="widgets\form\Editor.js" path="widgets\form" /> <file name="experimental\ext-base.js" path="experimental" /> <file name="ext.jsb" path="" /> <file name="widgets\ViewPanel.js" path="widgets" /> <file name="util\MasterTemplate.js" path="util" /> <file name="widgets\form\Layout.js" path="widgets\form" /> <file name="widgets\BorderLayout.js" path="widgets" /> <file name="widgets\ColumnLayout.js" path="widgets" /> <file name="widgets\ContainerLayout.js" path="widgets" /> <file name="widgets\JsonView.js" path="widgets" /> <file name="widgets\MenuButton.js" path="widgets" /> <file name="widgets\View.js" path="widgets" /> <file name="widgets\grid\AbstractGridView.js" path="widgets\grid" /> <file name="state\State.js" path="state" /> <file name="widgets\layout\AccordianLayout.js" path="widgets\layout" /> <file name="widgets\QuickTips.js" path="widgets" /> <file name="locale\ext-lang-sp.js" path="locale" /> <file name="locale\ext-lang-no.js" path="locale" /> <file name="widgets\layout\AbsoluteForm.js" path="widgets\layout" /> <file name="widgets\layout\AbsoluteFormLayout.js" path="widgets\layout" /> <file name="widgets\grid\GridColumn.js" path="widgets\grid" /> <file name="legacy\layout\BasicLayoutRegion.js" path="legacy\layout" /> <file name="legacy\layout\BorderLayout.js" path="legacy\layout" /> <file name="legacy\layout\BorderLayoutRegions.js" path="legacy\layout" /> <file name="legacy\layout\ContentPanels.js" path="legacy\layout" /> <file name="legacy\layout\LayoutManager.js" path="legacy\layout" /> <file name="legacy\layout\LayoutRegion.js" path="legacy\layout" /> <file name="legacy\layout\LayoutStateManager.js" path="legacy\layout" /> <file name="legacy\layout\ReaderLayout.js" path="legacy\layout" /> <file name="legacy\layout\SplitLayoutRegion.js" path="legacy\layout" /> <file name="legacy\AbstractGridView.js" path="legacy" /> <file name="legacy\BasicDialog.js" path="legacy" /> <file name="legacy\GridView2.js" path="legacy" /> <file name="legacy\JsonView.js" path="legacy" /> <file name="legacy\MasterTemplate.js" path="legacy" /> <file name="legacy\View.js" path="legacy" /> <file name="widgets\grid\Column.js" path="widgets\grid" /> <file name="adapter\ext-base.js" path="adapter" /> <file name="adapter\jquery-bridge.js" path="adapter" /> <file name="adapter\prototype-bridge.js" path="adapter" /> <file name="adapter\yui-bridge.js" path="adapter" /> <file name="core\CompositeElement.js" path="core" /> <file name="core\DomHelper.js" path="core" /> <file name="core\DomQuery.js" path="core" /> <file name="core\Element.js" path="core" /> <file name="core\EventManager.js" path="core" /> <file name="core\Ext.js" path="core" /> <file name="core\Fx.js" path="core" /> <file name="core\Template.js" path="core" /> <file name="core\UpdateManager.js" path="core" /> <file name="data\ArrayReader.js" path="data" /> <file name="data\Connection.js" path="data" /> <file name="data\DataField.js" path="data" /> <file name="data\DataProxy.js" path="data" /> <file name="data\DataReader.js" path="data" /> <file name="data\GroupingStore.js" path="data" /> <file name="data\HttpProxy.js" path="data" /> <file name="data\JsonReader.js" path="data" /> <file name="data\JsonStore.js" path="data" /> <file name="data\MemoryProxy.js" path="data" /> <file name="data\Record.js" path="data" /> <file name="data\ScriptTagProxy.js" path="data" /> <file name="data\SimpleStore.js" path="data" /> <file name="data\SortTypes.js" path="data" /> <file name="data\Store.js" path="data" /> <file name="data\StoreMgr.js" path="data" /> <file name="data\Tree.js" path="data" /> <file name="data\XmlReader.js" path="data" /> <file name="dd\DDCore.js" path="dd" /> <file name="dd\DragSource.js" path="dd" /> <file name="dd\DragTracker.js" path="dd" /> <file name="dd\DragZone.js" path="dd" /> <file name="dd\DropTarget.js" path="dd" /> <file name="dd\DropZone.js" path="dd" /> <file name="dd\Registry.js" path="dd" /> <file name="dd\ScrollManager.js" path="dd" /> <file name="dd\StatusProxy.js" path="dd" /> <file name="locale\ext-lang-af.js" path="locale" /> <file name="locale\ext-lang-bg.js" path="locale" /> <file name="locale\ext-lang-ca.js" path="locale" /> <file name="locale\ext-lang-cs.js" path="locale" /> <file name="locale\ext-lang-da.js" path="locale" /> <file name="locale\ext-lang-de.js" path="locale" /> <file name="locale\ext-lang-el_GR.js" path="locale" /> <file name="locale\ext-lang-en.js" path="locale" /> <file name="locale\ext-lang-en_UK.js" path="locale" /> <file name="locale\ext-lang-es.js" path="locale" /> <file name="locale\ext-lang-fa.js" path="locale" /> <file name="locale\ext-lang-fr.js" path="locale" /> <file name="locale\ext-lang-fr_CA.js" path="locale" /> <file name="locale\ext-lang-gr.js" path="locale" /> <file name="locale\ext-lang-he.js" path="locale" /> <file name="locale\ext-lang-hr.js" path="locale" /> <file name="locale\ext-lang-hu.js" path="locale" /> <file name="locale\ext-lang-id.js" path="locale" /> <file name="locale\ext-lang-it.js" path="locale" /> <file name="locale\ext-lang-ja.js" path="locale" /> <file name="locale\ext-lang-ko.js" path="locale" /> <file name="locale\ext-lang-lt.js" path="locale" /> <file name="locale\ext-lang-lv.js" path="locale" /> <file name="locale\ext-lang-mk.js" path="locale" /> <file name="locale\ext-lang-nl.js" path="locale" /> <file name="locale\ext-lang-no_NB.js" path="locale" /> <file name="locale\ext-lang-no_NN.js" path="locale" /> <file name="locale\ext-lang-pl.js" path="locale" /> <file name="locale\ext-lang-pt.js" path="locale" /> <file name="locale\ext-lang-pt_BR.js" path="locale" /> <file name="locale\ext-lang-ro.js" path="locale" /> <file name="locale\ext-lang-ru.js" path="locale" /> <file name="locale\ext-lang-sk.js" path="locale" /> <file name="locale\ext-lang-sl.js" path="locale" /> <file name="locale\ext-lang-sr.js" path="locale" /> <file name="locale\ext-lang-sr_RS.js" path="locale" /> <file name="locale\ext-lang-sv_SE.js" path="locale" /> <file name="locale\ext-lang-th.js" path="locale" /> <file name="locale\ext-lang-tr.js" path="locale" /> <file name="locale\ext-lang-ukr.js" path="locale" /> <file name="locale\ext-lang-vn.js" path="locale" /> <file name="locale\ext-lang-zh_CN.js" path="locale" /> <file name="locale\ext-lang-zh_TW.js" path="locale" /> <file name="state\CookieProvider.js" path="state" /> <file name="state\Provider.js" path="state" /> <file name="state\StateManager.js" path="state" /> <file name="util\ClickRepeater.js" path="util" /> <file name="util\CSS.js" path="util" /> <file name="util\Date.js" path="util" /> <file name="util\DelayedTask.js" path="util" /> <file name="util\Format.js" path="util" /> <file name="util\JSON.js" path="util" /> <file name="util\KeyMap.js" path="util" /> <file name="util\KeyNav.js" path="util" /> <file name="util\MixedCollection.js" path="util" /> <file name="util\Observable.js" path="util" /> <file name="util\TaskMgr.js" path="util" /> <file name="util\TextMetrics.js" path="util" /> <file name="util\XTemplate.js" path="util" /> <file name="widgets\form\Action.js" path="widgets\form" /> <file name="widgets\form\BasicForm.js" path="widgets\form" /> <file name="widgets\form\Checkbox.js" path="widgets\form" /> <file name="widgets\form\Combo.js" path="widgets\form" /> <file name="widgets\form\DateField.js" path="widgets\form" /> <file name="widgets\form\Field.js" path="widgets\form" /> <file name="widgets\form\FieldSet.js" path="widgets\form" /> <file name="widgets\form\Form.js" path="widgets\form" /> <file name="widgets\form\Hidden.js" path="widgets\form" /> <file name="widgets\form\HtmlEditor.js" path="widgets\form" /> <file name="widgets\form\Label.js" path="widgets\form" /> <file name="widgets\form\NumberField.js" path="widgets\form" /> <file name="widgets\form\Radio.js" path="widgets\form" /> <file name="widgets\form\TextArea.js" path="widgets\form" /> <file name="widgets\form\TextField.js" path="widgets\form" /> <file name="widgets\form\TimeField.js" path="widgets\form" /> <file name="widgets\form\TriggerField.js" path="widgets\form" /> <file name="widgets\form\VTypes.js" path="widgets\form" /> <file name="widgets\grid\AbstractSelectionModel.js" path="widgets\grid" /> <file name="widgets\grid\CellSelectionModel.js" path="widgets\grid" /> <file name="widgets\grid\CheckboxSelectionModel.js" path="widgets\grid" /> <file name="widgets\grid\ColumnDD.js" path="widgets\grid" /> <file name="widgets\grid\ColumnModel.js" path="widgets\grid" /> <file name="widgets\grid\ColumnSplitDD.js" path="widgets\grid" /> <file name="widgets\grid\EditorGrid.js" path="widgets\grid" /> <file name="widgets\grid\GridDD.js" path="widgets\grid" /> <file name="widgets\grid\GridEditor.js" path="widgets\grid" /> <file name="widgets\grid\GridPanel.js" path="widgets\grid" /> <file name="widgets\grid\GridView.js" path="widgets\grid" /> <file name="widgets\grid\GroupingView.js" path="widgets\grid" /> <file name="widgets\grid\PropertyGrid.js" path="widgets\grid" /> <file name="widgets\grid\RowNumberer.js" path="widgets\grid" /> <file name="widgets\grid\RowSelectionModel.js" path="widgets\grid" /> <file name="widgets\layout\AbsoluteLayout.js" path="widgets\layout" /> <file name="widgets\layout\AccordionLayout.js" path="widgets\layout" /> <file name="widgets\layout\AnchorLayout.js" path="widgets\layout" /> <file name="widgets\layout\BorderLayout.js" path="widgets\layout" /> <file name="widgets\layout\CardLayout.js" path="widgets\layout" /> <file name="widgets\layout\ColumnLayout.js" path="widgets\layout" /> <file name="widgets\layout\ContainerLayout.js" path="widgets\layout" /> <file name="widgets\layout\FitLayout.js" path="widgets\layout" /> <file name="widgets\layout\FormLayout.js" path="widgets\layout" /> <file name="widgets\layout\TableLayout.js" path="widgets\layout" /> <file name="widgets\menu\Adapter.js" path="widgets\menu" /> <file name="widgets\menu\BaseItem.js" path="widgets\menu" /> <file name="widgets\menu\CheckItem.js" path="widgets\menu" /> <file name="widgets\menu\ColorItem.js" path="widgets\menu" /> <file name="widgets\menu\ColorMenu.js" path="widgets\menu" /> <file name="widgets\menu\DateItem.js" path="widgets\menu" /> <file name="widgets\menu\DateMenu.js" path="widgets\menu" /> <file name="widgets\menu\Item.js" path="widgets\menu" /> <file name="widgets\menu\Menu.js" path="widgets\menu" /> <file name="widgets\menu\MenuMgr.js" path="widgets\menu" /> <file name="widgets\menu\Separator.js" path="widgets\menu" /> <file name="widgets\menu\TextItem.js" path="widgets\menu" /> <file name="widgets\tips\QuickTip.js" path="widgets\tips" /> <file name="widgets\tips\QuickTips.js" path="widgets\tips" /> <file name="widgets\tips\Tip.js" path="widgets\tips" /> <file name="widgets\tips\ToolTip.js" path="widgets\tips" /> <file name="widgets\tree\AsyncTreeNode.js" path="widgets\tree" /> <file name="widgets\tree\TreeDragZone.js" path="widgets\tree" /> <file name="widgets\tree\TreeDropZone.js" path="widgets\tree" /> <file name="widgets\tree\TreeEditor.js" path="widgets\tree" /> <file name="widgets\tree\TreeEventModel.js" path="widgets\tree" /> <file name="widgets\tree\TreeFilter.js" path="widgets\tree" /> <file name="widgets\tree\TreeLoader.js" path="widgets\tree" /> <file name="widgets\tree\TreeNode.js" path="widgets\tree" /> <file name="widgets\tree\TreeNodeUI.js" path="widgets\tree" /> <file name="widgets\tree\TreePanel.js" path="widgets\tree" /> <file name="widgets\tree\TreeSelectionModel.js" path="widgets\tree" /> <file name="widgets\tree\TreeSorter.js" path="widgets\tree" /> <file name="widgets\Action.js" path="widgets" /> <file name="widgets\BoxComponent.js" path="widgets" /> <file name="widgets\Button.js" path="widgets" /> <file name="widgets\ColorPalette.js" path="widgets" /> <file name="widgets\Component.js" path="widgets" /> <file name="widgets\ComponentMgr.js" path="widgets" /> <file name="widgets\Container.js" path="widgets" /> <file name="widgets\CycleButton.js" path="widgets" /> <file name="widgets\DataView.js" path="widgets" /> <file name="widgets\DatePicker.js" path="widgets" /> <file name="widgets\Editor.js" path="widgets" /> <file name="widgets\Layer.js" path="widgets" /> <file name="widgets\LoadMask.js" path="widgets" /> <file name="widgets\MessageBox.js" path="widgets" /> <file name="widgets\PagingToolbar.js" path="widgets" /> <file name="widgets\Panel.js" path="widgets" /> <file name="widgets\PanelDD.js" path="widgets" /> <file name="widgets\ProgressBar.js" path="widgets" /> <file name="widgets\Resizable.js" path="widgets" /> <file name="widgets\Shadow.js" path="widgets" /> <file name="widgets\Slider.js" path="widgets" /> <file name="widgets\SplitBar.js" path="widgets" /> <file name="widgets\SplitButton.js" path="widgets" /> <file name="widgets\TabPanel.js" path="widgets" /> <file name="widgets\Toolbar.js" path="widgets" /> <file name="widgets\Viewport.js" path="widgets" /> <file name="widgets\Window.js" path="widgets" /> <file name="widgets\WindowManager.js" path="widgets" /> <file name="debug.js" path="" /> <file name="widgets\StatusBar.js" path="widgets" /> </project>
export { default as ProvideAlerts, Alerts, useAlert } from "./ProvideAlerts";
const test = require('ava'); const request = require('supertest-as-promised'); const Trade = require('../../models/Trade'); const makeApp = require('./_app'); const userFixtures = require('./_users'); const testTrade = { requester: 1, requestee: 2, requestee_book: 1, }; let TOKEN_1; let TOKEN_2; function approveTrade(tradeId, token) { return request(makeApp()) .post(`/api/trade/${tradeId}/approve`) .set('Authorization', `Bearer ${token}`) .send(); } test.before('Get users\' tokens', async t => { try { [TOKEN_1, TOKEN_2] = await userFixtures.getUserTokens(); } catch (err) { console.log(err); t.fail(); } return; }); test('should get a user\'s pending trades', t => { return request(makeApp()) .get('/api/trade/pending') .set('Authorization', `Bearer ${TOKEN_1}`) .then(res => { res.body.map(trade => { t.is(trade.requester, 1); t.false(trade.requester_approval && trade.requestee_approval); }); }); }); test('should get a user\'s trade requests', t => { return request(makeApp()) .get('/api/trade/requests') .set('Authorization', `Bearer ${TOKEN_1}`) .then(res => { res.body.map(trade => { t.is(trade.requestee, 1); t.false(trade.requester_approval && trade.requestee_approval); }); }); }); test('should get a user\'s completed trades', t => { return request(makeApp()) .get('/api/trade/completed') .set('Authorization', `Bearer ${TOKEN_1}`) .then(res => { res.body.map(trade => { t.true(trade.requester === 1 || trade.requestee === 1); t.true(trade.requester_approval && trade.requestee_approval); }); }); }); test('should not add a trade for unauthenticated user', t => { return request(makeApp()) .post('/api/trade') .set('Accept', 'application/json') .then(res => t.is(res.status, 401)); }); test('should add a trade for an authenticated user', async t => { return request(makeApp()) .post('/api/trade') .set('Authorization', `Bearer ${TOKEN_1}`) .set('Accept', 'application/json') .send({ requestee: 2, requesteeBook: 2, }) .then(res => { return t.is(res.status, 200); }); }); test('should approve a trade for a user', async t => { const trade = await new Trade(testTrade).save(); return request(makeApp()) .post(`/api/trade/${trade.id}/approve`) .set('Authorization', `Bearer ${TOKEN_1}`) .send() .then(res => { t.is(res.status, 200); return trade.refresh() .then(updated => t.is(updated.get('requester_approval'), true)); }); }); test('should not approve a trade for unauthenticated users', async t => { const trade = await new Trade(testTrade).save(); await request(makeApp()) .post(`/api/trade/${trade.id}/approve`) .set('Authorization', 'Bearer poop') .send() .then(res => { t.is(res.status, 401); }); return trade.refresh() .then(updated => t.is(updated.get('requester_approval'), false)); }); test('should allow requestee and requester to add/edit book to trade', async t => { const trade = await new Trade(testTrade).save(); await request(makeApp()) .post(`/api/trade/${trade.id}/select-book/2`) .set('Authorization', `Bearer ${TOKEN_1}`) .send() .then(res => { t.is(res.status, 200); }); await trade.refresh() .then(updated => t.is(updated.get('requestee_book'), 2)); await request(makeApp()) .post(`/api/trade/${trade.id}/select-book/1`) .set('Authorization', `Bearer ${TOKEN_2}`) .send() .then(res => { t.is(res.status, 200); }); return trade.refresh() .then(updated => t.is(updated.get('requester_book'), 1)); }); test('should request trade as one user, then accept it as another', async t => { const app = makeApp(); const tradeId = await request(app) .post('/api/trade/') .set('Authorization', `Bearer ${TOKEN_1}`) .send({ requestee: 2, requesteeBook: 1 }) .then(res => { t.is(res.status, 200); t.truthy(res.body.id); return res.body.id; }); await approveTrade(tradeId, TOKEN_1) .then(res => { return t.is(res.status, 200); }); await approveTrade(tradeId, TOKEN_2) .then(res => { return t.is(res.status, 200); }); return Trade.forge({ id: tradeId }).fetch() .then(trade => trade.toJSON()) .then(trade => { t.true(trade.requester_approval); t.true(trade.requestee_approval); }); }); test('should request trade as one user, approve it, then decline it as another', async t => { const app = makeApp(); const tradeId = await request(app) .post('/api/trade/') .set('Authorization', `Bearer ${TOKEN_1}`) .send({ requestee: 2, requesteeBook: 1 }) .then(res => { t.is(res.status, 200); t.truthy(res.body.id); return res.body.id; }); await approveTrade(tradeId, TOKEN_1) .then(res => { return t.is(res.status, 200); }); await request(app) .delete(`/api/trade/${tradeId}`) .set('Authorization', `Bearer ${TOKEN_2}`) .then(res => t.is(res.status, 204)); return Trade.forge({ id: tradeId }).fetch() .then(trade => { if (trade) { return t.fail(); } return t.pass(); }); });
/** * Developer: Stepan Burguchev * Date: 8/14/2015 * Copyright: 2009-2015 Comindware® * All Rights Reserved * * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware * The copyright notice above does not evidence any * actual or intended publication of such source code. */ /* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */ define([ 'comindware/core', 'text!../templates/canvas.html' ], function (core, template) { 'use strict'; return Marionette.LayoutView.extend({ initialize: function (options) { core.utils.helpers.ensureOption(options, 'view'); }, template: Handlebars.compile(template), regions: { view: '.js-view-region' }, onShow: function () { if (this.options.canvas) { this.$el.css(this.options.canvas); } if (this.options.region) { this.listenTo(this.view, 'before:show', function () { this.view.$el.css(this.options.region); }.bind(this)); } this.view.show(this.options.view); } }); });
const Contact = require("../models/contact-model"); createContact = (req, res) => { Contact.create({ name: req.body.name, email: req.body.email, link: req.body.link, subject: req.body.subject, message: req.body.message }, (err) => { if (err) { return res.status(400).json({ success: false, error: err }); } return res.status(200).json({ success: true, data: "Contact was created successfully." }); }) }; module.exports = { createContact };