text
stringlengths
7
3.69M
/* eslint-disable react/jsx-indent */ import React from 'react'; import { Link } from 'react-router-dom'; import styles from './Header.module.css'; import logoImage from '../../resources/pokemon-logo.png'; import AuthorizationForm from '../Auth'; const Header = () => { return ( <div className={styles.main}> <div className={styles.leftSide}> <div className={styles.logo}> <Link to='/' > <img src={logoImage} alt='App-logo'/> </Link> </div> <div className={styles.title}> <p>App Title</p> </div> </div> <div className={styles.center}> <div><Link to='/'>Home</Link></div> <div><Link to='/'>Help</Link></div> <div><Link to='/'>Favorite</Link></div> <div><Link to='/'>About</Link></div> </div> <div className={styles.rightSide}> <AuthorizationForm /> </div> </div> ); }; export default Header;
/*! * miniquery */ /* * ---------------------------------------------------------------------------- * Element Selector * ---------------------------------------------------------------------------- */ class SweetSelector{ static select(input){ return document.querySelector(input); } } /* * ----------------------------------------------------------------------------- * DOM Manipulators * ----------------------------------------------------------------------------- */ class DOM { static hide(input){ return document.querySelector(input).style.visibility = "hidden"; } static show(input){ return document.querySelector(input).style.visibility = "visible" } static removeClass(kelas, rm){ return document.querySelector(kelas).classList.remove(rm); } static addClass(kelas, ad){ return document.querySelector(kelas).classList.add(ad); } } /* * ---------------------------------------------------------------------------- * Event Dispatcher * ---------------------------------------------------------------------------- */ class EventDispatcher { static on(input, action, cb){ return document.querySelector(input).addEventListener(action, cb); } } /* * ---------------------------------------------------------------------------- * AJAX Wrapper * ---------------------------------------------------------------------------- */ class AjaxWrapper { static request(obj) { let xhttp = new XMLHttpRequest() xhttp.open(obj.type, obj.url, true); xhttp.onload = function() { if (xhttp.status >= 200) { obj.success(this.responseText) } else { obj.fail() } }; xhttp.onerror = function() { obj.fail() }; xhttp.send(); } } /* * ---------------------------------------------------------------------------- * Alias miniquery * ---------------------------------------------------------------------------- */
import Sequelize from 'sequelize' import db from '../connect' const Image = db.define( 'image', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true }, title: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, description: { type: Sequelize.TEXT, allowNull: false, defaultValue: '' }, localId: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, format: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, host: { type: Sequelize.ENUM, values: ['s3', 'mia', 'local'], defaultValue: 's3' }, s3Bucket: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, captionCredit: { type: Sequelize.TEXT, allowNull: false, defaultValue: '' } // organizationId:{ // type: Sequelize.UUID, // references: { // model: 'organization', // key: 'id' // }, // onDelete: 'cascade', // onUpdate: 'cascade' // // } }, { freezeTableName: true, hooks: { afterDestroy: async (image, options) => { try { console.log(image.id) console.log('this is where we make sure to delete the s3 files') } catch (ex) { console.error(ex) } } } } ) export default Image
import React, { Component } from "react"; import "./loader.css"; export default class CoinLoader extends Component { render() { return <div styleName="loader">Loading...</div>; } }
var alert = require("../helpers/alert"); app.controller('MoreController', function($scope, $rootScope) { // $rootScope.addAll(); alert.alertInMore(); });
// # Learning Resource Router // ## learning_resource.router.js // Imports the required dependencies. const _ = require('lodash'); const highland = require('highland'); const { AMQP_URL } = require('../config'); const AmqpLib = require('simple-amqplib-wrapper'); const log = require('../commons/logger')('Learning_Resource_Router'); const amqp = new AmqpLib(AMQP_URL); // `routeLearningResourceToFactory` routes a Learning Resource to a Node Factory. // Checks for the properties.mediaContentId as a necessary property to create node. // If the property exists it sends the node to the Node Factory. const routeLearningResourceToFactory = (data) => { const { triples } = data; const createNodesAndRelationshipObjects = (triple) => { if (_.get(triple, 'source.properties.resourceId')) { log.debug('Sending to node factory'); amqp.sendToQueue('node_factory', triple.source); } if (_.get(triple, 'target.properties.name')) { log.debug('Sending to node factory'); amqp.sendToQueue('node_factory', triple.target); } if (_.get(triple, 'relation.properties.relation')) { log.debug('Sending to relation factory'); amqp.sendToQueue('relation_factory', triple); } }; triples.map(createNodesAndRelationshipObjects); return data; }; // Exports the routing pipeline. It maps the input stream to `routeConceptsToFactory` module.exports = highland.pipeline(highland.map(routeLearningResourceToFactory));
;if (typeof jQuery === 'undefined') { console.warn('Superfish requires jQuery to run'); } else { jQuery(function () { jQuery('ul.sf-menu').superfish(); }); }
import React, { PureComponent, Fragment } from 'react'; import ArticleSingleContainer from 'containers/ArticleSingleContainer'; import LineCaption from 'components/LineCaption'; import ArticleCommentsContainer from 'containers/ArticleCommentsContainer'; export default class ArticlePageContainer extends PureComponent { render() { return ( <Fragment> <ArticleSingleContainer idArticle = {this.props.match.params.idArticle} /> <LineCaption /> <ArticleCommentsContainer idArticle = {this.props.match.params.idArticle} /> </Fragment> ) } }
const mongoose = require('mongoose'); /**connection to the database */ mongoose.set('useNewUrlParser', true); mongoose.set('useCreateIndex', true); mongoose.set('useUnifiedTopology', true); mongoose.Promise = global.Promise; mongoose.connect('mongodb+srv://admin:admin@demodb-ynmyj.mongodb.net/booktopus?retryWrites=true&w=majority'); var uploadBookSchema = mongoose.Schema({ book_title: String, description: String, authorName: String, branch: String, semester: String, edition: Number, isbnCode: Number, imageName: String, availability: Boolean, uploadedBy_id: { type: mongoose.Schema.Types.ObjectId }, uploadedAt: { type: Date, default: Date.now(), }, updatedAt: { type: Date, default: Date.now() } }) var uploadBookModel = mongoose.model('upload_book_collection', uploadBookSchema); module.exports = uploadBookModel;
$(function() { $('#loginOutButton').click(function(){ var userName = $('#userName').val(); window.location.href="loginOut.htm?userName="+userName; }); });
const user = require("./typedefs/user"); module.exports = class UserDAO { constructor(dbConnection) { this.User = dbConnection.createModel('user', user); this.User.sync({ force: true }) .then(() => { this.User.create({ userName: 'flo', firstName: 'Florian', lastName: 'Dorau' }); }).catch((err) => { console.log(err); }); } async persist(data) { return this.User.create(data); } async findAll() { return this.User.findAll(); } async findById(id) { return this.User.findById(id); } };
// Built-in components import Head from "next/head"; // Custom components import Banner from "../components/Banner.js"; import APIPath from "../components/APIPath.js"; import AssetData from "../components/AssetData.js"; import SiteData from "../components/SiteData.js"; import UserData from "../components/UserData.js"; import currentTime from "../currentTime.js"; // Global constants const ivmCredentials = Buffer.from(process.env.IVM_CREDENTIALS).toString( "base64" ); const apiURL = "https://localhost:3780"; const requestHeaders = { headers: { Authorization: `Basic ${ivmCredentials}`, }, }; export async function getStaticProps() { const IVMRequest = await Promise.all([ // Asset data fetch(`${apiURL}/api/3/assets/1`, requestHeaders), // Site data fetch(`${apiURL}/api/3/sites/1`, requestHeaders), // User data fetch(`${apiURL}/api/3/users/1`, requestHeaders), ]); const IVMData = await Promise.all(IVMRequest.map((data) => data.json())); return { props: { IVMData, // Freeze currentTime at time of export currentTimeStatic: currentTime.valueOf() }, }; } export default function Home({ IVMData, currentTimeStatic }) { const [assetData, siteData, userData] = IVMData; return ( <main> <Head> <title>InsightVM API Thing</title> <link rel="icon" href="/favicon.ico" /> </Head> <Banner timestamp={ currentTimeStatic } /> {/* Asset block */} <h2 style={{ fontWeight: "bold" }}>Asset Data</h2> <APIPath path="/api/3/assets/1" /> <AssetData data={assetData} /> {/* Site block */} <h2 style={{ fontWeight: "bold" }}>Site Data</h2> <APIPath path="/api/3/sites/1" /> <SiteData data={siteData} /> {/* User block */} <h2 style={{ fontWeight: "bold" }}>User Data</h2> <APIPath path="/api/3/users/1" /> <UserData data={userData} /> </main> ); }
const lowerIdx = (arr, min) => { let l = 0, h = arr.length - 1; while (l <= h) { let mid = Math.floor((l + h) / 2); if (arr[mid]["salary"] >= min) h = mid - 1; else l = mid + 1; } return l; }; const higherIdx = (arr, max) => { let l = 0, h = arr.length - 1; while (l <= h) { let mid = Math.floor((l + h) / 2); if (arr[mid]["salary"] <= max) l = mid + 1; else h = mid - 1; } return h; }; const jobsInRange = (jobs, min, max) => { jobs = jobs.sort((job1, job2) => job1.salary - job2.salary); const l = lowerIdx(jobs, min); const h = higherIdx(jobs, max); return jobs.slice(l, h + 1); }; module.exports = { jobsInRange };
import {takeEvery,call,fork,put,takeLatest,take} from "redux-saga/effects"; // import { getBooksRequest } from "../actions"; function* getBooks(){ yield put({ type: "GET_BOOKS" }) } function* watchGetBooksRequest(){ yield takeEvery('GET_BOOKS_REQUEST', getBooks) } const booksSagas = [ fork(watchGetBooksRequest), ] export default booksSagas;
import { Component } from "react"; import { Card, Col, Container, Row } from "react-bootstrap"; import { Space, Typography } from "antd"; import Search from "antd/es/input/Search"; import decode from "jwt-decode"; import axios from "axios"; import { withRouter } from "react-router"; class Homepage extends Component { state = { routes: [] } componentDidMount = async () => { await axios.get('https://backendtransportsystem.herokuapp.com/public/getRoutes').then(res => { if (res.data.success) { this.setState({ routes: res.data.data }) } }) } checkLogin = () => { if (sessionStorage.token) { this.setState({ user: decode(sessionStorage.token).position }); } else { window.location = '/login' } } render() { return ( <> <div> <Container style={{ marginTop: '3%' }}> <Row> <Col > <Typography style={{ fontSize: '30px' }} gutterBottom> Welcome to Travels </Typography> </Col> <Col style={{ width: "50%"}}> <div> <Space direction="vertical" style={{ width: "100%"}}> <Search placeholder="Search Destination" style={{ width: "100%"}} enterButton /> </Space> </div> </Col> </Row> </Container> </div> <Container style={{ backgroundColor: 'white', marginBottom: '30px' }}> {this.state.routes.map((item) => ( <> <Card style={{ marginTop: '2%', width: '100%', background: '#f2f2f2', boxShadow: "0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)" }}> <Row> <Col style={{ width: '50%', height: 'auto' }}> <Card.Img variant="top" src={item.img} style={{ width: '100%', height: 'auto', marginTop: '1.1%', marginLeft: '1.1%', marginBottom: '1.1%' }} /> </Col> <Col> <Card.Body> <Row style={{ marginTop: '10%', marginRight: '10%' }}> <Col> <Card.Title style={{ fontSize: '20px' }}>{item.source} - {item.destination}</Card.Title> </Col> </Row> </Card.Body> </Col> </Row> </Card> </> ))} </Container> </> ) } } export default withRouter(Homepage);
import React from 'react' import { Container, Row, Col, Button, Input } from 'reactstrap'; import { Link } from 'react-router-dom'; import axios from 'axios'; import base64 from 'base-64'; class Signin extends React.Component { constructor() { super(); this.state = { admin_email: '', admin_password: '' } this.handleChangeEmail = this.handleChangeEmail.bind(this); this.handleChangePassword = this.handleChangePassword.bind(this); } handleChangeEmail = e => { this.setState({ admin_email: e.target.value }) } handleChangePassword = e => { this.setState({ admin_password: e.target.value }) } onSubmit = e => { e.preventDefault(); const admin = { admin_email: this.state.admin_email, admin_password: this.state.admin_password, } axios({ method: "POST", url: "http://localhost:4000/admins/login", data: admin, headers: { "Content-type": "application/json; charset=UTF-8" } }) .then(res => { if (res.data) { let data = JSON.stringify(res.data); data = base64.encode(data) console.log(data) localStorage.setItem('admin_login', data); window.location.replace('/') } }) } render() { return ( <> <Container> <Row className="justify-content-center"> <Col xs="12" sm="12" md={{ size: 4 }}> <h3 className="mt-4 text-center">Form Login</h3> <hr /> <form onSubmit={this.onSubmit}> <Row> <Col> <label>Email</label> <Input onChange={this.handleChangeEmail} name="email" type="email" value={this.state.admin_email} className="mb-3" placeholder="ex : admin@gmail.com" required /> </Col> </Row> <Row> <Col> <label>Password</label> <Input onChange={this.handleChangePassword} name="password" type="password" value={this.state.admin_password} className="mb-3" placeholder="ex : *******" required /> </Col> </Row> <Row> <Col> <Button type="submit" className="btn btn-info btn-block mb-3">Login</Button> </Col> </Row> </form> </Col> </Row> <Row> <Col> <center> <Link className="text-center mt-4" to="/signup">Didnt have any account ?</Link> </center> </Col> </Row> </Container> </> ) } } export default Signin;
{"Status":0,"Message":"","UserMessage":"Your reward has been granted"}
'use strict'; describe('Service: UsersBillingInfoService', function () { // load the service's module beforeEach(module('cg7App')); // instantiate service var UsersBillingInfoService; beforeEach(inject(function (_UsersBillingInfoService_) { UsersBillingInfoService = _UsersBillingInfoService_; })); it('should do something', function () { expect(!!UsersBillingInfoService).toBe(true); }); });
(function(){ function ArticleFinder(){ }; ArticleFinder.prototype.findArticleData = function(activeTab, data){ this.activeTab = activeTab; this.data = data; if(this.activeTab=='news'){ return this.data[0].news; }else if(this.activeTab=='enter'){ return this.data[1].enter; }else if(this.activeTab=='sports'){ return this.data[2].sports; } return undefined; }; window.ArticleFinder = ArticleFinder; })();
/** Really, any attributes will be carried accros */ var GridRowAttributes = (function () { function GridRowAttributes() { } return GridRowAttributes; }()); export { GridRowAttributes };
import Vue from 'vue' import permission from './mixin/permission' import permissionDemo from './views/permission-demo' import store from './store' Vue.config.productionTip = false //混入权限 Vue.mixin(permission) new Vue({ methods: { print: function () { console.log(this) } }, store, render: function (h) { return h(permissionDemo) } }).$mount('#app')
import CheckPage from '../pageobjects/CheckPage' describe('check', () => { const page = new CheckPage() it('open page', () => { page.auth() page.open('#/check/add') page.waitLoader() page.screenshot('open check page') }) it('check save format', () => { page.setFormat('%num%|%m%|%y%|%cvv2%') page.saveFormat() page.waitLoader() page.screenshot('save format') expect(page.getModalBodyText()).to.equal('Формат успешно сохранен') page.closeModal() }) it('check preview', () => { page.setCardFormat('1212365896578900|01|2018|600') page.showPreview() page.screenshot('preview') // expect(page.getPreviewCardNumber()).to.equal('1212365896578900') }) })
import { resolve, join } from 'path'; import cssnext from 'postcss-cssnext'; import values from 'postcss-modules-values'; import lost from 'lost'; import pxtorem from 'postcss-pxtorem'; import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import StatsPlugin from 'stats-webpack-plugin'; const dotenvPath = resolve(__dirname, '../.env'); require('dotenv').config( { path: dotenvPath }); process.env.NODE_ENV = 'production'; export default { context: resolve(join(__dirname, '../src')) , target: 'web' , devtool: 'sourcemap' , module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { babelrc: true } } , { test: /\.svg$/ , loader: 'svg!svgo' } , { test: /\.css$/ , loader: ExtractTextPlugin.extract('null', `css?modules&importLoaders=1 &localIdentName=[name]__[local]___[hash:base64:5]!postcss`) } ] } , plugins: [ new ExtractTextPlugin('styles.[hash].css') , new StatsPlugin('../webpack-stats.json') , new webpack.EnvironmentPlugin(Object.keys(process.env)) ] , postcss: () => [ cssnext, lost, pxtorem({ propWhiteList: [] }), values ] };
// @ts-check /* eslint-disable react/static-property-placement */ import React from 'react'; // BEGIN (write your solution here) export default class App extends React.Component { static defaultProps = { text: '', }; handleReset = () => { const { dispatch, resetText } = this.props; dispatch(resetText()); } handleUpdateText = (e) => { const { dispatch, updateText } = this.props; dispatch(updateText(e.target.value)); } render() { const {text} = this.props; return <div> <form> <input type="text" onChange = {this.handleUpdateText} value={text} /> <button type="button" onClick = {this.handleReset}>Reset</button> </form> {text.length > 0 && <div>{text}</div>} </div> } } // END
var dir_44c8ed0d325ab57ba67fdc8726f6a338 = [ [ "Private", "dir_ecc5ce1bacfbe3f0a86dfca4e0d40e86.html", "dir_ecc5ce1bacfbe3f0a86dfca4e0d40e86" ], [ "Public", "dir_e0b72804fc6af7ff2a40eccee45fe58a.html", "dir_e0b72804fc6af7ff2a40eccee45fe58a" ] ];
import React, { Component } from 'react'; class Counter extends Component { state = { items: ["Hello!"], value: undefined, }; handleSubmit= (event) => { event.preventDefault(); let userInput = event.target.item.value; event.target.item.value = ''; if (!userInput) return; this.setState({items: [ userInput, ...this.state.items ]}); } renderList = () => { let {items} = this.state; if (items.length === 0) return 'The list is empty!'; return( items.map((item, index) => (<li key={index}>{item} </li>)) ); } emptyList = () => { console.log('The list was emptied.') this.setState({items: this.state.items = []}); } itemCount = () => { let {items} = this.state; let are = 'are' let s = 's' if (items.length === 1) { are = 'is'; s = ''; } return (<p>There {are} currently {items.length} item{s} in the list.</p>) } render( ) { return ( <> <form style={{display: 'flex', flexDirection: 'column'}} onSubmit={this.handleSubmit}> <label htmlFor='item'>Add an item to the list</label> <input autoComplete= 'off' id= 'item' type='text' name='newItem' value={this.state.value}> </input> <button type='submit'>Submit</button> </form> <ul> {this.renderList()} </ul> <section className="info"> {this.itemCount()} <button onClick={this.emptyList}>Empty the list</button> </section> </> ); } } export default Counter;
const INVALID_CLASS = 'form-invalid'; var formFileLabel = document.querySelector('#form-file-label'); var formFileLabelInitVal = formFileLabel.innerText; var formFile = document.querySelector('#form-file'); var currentFile = ''; function formFileChange(e) { var file = e.target.value.split('\\').pop(); var fileOk = file !== ''; currentFile = fileOk ? file : ''; formFileLabel.innerText = fileOk ? file : formFileLabelInitVal; if (fileOk) { formFileLabel.classList.remove(INVALID_CLASS) } } formFile.addEventListener('change', formFileChange); formFile.addEventListener('click', formFileChange); var formTexts = document.querySelectorAll('.form-text'); function formSubmit() { var ok = true; if (currentFile === '') { ok = false; formFileLabel.classList.add(INVALID_CLASS); } else { formFileLabel.classList.remove(INVALID_CLASS); } var validate = function(formText, int, min, inclusive) { if (!validateNumberField(formText, int, min, inclusive)) { ok = false; formText.classList.add(INVALID_CLASS); } else { formText.classList.remove(INVALID_CLASS); } }; validate(document.querySelector('#form-x'), true, 0, true); validate(document.querySelector('#form-y'), true, 0, true); validate(document.querySelector('#form-width-l'), true, 1, true); validate(document.querySelector('#form-width-r'), true, 1, true); validate(document.querySelector('#form-height'), true, 1, true); validate(document.querySelector('#form-scale'), false, 0, false); validate(document.querySelector('#form-gap'), true, 0, true); return ok; } function validateNumberField(formText, int, min, inclusive) { // validate presence if (formText.value === '') { return false; } var fVal = parseFloat(formText.value); // validate min if ((inclusive && fVal < min) || (!inclusive && fVal <= min)) { return false; } // validate int return !(int && fVal !== Math.floor(fVal)); } for (var i = 0; i < formTexts.length; i++) { var formText = formTexts[i]; formText.addEventListener('change', function() { if (this.value !== '') { this.classList.remove(INVALID_CLASS); } }); }
var fs = require("fs"); var path = require("path"); var PACKAGE_KEY = "${PACKAGE}"; var CLASS_KEY = "${CLASS}"; var EMBEDS_KEY = "${EMBEDS}"; var PATH_KEY = "${PATH}"; var FILE_NAME_KEY = "${FILE_NAME}"; var FILE_EXT_KEY = "${FILE_EXT}"; var MIME_TYPE_KEY = "${MIME_TYPE}"; var templateFile = fs.readFileSync("templates/ClassEmbeds.tmpl", "utf8"); var templateEmbed = fs.readFileSync("templates/Embed.tmpl", "utf8"); if(process.argv.length != 7) { console.log("error arguments. args: folder:String className:String package:String saveFile:String embedPath:String"); return; } var folder = process.argv[2]; var className = process.argv[3]; var packageName = process.argv[4]; var saveFile = process.argv[5]; var embedPath = process.argv[6]; console.log("arguments: " + process.argv); var files = fs.readdirSync(folder); console.log("files: " + files); var embeds = ""; for (var prop in files) { var p = path.join(folder, files[prop]); if(!fs.statSync(p).isDirectory()) { var file = files[prop]; var ext = path.extname(file); var fileName = path.basename(p, ext); var mimeType = ""; switch(ext) { case ".png": case ".jpg": case ".jpeg": case ".bmp": case ".mp3": mimeType = ""; break; default: mimeType = ", mimeType = \"application/octet-stream\""; break; } embeds += templateEmbed.replace(PATH_KEY, embedPath).replace(FILE_NAME_KEY, fileName).replace(FILE_NAME_KEY, fileName).replace(FILE_EXT_KEY, ext).replace(MIME_TYPE_KEY, mimeType); embeds += "\r\n"; } } var fileContent = templateFile.replace(EMBEDS_KEY, embeds).replace(CLASS_KEY, className).replace(CLASS_KEY, className).replace(PACKAGE_KEY, packageName); fs.writeFileSync(saveFile, fileContent, "utf8"); console.log("DONE!");
import React from 'react'; import { ScatterChart, Scatter, XAxis, YAxis, ZAxis, CartesianGrid, Tooltip, Legend, ReferenceArea } from 'recharts'; const data01 = [ { x: 100, y: 200, z: 200 }, { x: 120, y: 100, z: 260 }, { x: 170, y: 300, z: 400 }, { x: 140, y: 250, z: 280 }, { x: 150, y: 400, z: 500 }, { x: 110, y: 280, z: 200 }, ]; const data02 = [ { x: 200, y: 260, z: 240 }, { x: 240, y: 290, z: 220 }, { x: 190, y: 290, z: 250 }, { x: 198, y: 250, z: 210 }, { x: 180, y: 280, z: 260 }, { x: 210, y: 220, z: 230 }, ]; const example = () => ( <ScatterChart width={730} height={250} margin={{ top: 20, right: 20, bottom: 10, left: 10 }}> <XAxis dataKey="x" name="stature" unit="cm" /> <YAxis dataKey="y" name="weight" unit="kg" /> <ZAxis dataKey="z" range={[4, 20]} name="score" unit="km" /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip cursor={{ strokeDasharray: '3 3' }} /> <Legend /> <Scatter name="A school" data={data01} fill="#8884d8" /> <Scatter name="B school" data={data02} fill="#82ca9d" /> <ReferenceArea x1={150} x2={180} y1={200} y2={300} stroke="red" strokeOpacity={0.3} /> </ScatterChart> ); export default { name: 'ReferenceArea', examples: [ { name: 'A ScatterChart with ReferenceArea', demo: example, code: `<ScatterChart width={730} height={250} margin={{ top: 20, right: 20, bottom: 10, left: 10 }}> <XAxis dataKey="x" name="stature" unit="cm" /> <YAxis dataKey="y" name="weight" unit="kg" /> <ZAxis dataKey="z" range={[4, 20]} name="score" unit="km" /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip cursor={{ strokeDasharray: '3 3' }} /> <Legend /> <Scatter name="A school" data={data01} fill="#8884d8" /> <Scatter name="B school" data={data02} fill="#82ca9d" /> <ReferenceArea x1={150} x2={180} y1={200} y2={300} stroke="red" strokeOpacity={0.3} /> </ScatterChart> `, }, ], props: [ { name: 'xAxisId', type: 'String | Number', defaultVal: '0', isOptional: false, desc: 'The id of x-axis which is corresponding to the data.', }, { name: 'yAxisId', type: 'String | Number', defaultVal: '0', isOptional: false, desc: 'The id of y-axis which is corresponding to the data.', }, { name: 'x1', type: 'Number | String', defaultVal: 'null', isOptional: true, desc: 'A boundary value of the area. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys. If one of x1 or x2 is invalidate, the area will cover along x-axis.', }, { name: 'x2', type: 'Number | String', defaultVal: 'null', isOptional: true, desc: 'A boundary value of the area. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys. If one of x1 or x2 is invalidate, the area will cover along x-axis.', }, { name: 'y1', type: 'Number | String', defaultVal: 'null', isOptional: true, desc: 'A boundary value of the area. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys. If one of y1 or y2 is invalidate, the area will cover along y-axis.', }, { name: 'y2', type: 'Number | String', defaultVal: 'null', isOptional: true, desc: 'A boundary value of the area. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys. If one of y1 or y2 is invalidate, the area will cover along y-axis.', }, { name: 'alwaysShow', type: 'Boolean', defaultVal: 'false', isOptional: false, desc: 'If the corresponding axis is a number axis and this option is set true, the value of reference line will be take into account when calculate the domain of corresponding axis, so that the reference line will always show.', examples: [{ name: 'A LineChart with alwaysShow ReferenceLine', url: '//jsfiddle.net/9shwdgtq/' }], }, { name: 'viewBox', type: 'Object', defaultVal: 'null', isOptional: false, desc: 'The box of viewing area, which has the shape of {x: someVal, y: someVal, width: someVal, height: someVal}, usually calculated internally.', }, { name: 'xAxis', type: 'Object', defaultVal: 'null', isOptional: false, desc: 'The configuration of the corresponding x-axis, usually calculated internally.', }, { name: 'yAxis', type: 'Object', defaultVal: 'null', isOptional: false, desc: 'The configuration of the corresponding y-axis, usually calculated internally.', }, { name: 'label', type: 'String | Number | ReactElement | Function', defaultVal: 'null', isOptional: true, desc: 'If set a string or a number, default label will be drawn, and the option is content. If set a React element, the option is the custom react element of drawing label. If set a function, the function will be called to render customized label.', format: [ `<ReferenceArea x1="01" x2="08" label="MAX"/>`, `<ReferenceArea y1={100} y2={500} label={<CustomizedLabel />}/>`, ], examples: [{ name: 'ReferenceLines with label', url: '/examples#LineChartWithReferenceLines', }] }, { name: 'isFront', type: 'Boolean', defaultVal: 'false', isOptional: false, desc: 'If set true, the line will be rendered in front of bars in BarChart, etc.' }, ], };
/** * Created by 项磊 on 2016/6/15. */ var setREM = function(){ var width = $(window).width()/10; $('html').css('font-size', width + 'px'); } var showTags = function(){ $('.tags').addClass('opacity-to-1'); $('.tags').removeClass('opacity-to-0'); } var closeTags = function(){ $('.tags').addClass('opacity-to-0'); $('.tags').removeClass('opacity-to-1'); } var removeTag = function(el){ $(el).parent().remove(); } setREM(); window.addEventListener('load', function(){ $('.lazyload').picLazyLoad({ threshold: 100 }); $('.tags').bind('touchmove', function(e){ e.preventDefault(); }); $('.img-list >.item').on('tap', function(e){ if($('.ui-checkbox',this).hasClass('selected')){ $('.ui-checkbox',this).removeClass('selected'); }else{ $('.ui-checkbox',this).addClass('selected'); } }); $('.style-table .row .item').on('tap', function(){ var name = $(this).html(); if($(this).hasClass('selected')){ $(this).removeClass('selected'); $('.tag-list .tag').each(function(){ if($('.title', this).html() === name){ $(this).remove(); return false; } }) }else{ $(this).addClass('selected'); var html = '<div class="tag">'+ '<div class="title">' + name + '</div>'+ '<div class="delete-btn"></div>'+ '</div>'; $('#showTages').parent().before(html); } }); $(document).on('tap', '.ui-btn', function(e){ var action = $(this).attr('data-action'); action && window[action](this); }) }); window.onresize=function(){ setREM(); }
import React, { Component } from 'react' import { View, Image, StyleSheet } from 'react-native' export default class LogoHead extends Component { render() { return ( <View style={ styles.box }> <Image style={ styles.logo } source={require('../components/assets/fortress_logo.png')}/> </View> ) } } const styles = StyleSheet.create({ box: { flexGrow: 1, paddingTop: 6, }, logo: { flex: 1, height: null, width: 150, alignSelf: 'center', resizeMode: 'contain', } })
let elasticsearch=require("elasticsearch"); elasticsearch = require('es'); var config = { server : { hosts : ['localhost:9200'] } }; var client = elasticsearch(config); // let client=new elasticsearch.Client({ // "host":"localhost:9200", // "log":'trace', // "apiVersion":"5.0", // "keepAlive":true // }); // client.ping({ // requestTimeout:1000 // },function(err){ // if(err){ // console.log("something went wrong"); // } // else{ // console.log("every thing is working fine"); // } // }); var options = { }; var commands = [ { index : { _index : 'dieties', _type : 'kitteh' } }, { name : 'hamish', breed : 'manx', color : 'tortoise' }, { index : { _index : 'dieties', _type : 'kitteh' } }, { name : 'dugald', breed : 'siamese', color : 'white' }, { index : { _index : 'dieties', _type : 'kitteh' } }, { name : 'keelin', breed : 'domestic long-hair', color : 'russian blue' } ]; client.bulk(options, commands, function (err, data) { if(err){ console.log("error occured",err); } }); // module.exports.elasticsearchobj= // client.search({ // "q":"elasticsearch" // }).then(function(body){ // var hits=body.hits.hits; // console.log("body contet in elasticsearch",hits); // },function(err){ // console.log("err occured during search"); // }); // client.search({ // "index":"bank", // "type":"account", // "body":{ // "query":{ // "bool":{ // "must": // [{ // "match_all":{} // }] // } // } // } // }).then(function(body){ // var hits=body.hits.hits; // console.log("hits",hits); // },function(err){ // console.log("error occured",err); // });
import React from 'react'; const App = () => ( <h1>Aplicacion de Erik</h1> ); export default App;
//Une fois mon HTML terminé, j'annonce toutes mes constantes const canvas = document.getElementById("canvas"); const score = document.getElementById("score"); const days = document.getElementById("days"); const endScreen = document.getElementById("endScreen"); daysLeft = 100; gameOverNumber = 50; loopPlay = false; start(); function start() { count = 0; // Quand on lance pas la fonction, le count se remet à 0 getFaster = 6000; // me permettra de faire poper les éléments plus vite :6 secondes daysRemaining = daysLeft; canvas.innerHTML = ""; // Quand je clique sur le bouton le canvas se vide et se met à 0 score.innerHTML = count; //et dans l'innerHtml on mettra le résultat de 0 // a chaque clic on fera un count ++1 et on affichera le counter (ligne56) days.innertHTML = daysRemaining; } loopPlay ? "" : game(); // Si tu es égale a vrai tu fais rien, si non tu lances la fonction game loopPlay = true; function game() { let randomTime = Math.round(Math.random() * getFaster); getFaster > 700 ? (getFaster = getFaster * 0.9) : ""; // SI tu es superieur a 700 alors getfaster tu es égal à get faster * 0.90 et si c'est faux on met rien setTimeout(() => { if (daysRemaining === 0) { // SI les jours restants sont === 0 on joue youWIng l'utilisateur à gagné youWin(); } else if (canvas.childElementCount < gameOverNumber) { // Si c'est en dessous de 50 virus, on continue à les faire poper et on relance game() virusPop(); game(); } else { // SI le nombre de gameOverNumber est superier, alors on lance la fonction gameover gameOver(); } }, randomTime); const gameOver = () => { endScreen.innerHTML = `<div class="gameOver">Game over <br/>score :${count} </div>`; endScreen.style.visibility = "visible"; endScreen.style.opacity = "1"; loopPlay = false; }; const youWin = () => { let accuracy = Math.round((count / daysLeft) * 100); // a chaque clic on perdra un jour de confinement on a droit a 60 clic dans le jeu donc en divisant le rsultat de nombre d'éléménet tué //par le nombre entier de clic possible, on tombera sur un pourcentage de réussite endScreen.innerHTML = `<div class="youWin">bravo ! tu as atomisé le virus <br/><span>précision : ${accuracy}%</span></div>`; endScreen.style.visibility = "visible"; endScreen.style.opacity = "1"; loopPlay = false; }; } virusPop(); function virusPop() { //Dans cette fonction je veux faire apparaitre des images de façon aléatoire let virus = new Image(); virus.src = "./media/basic-pics/pngwave.png"; virus.classList.add("virus"); // A chaque fois que je vais créer un virus, ça lui mettra la class"virus" MERCISASS virus.style.top = Math.random() * 500 + "px"; // ici je définis l'endroit ou le virus va pop. Dans la hauteur il va chercher aléatroirement entre 1 et 500px, tout pareil pour la largeur virus.style.left = Math.random() * 500 + "px"; let x, y; x = y = Math.random() * 45 + 30; // Je randomise la taille du virus. Grace au + 30, mon virus fera minimum 30px virus.style.setProperty("--x", `${x}px`); // La ou tu as la variable x, tu injectes le résultat de x virus.style.setProperty("--y", `${y}px`); let plusMinus = Math.random() < 0.5 ? -1 : 1; // Si math random est inferieur a 0.5 tu fais -1 SI NON +1 let trX = Math.random() * 500 * plusMinus; let trY = Math.random() * 500 * plusMinus; virus.style.setProperty("--trX", `${trX}px`); // La ou tu as la variable x, tu injectes le résultat de x virus.style.setProperty("--trY", `${trY}px`); canvas.appendChild(virus); //Virus est un enfant de canvas, il faut donc l'appeler } // Remove elemet clicked document.addEventListener("click", function (e) { // tu vas écouter le clc, a chaque clic tu vas faire ne fonction avec un evenemnt let targetElement = e.target || e.srcElement; // Let targetElement coorespond à = e.target OU || à z.qrcElement //console.log(targetElement); // Me permet d'identifier tous les éléments cliqués if (targetElement.classList.contains("virus")) { // SI targetElement sa classList contient 'virus' targetElement.remove(); /// Alors l'élément que tu as ciblé/cliqué tu l'enlève count++; //counteur +1 score.innerHTML = count; } }); canvas.addEventListener("click", () => { if (daysRemaining > 0) { daysRemaining--; // à chaque fois qu'on clic sur canvas t fais -1 days.innerHTML = daysRemaining; // on remet a jour sur le DOM } }); endScreen.addEventListener("click", () => { start(); endScreen.style.opacity = "0"; endScreen.style.visibility = "hidden"; });
import {useEffect, useState} from 'react'; import {getComponentName, getProps} from '../utils/pageDescription'; import loadImage from '../utils/loadImage'; export default (urlBase) => { const [pageDescriptions, setPageDescriptions] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { (async function getPages() { setLoading(true); let emptyPage = false; const loadedPageDescriptions = []; for (let pageNo = 1; !emptyPage; pageNo++) { const response = await fetch(`${urlBase}/${pageNo}.json`); if (response.status === 200) { try { const json = await response.json(); if (['ImagePage', 'FullscreenImagePage'].includes(getComponentName(json))) { await loadImage(getProps(json).imageLink); } loadedPageDescriptions.push(json); } catch (e) { emptyPage = true; } } else { emptyPage = true; } } setPageDescriptions(loadedPageDescriptions); setLoading(false); })(); }, [urlBase]); return [pageDescriptions, loading]; };
$(document).ready(function (e) { $('.cloned').fadeOut(0) $('.oneway').click(function () { if ($(this).is(':checked')) { $('.cloned').fadeOut(0); $('.toggler_one').fadeOut('slow'); } }) $('.return').click(function () { if ($(this).is(':checked')) { $('.cloned').fadeOut(0); $('.toggler_one').fadeIn('slow'); } }); $('.multi').click(function () { if ($(this).is(':checked')) { $('.cloned').fadeIn(0); $('.toggler_one').fadeOut(0); } }); $('.depart_date,.return_date').datepicker({ dateFormat: "dd, MM yy", numberOfMonths: 2, stepMonths: 2, minDate: +0, maxDate: "+331D" }); }); function loader() { var a = $('#CityPares_0__ReturnDateTime'); var b = $('#CityPares_0__ReturnDateTime').val(); var c = $('#CityPares_0__DepartureDateTime').val(); if ((a != null && b != "" && c != "" && (new Date(b).getTime() > new Date(c).getTime())) || (b == "" && c != "")) { if ($('#CityPares_0__Origin').val() != $('#CityPares_0__Destination').val()) { var wid = $(window).width(); var hei = $(window).height(); $('body').append('<div class="overBg"><p><img href="~/images/ajax-loader.gif" /> Loading please wait...</p></div>') $('.overBg').css({ 'width': wid, 'height': hei }) } else { alert('Check the origin destination'); return false; } } else { alert('Invalid dates'); return false; } }
import { connect } from 'react-redux'; import { push } from 'connected-react-router'; import Book from '../components/book/index.jsx'; import { actions } from '../modules/book/action'; import { actions as bookmarkActions } from '../modules/bookmark/action'; import File from '../models/file'; import { getUrlFromFile } from '../utils/consts'; function mapStateToProps(state) { const pageCount = state.book.pageCount; const page = Math.min(pageCount - 1, state.book.page); let prevDiff = 2; let nextDiff = 2; let singleMode = false; if (pageCount > 0 && state.book.images.length > 0) { if (page > 1) { const p1Img = state.book.images[page - 1]; const p2Img = state.book.images[page - 2]; if (p1Img && p1Img.width > p1Img.height || p2Img && p2Img.width > p2Img.height) { prevDiff = 1; } } const c1Img = state.book.images[page]; if (c1Img && c1Img.width > c1Img.height) { nextDiff = 1; singleMode = true; } if (pageCount - 1 > page) { const c2Img = state.book.images[page + 1]; if (c2Img && c2Img.width > c2Img.height) { nextDiff = 1; singleMode = true; } } } return { pageCount: state.book.pageCount, page: state.book.page, cacheStatus: state.book.cacheStatus, images: state.book.images, reverse: state.book.reverse, prevDiff, nextDiff, singleMode }; } function mapDispatchToProps(dispatch) { return { change_page: (page) => { dispatch(actions.change_page(page)); }, toggle_reverse: () => { dispatch(actions.toggle_reverse()); } }; } export default connect( mapStateToProps, mapDispatchToProps )(Book);
import { ERROR_KICKING_OUT_PLAYER, ERROR_LOADING_PLAYER, ERROR_LOADING_PLAYERS, ERROR_UPDATING_SETTINGS, KICK_OUT_CLEAR_ERROR, KICK_OUT_RESET_STATE, KICKED_OUT_PLAYER, KICKING_OUT_PLAYER, LOADED_PLAYER, LOADED_PLAYERS, LOADING_PLAYER, LOADING_PLAYERS, RESET_PLAYERS_STATE, UPDATE_SETTINGS_CLEAR_ERROR, UPDATE_SETTINGS_RESET_STATE, UPDATED_SETTINGS, UPDATING_SETTINGS, } from '../constants/players'; import omit from 'lodash/omit'; const INITIAL_STATE = { // players loadingPlayers: false, errorLoadingPlayers: null, lastVisible: null, byId: {}, // player loadingPlayer: false, errorLoadingPlayer: null, // kick out player kickingOutPlayer: false, errorKickingOut: '', requestKickOutSuccess: false, // updating player settings updatingPlayerSettings: {}, errorUpdatingPlayerSettings: {}, requestSentUpdatePlayerSettings: {}, }; export default function (state = INITIAL_STATE, action) { switch (action.type) { case RESET_PLAYERS_STATE: { return { ...INITIAL_STATE, }; } case LOADING_PLAYERS: { return { ...state, loadingPlayers: action.payload, }; } case ERROR_LOADING_PLAYERS: { return { ...state, errorLoadingPlayers: action.payload, }; } case LOADED_PLAYERS: { const players = action.payload.players; const updatedPlayers = players.reduce((accumulator, current) => { return Object.assign(accumulator, {[current.id]: current}); }, {}); return { ...state, lastVisible: action.payload.lastVisible, byId: Object.assign({}, state.byId, updatedPlayers), }; } case LOADING_PLAYER: { return { ...state, loadingPlayer: action.payload, }; } case ERROR_LOADING_PLAYER: { return { ...state, errorLoadingPlayer: action.payload, }; } case LOADED_PLAYER: { let updatedPlayer = { byId: { [action.payload.id]: action.payload, }, }; return { ...state, byId: Object.assign({}, state.byId, updatedPlayer.byId), }; } case KICKING_OUT_PLAYER: { return { ...state, kickingOutPlayer: action.payload, }; } case ERROR_KICKING_OUT_PLAYER: { return { ...state, errorKickingOut: action.payload, }; } case KICK_OUT_CLEAR_ERROR: { return { ...state, errorKickingOut: '', }; } case KICKED_OUT_PLAYER: { let player = state.byId[action.payload.id]; if (!player) { return { ...state, }; } player = { ...player, g: player.g.filter((gr) => gr !== action.payload.gid), groups: omit(player.g, [action.payload.gid]), roles: omit(player.roles, [action.payload.gid]), st: omit(player.roles, [action.payload.gid]), lastMatch: omit(player.lastMatch, [action.payload.gid]), }; return { ...state, byId: { ...state.byId, [action.payload.id]: player, }, requestKickOutSuccess: true, }; } case KICK_OUT_RESET_STATE: { return { ...state, kickingOutPlayer: false, errorKickingOut: '', requestKickOutSuccess: false, }; } case UPDATING_SETTINGS: { return { ...state, updatingPlayerSettings: { ...state.updatingPlayerSettings, [action.payload.g]: action.payload.updating, }, }; } case ERROR_UPDATING_SETTINGS: { return { ...state, errorUpdatingPlayerSettings: { ...state.errorUpdatingPlayerSettings, [action.payload.g]: action.payload.err, }, }; } case UPDATED_SETTINGS: { return { ...state, requestSentUpdatePlayerSettings: { ...state.requestSentUpdatePlayerSettings, [action.payload.g]: true, }, }; } case UPDATE_SETTINGS_CLEAR_ERROR: { return { ...state, errorUpdatingPlayerSettings: {}, }; } case UPDATE_SETTINGS_RESET_STATE: { return { ...state, updatingPlayerSettings: {}, errorUpdatingPlayerSettings: {}, requestSentUpdatePlayerSettings: {}, }; } default: return state; } }
$(document).ready(function(){ $(".btn-close").click(function(){ $(this).parent().animate({'height':'0px'}, function() { var btnId = "#" + $(this).closest("div").attr("id") + "-btn"; $(btnId).attr("disabled", false); $(btnId).css({ opacity: 1.0 }); }); }); // VDB Details $("#vdb-folder-btn").click(function(){ $("#vdb-folder").animate({'height':'360px'}); $(this).attr("disabled", true); $(this).css({ opacity: 0.2 }); }); $("#page1").css({ opacity: 0.2 }); $("#page3").click(function(){ if ($.browser.mozilla) { $('#vdb-folder').css({ 'background-position': '-1480px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#vdb-folder").animate({'background-position-x':'-1480px'}); } $("#page1").css({ opacity: 1.0 }); $("#page2").css({ opacity: 1.0 }); $("#page3").css({ opacity: 0.2 }); }); $("#page2").click(function() { if ($.browser.mozilla) { $('#vdb-folder').css({ 'background-position': '-740px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#vdb-folder").animate({'background-position-x':'-740px'}); } $("#page1").css({ opacity: 1.0 }); $("#page2").css({ opacity: 0.2 }); $("#page3").css({ opacity: 1.0 }); }); $("#page1").click(function(){ if ($.browser.mozilla) { $('#vdb-folder').css({ 'background-position': '0px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#vdb-folder").animate({'background-position-x':'0px'}); } $("#page1").css({ opacity: 0.2 }); $("#page2").css({ opacity: 1.0 }); $("#page3").css({ opacity: 1.0 }); }); // Conversion $("#conversion-folder-btn").click(function(){ $("#conversion-folder").animate({'height':'360px'}); $(this).attr("disabled", true); $(this).css({ opacity: 0.2 }); }); $("#conversion-page1").css({ opacity: 0.2 }); $("#conversion-page1").click(function(){ if ($.browser.mozilla) { $('#conversion-folder').css({ 'background-position': '0px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#conversion-folder").animate({'background-position-x':'0px'}); } $("#conversion-page1").css({ opacity: 0.2 }); $("#conversion-page2").css({ opacity: 1.0 }); $("#conversion-page3").css({ opacity: 1.0 }); $("#conversion-page4").css({ opacity: 1.0 }); $("#conversion-page5").css({ opacity: 1.0 }); $("#conversion-page6").css({ opacity: 1.0 }); }); $("#conversion-page2").click(function(){ if ($.browser.mozilla) { $('#conversion-folder').css({ 'background-position': '-740px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#conversion-folder").animate({'background-position-x':'-740px'}); } $("#conversion-page1").css({ opacity: 1.0 }); $("#conversion-page2").css({ opacity: 0.2 }); $("#conversion-page3").css({ opacity: 1.0 }); $("#conversion-page4").css({ opacity: 1.0 }); $("#conversion-page5").css({ opacity: 1.0 }); $("#conversion-page6").css({ opacity: 1.0 }); }); $("#conversion-page3").click(function(){ if ($.browser.mozilla) { $('#conversion-folder').css({ 'background-position': '-1480px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#conversion-folder").animate({'background-position-x':'-1480px'}); } $("#conversion-page1").css({ opacity: 1.0 }); $("#conversion-page2").css({ opacity: 1.0 }); $("#conversion-page3").css({ opacity: 0.2 }); $("#conversion-page4").css({ opacity: 1.0 }); $("#conversion-page5").css({ opacity: 1.0 }); $("#conversion-page6").css({ opacity: 1.0 }); }); $("#conversion-page4").click(function(){ if ($.browser.mozilla) { $('#conversion-folder').css({ 'background-position': '-2220px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#conversion-folder").animate({'background-position-x':'-2220px'}); } $("#conversion-page1").css({ opacity: 1.0 }); $("#conversion-page2").css({ opacity: 1.0 }); $("#conversion-page3").css({ opacity: 1.0 }); $("#conversion-page4").css({ opacity: 0.2 }); $("#conversion-page5").css({ opacity: 1.0 }); $("#conversion-page6").css({ opacity: 1.0 }); }); $("#conversion-page5").click(function(){ if ($.browser.mozilla) { $('#conversion-folder').css({ 'background-position': '-2960px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#conversion-folder").animate({'background-position-x':'-2960px'}); } $("#conversion-page1").css({ opacity: 1.0 }); $("#conversion-page2").css({ opacity: 1.0 }); $("#conversion-page3").css({ opacity: 1.0 }); $("#conversion-page4").css({ opacity: 1.0 }); $("#conversion-page5").css({ opacity: 0.2 }); $("#conversion-page6").css({ opacity: 1.0 }); }); $("#conversion-page6").click(function(){ if ($.browser.mozilla) { $('#conversion-folder').css({ 'background-position': '-3700px 0px', '-moz-transition': 'all 500ms ease' }); } else { $("#conversion-folder").animate({'background-position-x':'-3700px'}); } $("#conversion-page1").css({ opacity: 1.0 }); $("#conversion-page2").css({ opacity: 1.0 }); $("#conversion-page3").css({ opacity: 1.0 }); $("#conversion-page4").css({ opacity: 1.0 }); $("#conversion-page5").css({ opacity: 1.0 }); $("#conversion-page6").css({ opacity: 0.2 }); }); });
const express = require("express"); const Genres = require("../../services/genres"); const router = express.Router(); router.get("/", async (req, res) => { const genres= await Genres(); res.send(genres); }); router.get("/:id", (req, res) => { console.log(Genres); res.send(JSON.parse(Genres)); }); module.exports = router;
module.exports = { LONG_DELAY: 8, AMAZING_DELAY: 15, MID_DELAY: 6, SHORT_DELAY: 4, LOG_LEVELS: { Debug: 0, Info: 1, Warn: 2, Error:3 } };
require('dotenv').config() import winston from "winston"; function DefaultJsonFormatter() { const {combine, timestamp, errors, json, prettyPrint} = winston.format; return combine( errors({stack: true}), timestamp({format: 'YYYY-MM-DD HH:mm:ss'}), json(), prettyPrint() ); } export default DefaultJsonFormatter
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { 'use strict'; /** * Class constructor for Data Table Card MDL component. * Implements MDL component design pattern defined at: * https://github.com/jasonmayes/mdl-component-design-pattern * * @constructor * @param {Element} element The element that will be upgraded. */ var CustomCropper = function CustomCropper(element) { this.element_ = element; this.bt_ = null; this.container_ = null; // Initialize instance. this.init(); }; window['CustomCropper'] = CustomCropper; /** * Store constants in one place so they can be updated easily. * * @enum {string | number} * @private */ CustomCropper.prototype.Constant_ = { // None at the moment. }; /** * Store strings for class names defined by this component that are used in * JavaScript. This allows us to simply change it in one place should we * decide to modify at a later date. * * @enum {string} * @private */ CustomCropper.prototype.CssClasses_ = { IS_UPGRADED: 'is-upgraded', }; /** * Handle file changes. * @private */ CustomCropper.prototype.onFileChanged = function(ev) { var files = this.file_.files; if (files && files.length) { this.img_.style.height = 'auto'; this.componentContainer_.style.height = 'auto'; this.componentContainer_.style.width = 'auto'; this.dialog_.classList.add('beforeshow'); if (this.cropper_) { URL.revokeObjectURL(this.img_.src); this.cropper_.destroy(); } this.img_.src = URL.createObjectURL(files[0]); this.textEl_.classList.remove('is-dirty'); this.pendingImg_ = files[0].name; this.textInput_.value = ''; this.file_.value = null; this.updateBoxHeight_(); } else { // ? } }; /** * Create the cropper instance once the image to crop is loaded. */ CustomCropper.prototype.onCropImgLoaded = function() { var Cropper = window.Cropper; this.cropper_ = new Cropper(this.img_, this.cropperOptions_); }; /** * Update the dialog positionning. */ CustomCropper.prototype.updateBoxPosition_ = function() { this.updateBoxHeight_(); }; /** * Update the dialog height. */ CustomCropper.prototype.updateBoxHeight_ = function() { var cherry = window.cherry; var containerHeight = this.dialogContainer_.offsetHeight; var contentInner = cherry.innerHeight(this.dialogContent_); var contentOuter = cherry.outerHeight(this.dialogContent_); var actionsHeight = cherry.outerHeight(this.dialogActions_); var titleHeight = cherry.outerHeight(this.dialogTtile_); var imgH = containerHeight - actionsHeight - titleHeight - (contentOuter - contentInner); this.preview_.style.right = (contentOuter - contentInner) / 2; this.preview_.style.bottom = actionsHeight + (contentOuter - contentInner) / 2; this.img_.style.height = '' + imgH + 'px'; this.componentContainer_.style.height = '' + imgH + 'px'; }; /** * xxxxxx. */ CustomCropper.prototype.onDialogConfirmed_ = function() { if (this.b64result_) { this.b64result_.value = this.cropper_.getCroppedCanvas({ width: this.b64ExportWidth, height: this.b64ExportHeight, }).toDataURL('image/png'); } if (this.dataResult_) { this.dataResult_.value = JSON.stringify(this.cropper_.getData()); } if (this.currentImg_) { this.currentImg_.src = this.cropper_.getCroppedCanvas({ width: this.b64ExportWidth, height: this.b64ExportHeight, }).toDataURL('image/png'); } if (this.pendingImg_) { this.textInput_.value = this.pendingImg_; this.textEl_.classList.add('is-dirty'); } this.cropper_.destroy(); }; /** * xxxxxx. */ CustomCropper.prototype.onDialogCanceled_ = function() { this.cropper_.destroy(); }; /** * xxxxxx. */ CustomCropper.prototype.onFileCleared = function(ev) { if (!this.file_.files.length) { ev.stopPropagation(); ev.stopImmediatePropagation(); ev.preventDefault(); if (this.b64result_) { this.b64result_.value = null; } if (this.dataResult_) { this.dataResult_.value = null; } if (this.currentImg_ && this.originalCurrentImg_) { this.currentImg_.src = this.originalCurrentImg_; } } }; /** * Initialize element. */ CustomCropper.prototype.init = function() { if (this.element_) { var that = this; this.file_ = this.element_.querySelector('.mdl-textfield input[type="file"]'); this.dialog_ = this.element_.querySelector('.custom-cropper-dialog'); this.componentContainer_ = this.element_.querySelector('.custom-cropper-component-container'); this.img_ = this.element_.querySelector('.custom-cropper-dialog-img'); this.currentImg_ = this.element_.querySelector('.custom-cropper-current-img img'); this.preview_ = this.element_.querySelector('.custom-cropper-preview'); this.b64result_ = this.element_.querySelector('.custom-cropper-b64-result'); this.dataResult_ = this.element_.querySelector('.custom-cropper-data-result'); this.btAction_ = this.element_.querySelector('.mdl-button--icon'); this.textInput_ = this.element_.querySelector('.mdl-textfield__input'); this.textEl_ = this.element_.querySelector('.mdl-textfield'); this.dialogContainer_ = this.dialog_.querySelector('.custom-dialog-container'); this.dialogActions_ = this.dialog_.querySelector('.mdl-dialog__actions'); this.dialogTtile_ = this.dialog_.querySelector('.mdl-dialog__title'); this.dialogContent_ = this.dialog_.querySelector('.mdl-dialog__content'); this.dialogContent_ = this.dialog_.querySelector('.mdl-dialog__content'); this.dialogConfirm_ = this.dialog_.querySelector('.custom-dialog-confirm'); this.dialogClose_ = this.dialog_.querySelector('.custom-dialog-close'); this.dialogCancel_ = this.dialog_.querySelector('.custom-dialog-cancel'); var cherry = window.cherry; var imagesLoaded = window.imagesLoaded; this.b64ExportWidth = parseInt(this.element_.getAttribute('b64-export-width')); this.b64ExportHeight = parseInt(this.element_.getAttribute('b64-export-height')); if (this.currentImg_) { imagesLoaded(this.currentImg_, function() { if (this.currentImg_) { if (this.currentImg_.src.match(/^data:/)) { this.originalCurrentImg_ = this.currentImg_.src; } else { this.originalCurrentImg_ = cherry.imgAsDataUrl(this.currentImg_); } this.b64ExportWidth = this.b64ExportWidth || this.currentImg_.offsetWidth; this.b64ExportHeight = this.b64ExportHeight || this.currentImg_.offsetHeight; } }.bind(this)); } this.cropper_ = null; this.cropperOptions_ = { aspectRatio: parseInt(this.element_.getAttribute('aspect-ratio')) || NaN, movable: trueLike(this.element_.getAttribute('movable'), true), scalable: trueLike(this.element_.getAttribute('scalable'), true), rotatable: trueLike(this.element_.getAttribute('rotatable'), true), dragMode: (this.element_.getAttribute('drag-mode')) || 'crop', viewMode: parseInt(this.element_.getAttribute('view-mode')) || 0, responsive: trueLike(this.element_.getAttribute('responsive'), true), restore: trueLike(this.element_.getAttribute('restore'), true), modal: trueLike(this.element_.getAttribute('modal'), true), guides: trueLike(this.element_.getAttribute('guides'), true), background: trueLike(this.element_.getAttribute('background'), true), center: trueLike(this.element_.getAttribute('center'), true), highlight: trueLike(this.element_.getAttribute('highlight'), true), data: jsonParse(this.element_.getAttribute('cropper-data')), toggleDragModeOnDblclick: trueLike(this.element_.getAttribute('toggle-dragmode-ondblcick'), true), minCropBoxHeight: parseInt(this.element_.getAttribute('min-crop-box-height')) || 0, minCropBoxWidth: parseInt(this.element_.getAttribute('min-crop-box-width')) || 0, minCanvasHeight: parseInt(this.element_.getAttribute('min-canvas-height')) || 0, minCanvasWidth: parseInt(this.element_.getAttribute('min-canvas-width')) || 0, minContainerHeight: parseInt(this.element_.getAttribute('min-container-height')) || 100, minContainerWidth: parseInt(this.element_.getAttribute('min-container-width')) || 200, cropBoxResizable: trueLike(this.element_.getAttribute('crop-box-resizable'), true), cropBoxMovable: trueLike(this.element_.getAttribute('crop-box-movable'), true), zoomOnWheel: trueLike(this.element_.getAttribute('zoom-on-wheel'), true), zoomOnTouch: trueLike(this.element_.getAttribute('zoom-on-touch'), true), wheelZoomRatio: parseFloat(this.element_.getAttribute('wheel-zoom-ratio')) || 0.1, autoCropArea: parseFloat(this.element_.getAttribute('auto-crop-area')) || 0.8, autoCrop: trueLike(this.element_.getAttribute('auto-crop'), true), checkCrossOrigin: trueLike(this.element_.getAttribute('check-cross-origin'), true), checkOrientation: trueLike(this.element_.getAttribute('check-orientation'), true), zoomable: trueLike(this.element_.getAttribute('zoomable'), true), preview: this.preview_, /** * Ready function show the dialog, clean up image resource. */ ready: function() { that.dialog_['CustomDialog'].showBox_(); window.URL.revokeObjectURL(that.img_.src); }, }; cherry.on(this.file_, 'customcropper.change', this.onFileChanged).bind(this); cherry.on(this.img_, 'customcropper.load', this.onCropImgLoaded).bind(this); cherry.on(this.dialogConfirm_, 'customcropper.click', this.onDialogConfirmed_).bind(this); cherry.on(this.dialogClose_, 'customcropper.click', this.onDialogCanceled_).bind(this); cherry.on(this.dialogCancel_, 'customcropper.click', this.onDialogCanceled_).bind(this); cherry.on(this.btAction_, 'customcropper.click', this.onFileCleared).bind(this); cherry.on(window, 'customcropper.optimizedResize', this.updateBoxPosition_).bind(this); this.element_.classList.add(this.CssClasses_.IS_UPGRADED); } }; /** * Downgrade element. */ CustomCropper.prototype.mdlDowngrade_ = function() { var cherry = window.cherry; cherry.off(this.file_, 'customcropper.change', this.onFileChanged); cherry.off(this.img_, 'customcropper.load', this.onCropImgLoaded); cherry.off(this.dialogConfirm_, 'customcropper.click', this.onDialogConfirmed_); cherry.off(this.dialogClose_, 'customcropper.click', this.onDialogCanceled_); cherry.off(this.dialogCancel_, 'customcropper.click', this.onDialogCanceled_); cherry.off(this.btAction_, 'customcropper.click', this.onFileCleared); cherry.off(window, 'customcropper.optimizedResize', this.updateBoxPosition_, this); this.file_ = null; this.dialog_ = null; this.componentContainer_ = null; this.img_ = null; this.currentImg_ = null; this.preview_ = null; this.b64result_ = null; this.dataResult_ = null; this.clearFile_ = null; this.textInput_ = null; this.textEl_ = null; this.dialogContainer_ = null; this.dialogActions_ = null; this.dialogTtile_ = null; this.dialogContent_ = null; this.dialogContent_ = null; this.dialogConfirm_ = null; this.dialogClose_ = null; this.dialogCancel_ = null; this.b64ExportWidth = null; this.b64ExportHeight = null; this.originalCurrentImg_ = null; this.cropper_ = null; this.cropperOptions_ = null; this.element_.classList.remove(this.CssClasses_.IS_UPGRADED); }; // The component registers itself. It can assume componentHandler is available // in the global scope. componentHandler.register({ constructor: CustomCropper, classAsString: 'CustomCropper', cssClass: 'custom-js-cropper' }); /** * Is is something like true ? */ function trueLike(some, d) { if (some === 'true' || some === '1') { return true; } if (some === 'false' || some === '0') { return false; } return d; } /** * JSON parse no exception. */ function jsonParse(some) { try { return JSON.parse(some); }catch (ex) { return null; } } })();
var sql=require('./db'); var Occupation=function(occupation) { this.OccupationName= occupation.OccupationName; this.PhoneNumber= occupation.PhoneNumber; this.WorkType=occupation.WorkType; this.Designation=occupation.Designation; this.Patientid= parseInt(occupation.Patientid); }; Occupation.getAllOccupation = function(result) { sql.query('Select * from Occupations', function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { console.log('logins : ', res); result(null, res.recordset); } }); }; Occupation.getOccupationById = function(OccupationId, result) { // eslint-disable-next-line quotes sql.query("Select * from Occupations where OccupationId ='"+OccupationId+"'", function(err, res) { if (err) { console.log('error: ', err); result(err, null); } else { result(null, res.recordset); } }); }; Occupation.createOccupation = function(newOccupation, result) { // eslint-disable-next-line quotes sql.query("Insert into Occupations(OccupationName,PhoneNumber,WorkType,Designation,Patientid) values('"+newOccupation.OccupationName+"','"+newOccupation.PhoneNumber+"','"+newOccupation.WorkType+"','"+newOccupation.Designation+"','"+newOccupation.Patientid+"')", function(err, res) { if (err) { console.log('error: ', err); result(err, null); } else { console.log(res.OccupationId); result(null, res.OccupationId); } }); }; Occupation.updateById = function(id, occupation, result) { // eslint-disable-next-line quotes sql.query("Update Occupations Set OccupationName='"+occupation.OccupationName+"', PhoneNumber='"+occupation.PhoneNumber+"', WorkType='"+occupation.WorkType+"', Designation='"+occupation.Designation+"', Patientid='"+occupation.Patientid+"'where OccupationId='"+id+"'", function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { result(null, res.recordset); } }); }; Occupation.remove = function(id, result) { // eslint-disable-next-line quotes sql.query("DELETE FROM Occupations WHERE OccupationId ='"+id+"'", function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { result(null, res); } }); }; module.exports= Occupation;
config({ 'editor/plugin/justify-left/cmd': {requires: ['editor/plugin/justify-cmd']} });
'use strict' const refs = { sidebar: document.querySelector('#sidebar'), toggleBtn: document.querySelector('.toggle-btn'), navItem: document.querySelector('.nav__item'), subnav: document.querySelector('.subnav'), } const openMenu = function() { setTimeout(() => { refs.sidebar.classList.toggle('active'); }, 200); refs.toggleBtn.classList.toggle('close-btn'); if(refs.subnav.className.includes('activated')) { refs.subnav.classList.remove('activated'); } } const openSubNav = function(event) { if(event.target.nodeName == 'LI' || event.target.nodeName == 'A') { refs.subnav.classList.toggle('activated'); } else { refs.subnav.classList.remove('activated'); } } const closeMenu = function(event) { if(event.target.nodeName == 'A' && event.target.className == 'subnav__item__link') { setTimeout(() => { refs.sidebar.classList.toggle('active'); refs.toggleBtn.classList.toggle('close-btn'); }, 200); } } refs.navItem.addEventListener('click', openSubNav); refs.sidebar.addEventListener('click', closeMenu)
export const qri = (invoice_number, total) => { var data = { "invoice_number": invoice_number, "total": total }; var url = 'http://localhost:3001/qr', params = { method: 'POST', headers: new Headers({ 'x-auth': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YWEyOGVhMjhjOTNhZDE3MWIxZTk0YjAiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTIxNDg3MTQwfQ.y8e34ti4VxIL2GCuIppz5L1gyTy7YvdAgW0uvqnM3lk', 'Content-Type': 'application/json' }), body: JSON.stringify(data) }; const pb = true; const imagenes = new Array(); fetch(url, params) .then(response => response.json()) .then(data => { for (let i = 0; pb; i++) { if (data[i]) { var code = data[`${i}`]; var qr_png = `<QRCode value=${code} />`; imagenes.push(qr_png); } else { this.pb = false; } } }) return imagenes; }
import React from "react"; import './book.css'; function Book(props) { return ( <div className="Books"> <div className="card" > <div className="imgWrapper"> <img src={props.info.imageLinks.thumbnail} className="image" /> </div> <div className="card-body"> <h5 className="cardtitle"> Title: {props.info.title}</h5> <p className="card-text"> {props.info.description} </p> <div className="column"> {props.delete ? <button type="button" onClick={() => props.deleteBook(props.info)} class="btn btn-secondary" data-toggle="tooltip" data-placement="right" title="Tooltip on right"> Delete </button> : <button type="button" onClick={() => props.selectBook(props.info)} class="btn btn-secondary" data-toggle="tooltip" data-placement="right" title="Tooltip on right"> Saved </button> } </div> {/* {props.showSave ? <div className="column"> <button type="button" onClick={() => props.selectBook(props.info)} class="btn btn-secondary" data-toggle="tooltip" data-placement="right" title="Tooltip on right"> Saved </button> </div> : <div className="column"> <button type="button" onClick={() => props.deleteBook(props.info._id)} class="btn btn-secondary" data-toggle="tooltip" data-placement="right" title="Tooltip on right"> delete </button> </div> } */} </div> </div> </div> ) }; export default Book;
import React from "react"; import { Redirect, Route, Switch } from "react-router-dom"; import Login from "components/pages/login-page/login/login"; import Dashboard from "components/pages/dashboard/dashboard"; import { AuthConsumer } from "components/context/auth-context/auth-context" const routes = () => ( <Switch> <Route path="/login"> <Login /> </Route> {/* All redirects should be placed after public and before protected routes */} <AuthConsumer> { ({ user }) => { if (!user.isAuth) return <Redirect push to="/login" /> return ( <React.Fragment> <Route exact path="/"> <Dashboard/> </Route> </React.Fragment> ) } } </AuthConsumer> </Switch> ) export default routes
const TRAGEDY = 'tragedy'; const COMEDY = 'comedy' const usdFormat = () => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, }).format; } const calculateTragedyAmount = (performance) => { let tragedyAmount = 40000; if (performance.audience > 30) { tragedyAmount += 1000 * (performance.audience - 30); } return tragedyAmount; } const calculateComedyAmount = (performance) => { comedyAmount = 30000; if (performance.audience > 20) { comedyAmount += 10000 + 500 * (performance.audience - 20); } comedyAmount += 300 * performance.audience; return comedyAmount; } const calculateThisAmountByPlayType = (thisAmount, performance, play) => { switch (play.type) { case TRAGEDY: thisAmount = calculateTragedyAmount(performance); break; case COMEDY: thisAmount += calculateComedyAmount(performance); break; default: throw new Error(`unknown type: ${play.type}`); } return thisAmount; } function statement (invoice, plays) { let totalAmount = 0; let volumeCredits = 0; let result = `Statement for ${invoice.customer}\n`; const format = usdFormat(); for (let performance of invoice.performances) { const play = plays[performance.playID]; let thisAmount = calculateThisAmountByPlayType(0, performance, play); volumeCredits += Math.max(performance.audience - 30, 0); if (COMEDY === play.type) { volumeCredits += Math.floor(performance.audience / 5); } result += ` ${play.name}: ${format(thisAmount / 100)} (${performance.audience} seats)\n`; totalAmount += thisAmount; } result += `Amount owed is ${format(totalAmount / 100)}\n`; result += `You earned ${volumeCredits} credits \n`; return result; } const htmlStatement = (invoice, plays) => { let totalAmount = 0; let volumeCredits = 0; let result = `<h1>htmlStatement for ${invoice.customer}</h1>`; result += `<table>\n`; result += `<tr><th>play</th><th>seats</th><th>cost</th></tr>\n` const format = usdFormat(); for (let performance of invoice.performances) { const play = plays[performance.playID]; let thisAmount = calculateThisAmountByPlayType(0, performance, play); volumeCredits += Math.max(performance.audience - 30, 0); if (COMEDY === play.type) { volumeCredits += Math.floor(performance.audience / 5); } result += `<tr><td>${play.name}</td>`;; result += `<td>${performance.audience}</td>`; result += `<td>${format(thisAmount / 100)}</td></tr>\n`; totalAmount += thisAmount; } result += `</table>\n`; result += `<p>Amount owed is <em>${format(totalAmount / 100)}</em></p>\n`; result += `<p>You earned <em>${volumeCredits}</em> credits</p>`; return result; } module.exports = { statement, htmlStatement, };
'use strict' const Envio = use('App/Models/Paquexpress/Envio') const Vendedor = use('App/Models/Paquexpress/Vendedore') const Producto = use('App/Models/Paquexpress/Producto') const Transporte = use('App/Models/Paquexpress/Transporte') const Ciudad = use('App/Models/Paquexpress/Ciudade') const TEnvio = use('App/Models/Paquexpress/TipoEnvio') const Usuario = use('App/Models/User'); class EnvioController { async index ({request,auth, response }) { const envios = Envio.query().join('vendedores','vendedores.id','=','id_Vendedor') .join('productos','envios.id_Producto','=','productos.id') .join('transportes','transportes.id','=','envios.id_transporte') .join('ciudades','ciudades.id','=','envios.id_Ciudad') .join('tipo_envios','tipo_envios.id','=','id_TipoEnvio') .select('envios.id','vendedores.Nombre AS id_Vendedor', 'productos.Nombre AS id_Producto', 'envios.created_at','envios.updated_at','transportes.Tipo AS id_transporte', 'ciudades.Ciudad AS id_Ciudad', 'tipo_envios.Nombre AS id_TipoEnvio'); return response.status(200).json({ productos: await Producto.all(), transportes : await Transporte.all(), ciudades : await Ciudad.all(), vendedores : await Vendedor.all(), tenvios: await TEnvio.all(), envios : await envios.fetch() }) } async Insert ({request,response}) { try { const objeto = request.all(); const envios = new Envio() envios.id_Vendedor = objeto.id_Vendedor envios.id_Producto = objeto.id_Producto envios.id_transporte = objeto.id_transporte envios.id_Ciudad = objeto.id_Ciudad envios.id_TipoEnvio = objeto.id_TipoEnvio // envios.id_Pago = objeto.id_Pago await envios.save() return response.status(200).json({ message: 'Envio creado con exito' }) }catch(error) { return response.status(404).json({ message: error }) } } async edit({params,response}) { const envios = await Envio.find(params.id) return response.status(200).json({ Envio: envios }) } async update({params,request,response}) { const envios = await Envio.find(params.id) const objeto = request.all(); envios.id_Vendedor = objeto.id_Vendedor envios.id_Producto = objeto.id_Producto envios.id_transporte = objeto.id_transporte envios.id_Ciudad = objeto.id_Ciudad envios.id_TipoEnvio = objeto.id_TipoEnvio await envios.save() return response.status(200).json({ envio: 'Envio actualizada con exito!' }) } async delete({params,request,response}) { const envios = await Envio.find(params.id) await envios.delete(); return response.status(200).json({ Envio: 'Envio borrada con exito!' }) } async dashboard({request,response}) { let productoCount = await Producto.query().count(); const totalproductos = productoCount[0]['count(*)'] let transporteCount = await Transporte.query().count(); const totaltransportes = transporteCount[0]['count(*)'] let ciudadCOunt = await Ciudad.query().count(); const totalCiudades = ciudadCOunt[0]['count(*)'] let vendedorCount = await Vendedor.query().count(); const totalvendedor = vendedorCount[0]['count(*)'] let EnvioCount = await Envio.query().count(); const totalEnvio = EnvioCount[0]['count(*)'] let UsuarioCount = await Usuario.query().count(); const totalUsuarios = UsuarioCount[0]['count(*)'] // returns number return response.status(200).json({ productos: totalproductos, transportes : totaltransportes, ciudades : totalCiudades, vendedores : totalvendedor, envios : totalEnvio, usuarios : totalUsuarios }) } } module.exports = EnvioController
import axios from 'axios' // import * as constants from '../constants' axios.interceptors.request.use((req) => { if (localStorage.getItem('profile')) { req.headers.Authorization = `Bearer ${ JSON.parse(localStorage.getItem('profile')).token }` } return req }) const getPost = async (dataSend) => { const response = await axios.get(dataSend.url).catch((error) => { return new Promise((_resolve, reject) => { reject(error) }) }) return response.data } const addPost = async (dataSend) => { const response = await axios .post(dataSend.url, dataSend.data) .catch((error) => { return new Promise((_resolve, reject) => { reject(error) }) }) return response } const updatePost = async (dataSend) => { const response = await axios .put(dataSend.url, dataSend.data) .catch((error) => { return new Promise((_resolve, reject) => { reject(error) }) }) return response } const deletePost = async (dataSend) => { const response = await axios.delete(dataSend.url).catch((error) => { return new Promise((_resolve, reject) => { reject(error) }) }) return response } const signin = async (dataSend) => { const response = await axios .post(dataSend.url, dataSend.data) .catch((error) => { return new Promise((_resolve, reject) => { reject(error) }) }) return response } const signup = async (dataSend) => { const response = await axios .post(dataSend.url, dataSend.data) .catch((error) => { return new Promise((_resolve, reject) => { reject(error) }) }) return response } export { getPost, addPost, updatePost, deletePost, signin, signup }
import * as firebase from "firebase"; import {FirebaseConfig} from "../config/keys"; firebase.initializeApp(FirebaseConfig); const databaseRef = firebase.database().ref(); export const usersRef = databaseRef.child("users"); export const authRef = firebase.auth(); export const provider = new firebase.auth.GoogleAuthProvider();
"use strict"; var _vue = _interopRequireDefault(require("vue")); var _SvgIcon = _interopRequireDefault(require("@/components/svg/SvgIcon")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } // 全局注册组件 _vue["default"].component('svg-icon', _SvgIcon["default"]); // 定义一个加载目录的函数 var requireAll = function requireAll(requireContext) { return requireContext.keys().map(requireContext); }; var req = require.context('@/assets/icons', false, /\.svg$/); // 加载目录下的所有 svg 文件 requireAll(req);
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import Box from '@material-ui/core/Box'; import Button from '@material-ui/core/Button'; import Container from '@material-ui/core/Container'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import SaveIcon from '@material-ui/icons/Save'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import { LinearProgress } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import { ElectronFileInputButton } from './ElectronFileInputButton'; import { WebFileInputButton } from './WebFileInputButton'; import { selectApi } from './selector'; import { ADD_FILE } from '../actions/file'; import { isWebApp } from '../utils/env'; export default function LibraryControl(props) { const [open, setOpen] = React.useState(false); const [uploading, setUploading] = React.useState(false); const [uploadError, setUploadError] = React.useState(null); const [description, setDescription] = React.useState(''); const [fileName, setFileName] = React.useState(''); const [fileContent, setFileContent] = React.useState(null); const { dataApi } = useSelector(selectApi); const dispatch = useDispatch(); const addFileToLibrary = async () => { const newFile = { file: fileName, description, content: fileContent, }; const newId = await dataApi.AddDocument(newFile); if (newId !== '') { dispatch({ type: ADD_FILE, }); } }; const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleSelect = (name, content) => { setFileName(name); setFileContent(content); }; const handleDescriptionChange = (e) => { setDescription(e.target.value); }; const handleAdd = () => { setUploading(true); addFileToLibrary() .then(() => { setUploading(false); setOpen(false); return true; }) .catch((e) => { setUploadError(e.toString()); }); }; const inputValid = Boolean(fileName) && Boolean(description); return ( <Container> <Button variant="contained" color="primary" onClick={handleClickOpen}> Add File </Button> <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title">Add Document</DialogTitle> <DialogContent> <DialogContentText> Add a document to library, enter description and select file </DialogContentText> <TextField autoFocus margin="dense" id="name" label="Description" fullWidth onChange={handleDescriptionChange} /> <Box display="flex" flexDirection="row" alignItems="center"> <Box flexGrow={1}> <TextField autoFocus margin="dense" id="name" label="File" value={fileName} fullWidth /> </Box> <Box ml={2}> {isWebApp() ? ( <WebFileInputButton label="Select" onFileSelected={handleSelect} /> ) : ( <ElectronFileInputButton label="Select" onFileSelected={handleSelect} /> )} </Box> </Box> {uploading && <LinearProgress />} {uploadError && ( <Alert severity="error"> Error adding file: {uploadError} </Alert> )} </DialogContent> <DialogActions> <Button onClick={handleClose} variant="contained"> Cancel </Button> <Button onClick={handleAdd} variant="contained" color="primary" disabled={!inputValid} > Add </Button> </DialogActions> </Dialog> </Container> ); }
export function getArgs(strParame) { const args = {}; let query; // eslint-disable-next-line prefer-rest-params if (arguments.length === 2) { [query] = arguments; } else { query = window.location.search.substring(1); } const pairs = query.split('&'); for (let i = 0; i < pairs.length; i += 1) { const pos = pairs[i].indexOf('='); // eslint-disable-next-line no-continue if (pos === -1) continue; const argname = pairs[i].substring(0, pos); let value = pairs[i].substring(pos + 1); value = decodeURIComponent(value); args[argname] = value; } return args[strParame]; } export function format_date(num=0,format = 'YY-MM-DD hh:mm:ss'){ let date = new Date(Number(num)); let year = date.getFullYear(), month = date.getMonth()+1,//月份是从0开始的 day = date.getDate(), hour = date.getHours(), min = date.getMinutes(), sec = date.getSeconds(); let preArr = Array.apply(null,Array(10)).map(function(elem, index) { return '0'+index; });////开个长度为10的数组 格式为 00 01 02 03 let newTime = format.replace(/YY/g,year) .replace(/MM/g,preArr[month]||month) .replace(/DD/g,preArr[day]||day) .replace(/hh/g,preArr[hour]||hour) .replace(/mm/g,preArr[min]||min) .replace(/ss/g,preArr[sec]||sec); return newTime; }
let json_data='' let suggestions var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { json_data = JSON.parse(this.responseText); suggestions = JSON.parse(json_data); } }; xmlhttp.open("GET", "../Static/data.txt", true); xmlhttp.send(); const searchWrapper = document.querySelector(".search-input"); const inputBox = searchWrapper.querySelector("input"); const suggBox = searchWrapper.querySelector(".autocom-box"); const icon = searchWrapper.querySelector(".icon"); let linkTag = searchWrapper.querySelector("a"); let webLink; inputBox.onkeyup = (e)=>{ let userData = e.target.value; let emptyArray = []; if(userData){ emptyArray = suggestions.filter((data)=>{ return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase()); }); emptyArray = emptyArray.map((data)=>{ return data = '<li type="submit" form="contact_form">'+ data +'</li>'; }); searchWrapper.classList.add("active"); showSuggestions(emptyArray); let allList = suggBox.querySelectorAll("li"); for (let i = 0; i < allList.length; i++) { allList[i].setAttribute("onclick", "select(this)"); } }else{ searchWrapper.classList.remove("active"); //hide autocomplete box } } function select(element){ let selectData = element.textContent; inputBox.value = selectData; searchWrapper.classList.remove("active"); console.log(selectData) } function showSuggestions(list){ let listData; if(!list.length){ userValue = inputBox.value; listData = '<li>'+ userValue +'</li>'; }else{ listData = list.join(''); } suggBox.innerHTML = listData; } let lenght_item = 0 function loadDoc(data) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { console.log(this.responseText) if (this.readyState == 4 && this.status == 200) { out = JSON.parse(this.responseText) movie_detail_create() create_card() } else { console.log('error occur') } }; xhttp.open("POST", "get_movies", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(`id=${data}`); } var myForm = "" function sub(e) { ouput_data = [] e.preventDefault(); console.log("Done") myForm = document.getElementById('contact_form'); senddata(myForm.elements[0].value) } function senddata(dat) { let temp = dat.toString() loadDoc(temp) } // create movie details function movie_detail_create(){ let temp=`<div class="main_heading"> <h1 style="text-align: center;">${out.movie_info.name}</h1> </div> <div class="movie_detail" style="display: flex;"> <div class="movie_image" style=" width: 80%;"> <img style=" width: 80%;" src="https://image.tmdb.org/t/p/w500${out.movie_info.image}" alt=""> </div> <div class="movie_few_info" style="display: flex; flex-direction: column; justify-content: space-evenly;"> <h3>Overview:</h3> <h3>${out.movie_info.overview}</h3> <h3>Release date: ${out.movie_info.release_date}</h3> <h3>Runtime: ${out.movie_info.runtime} minutes</h3> <h3>Language: ${out.movie_info.original_language}</h3> <h3>Revenue: $${out.movie_info.revenue}</h3> <h3>status: ${out.movie_info.status}</h3> </div> </div> <div></div>` document.getElementsByClassName('main_movie')[0].innerHTML=temp searchWrapper.classList.remove("active"); } function create_card(){ let temp_data='' for( let i=0; i<out.rec_movies.name.length ; i++) { let temp=`<li class="card"> <a class="card-image" onclick="senddata('${out.rec_movies.name[i]}')" style="background-image: url(${out.rec_movies.image[i]});"> <img src="${out.rec_movies.image[i]}" alt="Psychopomp" /> </a> <a class="card-description"> <h2>${out.rec_movies.name[i]}</h2> </a> </li>` temp_data+=temp } document.getElementsByClassName('card-list')[0].innerHTML=temp_data window.scrollTo(0, 0); }
import React from "react"; import "./OccupantItem.css"; import img from "../assets/img.png"; import { connect } from "react-redux"; import { MOVEUP, moveUp } from "../store/action/action"; console.log(MOVEUP); const OccupantItem = (props) => { // console.log(props); const { // The moveup here is gotten from object returned from mapDispatchToProps moveup, date, id, room, address, location, occupant, uid, balance, dispatch, } = props; console.log(dispatch); return ( <div className="occupant-item-column"> <div className="occupant-column-title title-width-date "> <p>{date}</p> </div> <div className="occupant-column-title title-width-id "> <p>{id}</p> </div> <div className="occupant-column-title title-width-address "> <div className="occupant-address-div"> <div className="home-div"> <img src={img} alt="home" /> </div> <div> <p className="text-dark-green">2{address}</p> </div> </div> </div> <div className="occupant-column-title title-width-room "> <p>{room}</p> </div> <div className="occupant-column-title title-width-location "> <p>{location}</p> </div> <div className="occupant-column-title title-width-occupant "> <p className="text-dark-green">{occupant}</p> </div> <div className="occupant-column-title title-width-uid "> <p>{uid}</p> </div> <div className="occupant-column-title title-width-balance "> <p>(${balance})</p> </div> <div className="occupant-column-title title-width-button "> <div> <button className="flip-btn" onClick={() => moveup()}> Flip room </button> </div> </div> </div> ); }; const mapDispatchToProps = (dispatch, ownProps) => { console.log(ownProps); const { id } = ownProps; // return { moveup: () => dispatch({ type: MOVEUP, payload: { id: id } }) }; return { moveup: () => dispatch(moveUp(id)) }; }; export default connect(null, mapDispatchToProps)(OccupantItem);
const Sequelize = require('sequelize'); const databaseManager = require('../user_modules/database-manager'); const AttributeDateValueMap = require('./maps/attribute-date-value.map'); module.exports = {}; const AttributeDateValue = databaseManager.context.define('attributeDateValue', { Id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, Value: { allowNull: false, type: Sequelize.DATE }, AttributeId: { type: Sequelize.INTEGER, unique: 'User_Attribute_unique', }, UserId: { type: Sequelize.INTEGER, unique: 'User_Attribute_unique', } },{ instanceMethods: { getMap: function() { return AttributeDateValue.getMap(); } }, }); /** * Figures out how to serialize and deserialize this model * @returns {Object} */ AttributeDateValue.getMap = function () { return AttributeDateValueMap; }; module.exports = AttributeDateValue;
export class Stack { constructor(l) { this.s = l ? new Array(l) : new Array(); } [Symbol.iterator]() { return this.s.values(); } push(n) { this.s.push(n); return this; } pop() { return this.s.pop(); } peek() { return this.s[this.s.length - 1]; } get length() { return this.s.length; } }
import React from "react"; import { createDrawerNavigator } from "@react-navigation/drawer"; import { StackNavigator } from "./StackNavigator"; import Login from './layouts/Content/Login/LoginScreen'; import Main from './layouts/Content/Main/MainScreen'; import Initial from './layouts/Content/InitialScreen'; import Sidebar from "./customDrawer"; const Drawer = createDrawerNavigator(); const DrawerNavigator = () => { return ( <Drawer.Navigator initialRouteName="메인페이지" drawerContent={props => <Sidebar {...props} />}> <Drawer.Screen name="로그인" component={Login} options={{drawerLabel: '로그인'}}/> <Drawer.Screen name="지도페이지" component={Main} options={{drawerLabel: '지도페이지'}}/> <Drawer.Screen name="메인페이지" component={StackNavigator} options={{drawerLabel: '메인페이지'}}/> </Drawer.Navigator> ); } export default DrawerNavigator;
window.Algorithmia = window.Algorithmia || {}; Algorithmia.api_key = "YOUR_API_KEY" function updateUrl() { var dropDown = document.getElementById("urlDD"); var usrSel = dropDown.options[dropDown.selectedIndex].value; document.getElementById("inputStrings").value = usrSel; } function analyze() { var output = document.getElementById("output"); var statusLabel = document.getElementById("status-label") statusLabel.innerHTML = ""; startTask(); // Get the URL of the feed var inputUrl = document.getElementById("inputStrings").value; // Clear table to prep for new data output.innerHTML = ""; statusLabel.innerHTML = ""; // Query RSS scraper algorithm Algorithmia.query("/tags/ScrapeRSS", Algorithmia.api_key, inputUrl, function(error, items) { finishTask(); // Print debug output if(error) { statusLabel.innerHTML = '<span class="text-danger">Failed to load RSS feed (' + error + ')</span>'; return; } // Trim items items.length = 6; // Iterate over each item returned from ScrapeRSS for(var i in items) { startTask(); // Create closure to capture item (function() { var index = i; var item = items[i]; var itemUrl = item.url // Create table and elements into which we will stick the results of our algorithms var row = document.createElement("tr"); output.appendChild(row); var itemHTML = '<td>' + (Number(index) + 1) + '.&nbsp;</td>'; itemHTML += '<td>'; itemHTML += '<div><a href="' + itemUrl + '">' + item.title + '</a></div>'; itemHTML += '<div class="summary small"></div>'; itemHTML += '<div class="tags"></div>'; itemHTML += '</td>'; itemHTML += '<td class="sentiment" width="20"></td>'; row.innerHTML += itemHTML; var summaryElement = row.getElementsByClassName("summary")[0]; var tagsElement = row.getElementsByClassName("tags")[0]; var sentimentElement = row.getElementsByClassName("sentiment")[0]; // Use a utility algorithm to fetch page text Algorithmia.query("/util/Html2Text", Algorithmia.api_key, itemUrl, function(error, itemText) { finishTask(); if(error) { statusLabel.innerHTML = '<span class="text-danger">Error fetching ' + itemUrl + '</span>'; return; } // Run NLP algos on the links summarize(itemText, summaryElement); autotag(itemText, tagsElement); sentiment(itemText, sentimentElement); }); })(); } }); } function summarize(itemText, summaryElement) { startTask(); // Query summarizer analysis Algorithmia.query("/nlp/Summarizer", Algorithmia.api_key, itemText, function(error, summaryText) { finishTask(); if(error) { statusLabel.innerHTML = '<span class="text-danger">' + error + '</span>'; return; } summaryElement.textContent = summaryText; }); } function autotag(itemText, tagsElement) { startTask(); var topics = []; var topicLabels = []; if(typeof(itemText) == "string") { itemText = itemText.split("\n"); } else { itemText = []; } // Query autotag analysis Algorithmia.query("/nlp/AutoTag", Algorithmia.api_key, itemText, function(error, topics) { finishTask(); if(error) { statusLabel.innerHTML = '<span class="text-danger">' + error + '</span>'; return; } for (var key in topics) { topicLabels.push('<span class="label label-info">' + topics[key] + '</span> '); } tagsElement.innerHTML = topicLabels.join(''); }); } function sentiment(itemText, sentimentElement) { startTask(); var smileys = [ '<i class="fa fa-frown-o"></i>', '<i class="fa fa-frown-o"></i>', '<i class="fa fa-meh-o"></i>', '<i class="fa fa-smile-o"></i>', '<i class="fa fa-smile-o"></i>' ]; // Query sentiment analysis Algorithmia.query("/nlp/SentimentAnalysis", Algorithmia.api_key, itemText, function(error, sentimentScore) { finishTask(); if(error) { statusLabel.innerHTML = '<span class="text-danger">' + error + '</span>'; return; } sentimentElement.innerHTML = smileys[sentimentScore]; }); } var numTasks = 0; function startTask() { numTasks++; document.getElementById("algo-spinner").classList.remove("hidden"); } function finishTask() { numTasks--; if(numTasks <= 0) { document.getElementById("algo-spinner").classList.add("hidden"); } }
/** * Created by Phani on 9/14/2016. * * This file provides methods to ensure proper structure of * returned objects in the REST interface. This maps the mongo * objects into the REST format. It is mostly similar with some differences. */ import * as Charts from "/imports/api/charts/charts.js"; import * as Graphs from "/imports/api/graphs/graphs.js"; import * as Comments from "/imports/api/comments/comments.js"; import * as Users from "/imports/api/users/users.js"; import {getGraphWithoutLinks} from "/imports/api/graphs/methods.js"; import {getAllChartResources, getAllChartUsers} from "/imports/api/charts/methods"; import {getUserVotedCharts, UPVOTES, DOWNVOTES} from "/imports/api/users/methods.js"; /** * Names of the user REST json fields */ export const USER_ID = "_id"; export const USER_EMAIL = "email"; export const USER_NAME = "name"; export const USER_COUNTRY_CODE = "countryCode"; export const USER_COUNTRY = "country"; export const USER_ORGANIZATION = "organization"; export const USER_EXPERTISES = "expertises"; export const USER_PIC = "pic"; export const USER_UPVOTED_CHARTS = "upCharts"; export const USER_DOWNVOTED_CHARTS = "downCharts"; /** * Names of the flowchart REST json fields. */ export const FLOWCHART_ID = "_id"; export const FLOWCHART_NAME = "name"; export const FLOWCHART_DESCRIPTION = "description"; export const FLOWCHART_UPDATED_DATE = "updatedDate"; export const FLOWCHART_VERSION = "version"; export const FLOWCHART_OWNER = "owner"; export const FLOWCHART_GRAPH = "graph"; export const FLOWCHART_ALL_RES = "all_res"; export const FLOWCHART_ALL_USR_ID = "all_usr_id"; export const FLOWCHART_COMMENTS = "comments"; export const FLOWCHART_SCORE = "score"; export const FLOWCHART_UPVOTES = "upvotes"; export const FLOWCHART_DOWNVOTES = "downvotes"; export const FLOWCHART_RESOURCES = "resources"; export const FLOWCHART_IMAGE = "image"; export const FLOWCHART_TYPE = "type"; /** * Names of the graph REST json fields. */ export const GRAPH_NODES = "vertices"; export const GRAPH_EDGES = "edges"; export const GRAPH_FIRST_VERTEX = "firstVertex"; export const GRAPH_NODE_ID = "_id"; export const GRAPH_NODE_NAME = "name"; export const GRAPH_NODE_DETAILS = "details"; export const GRAPH_NODE_RESOURCES = "resources"; export const GRAPH_NODE_IMAGES = "images"; export const GRAPH_NODE_COMMENTS = "comments"; export const GRAPH_EDGE_ID = "_id"; export const GRAPH_EDGE_NAME = "_label"; export const GRAPH_EDGE_SOURCE = "_outV"; export const GRAPH_EDGE_TARGET = "_inV"; export const GRAPH_EDGE_DETAILS = "details"; /** * Names of the comment REST json fields. */ export const COMMENT_ID = "_id"; export const COMMENT_OWNER = "owner"; export const COMMENT_OWNER_NAME = "ownerName"; export const COMMENT_TEXT = "text"; export const COMMENT_CREATED_DATE = "createdDate"; export const COMMENT_ATTACHMENT = "attachment"; export const formatUserForREST = function (rawUser) { let user = {}; user[USER_ID] = rawUser[Users.USER_ID]; user[USER_EMAIL] = rawUser[Users.EMAILS][0][Users.EMAIL_ADDRESS]; user[USER_NAME] = rawUser[Users.PROFILE][Users.PROFILE_NAME]; user[USER_COUNTRY_CODE] = rawUser[Users.PROFILE][Users.PROFILE_COUNTRY][Users.COUNTRY_CODE]; user[USER_COUNTRY] = rawUser[Users.PROFILE][Users.PROFILE_COUNTRY][Users.COUNTRY_NAME]; user[USER_ORGANIZATION] = rawUser[Users.PROFILE][Users.PROFILE_ORGANIZATION]; user[USER_EXPERTISES] = rawUser[Users.PROFILE][Users.PROFILE_EXPERTISES]; user[USER_PIC] = rawUser[Users.PROFILE][Users.PROFILE_PIC]; let votes = getUserVotedCharts.call({userId: rawUser[Users.USER_ID]}); user[USER_UPVOTED_CHARTS] = votes[UPVOTES]; user[USER_DOWNVOTED_CHARTS] = votes[DOWNVOTES]; return user; }; /** * Converts the MongoDB representation of a chart into * what is used by the REST interface. * @param rawChart */ export const formatChartForREST = function (rawChart) { let chart = {}; chart[FLOWCHART_ID] = rawChart[Charts.CHART_ID]; chart[FLOWCHART_NAME] = rawChart[Charts.NAME]; chart[FLOWCHART_DESCRIPTION] = rawChart[Charts.DESCRIPTION]; chart[FLOWCHART_UPDATED_DATE] = rawChart[Charts.UPDATED_DATE]; chart[FLOWCHART_VERSION] = rawChart[Charts.VERSION]; chart[FLOWCHART_OWNER] = rawChart[Charts.OWNER]; chart[FLOWCHART_RESOURCES] = rawChart[Charts.RESOURCES]; chart[FLOWCHART_TYPE] = rawChart[Charts.TYPE]; chart[FLOWCHART_IMAGE] = rawChart[Charts.IMAGE]; chart[FLOWCHART_UPVOTES] = rawChart[Charts.UPVOTED_IDS].length; chart[FLOWCHART_DOWNVOTES] = rawChart[Charts.DOWNVOTED_IDS].length; chart[FLOWCHART_SCORE] = computeScore(rawChart); chart[FLOWCHART_GRAPH] = formatGraphForREST(getGraphWithoutLinks.call(rawChart[Charts.GRAPH_ID])); chart[FLOWCHART_ALL_RES] = getAllChartResources.call(rawChart[Charts.CHART_ID]); chart[FLOWCHART_ALL_USR_ID] = getAllChartUsers.call(rawChart[Charts.CHART_ID]); let sortedComments = _.sortBy(rawChart[Charts.COMMENTS], function (cmnt) { return new Date(cmnt[Comments.CREATED_DATE]).getTime(); }).reverse(); chart[FLOWCHART_COMMENTS] = _.map(sortedComments, function (rawComment) { return formatCommentForREST(rawComment); } ); if (!chart[FLOWCHART_IMAGE]) { chart[FLOWCHART_IMAGE] = null; } return chart; }; /** * Converts the MongoDB representation of a graph into * what is used by the REST interface. * @param rawGraph */ export const formatGraphForREST = function (rawGraph) { let graph = {}; graph[GRAPH_NODES] = _.map(rawGraph[Graphs.NODES], function (rawNode) { return formatNodeForREST(rawNode); }); graph[GRAPH_EDGES] = _.map(rawGraph[Graphs.EDGES], function (rawEdge) { return formatEdgeForREST(rawEdge); }); graph[GRAPH_FIRST_VERTEX] = rawGraph[Graphs.FIRST_NODE]; return graph; }; /** * Computes the score of a chart as the percentage upvotes. * If no feedback exists, -1 is returned. * @param chart * @returns {*} */ function computeScore(chart) { let up = chart[Charts.UPVOTED_IDS].length; let down = chart[Charts.DOWNVOTED_IDS].length; if (up == 0 && down == 0) { return -1; } return parseInt(100.0 * parseFloat(up) / parseFloat(up + down)); } function formatNodeForREST(rawNode) { let node = {}; node[GRAPH_NODE_ID] = rawNode[Graphs.NODE_ID]; node[GRAPH_NODE_NAME] = rawNode[Graphs.NODE_NAME]; node[GRAPH_NODE_DETAILS] = rawNode[Graphs.NODE_DETAILS]; node[GRAPH_NODE_RESOURCES] = rawNode[Graphs.NODE_RESOURCES]; node[GRAPH_NODE_IMAGES] = rawNode[Graphs.NODE_IMAGES]; let sortedComments = _.sortBy(rawNode[Graphs.NODE_COMMENTS], function (cmnt) { return new Date(cmnt[Comments.CREATED_DATE]).getTime(); }).reverse(); node[GRAPH_NODE_COMMENTS] = _.map(sortedComments, function (rawComment) { return formatCommentForREST(rawComment); }); return node; } function formatEdgeForREST(rawEdge) { let edge = {}; edge[GRAPH_EDGE_ID] = rawEdge[Graphs.EDGE_ID]; edge[GRAPH_EDGE_NAME] = rawEdge[Graphs.EDGE_NAME]; edge[GRAPH_EDGE_SOURCE] = rawEdge[Graphs.EDGE_SOURCE]; edge[GRAPH_EDGE_DETAILS] = rawEdge[Graphs.EDGE_DETAILS]; if (rawEdge[Graphs.EDGE_TARGET]) { edge[GRAPH_EDGE_TARGET] = rawEdge[Graphs.EDGE_TARGET]; } else { edge[GRAPH_EDGE_TARGET] = null; } return edge; } export const formatCommentForREST = function (rawComment) { let comment = {}; comment[COMMENT_ID] = rawComment[Comments.COMMENT_ID]; comment[COMMENT_OWNER] = rawComment[Comments.OWNER]; comment[COMMENT_TEXT] = rawComment[Comments.TEXT]; comment[COMMENT_CREATED_DATE] = rawComment[Comments.CREATED_DATE]; comment[COMMENT_ATTACHMENT] = rawComment[Comments.ATTACHMENT]; comment[COMMENT_OWNER_NAME] = Users.Users.findOne({_id: rawComment[Comments.OWNER]})[Users.PROFILE][Users.PROFILE_NAME]; if (!comment[COMMENT_ATTACHMENT]) { comment[COMMENT_ATTACHMENT] = null; } return comment; };
import React from 'react'; import PureRenderMixin from 'react-addons-pure-render-mixin'; import style from '../style'; const decksMenuStyle = { position: 'absolute', left: 0, top: 100, bottom: 100, right: 0, backgroundColor: style.backgroundColor, overflowY: 'scroll' }; const outerDivStyle = { display: 'flex', justifyContent: 'center', }; const deckNameStyle = { display: 'flex', justifyContent: 'center', }; const newFlashcardLeftInputStyle = { left: 0 }; const newFlashcardRightInputStyle = { }; const addFlashcardButtonStyle = { fontSize: '30', width: '400' }; const createDeckButtonStyle = { fontSize: '30', width: '400' }; export const CreateDeckMenu = React.createClass({ mixins: [PureRenderMixin], render: function() { const newFlashcards = []; for (let i = 0; i < this.props.flashcardsCount; i++) { newFlashcards.push((<NewFlashcard key={i}/>)); } return ( <div style={decksMenuStyle}> <input style={deckNameStyle} placeholder="Deck name"/> {newFlashcards} <NewFlashcardInput/> <div style={outerDivStyle}> <button style={addFlashcardButtonStyle}> Add another flashcard </button> </div> <div style={outerDivStyle}> <button style={createDeckButtonStyle}> Create deck </button> </div> </div> ); } }); const NewFlashcardInput = React.createClass({ mixins: [PureRenderMixin], render: function() { return ( <div style={outerDivStyle}> <input style={newFlashcardLeftInputStyle}/> <input style={newFlashcardRightInputStyle}/> </div> ); } }); const NewFlashcard = React.createClass({ mixins: [PureRenderMixin], render: function() { return ( <div style={outerDivStyle}> <div style={newFlashcardLeftInputStyle}> Left </div> <div style={newFlashcardRightInputStyle}> Right </div> </div> ); } });
import React from 'react' import { useSelector } from 'react-redux' import './AssetTable.css' import PropTypes from 'prop-types' const AssetTable = ({ tableRowClicked, assets }) => { const settings = useSelector(state => state.settings) const threshold = settings.balanceThreshold const getProfitAbsolute = (stock) => { let profit = stock.shares * (stock.price - stock.costBasis) if (profit > 0) { return <div className="profit-text">{`$${profit.toFixed(2)}`}</div> } else { profit *= -1 return <div className="loss-text">{`$${profit.toFixed(2)}`}</div> } } const getStockWeight = (stock) => { const weightString = `${(stock.currentWeight * 100).toFixed(1)}%` return <div>{weightString}</div> } const getTarget = (stock) => { if (stock.targetWeight) { return `${(stock.targetWeight * 100).toFixed(1)}%` } return '--' } const getError = (stock) => { if (stock.targetWeight) { const error = ((stock.targetWeight - stock.currentWeight) * 100).toFixed(1) if (Math.abs(error) > Number(threshold)) { return <td className="loss-text">{error}%</td> } return <td className="profit-text">{error}</td> } return <td>--</td> } const outOfBalance = (stock) => { if (stock.targetWeight) { const error = ((stock.targetWeight - stock.currentWeight) * 100).toFixed(1) if (Math.abs(error) > Number(threshold)) { return true } } return false } if (!assets.stocks) { return ( <div className="placeholder-box box"> <div className="placeholder-text"> Add a stock with the Order button </div> </div> ) } return ( <div> <table className="stock-table"> <tbody> <tr id="table-header"> <th className="info-header">Symbol</th> <th className="info-header price-header">Current Price</th> <th className="info-header shares-header">Shares</th> <th className="info-header value-header">Value</th> <th className="info-header profit-header">Profit</th> <th className="info-header current-weight-header">Current Weight</th> <th className="info-header target-weight-header">Target Weight</th> <th className="info-header">Error</th> </tr> {assets && assets.stocks.map(stock => { let rowClass = '' if (outOfBalance(stock)) { rowClass = "red-background" } return ( <tr key={stock.ticker} className={rowClass} onClick={tableRowClicked(stock)}> <td> <div> <div>{stock.ticker}</div> <small>{stock.name}</small> </div> </td> <td className="price">${Number(stock.price).toFixed(2)}</td> <td className="shares">{stock.shares}</td> <td className="value"><span >${(stock.price * stock.shares).toFixed(2)}</span></td> <td className="profit">{getProfitAbsolute(stock)}</td> <td className="current-weight">{getStockWeight(stock)}</td> <td className="target-weight">{getTarget(stock)}</td> {getError(stock)} </tr> ) } )} </tbody> </table> </div> ) } AssetTable.propTypes = { assets: PropTypes.object, tableRowClicked: PropTypes.func } export default AssetTable
var _viewer = this; //针对开始和结束时间的校验 _viewer.getItem("RYSZQZ_STARTTIME").obj.unbind("click").bind("click", function() {     WdatePicker({         maxDate : "#F{$dp.$D('" + _viewer.servId + "-RYSZQZ_ENDTTIME')}"     }); }); _viewer.getItem("RYSZQZ_ENDTTIME").obj.unbind("click").bind("click", function() {     WdatePicker({         minDate : "#F{$dp.$D('" + _viewer.servId + "-RYSZQZ_STARTTIME')}"     }); });
import React, {useState, useEffect} from 'react'; import {useRouter} from 'next/router'; export default function Loading() { const router = useRouter(); useEffect(() => { setTimeout(() =>{ router.push('/Home') }, 2000) }, []) return ( <div className="main"> <div className="center_content" > <img src="/logo.png" class="logo"/> </div> </div> ) }
require("./variables.js") require("./common.js") require("./Controller.js") require("./Model.js") require("./View.js") require("./libraries/Encryption.js")
const path = require('path'); const util = require('@js-lib/util'); function init(cmdPath, name, option) { console.log('@js-lib/test: init'); const type = option.type; util.copyFile( path.resolve(__dirname, `./template/${type}/.nycrc`), path.resolve(cmdPath, name, './.nycrc') ); util.copyTmpl( path.resolve(__dirname, `./template/${type}/index.html.tmpl`), path.resolve(cmdPath, name, './test/browser/index.html'), option, ); util.copyFile( path.resolve(__dirname, `./template/${type}/test.js`), path.resolve(cmdPath, name, './test/test.js') ); util.mergeJSON2JSON( path.resolve(__dirname, `./template/${type}/package.json`), path.resolve(cmdPath, name, './package.json') ); } function update(cmdPath, option) { console.log('@js-lib/test: update'); const type = option.type; util.copyFile( path.resolve(__dirname, `./template/${type}/.nycrc`), path.resolve(cmdPath, './.nycrc') ); util.copyTmpl( path.resolve(__dirname, `./template/${type}/index.html.tmpl`), path.resolve(cmdPath, './test/browser/index.html'), option, ); util.mergeJSON2JSON( path.resolve(__dirname, `./template/${type}/package.json`), path.resolve(cmdPath, './package.json') ); } module.exports = { init: init, update: update, }
import React from 'react'; import $ from 'jquery'; import moment from 'moment'; import NewsfeedArticle from './NewsfeedArticle.jsx'; import NewsfeedFocusedArticle from './NewsfeedFocusedArticle.jsx'; import NewsfeedBackground from './NewsfeedBackground.jsx'; import NewsfeedAppNav from './NewsfeedAppNav.jsx'; import NewsfeedAppAbout from './NewsfeedAppAbout.jsx'; import Loading from './../common/loading/Loading.jsx'; import getShuffledArray from './../../utility/getShuffledArray'; const apiKey = 'cb15d26e791f471abee466ce78d79760'; class NewsfeedApp extends React.Component { constructor(props) { super(props); this.state = { sources: [], articles: [], initialArticles: [], displayEnd: 20, isLoaded: false, sourcesDictionary: {}, count: {}, clicks: 0, countBySource: {}, categories: [], focus: false, isSorted: false, query: '' } this.loadMore = this.loadMore.bind(this); this.toggleFocusedArticle = this.toggleFocusedArticle.bind(this); this.track = this.track.bind(this); this.setSources = this.setSources.bind(this); this.toggleSortedArray = this.toggleSortedArray.bind(this); this.refreshPage = this.refreshPage.bind(this); this.search = this.search.bind(this); this.setArticles = this.setArticles.bind(this); this.setSources(); } componentDidMount() { setTimeout(function () { if (!this.state.isLoaded) { this.setState({ isLoaded: true }) } }.bind(this), 10000) } refreshPage() { this.setState({ count: {}, countBySource: {}, clicks: 0, articles: [], initialArticles: [], displayEnd: 20, isSorted: false, isLoaded: false }); this.setArticles(1, []); } setSources() { $.ajax({ url: "https://newsapi.org/v1/sources?language=en", success: function(data){ this.setState({ sources: data.sources, sourcesDictionary: this._getSourcesDictionary(data.sources), categories: this._getCategories(data.sources) }); this.setArticles(); }.bind(this) }); } setArticles(page = 1, articles = this.state.articles.slice()) { let allSources = ''; this.state.sources.forEach((source) => { allSources += source.id + ','; }); allSources = allSources.slice(0,-1); $.ajax({ url: "https://newsapi.org/v2/top-headlines?" + "sources=" + allSources + "&apiKey=" + apiKey + "&pageSize=" + 100 + "&page=" + page , success: function(data){ data.articles.forEach((article) => { article.source = article.source.id; if (article.title && article.publishedAt) { articles.push(article); } }); this.setState({ articles: articles, initialArticles: articles.slice() }); if (data.totalResults/100 > page) { this.setArticles(page + 1); } else { articles = getShuffledArray(articles); this.setState({ isLoaded: true, articles: articles, initialArticles: articles.slice() }) } }.bind(this), error: function (xhr, status) { console.log(xhr, status) }.bind(this) }); } loadMore() { this.setState({ displayEnd: this.state.displayEnd + 20 }) } track(article) { const category = this.state.sourcesDictionary[article.source].category; let count = this.state.count; let countBySource = this.state.countBySource; //categories: business, entertainment, gaming, general, music, politics, science-and-nature, sport, technology if (count[category]) { count[category] += 1; } else { count[category] = 1; } if (countBySource[article.source]) { countBySource[article.source] += 1; } else { countBySource[article.source] = 1; } this.toggleFocusedArticle(article); this.setState({ count: count, clicks: this.state.clicks + 1, countBySource: countBySource }) } toggleFocusedArticle(article) { this.setState({ focus: article }) } toggleSortedArray() { const newState = !this.state.isSorted; let arr = []; if (newState) { arr = this._getSortedArray(this.state.articles); } else { arr = getShuffledArray(this.state.articles); } this.setState({ articles: arr, isSorted: newState }) } search(e) { const query = e.target.value.replace(/\s+/g,' ').toLowerCase().trim().split(' '); let j; let articles = $.grep(this.state.initialArticles, function (article, i) { for (j = 0; j < query.length; j += 1) { if (article.title.toLowerCase().indexOf(query[j]) === -1 && (article.description || '').toLowerCase().indexOf(query[j]) === -1) { return false; } } return true; }); this.setState({ articles: articles, query: e.target.value.trim() }) } _getSortedArray(arr) { return arr.sort(function (a, b) { return moment(a.publishedAt).isBefore(b.publishedAt) ? 1 : -1 }) } _getSourcesDictionary(sources) { let dictionary = {}; sources.forEach(function(source) { dictionary[source.id] = source; }); return dictionary; } _getCategories(sources) { let categories = {}; sources.forEach(function(source) { categories[source.category] = true; }); return Object.keys(categories); } render() { const { count, countBySource, sourcesDictionary, categories, articles, clicks, isLoaded, isSorted, displayEnd, query } = this.state; return ( <div className='newsfeed container'> <NewsfeedAppNav> <NewsfeedAppAbout count={count} countBySource={countBySource} sourcesDictionary={sourcesDictionary} categories={categories} articles={articles} /> </NewsfeedAppNav> <NewsfeedBackground clicks={clicks} count={count} /> {isLoaded === false ? <Loading /> : <div> <div className='newsfeed-actions'> <div className='newsfeed-sort'> <label> <input type='checkbox' checked={isSorted} onChange={this.toggleSortedArray} /> sort by most recent </label> </div> <button type='button' className='btn-primary newsfeed-refresh' onMouseUp={this.refreshPage} > Refresh &nbsp; <span className='symbol-refresh'>&#x21bb;</span> </button> </div> <div className='newsfeed-search'> <input type='text' className={query.length === 0 ? 'empty' : ''} spellCheck={false} onKeyUp={this.search} placeholder={'search'}/> {articles.length} articles </div> <ul className='newsfeed-articles'> {articles.map(function (article, i) { if (i <= displayEnd) { return ( <NewsfeedArticle article={article} key={article.url + '_' + i} index={i} isActive={this.state.focus.url === article.url} onTrack={this.track.bind(this, article)} /> ) } }.bind(this))} </ul> {displayEnd < articles.length && <div className='newsfeed-load-more'> <button type="button" onMouseUp={this.loadMore} > More + </button> </div> } </div> } <NewsfeedFocusedArticle article={this.state.focus} source={this.state.focus ? sourcesDictionary[this.state.focus.source] : {}} onToggleFocusedArticle={this.toggleFocusedArticle} /> </div> ) } } export default NewsfeedApp;
module.exports = (base = 240000, variation = 120000) => { return Math.floor(Math.random() * variation + base); }
const loginForm = document.querySelector("form.login"); const passwordInput = document.querySelector("[name = \"admin-password\"]"); const addProductForm = document.querySelector("form.add-product"); const nameInput = document.querySelector("[name = \"product-name\"]"); const priceInput = document.querySelector("[name = \"product-price\"]"); const productsUl = document.querySelector(".products-list"); const PASSWORD = "password"; const login = (e) => { e.preventDefault(); if (passwordInput.value === PASSWORD) openAdminPanel(); else alert("Podałeś błędne hasło!"); }; const openAdminPanel = () => { addProductForm.classList.remove("invisible"); loginForm.classList.add("invisible"); }; const addProductToShop = (e) => { e.preventDefault(); const name = nameInput.value; const price = Number(priceInput.value); const newLi = document.createElement("li"); const newStrong = document.createElement("strong"); newStrong.innerText = name; const newPrice = document.createElement("span"); newPrice.innerText = `${price}zł`; const newBtn = document.createElement("button"); newBtn.classList.add("buy-product"); newBtn.dataset.name = name; newBtn.dataset.price = String(price); newBtn.innerText = "Kup"; newBtn.addEventListener("click", buyProduct); newLi.appendChild(newStrong); newLi.appendChild(newPrice); newLi.appendChild(newBtn); console.log(newLi); productsUl.appendChild(newLi); nameInput.value = ""; priceInput.value = ""; }; loginForm.addEventListener("submit", login); addProductForm.addEventListener("submit", addProductToShop);
/** * ApplyReported.js 技术支持单录入填报或申请 */ Ext.ns('ext.techsupport'); ext.techsupport.ApplyReported = Ext.extend(Ext.Panel, { constructor : function(cfg) { // 构造器 cfg = cfg || { id : 'applyCt', renderTo : Ext.get('applyReportedCt'), layout : 'fit', frame:true, autoScroll:true, width : '100%', height : 380, title : '技术支持单录入', margins : '5 5 5 5', padding : '5 5 40 40', defaults : { border : false, labelWidth : 140, labelAlign : "right", buttonAlign:'right', buttonMagin:'' } }; ext.techsupport.ApplyReported.superclass.constructor.call(this, cfg); }, initComponent : function() { this.items = [ { xtype : 'form', autoScroll:true, height:370, layout:'form', witdh:'96%', items : [ { xtype : 'textfield', name : 'st.stNo', fieldLabel : '技术支持单编号', maxLength : 100, maxLengthText : '最多100位', readOnly : true }, { xtype : 'panel', layout : 'column', items : [ { xtype : 'panel', layout : 'form', items : [ { xtype : 'combo', fieldLabel : '申请人', displayField : 'display_name', valueField : 'fact_value', lazyRender:true, mode: 'local', store : new Ext.data.JsonStore({ proxy : new Ext.data.HttpProxy({ url : './sysadmin/querySelDict_dict_item.action' }), fields:['fact_value','display_name'], root:'ldata', baseParams:{'dict_code':'ts_applicant'}, autoLoad:true }) } ] }, { xtype : 'panel', layout : 'form', labelWidth : 100, items : [ { xtype : 'combo', fieldLabel : '区域', displayField : 'display_name', valueField : 'fact_value', lazyRender:true, mode: 'local', store : new Ext.data.JsonStore({ proxy : new Ext.data.HttpProxy({ url : './sysadmin/querySelDict_dict_item.action' }), fields:['fact_value','display_name'], root:'ldata', baseParams:{'dict_code':'dm_xzqh'}, autoLoad:true }) } ] }, { xtype : 'panel', layout : 'form', labelWidth : 100, items : [ { xtype : 'combo', fieldLabel : '序号', displayField : 'text', valueField : 'value', triggerAction: 'all', lazyRender:true, mode: 'local', store : new Ext.data.ArrayStore({ id:'sn', fields:['value','text'], data:function(){ var num=new Array(); for(i=1;i<=100;i++) { arrtemp=[i,i]; num.push(arrtemp); } return num; }() }) } ] } ] }, { xtype : 'panel', layout : 'column', items : [ { xtype : 'panel', layout : 'form', items : [ { xtype : 'datefield', fieldLabel : '总工批复日期' } ] }, { xtype : 'panel', layout : 'form', items : [ { xtype : 'textarea', fieldLabel : '总工意见批复', maxLength : 4000, maxLengthText : '最多4000个字符', width : 400 } ] } ] }, { xtype : 'panel', layout : 'column', items : [ { xtype : 'panel', layout : 'form', items : [ { xtype : 'datefield', fieldLabel : '日期' } ] }, { xtype : 'panel', layout : 'form', items : [ { xtype : 'textarea', fieldLabel : '产品方案部主管批复意见', maxLength : 4000, maxLengthText : '最多4000个字符', width : 400 } ] } ] }, { xtype : 'panel', layout : 'column', items : [ {xtype:'panel',layout:'form',items:[{xtype:'datefield',fieldLabel:'计划完成时间'}]} , {xtype:'panel',layout:'form',items:[{xtype : 'checkbox',fieldLabel : '阶段',handler:function(e,checked){ var ardatefield=e.ownerCt.ownerCt.findByType('datefield'); var arel=[]; Ext.each(ardatefield,function(item,idx,items){ if(item.initialConfig.cls == e.id ){ arel.push(item); } }); if(checked){ for(i=0;i<arel.length;i++){ arel[i].setVisible(true); } } else{ for(i=0;i<arel.length;i++){ arel[i].setVisible(false); } } },id:'pgms_'}]}, {xtype:'panel',layout:'form',labelWidth:60,items:[{xtype:'datefield',fieldLabel:'需求',cls:'pgms_',hidden:true}]}, {xtype:'panel',layout:'form',labelWidth:60,items:[{xtype:'datefield',fieldLabel:'实施',cls:'pgms_',hidden:true}]} ] }, { xtype : 'panel', layout : 'column', items : [ { xtype : 'panel', layout : 'form', items : [ { xtype : 'datefield', fieldLabel : '日期' } ] }, { xtype : 'panel', layout : 'form', items : [ { xtype : 'textarea', fieldLabel : '技术开发部主管批复意见', maxLength : 4000, maxLengthText : '最多4000个字符', width : 400 } ] } ] }, { xtype : 'panel', layout : 'column', items : [{xtype:'panel',layout:'form',items:[{xtype:'datefield',fieldLabel:'计划完成时间'}]} , {xtype:'panel',layout:'form',items:[{xtype : 'checkbox',fieldLabel : '阶段',handler:function(e,checked){ var ardatefield=e.ownerCt.ownerCt.findByType('datefield'); var arel=[]; Ext.each(ardatefield,function(item,idx,items){ if(item.initialConfig.cls == e.id ){ arel.push(item); } }); if(checked){ for(i=0;i<arel.length;i++){ arel[i].setVisible(true); } } else{ for(i=0;i<arel.length;i++){ arel[i].setVisible(false); } } },id:'dvml_'}]}, {xtype:'panel',layout:'form',labelWidth : 60,items:[{xtype:'datefield',fieldLabel:'设计开发',cls:'dvml_',hidden:true}]}, {xtype:'panel',layout:'form',labelWidth : 60,items:[{xtype:'datefield',fieldLabel:'测试',cls:'dvml_',hidden:true}]} ] },{xtype:'panel',layout:'column',defaults:{abelWidth : 100,labelAlign : "right"},items:[{xtype:'panel',layout:'form', items:[{xtype:'combo',fieldLabel:'技术负责人',displayField:'display_name',valueField:'fact_value',lazyRender:true, mode: 'local', loadingText:'加载中', store:new Ext.data.JsonStore({ proxy:new Ext.data.HttpProxy({url:'./sysadmin/querySelDict_dict_item.action'}), fields:['fact_value','display_name'], root:'ldata', baseParams:{'dict_code':'ts_sl'}, autoLoad:true })} ] }, {xtype:'panel',layout:'form',items:[{ xtype:'combo',fieldLabel:'技术支持部门',displayField:'display_name',valueField:'fact_value', lazyRender:true, mode: 'local', loadingText:'加载中', store:new Ext.data.JsonStore({ proxy:new Ext.data.HttpProxy({url:'./sysadmin/querySelDict_dict_item.action'}), fields:['fact_value','display_name'], root:'ldata', baseParams:{'dict_code':'ts_sdept'}, autoLoad:true }) }] }]} ] } ]; this.buttons=[{xtype:'button',text:'保存',width:80,handler:this.save,id:'savebtn'}]; //this.on('afterrender', this.afterrender, this); ext.techsupport.ApplyReported.superclass.initComponent.call(this); }, save:function(){ //保存并且开始流程 }, afterrender : function(ct, postion) { var offsetTop = (Ext.getBody().getHeight() - ct.el.getHeight()) / 2; if (offsetTop < 0) offsetTop = 0; ct.el.setTop(offsetTop); } }); Ext.onReady(function() { var appreport = new ext.techsupport.ApplyReported(); // appreport.show(); });
var connection, mySessionID, groupSessionID, messagesDialogOpen = true; var openCloseMessages = function( ) { if ( messagesDialogOpen ) { messagesDialogOpen = false; $ ( "#messages-open-temp-holder" ).html ( $ ( "#messages-place-holder" ).html ( ) ); $ ( "#messages-place-holder" ).html ( $ ( "#messages-closed" ).html ( ) ); }else { messagesDialogOpen = true; $ ( "#messages-place-holder" ).html ( $ ( "#messages-open-temp-holder" ).html ( ) ); $ ( "#messages-open-temp-holder" ).html ( "" ); $ ( "#messages-main-view" ).animate ( { scrollTop: $ ( "#messages-content-view" ).height ( ) }, 450 ); } }; var sendGroupMessage = function( ) { var text = $ ( "#group-message-input" ).val ( ); $ ( "#group-message-input" ).val ( "" ); var messageShape = new groupChatMessageShape ( ); messageShape.initialise ( myName, text ); recordShape ( messageShape ); }; $ ( document ) .ready ( function( ) { isGroupSession = true; $ ( "#nav-invite-friends-button" ).css ( "visibility", "visible" ); $ ( "#nav-invite-friends-button" ).click ( function( ) { clearSelections ( ); currShapeSelected = ""; openInviteFriendsDialog ( ); } ); // get my session ID $.post ( "/get-my-session-id/", {} ).done ( function( data ) { mySessionID = data.session; groupSessionID = $ ( "#group-session-session-id" ).html ( ); } ).fail ( function( header ) { location = "/"; } ); setTimeout ( function( ) { // connect to server over socket io connection = io.connect ( "http://127.0.0.1:8080/communication/" ); // add to group[ sesion connection .on ( "accepted", function( ) { connection.emit ( "init", { groupSession: groupSessionID, userSession: mySessionID } ); connection .on ( "user-added", function( data ) { if ( data === "ok" ) { connection.emit ( "get-full-drawing", { groupSession: groupSessionID } ); connection .on ( "draw-full-drawing", function( data ) { currentDrawing .setDrawingSequence ( data.data.drawingInstructions.drawingSequence ); clearCanvas ( canContext ); drawFull ( canContext, currentDrawing .getJSON ( ) ); } ); }else { location = "/"; } } ); } ); connection.on ( "draw-this", function( data ) { if ( data.drawingInstruction.shape === "groupmessage" ) { currentDrawing.addShape ( data.drawingInstruction ); $ ( "#messages-content-view" ).append ( "<div class=\"messages-message-text\">" + data.drawingInstruction.sender + ": " + data.drawingInstruction.text + "</div>" ); if ( !scrollRecent ) { scrollRecent = true; $ ( "#messages-main-view" ).animate ( { scrollTop: $ ( "#messages-content-view" ).height ( ) }, 500 ); setTimeout ( function( ) { scrollRecent = false; }, 500 ); }else { $ ( "#messages-main-view" ).animate ( { scrollTop: $ ( "#messages-content-view" ).height ( ) }, 1 ); } $ ( "#messages-main-view" ).animate ( { scrollTop: $ ( "#messages-content-view" ).height ( ) }, 450 ); if ( !( messagesDialogOpen ) ) { openCloseMessages ( ); } }else { var instructions = new Array ( ); instructions.push ( data.drawingInstruction ); currentDrawing.addShape ( data.drawingInstruction ); drawFull ( canContext, instructions ); } } ); connection .on ( "update-layer", function( data ) { var id = data.drawingInstruction.elemID, type = data.drawingInstruction.type, value = data.drawingInstruction.value; if ( type === "visible" ) { currentDrawing.drawingSequence [ id ].visible = value; }else if ( type === "filled" ) { currentDrawing.drawingSequence [ id ].filled = value; }else if ( type === "lWidth" ) { currentDrawing.drawingSequence [ id ].lWidth = value; }else if ( type === "colour" ) { currentDrawing.drawingSequence [ id ].colour = value; } refreshCanvas ( ); } ); connection.on ( "clear-canvas", function( data ) { clearDrawingDataFromServer ( ); } ); connection.on ( "request-full-drawing", function( data ) { connection.emit ( "get-full-drawing", { drawingInstructions: currentDrawing } ); } ); }, 100 ); } );
var intervalID = setInterval( function() { alert('message again!'); }, 5000); //clearInterval(intervalID);
module.exports.APP_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9k7INCN_gkvzJUlfo"; module.exports.CLIENT = { APP_CLIENT:{ id:"7tG8xai2sU7BIMCIUzI1NiIsvzxxw", name:"APP_CLIENT", secret:"eovN9CnOiJIUzOn9m4ichcD3Wd" } } module.exports.ERROR_OBJ = { WRONG_USERNAME_PASSWORD:'WRONG_USERNAME_PASSWORD', SUSPENED_ACCOUNT:'SUSPENED_ACCOUNT' , UNKNOW_ERROR:'UNKNOW_ERROR', CHI_NHANH_DUNG_HOAT_DONG:'CHI_NHANH_DUNG_HOAT_DONG', CHUA_CHON_CHI_NHANH:'CHUA_CHON_CHI_NHANH', SAI_CHI_NHANH:'SAI_CHI_NHANH', ERR_TRANG_QUAN_TRI_CUA_ADMIN:'ERR_TRANG_QUAN_TRI_CUA_ADMIN', ERR_ACCESS_TOKEN_REQUIRED:'ERR_ACCESS_TOKEN_REQUIRED', ERR_ACCESS_TOKEN_NOT_VALID :'ERR_ACCESS_TOKEN_NOT_VALID', ERR_PARSE_JSON:'ERR_PARSE_JSON', ERR_DONT_HAVE_PERMISSION:'ERR_DONT_HAVE_PERMISSION', ERR_EXPIRIED_TOKEN:'ERR_EXPIRIED_TOKEN', ERR_CLIENT_IS_NOT_VALID:'ERR_CLIENT_IS_NOT_VALID' }
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.ui.visualization.SectionTimeDomainVisualization'); goog.require('audioCat.audio.AudioOrigination'); goog.require('audioCat.state.editMode.EditModeName'); goog.require('audioCat.state.editMode.Events'); goog.require('audioCat.state.editMode.MoveSectionEntry'); goog.require('audioCat.state.events'); goog.require('audioCat.ui.tracks.StringConstant'); goog.require('audioCat.ui.visualization.SectionSpeedDragger'); goog.require('audioCat.ui.visualization.TimeUnit'); goog.require('audioCat.ui.widget.Widget'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.style'); /** * Visualizes a section of audio in a track. * @param {!audioCat.state.Section} section The section of audio to visualize. * @param {!audioCat.state.Track} track The track the section belongs to. * @param {!audioCat.ui.visualization.Context2dPool} context2dPool Pools * contexts so that we don't run out of memory by accident. * @param {!audioCat.ui.visualization.TimeDomainScaleManager} * timeDomainScaleManager Manages the scale at which we visualize audio in * the time domain. * @param {!audioCat.state.editMode.EditModeManager} editModeManager Maintains * and updates the current edit mode. * @param {!audioCat.utility.DomHelper} domHelper Facilitates interactions with * the DOM. * @param {!audioCat.audio.play.TimeManager} timeManager Manages the time * indicated to the user by the UI. * @param {!audioCat.audio.play.PlayManager} playManager Manages the playing of * audio. * @param {!audioCat.ui.text.TimeFormatter} timeFormatter Formats time. * @param {!audioCat.ui.window.ScrollResizeManager} scrollResizeManager Manages * responding to scrolls and resizes. * @param {!audioCat.state.command.CommandManager} commandManager Manages * commands so that the user can undo and redo. * @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique * throughout the application. * @constructor * @extends {audioCat.ui.widget.Widget} */ audioCat.ui.visualization.SectionTimeDomainVisualization = function( section, track, context2dPool, timeDomainScaleManager, editModeManager, domHelper, timeManager, playManager, timeFormatter, scrollResizeManager, commandManager, idGenerator) { /** * @private {!audioCat.utility.IdGenerator} */ this.idGenerator_ = idGenerator; /** * An ID unique to the latest draw operation. * @private {audioCat.utility.Id} */ this.drawId_ = idGenerator.obtainUniqueId(); /** * The section of audio to visualize. * @private {!audioCat.state.Section} */ this.section_ = section; // TODO(chizeng): Remove this listener if the visualization is removed. // Change how the section is visualized based on whether it is selected. goog.events.listen( section, audioCat.state.events.SECTION_MOVING_STATE_CHANGED, this.handleSectionMovingStateChange_, false, this); /** * The track that the section belongs to. * @private {!audioCat.state.Track} */ this.track_ = track; /** * Enqueues and dequeues commands, allowing for control and undo. * @private {!audioCat.state.command.CommandManager} */ this.commandManager_ = commandManager; /** * Manages the time indicated to the user. * @private {!audioCat.audio.play.TimeManager} */ this.timeManager_ = timeManager; /** * Manages the playing of audio. * @private {!audioCat.audio.play.PlayManager} */ this.playManager_ = playManager; /** * Formats time for display. * @private {!audioCat.ui.text.TimeFormatter} */ this.timeFormatter_ = timeFormatter; // Change the track if the section is put into a different track. goog.events.listen(section, audioCat.state.events.TRACK_CHANGED_FOR_SECTION, this.handleTrackChanged_, false, this); /** * The pool of 2D contexts. * @private {!audioCat.ui.visualization.Context2dPool} */ this.context2dPool_ = context2dPool; /** * Manages the scale at which we visualize audio in the time domain. * @private {!audioCat.ui.visualization.TimeDomainScaleManager} */ this.timeDomainScaleManager_ = timeDomainScaleManager; /** * The contexts to render the section in. * @private {!Array.<!CanvasRenderingContext2D>} */ this.context2ds_ = []; var canvasContainer = domHelper.createDiv( goog.getCssName('sectionVisualizationCanvasContainer')); /** * Shows the current time to the user. * @private {!Element} */ this.timeIndicator_ = domHelper.createDiv( goog.getCssName('sectionBeginTimeIndicator')); domHelper.appendChild(canvasContainer, this.timeIndicator_); /** * Facilitates interactions with the DOM. * @private {!audioCat.utility.DomHelper} */ this.domHelper_ = domHelper; /** * The container for this section visualization widget. * @private {!Element} */ this.container_ = domHelper.createDiv( goog.getCssName('sectionVisualizationContainer')); goog.base(this, this.container_); /** * The width of the last canvas to be drawn. * @private {number} */ this.unscaledLastCanvasWidth_ = 0; /** * The container for all the canvases used to represent the audio. * @private {!Element} */ this.canvasContainer_ = canvasContainer; domHelper.appendChild(this.container_, this.canvasContainer_); this.setCanvasContainerColor_(); this.setCanvasContainerHeight_(); /** * A container that displays the start time as the user drags the section * around. Only appears upon drag. * @private {!Element} */ this.startTimeDisplayer_ = domHelper.createDiv( goog.getCssName('sectionStartTimeDisplayer')); this.updateTimeDisplay_(); /** * The dragger that lets the user alter the speed of the section of audio. * Null if the current visualization is too small to visualize the audio. * @private {audioCat.ui.visualization.SectionSpeedDragger} */ this.sectionSpeedDragger_ = null; /** * Manages scrolling and resizing. * @private {!audioCat.ui.window.ScrollResizeManager} */ this.scrollResizeManager_ = scrollResizeManager; // Actually draw the wave form. this.drawWaves_(); // TODO(chizeng): Find a way to visualize the section that allows for // updates by the section. Perhaps let the section fire events like finished // rendering. /** * An integer. The number of pixels from the left this section visualization * is positioned. * @private {number} */ this.pixelsFromLeft_ = 0; // Set the correct distance from the left. this.setCorrectLeftDistance_(); /** * The display level. Indicates how far from the top of a track entry to draw * the visualization. The visualization will be located this many times the * height of a single section from the top. * @private {number} */ this.displayLevel_ = 1; // Trigger a change by changing the value. this.setDisplayLevel(0); /** * Maintains and updates the current edit mode. * @private {!audioCat.state.editMode.EditModeManager} */ this.editModeManager_ = editModeManager; var lineMarkingTimeInSection = domHelper.createElement('div'); /** * A line that is displayed at a certain position in the section at various * times when it is needed. * @private {!Element} */ this.lineMarkingTimeInSection_ = lineMarkingTimeInSection; goog.dom.classes.add( lineMarkingTimeInSection, goog.getCssName('lineMarkingTimeInSection')); // Change the width of canvases based on the playback rate. goog.events.listen(section, audioCat.state.events.PLAYBACK_RATE_CHANGED, this.handlePlaybackRateChanged_, false, this); // Respond to changes in edit mode. goog.events.listen(editModeManager, audioCat.state.editMode.Events.EDIT_MODE_CHANGED, this.handleEditModeChange_, false, this); // Activate the current mode. this.activateMode_(editModeManager.getCurrentEditMode()); // Change the X-position of the section visualization when the begin time of // the section changes. // TODO(chizeng): Remove this listener after the section visualization is // removed. goog.events.listen(section, audioCat.state.events.SECTION_BEGIN_TIME_CHANGED, this.handleSectionBeginTimeChange_, false, this); this.visualizeMovingState_(); // For mobile browers, we artificially scroll, so we must change the position // of the section manually. Call the function upon adding. /** * The function (with a bound context) to call upon scrolling. The null * function when we do not implement our own scrolling. * @private {!Function} */ this.boundMobileScrollHandleFunction_ = goog.nullFunction; if (FLAG_MOBILE) { this.boundMobileScrollHandleFunction_ = goog.bind(this.handleScrollForMobile_, this); scrollResizeManager.callAfterScroll( this.boundMobileScrollHandleFunction_, true); } }; goog.inherits(audioCat.ui.visualization.SectionTimeDomainVisualization, audioCat.ui.widget.Widget); /** * Determines the color of the section visualization given the origination of * the audio. A static method. * @param {audioCat.audio.AudioOrigination} audioOrigination Where the audio * came from. * @return {string} The associated hexadecimal color value. */ audioCat.ui.visualization.SectionTimeDomainVisualization.determineColor = function(audioOrigination) { var originations = audioCat.audio.AudioOrigination; switch (audioOrigination) { case originations.IMPORTED: return 'rgba(189, 255, 68, 0.65)'; // A light green. case originations.RECORDED: return 'rgba(147, 211, 250, 0.65)'; // A light blue. case originations.RENDERED: return 'rgba(255, 255, 0, 0.65)'; } // A light gray is the default. // We should never see it. return 'rgba(225, 225, 225, 0.65)'; }; /** * How wide each canvas is at max in pixels. * @const * @type {number} */ audioCat.ui.visualization.SectionTimeDomainVisualization.MAX_CANVAS_WIDTH = 800; /** * Updates the displayed time. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. updateTimeDisplay_ = function() { this.domHelper_.setTextContent( this.timeIndicator_, this.timeFormatter_.formatTime(this.section_.getBeginTime())); }; /** * Sets the correct background color for the canvas container. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setCanvasContainerColor_ = function() { this.canvasContainer_.style.background = audioCat.ui.visualization.SectionTimeDomainVisualization.determineColor( this.section_.getAudioChest().getAudioOrigination()); }; /** * Sets the display level of the visualization. Determines how far from the top * of the track entry to display the visualization. * @param {number} displayLevel The display level. */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setDisplayLevel = function(displayLevel) { if (this.displayLevel_ != displayLevel) { // Only change if there is a need to. this.displayLevel_ = displayLevel; this.canvasContainer_.style.top = String(displayLevel * this.timeDomainScaleManager_.getSectionHeight()) + 'px'; } }; /** * Sets the correct display CSS height for the canvas container. This could * differ from the height canvases are drawing into. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setCanvasContainerHeight_ = function() { this.canvasContainer_.style.height = String(this.timeDomainScaleManager_.getSectionHeight()) + 'px'; }; /** * Redraws and repositions the section visualization using the current scale. */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. redrawAndReposition = function() { this.setCorrectLeftDistance_(); this.drawWaves_(); // Support horizontal zooming for mobile. this.setOuterContainerDimensions_(); }; /** * Sets the correct distance from the left in pixels. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setCorrectLeftDistance_ = function() { this.setPixelsFromLeft(this.computeCorrectLeftDistance_()); }; /** * Computes the correct distance from the left a section should be. * @return {number} The correct distance in pixels. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. computeCorrectLeftDistance_ = function() { var scale = this.timeDomainScaleManager_.getCurrentScale(); // This distance is due to begin time alone. return scale.convertToPixels(this.section_.getBeginTime()); }; /** * Handles what happens when the selected state of the section changes. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleSectionMovingStateChange_ = function() { this.visualizeMovingState_(); // TODO(chizeng): Consider changing the play time with the section time. }; /** * Sets the section visualization to reflect whether or not the section is * selected. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. visualizeMovingState_ = function() { var section = this.section_; var movingState = section.getMovingState(); (movingState ? goog.dom.classes.add : goog.dom.classes.remove)( this.canvasContainer_, goog.getCssName('movingSectionContainer')); }; /** * @return {number} The number of pixels from the left the visualization is * positioned. */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. getPixelsFromLeft = function() { return this.pixelsFromLeft_; }; /** * Sets the pixels from the left the section visualization should be positioned * at. Updates the UI. * @param {number} pixelsFromLeft */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setPixelsFromLeft = function(pixelsFromLeft) { this.pixelsFromLeft_ = pixelsFromLeft; this.canvasContainer_.style.left = String(pixelsFromLeft) + 'px'; }; /** * Handles what happens when the begin time of the section changes. Changes the * X-position of the visualization when that happens. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleSectionBeginTimeChange_ = function() { this.setCorrectLeftDistance_(); // Update the time shown. this.updateTimeDisplay_(); }; /** * Handles what happens when the playback rate of the section of audio changes. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handlePlaybackRateChanged_ = function() { this.scaleGivenPlaybackRate_(); }; /** * Scales all the canvases with CSS with the playback rate. * @return {number} The collective CSS width in pixels of the canvases. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. scaleGivenPlaybackRate_ = function() { var context2ds = this.context2ds_; // Scale the last canvas first since it is the only one that has not maxed out // in width. var lastIndex = context2ds.length - 1; var playbackRate = this.section_.getPlaybackRate(); var canvas = context2ds[lastIndex].canvas; var thisCanvasWidth = this.unscaledLastCanvasWidth_ / playbackRate; var collectiveWidth = thisCanvasWidth; canvas.style.width = '' + thisCanvasWidth + 'px'; var canvasHeight = '' + canvas.height + 'px'; canvas.style.height = canvasHeight; for (var i = 0; i < lastIndex; ++i) { canvas = context2ds[i].canvas; thisCanvasWidth = audioCat.ui.visualization.SectionTimeDomainVisualization .MAX_CANVAS_WIDTH / playbackRate; collectiveWidth += thisCanvasWidth; canvas.style.width = '' + thisCanvasWidth + 'px'; canvas.style.height = canvasHeight; } return collectiveWidth; }; /** * Handles what happens when the track of the section changes. * @param {!audioCat.state.TrackChangedForSectionEvent} event The event * associated with the track of the section changing. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleTrackChanged_ = function(event) { var track = event.getTrack(); if (track) { // The visualization is only visible if there is a track anyway. this.track_ = track; } }; /** * Handles changes in edit mode. * @param {!audioCat.state.editMode.EditModeChangedEvent} event The event * dispatched when the edit mode changes. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleEditModeChange_ = function(event) { this.deactivateMode_(event.getPreviousEditMode()); this.activateMode_(event.getNewEditMode()); }; /** * Handles a down press on the visualization of the section in select mode. This * corresponds to starting to move the section. * @param {!goog.events.BrowserEvent} event The event associated with the down * press. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleDownPressInSelectMode_ = function(event) { if (!this.hasDraggerTarget_(event)) { event.preventDefault(); var editModeManager = this.editModeManager_; var editMode = /** @type {!audioCat.state.editMode.SelectEditMode} */ ( editModeManager.getCurrentEditMode()); var section = this.section_; var scale = this.timeDomainScaleManager_.getCurrentScale(); var domHelper = this.domHelper_; var clientXValue = domHelper.obtainClientX(event); editMode.setSelectedSections([ new audioCat.state.editMode.MoveSectionEntry( section, this.track_, section.getBeginTime(), scale.convertToSeconds(clientXValue), clientXValue, this.scrollResizeManager_.getLeftRightScroll()) ]); editMode.pressDownInstigated(); // Listen to move around the document. var doc = domHelper.getDocument(); domHelper.listenForMove(doc, this.handleSectionMoveAround_, false, this); // When an up-press is detected on the document once afterwards ... domHelper.listenForUpPress( doc, this.handleUpPress_, false, this, true); section.setMovingState(true); } }; /** * Changes the x offset of the section as the user drags it around. * @param {!goog.events.BrowserEvent} event The event associated with the * movement. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleSectionMoveAround_ = function(event) { event.preventDefault(); // Get the section being moved. var mode = /** {!audioCat.state.editMode.SelectEditMode} */ ( this.editModeManager_.getCurrentEditMode()); var sectionEntries = mode.getSelectedSectionEntries(); var numberOfSectionEntries = sectionEntries.length; // For mobile, use elementFromPoint to determine whether we need to switch // tracks. Kind of slow ... but this is the only way. For Desktop, this logic // is handled in the track entry object when the select mode is activated. if (FLAG_MOBILE) { var browserTouchEvent = /** @type {!TouchEvent} */ (event.getBrowserEvent()); var touches = browserTouchEvent.changedTouches; if (touches.length > 0) { var domHelper = this.domHelper_; var touch = touches[0]; // Use clientX and clientY anyway, not the DomHelper helper method since // we know we are using mobile now. var touchedElement = domHelper.getDocument().elementFromPoint( touch.clientX, touch.clientY); while (touchedElement) { var newTrack = /** @type {audioCat.state.Track|undefined} */ ( touchedElement[audioCat.ui.tracks.StringConstant.TRACK_OBJECT]); if (newTrack) { // Check all sections to see if they need to switch tracks. for (var i = 0; i < numberOfSectionEntries; ++i) { var sectionEntry = sectionEntries[i]; var section = sectionEntry.getSection(); var currentSectionTrack = section.getTrack(); if (currentSectionTrack && currentSectionTrack.getId() != newTrack.getId()) { var scrollResizeManager = this.scrollResizeManager_; // Do not compute the horizontal scroll while in limbo (ie, while // section is being switched). scrollResizeManager.setIsGoodTimeForScrollCompute(false); // Switch the track of the section. // Remove the section from the previous track. currentSectionTrack.removeSection(section); // Add the section to this track. newTrack.addSection(section); // Re-allow horizontal scroll computations. scrollResizeManager.setIsGoodTimeForScrollCompute(false); } } // Already found new track. Don't check further up the DOM tree. break; } touchedElement = domHelper.getParentElement(touchedElement); } } } var timeDomainScaleManager = this.timeDomainScaleManager_; var scale = timeDomainScaleManager.getCurrentScale(); var scrollX = this.scrollResizeManager_.getLeftRightScroll(); for (var i = 0; i < numberOfSectionEntries; ++i) { var sectionEntry = sectionEntries[i]; var section = sectionEntry.getSection(); // Compute the delta of the mouse X. var originalBeginTime = sectionEntry.getBeginTime(); // Convert the delta to a time delta. // Take into account changes in clientX and scroll. var changeInTimeValue = scale.convertToSeconds( this.domHelper_.obtainClientX(event) - sectionEntry.getBeginClientX() + scrollX - sectionEntry.getBeginScrollX()); // TODO(chizeng): To fix moving and zooming at the same time, compute using // time information first. Then, compute back into pixels. This involves // storing the initial scale. var sectionOriginalTimeOffset = sectionEntry.getTimeOffset(); var newBeginTime = sectionEntry.getBeginTime() + changeInTimeValue; if (mode.getSnapToGridState()) { // We must snap the computed time to the grid. var intervalSeconds; if (timeDomainScaleManager.getDisplayAudioUsingBars()) { // Snap to the time interval that is a single beat. Tempo is beats/min. intervalSeconds = 60 / timeDomainScaleManager.getSignatureTempoManager().getTempo(); } else { // Snap to the time interval that is a single minor tick. var majorTickTime = scale.getMajorTickTime(); var timeConversion = 0; var timeUnit = scale.getTimeUnit(); if (timeUnit == audioCat.ui.visualization.TimeUnit.S) { timeConversion = 1; // 1 second in a second. } else if (timeUnit == audioCat.ui.visualization.TimeUnit.MS) { timeConversion = 1000; // 1000 ms in a second. } var minorsPerMajorTick = scale.getMinorTicksPerMajorTick(); // Minor ticks per major tick actually refers to the number of lines to // draw in a major tick that represent minor ticks. intervalSeconds = majorTickTime / timeConversion / (minorsPerMajorTick + 1); } // Floor to the previous interval matching value. newBeginTime = Math.floor(newBeginTime / intervalSeconds) * intervalSeconds; } // Clamp the time sum so it never goes under 0. newBeginTime = Math.max(newBeginTime, 0); // Set the section's begin time to this new value. section.setBeginTime(newBeginTime); } this.setOuterContainerDimensions_(); }; /** * Handles what do to once the user lifts the mouse. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleUpPress_ = function() { var domHelper = this.domHelper_; var doc = domHelper.getDocument(); domHelper.unlistenForMove(doc, this.handleSectionMoveAround_, false, this); // Empty selected tracks. var editMode = /** @type {!audioCat.state.editMode.SelectEditMode} */ ( this.editModeManager_.getCurrentEditMode()); editMode.confirmSectionMovement(); // TODO(chizeng): Verify if we really want to unselect ALL sections here. editMode.setSelectedSections([]); this.section_.setMovingState(false); }; /** * Handles what happens when the user clicks on a section in remove section * mode. The section gets removed from its track. * @param {!goog.events.BrowserEvent} e The event. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handlePressInRemoveSectionMode_ = function(e) { if (!this.hasDraggerTarget_(e)) { var editMode = /** @type {!audioCat.state.editMode.SectionRemoveMode} */ ( this.editModeManager_.getCurrentEditMode()); // Issues the command (so it's stored in history) to remove the section. editMode.removeSection(this.section_); } }; /** * Deactivates an edit mode. * @param {!audioCat.state.editMode.EditMode} mode The edit mode to deactivate. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. activateMode_ = function(mode) { var domHelper = this.domHelper_; var domElement = this.canvasContainer_; var editModeName = mode.getName(); var specificMode; switch (editModeName) { case audioCat.state.editMode.EditModeName.DUPLICATE_SECTION: domHelper.listenForPress(domElement, this.handlePressInDuplicateSectionMode_, false, this); this.setVisualizeDuplicateSectionMode_(true); break; case audioCat.state.editMode.EditModeName.REMOVE_SECTION: domHelper.listenForPress(domElement, this.handlePressInRemoveSectionMode_, false, this); this.setVisualizeRemoveSectionMode_(true); break; case audioCat.state.editMode.EditModeName.SELECT: specificMode = /** @type {!audioCat.state.editMode.SelectEditMode} */ ( mode); // Listen to mouse downs on the visualization of the audio section. domHelper.listenForDownPress(domElement, this.handleDownPressInSelectMode_, false, this); break; case audioCat.state.editMode.EditModeName.SPLIT_SECTION: // Listen for clicks - we should split the section on clicks. domHelper.listenForUpPress(domElement, this.handlePressInSectionSplitMode_, false, this); this.setVisualizeSectionSplitMode_(true); break; } }; /** * Deactivates an edit mode. * @param {!audioCat.state.editMode.EditMode} mode The edit mode to deactivate. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. deactivateMode_ = function(mode) { var domHelper = this.domHelper_; var editModeName = mode.getName(); var specificMode; var domElement = this.canvasContainer_; switch (editModeName) { case audioCat.state.editMode.EditModeName.DUPLICATE_SECTION: domHelper.unlistenForPress(domElement, this.handlePressInDuplicateSectionMode_, false, this); this.setVisualizeDuplicateSectionMode_(false); break; case audioCat.state.editMode.EditModeName.REMOVE_SECTION: domHelper.unlistenForPress(domElement, this.handlePressInRemoveSectionMode_, false, this); this.setVisualizeRemoveSectionMode_(false); break; case audioCat.state.editMode.EditModeName.SELECT: domHelper.unlistenForDownPress( domElement, this.handleDownPressInSelectMode_, false, this); break; case audioCat.state.editMode.EditModeName.SPLIT_SECTION: domHelper.unlistenForUpPress(domElement, this.handlePressInSectionSplitMode_, false, this); this.setVisualizeSectionSplitMode_(false); break; } }; /** * Handles duplicating a section when the user clicks on the section during * duplicate section mode. * @param {!goog.events.BrowserEvent} event The relevant event. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handlePressInDuplicateSectionMode_ = function(event) { if (!this.hasDraggerTarget_(event)) { event.preventDefault(); var editMode = /** @type {!audioCat.state.editMode.DuplicateSectionMode} */ ( this.editModeManager_.getCurrentEditMode()); editMode.duplicateSection(this.section_); } }; /** * Determines whether an event originally propagated from the dragger that lets * the user adjust speed. * @param {!goog.events.Event} event The event. * @return {boolean} Whether the dragger was the specific target. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. hasDraggerTarget_ = function(event) { return !!this.sectionSpeedDragger_ && event.target == this.sectionSpeedDragger_.getDom(); }; /** * Handles what happens when a user clicks on a section in section split mode. * @param {!goog.events.BrowserEvent} event The relevant event. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handlePressInSectionSplitMode_ = function(event) { if (this.hasDraggerTarget_(event)) { return; } event.preventDefault(); var mode = /** @type {!audioCat.state.editMode.SectionSplitMode} */ ( this.editModeManager_.getCurrentEditMode()); this.turnOffLineMarkingTimeInSection_(); // TODO(chizeng): Split the section, but do so in a way that allows us to copy // the contents of the section's canvases to the new canvases. That way, we // don't have to redraw the canvases. var domHelper = this.domHelper_; var domElement = this.canvasContainer_; var visualizationOffset = goog.style.getPageOffsetLeft(domElement); var clickOffset = this.domHelper_.obtainClientX(event); if (!FLAG_MOBILE) { // If we're not mobile, we don't need to take out the left-right scroll. clickOffset += this.scrollResizeManager_.getLeftRightScroll(); } var withinOffset = clickOffset - visualizationOffset; var offsetInSeconds = this.timeDomainScaleManager_.getCurrentScale() .convertToSeconds(withinOffset); mode.splitSection(this.section_, offsetInSeconds); }; /** * Sets whether the visualizer should reflect that we're in duplicate section * mode, in which the user can duplicate sections by clicking on them. * @param {boolean} status Whether we are in duplicate section mode. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setVisualizeDuplicateSectionMode_ = function(status) { (status ? goog.dom.classes.add : goog.dom.classes.remove)( this.canvasContainer_, goog.getCssName('duplicateSectionMode')); }; /** * Sets whether the visualizer should reflect that we're in section split mode. * @param {boolean} sectionSplitModeStatus Whether we are in section split mode. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setVisualizeSectionSplitMode_ = function(sectionSplitModeStatus) { var canvasContainer = this.canvasContainer_; if (sectionSplitModeStatus) { goog.dom.classes.add(canvasContainer, goog.getCssName('splitModeSection')); this.turnOnLineMarkingTimeInSection_(); } else { goog.dom.classes.remove( canvasContainer, goog.getCssName('splitModeSection')); this.turnOffLineMarkingTimeInSection_(); } }; /** * Turns on the line marking the place where the user is hovering over the * section. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. turnOnLineMarkingTimeInSection_ = function() { var domHelper = this.domHelper_; var canvasContainer = this.canvasContainer_; domHelper.listenForMove(canvasContainer, this.handleMouseMoveInSplitMode_, false, this); // Hide the line marking time when the user mouses out. domHelper.listenForMouseOut(canvasContainer, this.hideLineMarkingTimeInSection_, false, this); // Display the line marking time when the user mouses in. domHelper.listenForMouseOver(canvasContainer, this.displayLineMarkingTimeInSection_, false, this); }; /** * Appends the line marking time to the canvas container. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. displayLineMarkingTimeInSection_ = function() { this.domHelper_.appendChild( this.canvasContainer_, this.lineMarkingTimeInSection_); }; /** * Removes the line marking time from the canvas container. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. hideLineMarkingTimeInSection_ = function() { this.domHelper_.removeNode(this.lineMarkingTimeInSection_); }; /** * Turns off the line marking the place where the user is hovering over the * section. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. turnOffLineMarkingTimeInSection_ = function() { var domHelper = this.domHelper_; this.hideLineMarkingTimeInSection_(); var canvasContainer = this.canvasContainer_; domHelper.unlistenForMove(canvasContainer, this.handleMouseMoveInSplitMode_, false, this); domHelper.unlistenForMouseOut(canvasContainer, this.hideLineMarkingTimeInSection_, false, this); domHelper.unlistenForMouseOver(canvasContainer, this.displayLineMarkingTimeInSection_, false, this); }; /** * Handles mouse move in split mode. Makes the line follow the cursor. * @param {!goog.events.BrowserEvent} e The move event. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleMouseMoveInSplitMode_ = function(e) { if (!this.hasDraggerTarget_(e)) { e.preventDefault(); this.displayLineMarkingTimeInSection_(); var lineLeftValue = this.domHelper_.obtainClientX(e) - goog.style.getPageOffsetLeft(this.canvasContainer_); if (!FLAG_MOBILE) { // Account for scrolling iff we are not implementing our own scrolling, // which we do for mobile. lineLeftValue += this.scrollResizeManager_.getLeftRightScroll(); } this.lineMarkingTimeInSection_.style.left = String(lineLeftValue) + 'px'; } }; /** * Sets whether the visualizer should reflect that we're in section remove mode. * @param {boolean} status Whether we are in section remove mode. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setVisualizeRemoveSectionMode_ = function(status) { var functionToUse = status ? goog.dom.classes.add : goog.dom.classes.remove; functionToUse( this.canvasContainer_, goog.getCssName('sectionRemoveModeSection')); }; /** * Initializes the canvas. Draws the full wave form. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype.drawWaves_ = function() { // Update the ID of rendering so we can cancel if we're performing an // outdated render operation. this.drawId_ = this.idGenerator_.obtainUniqueId(); var drawId = this.drawId_; var domHelper = this.domHelper_; var canvasContainer = this.canvasContainer_; var context2dPool = this.context2dPool_; var context2ds = this.context2ds_; // Remove all canvases. Return them. for (var i = 0; i < context2ds.length; ++i) { var context2d = context2ds[i]; context2dPool.return2dContext(context2d); domHelper.removeNode(context2d.canvas); } context2ds.length = 0; var section = this.section_; var numberOfClips = section.getNumberOfClips(); if (numberOfClips == 0) { // No clips to render. return; } var maxCanvasWidth = audioCat.ui.visualization.SectionTimeDomainVisualization.MAX_CANVAS_WIDTH; var scale = this.timeDomainScaleManager_.getCurrentScale(); // Compute total width of the section visualization. var timeConversion = 0; var timeUnit = scale.getTimeUnit(); if (timeUnit == audioCat.ui.visualization.TimeUnit.S) { timeConversion = 1; // 1 second in a second. } else if (timeUnit == audioCat.ui.visualization.TimeUnit.MS) { timeConversion = 1000; // 1000 ms in a second. } // Compute width required to represent entire audio. Round up. var sectionDuration = section.getPlaybackRate1Duration(); var widthForWholeSection = Math.ceil(sectionDuration * timeConversion * scale.getMajorTickWidth() / scale.getMajorTickTime()); // Create canvases. var totalCanvasHeight = 100; // Arbitrary. Small enough to render quickly. // Will get resized by CSS anyway based on the time domain scale manager. var numberCanvasesNeeded = Math.ceil(widthForWholeSection / maxCanvasWidth); var lastContextIndex = numberCanvasesNeeded - 1; var new2dContext; var new2dContextCanvas; for (var i = 0; i < lastContextIndex; ++i) { new2dContext = context2dPool.retrieve2dContext(); new2dContextCanvas = new2dContext.canvas; new2dContextCanvas.width = maxCanvasWidth; new2dContextCanvas.height = totalCanvasHeight; context2ds.push(new2dContext); new2dContext.beginPath(); domHelper.appendChild(canvasContainer, new2dContextCanvas); } new2dContext = context2dPool.retrieve2dContext(); new2dContextCanvas = new2dContext.canvas; this.unscaledLastCanvasWidth_ = widthForWholeSection % maxCanvasWidth; new2dContextCanvas.width = this.unscaledLastCanvasWidth_; new2dContextCanvas.height = totalCanvasHeight; context2ds.push(new2dContext); new2dContext.beginPath(); domHelper.appendChild(canvasContainer, new2dContextCanvas); var sampleRate = section.getSampleRate(); var approxNumberOfSamplesInSection = sectionDuration * sampleRate; // Compute the number of samples each pixel represents in interval_size. var samplesPerPixel = Math.ceil( approxNumberOfSamplesInSection / widthForWholeSection); // How many samples to consider per pixel. // Higher values yield greater resolution, but slower speed. var samplesToTake = 30; var channelHeight = Math.floor( totalCanvasHeight / section.getNumberOfChannels()); var halfChannelHeight = Math.floor(channelHeight / 2); var midline = halfChannelHeight; // Compute the total sample length. var totalSampleLength = 0; for (var i = 0; i < section.getNumberOfClips(); ++i) { var clip = section.getClipAtIndex(i); totalSampleLength += clip.getRightSampleBound() - clip.getBeginSampleIndex(); } totalSampleLength = Math.min( totalSampleLength, approxNumberOfSamplesInSection); // Compute how many samples each pixel represents. Note that this number // differs from the var computedSamplesPerPixel = totalSampleLength / widthForWholeSection; // Consider the playback rate by altering CSS. var collectiveCssWidth = this.scaleGivenPlaybackRate_(); if (collectiveCssWidth > audioCat.ui.visualization.SectionSpeedDragger. MIN_VISUALIZATION_WIDTH_FOR_SHOW) { // The collective visualization is long enough for us to show the dragger. if (!this.sectionSpeedDragger_) { this.sectionSpeedDragger_ = new audioCat.ui.visualization.SectionSpeedDragger( this.domHelper_, this.section_, this.canvasContainer_, this.commandManager_, this.idGenerator_); domHelper.appendChild( this.canvasContainer_, this.sectionSpeedDragger_.getDom()); } } else { this.sectionSpeedDragger_ = null; } var canvasIndex = 0; var context = context2ds[canvasIndex]; var pixelIndex = 0; var overallSampleIndex = 0; var clipIndex = 0; var clip = section.getClipAtIndex(clipIndex); var withinClipSampleIndex = clip.getBeginSampleIndex(); var minSample = 0; var maxSample = 0; var sampleIncrement = Math.floor(computedSamplesPerPixel / samplesToTake); var channelIndex = 0; var channelMins = new Array(section.getNumberOfChannels()); var channelMaxes = new Array(section.getNumberOfChannels()); for (var i = 0; i < channelMins.length; ++i) { channelMins[i] = 0; channelMaxes[i] = 0; } var generateWaveForms = goog.bind(function() { if (this.drawId_ != drawId) { // This generation of wave forms is outdated. return; } while (overallSampleIndex < totalSampleLength) { if (clipIndex >= section.getNumberOfClips()) { // No more clips to render. break; } clip = section.getClipAtIndex(clipIndex); withinClipSampleIndex = clip.getBeginSampleIndex(); while (withinClipSampleIndex < clip.getRightSampleBound()) { // For all channels, while (channelIndex < section.getNumberOfChannels()) { // Get the samples for all channels. var sample = section.getSampleAtIndex( channelIndex, withinClipSampleIndex); // Update mins and maxes of samples in this pixel. channelMins[channelIndex] = Math.min(channelMins[channelIndex], sample); channelMaxes[channelIndex] = Math.max(channelMaxes[channelIndex], sample); channelIndex++; } channelIndex = 0; // Update sample count. overallSampleIndex += sampleIncrement; withinClipSampleIndex += sampleIncrement; // Check if we finished computing 1 pixel of samples. var localPixelIndex = Math.floor( overallSampleIndex / computedSamplesPerPixel); if (localPixelIndex > pixelIndex) { // Create the lines. var canvasPixelIndex = pixelIndex % maxCanvasWidth; // For each channel, move to the right vertical position. Make curve. for (var c = 0; c < section.getNumberOfChannels(); ++c) { var localMidline = c * channelHeight + halfChannelHeight; context.moveTo(canvasPixelIndex + 0.5, localMidline - halfChannelHeight * channelMaxes[c]); context.lineTo(canvasPixelIndex + 0.5, localMidline - halfChannelHeight * channelMins[c]); } // Update the pixel index. pixelIndex = localPixelIndex; // Reset channel min / max calculations. for (var i = 0; i < channelMins.length; ++i) { channelMins[i] = 0; channelMaxes[i] = 0; } // Possibly update which canvas to draw on. If we are to update, draw. // Also if we are to update, use a set timeout so that we do not have // 1 really long-lasting function. if (localPixelIndex >= canvasIndex * maxCanvasWidth + context.canvas.width) { // Render. context.clearRect( 0, 0, context.canvas.width, context.canvas.height); context.closePath(); context.strokeStyle = '#000'; context.stroke(); // Update the context we are drawing on. canvasIndex++; if (canvasIndex < context2ds.length) { // Set a new timeout we are not done yet. context = context2ds[canvasIndex]; context.beginPath(); goog.global.setTimeout(generateWaveForms, 1); } } } } clipIndex++; } }, this); // Store mins and maxes. // var mins = new Float32Array(widthForWholeSection, 1.0); // var maxes = new Float32Array(widthForWholeSection, -1.0); // var numberOfChannels = section.getNumberOfChannels(); // var channelHeight = Math.floor(totalCanvasHeight / numberOfChannels); // var halfChannelHeight = Math.floor(channelHeight / 2); // var midline = halfChannelHeight; // for (var channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex) { // // Store a current clip. // var clipIndex = 0; // var clip = section.getClipAtIndex(clipIndex); // // Iterate through each pixel in the width. // var accumulatedSampleCount = section.getBeginAudioChestSampleIndex(); // var doneComputingMinsMaxes = false; // for (var pixelIndex = 0; pixelIndex < widthForWholeSection; ++pixelIndex) { // // Compute a scaled base sample value. Add in the accumulated value. // var baseSampleIndex = Math.floor( // pixelIndex * approxNumberOfSamplesInSection / widthForWholeSection) + // accumulatedSampleCount; // for (var randomSampleIndex = 0; randomSampleIndex < samplesToTake; // ++randomSampleIndex) { // var sampleIndex = baseSampleIndex + // Math.floor(samplesPerPixel * randomSampleIndex / samplesToTake); // // Advance to the next clip if necessary. // while (clip.getRightSampleBound() <= sampleIndex) { // ++clipIndex; // if (clipIndex >= numberOfClips) { // doneComputingMinsMaxes = true; // break; // } // var nextClip = section.getClipAtIndex(clipIndex); // accumulatedSampleCount += // nextClip.getBeginSampleIndex() - clip.getRightSampleBound(); // clip = nextClip; // } // if (doneComputingMinsMaxes) { // break; // } // // Get the sample value. // var sampleValue = section.getSampleAtIndex(channelIndex, sampleIndex); // // Set the new min / max found for the segment if necessary. // if (sampleValue < mins[pixelIndex]) { // mins[pixelIndex] = sampleValue; // } // if (sampleValue > maxes[pixelIndex]) { // maxes[pixelIndex] = sampleValue; // } // } // if (doneComputingMinsMaxes) { // break; // } // } // // Create the paths for the waveform. // var pixelIndex = 0; // for (var canvasIndex = 0; canvasIndex < numberCanvasesNeeded; // ++canvasIndex) { // for (var perCanvasPixelIndex = 0; perCanvasPixelIndex < maxCanvasWidth; // ++perCanvasPixelIndex) { // var context2d = context2ds[canvasIndex]; // var perCanvasPixelIndexFrontHalf = perCanvasPixelIndex + 0.5; // context2d.moveTo(perCanvasPixelIndexFrontHalf, // midline - mins[pixelIndex] * halfChannelHeight); // context2d.lineTo(perCanvasPixelIndexFrontHalf, // midline - maxes[pixelIndex] * halfChannelHeight); // // Reset the min and max. // mins[pixelIndex] = 1.0; // maxes[pixelIndex] = -1.0; // ++pixelIndex; // } // } // // Update canvas draw settings. // midline += channelHeight; // } goog.global.setTimeout(generateWaveForms, 0); }; /** * Cleans up the visualization to conserve memory. For instance, this method * puts the contexts back into the pool. * @override */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype.cleanUp = function() { var unlistenFunction = goog.events.unlisten; var section = this.section_; var editModeManager = this.editModeManager_; unlistenFunction(section, audioCat.state.events.TRACK_CHANGED_FOR_SECTION, this.handleTrackChanged_, false, this); unlistenFunction(editModeManager, audioCat.state.editMode.Events.EDIT_MODE_CHANGED, this.handleEditModeChange_, false, this); unlistenFunction(section, audioCat.state.events.SECTION_BEGIN_TIME_CHANGED, this.handleSectionBeginTimeChange_, false, this); unlistenFunction(section, audioCat.state.events.PLAYBACK_RATE_CHANGED, this.handlePlaybackRateChanged_, false, this); if (FLAG_MOBILE) { this.scrollResizeManager_.removeCallAfterScroll( this.boundMobileScrollHandleFunction_); } // Return all the contexts. goog.dom.removeChildren(this.canvasContainer_); var context2dPool = this.context2dPool_; var context2ds = this.context2ds_; var numberOfContexts = context2ds.length; for (var i = 0; i < numberOfContexts; ++i) { context2dPool.return2dContext(context2ds[i]); } // Clean up the dragger that lets the user adjust speed. if (this.sectionSpeedDragger_) { this.sectionSpeedDragger_.cleanUp(); this.sectionSpeedDragger_ = null; } audioCat.ui.visualization.SectionTimeDomainVisualization.base( this, 'cleanUp'); }; /** * Sets the left offset and width of the outer container (the container of the * container of canvases) so that part of it still reaches its original * position, allowing for the application to fully scroll. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. setOuterContainerDimensions_ = function() { if (FLAG_MOBILE) { // For mobile browsers, make up for scrolling distance. Otherwise, the width // of the app container shrinks since we move elements leftward. var scrollDistance = this.scrollResizeManager_.getLeftRightScroll(); // This width should be large enough to make the browser not reduce width. var totalWidth = scrollDistance + this.computeCorrectLeftDistance_() + this.canvasContainer_.clientWidth; var container = this.getDom(); container.style.width = '' + totalWidth + 'px'; container.style.left = '-' + scrollDistance + 'px'; } }; /** * Sets the dimensions of the outer container so that this section visualization * could contribute to the overall scroll width of the application, allowing us * to properly implement horizontal scrolling. Call this as soon as this element * is appended to the DOM. */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. rectifyDimensions = function() { // Set the right outer dimensions for scrolling. this.setOuterContainerDimensions_(); }; /** * Handles scrolling for mobile browers, which we implement on our own. * @private */ audioCat.ui.visualization.SectionTimeDomainVisualization.prototype. handleScrollForMobile_ = function() { this.setOuterContainerDimensions_(); };
import { sign as mathSign, fitIntoRange } from '../core/utils/math'; import * as iteratorUtils from '../core/utils/iterator'; import { hasTouches } from './utils/index'; import Emitter from './core/emitter'; import registerEmitter from './core/emitter_registrator'; var DX_PREFIX = 'dx'; var TRANSFORM = 'transform'; var TRANSLATE = 'translate'; var PINCH = 'pinch'; var ROTATE = 'rotate'; var START_POSTFIX = 'start'; var UPDATE_POSTFIX = ''; var END_POSTFIX = 'end'; var eventAliases = []; var addAlias = function addAlias(eventName, eventArgs) { eventAliases.push({ name: eventName, args: eventArgs }); }; addAlias(TRANSFORM, { scale: true, deltaScale: true, rotation: true, deltaRotation: true, translation: true, deltaTranslation: true }); addAlias(TRANSLATE, { translation: true, deltaTranslation: true }); addAlias(PINCH, { scale: true, deltaScale: true }); addAlias(ROTATE, { rotation: true, deltaRotation: true }); var getVector = function getVector(first, second) { return { x: second.pageX - first.pageX, y: -second.pageY + first.pageY, centerX: (second.pageX + first.pageX) * 0.5, centerY: (second.pageY + first.pageY) * 0.5 }; }; var getEventVector = function getEventVector(e) { var pointers = e.pointers; return getVector(pointers[0], pointers[1]); }; var getDistance = function getDistance(vector) { return Math.sqrt(vector.x * vector.x + vector.y * vector.y); }; var getScale = function getScale(firstVector, secondVector) { return getDistance(firstVector) / getDistance(secondVector); }; var getRotation = function getRotation(firstVector, secondVector) { var scalarProduct = firstVector.x * secondVector.x + firstVector.y * secondVector.y; var distanceProduct = getDistance(firstVector) * getDistance(secondVector); if (distanceProduct === 0) { return 0; } var sign = mathSign(firstVector.x * secondVector.y - secondVector.x * firstVector.y); var angle = Math.acos(fitIntoRange(scalarProduct / distanceProduct, -1, 1)); return sign * angle; }; var getTranslation = function getTranslation(firstVector, secondVector) { return { x: firstVector.centerX - secondVector.centerX, y: firstVector.centerY - secondVector.centerY }; }; var TransformEmitter = Emitter.inherit({ validatePointers: function validatePointers(e) { return hasTouches(e) > 1; }, start: function start(e) { this._accept(e); var startVector = getEventVector(e); this._startVector = startVector; this._prevVector = startVector; this._fireEventAliases(START_POSTFIX, e); }, move: function move(e) { var currentVector = getEventVector(e); var eventArgs = this._getEventArgs(currentVector); this._fireEventAliases(UPDATE_POSTFIX, e, eventArgs); this._prevVector = currentVector; }, end: function end(e) { var eventArgs = this._getEventArgs(this._prevVector); this._fireEventAliases(END_POSTFIX, e, eventArgs); }, _getEventArgs: function _getEventArgs(vector) { return { scale: getScale(vector, this._startVector), deltaScale: getScale(vector, this._prevVector), rotation: getRotation(vector, this._startVector), deltaRotation: getRotation(vector, this._prevVector), translation: getTranslation(vector, this._startVector), deltaTranslation: getTranslation(vector, this._prevVector) }; }, _fireEventAliases: function _fireEventAliases(eventPostfix, originalEvent, eventArgs) { eventArgs = eventArgs || {}; iteratorUtils.each(eventAliases, function (_, eventAlias) { var args = {}; iteratorUtils.each(eventAlias.args, function (name) { if (name in eventArgs) { args[name] = eventArgs[name]; } }); this._fireEvent(DX_PREFIX + eventAlias.name + eventPostfix, originalEvent, args); }.bind(this)); } }); /** * @name UI Events.dxtransformstart * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 cancel:boolean * @module events/transform */ /** * @name UI Events.dxtransform * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 scale:number * @type_function_param1_field2 deltaScale:number * @type_function_param1_field3 rotation:number * @type_function_param1_field4 deltaRotation:number * @type_function_param1_field5 translation:object * @type_function_param1_field6 deltaTranslation:object * @type_function_param1_field7 cancel:boolean * @module events/transform */ /** * @name UI Events.dxtransformend * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 scale:number * @type_function_param1_field2 deltaScale:number * @type_function_param1_field3 rotation:number * @type_function_param1_field4 deltaRotation:number * @type_function_param1_field5 translation:object * @type_function_param1_field6 deltaTranslation:object * @type_function_param1_field7 cancel:boolean * @module events/transform */ /** * @name UI Events.dxtranslatestart * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 cancel:boolean * @module events/transform */ /** * @name UI Events.dxtranslate * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 translation:object * @type_function_param1_field2 deltaTranslation:object * @type_function_param1_field3 cancel:boolean * @module events/transform */ /** * @name UI Events.dxtranslateend * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 translation:object * @type_function_param1_field2 deltaTranslation:object * @type_function_param1_field3 cancel:boolean * @module events/transform */ /** * @name UI Events.dxpinchstart * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 cancel:boolean * @module events/transform */ /** * @name UI Events.dxpinch * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 scale:number * @type_function_param1_field2 deltaScale:number * @type_function_param1_field3 cancel:boolean * @module events/transform */ /** * @name UI Events.dxpinchend * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 scale:number * @type_function_param1_field2 deltaScale:number * @type_function_param1_field3 cancel:boolean * @module events/transform */ /** * @name UI Events.dxrotatestart * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 cancel:boolean * @module events/transform */ /** * @name UI Events.dxrotate * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 rotation:number * @type_function_param1_field2 deltaRotation:number * @type_function_param1_field3 cancel:boolean * @module events/transform */ /** * @name UI Events.dxrotateend * @type eventType * @type_function_param1 event:event * @type_function_param1_field1 rotation:number * @type_function_param1_field2 deltaRotation:number * @type_function_param1_field3 cancel:boolean * @module events/transform */ var eventNames = eventAliases.reduce((result, eventAlias) => { [START_POSTFIX, UPDATE_POSTFIX, END_POSTFIX].forEach(eventPostfix => { result.push(DX_PREFIX + eventAlias.name + eventPostfix); }); return result; }, []); registerEmitter({ emitter: TransformEmitter, events: eventNames }); var exportNames = {}; iteratorUtils.each(eventNames, function (_, eventName) { exportNames[eventName.substring(DX_PREFIX.length)] = eventName; }); /* eslint-disable spellcheck/spell-checker */ export var { transformstart, transform, transformend, translatestart, translate, translateend, zoomstart, zoom, zoomend, pinchstart, pinch, pinchend, rotatestart, rotate, rotateend } = exportNames;
const chalk = require('chalk'); module.exports = function() { console.log( chalk.yellow( ` 1) Classes have a constructor method - if you don't know how to use it, google it ` ) ); process.exit(); };
module.exports = (app, db) => { const users = require('./controllers/users')(db); const tweets = require('./controllers/tweets')(db); // Root Route app.get('/', tweets.showAllTweetsForm); /* * ========================================= * Users * ========================================= */ // CRUD users app.get('/users/new', users.newForm); app.get('/users/login', users.loginForm); app.get('/users/logout', users.logoutUser); app.get('/users/:id/show', users.showUser) app.post('/users', users.create); app.post('/users/login', users.loginUser); app.post('/users/:id/follow', users.followUser) /* * ========================================= * Tweets * ========================================= */ // CRUD tweets app.get('/tweets/new', tweets.newTweetForm); app.get('/tweets/following', tweets.showFollowingTweetsForm) app.get('/tweets/followers', tweets.showFollowerTweetsForm) app.get('/tweets/:id/show', tweets.showSingleTweetForm) app.post('/tweets', tweets.newTweetPost) };
import axios from 'axios' import { t } from '../common/i18n.js' import { message } from 'ant-design-vue'; // import { getUrl } from './util' import { getCookie, setCookie, delCookie } from './sessionstorge' import { sign } from './sign' // 默认实例参数 const defaultOptions = { // baseURL: `${getUrl()}`, baseURL: import.meta.env.VITE_API_ROOT, method: 'POST', timeout: 30000, validateStatus: function () { return true } } const xhr = axios.create(defaultOptions) const request = axios.create(defaultOptions) xhr.interceptors.request.use(function (config) { config.headers.Accept = 'application/json' config.headers.language = getCookie('language') return config }) let systemUrl = import.meta.env.VITE_NODE_ENV == 'test' ? 'http://47.114.131.143:9012/#' : import.meta.env.VITE_NODE_ENV == 'development' ? 'http://47.114.117.27:9003/#' : import.meta.env.VITE_NODE_ENV == 'production' ? 'https://iot.hdlcontrol.com/iot-common/#' : 'https://iot-en.hdlcontrol.com/iot-common/#' request.interceptors.request.use(async function (config) { config.headers.Accept = 'application/json' config.headers.language = getCookie('language') // const auth = get('auth') || {} let cancel let data = config.data || {} const appkey = import.meta.env.VITE_ENV_CONFIG === 'prod' || import.meta.env.VITE_ENV_CONFIG === 'proden' ? 'HDL-IOT-PLATFORM' : 'HDL-IOT-PLATFORM-TEST' const secret = import.meta.env.VITE_ENV_CONFIG === 'prod' || import.meta.env.VITE_ENV_CONFIG === 'proden' ? 'rjcccssaa028gHnbi8c4tmbqucvYdxix' : '5577b738048e88db2201d697685674yn' config.data = sign(data, appkey, secret) config.cancelToken = new axios.CancelToken(function (c) { cancel = c }) if (getCookie('accessTokenIot')) { // const timestamp = Math.round(new Date().getTime() / 1000) const timestamp = new Date().getTime() if (timestamp > getCookie('expirationIot')) { // if (timestamp < auth.expiresIn - 300) { // token 已过期 // if (timestamp - auth.lastFetchedTime < 2592000) { // refreshToken 未过期 // 同步刷新Token // const newAuthData = await request.post('/userCenter/user/refreshToken', { refreshToken: auth.refreshToken});//xhr.post('/userCenter/user/refreshToken', { refreshToken: auth.refreshToken}); let refreshTokenData = {refreshToken: getCookie('refreshTokenIot'), grantType: 'refresh_token'} const newAuthData = await xhr.post('/basis-footstone/mgmt/user/oauth/login', sign(refreshTokenData, appkey, secret)) if (newAuthData.code === 0) { newAuthData.data.expiresIn += Math.round(new Date().getTime() / 1000) // let authData = get('auth') || {} // authData = Object.assign(authData, newAuthData.data) // set('auth', authData) setCookie('accessTokenIot', newAuthData.data.accessToken, 'd1') config.headers.Authorization = `Bearer ${newAuthData.data.accessToken}` } else { // remove('auth') delCookie('accessTokenIot') delCookie('expirationIot') delCookie('refreshTokenIot') delCookie('userIdIot') delCookie('accountIot') window.location.href = `${systemUrl}/login?companyId=1&sysCode=iot-partner` // message.destroy() // message.error('登录失效,请重新登录!') cancel() } config.cancelToken = new axios.CancelToken(c => { cancel = c }) // } else { // location.href = '#/'; // } } else { // token 未过期 config.headers.Authorization = `Bearer ${getCookie('accessTokenIot')}` } } else { window.location.href = `${systemUrl}/login?companyId=1&sysCode=iot-partner` } return config }) // 通用响应拦截器 const responseInterceptor = async (response) => { const { status, data } = response if (status >= 200 & status < 300) { if (data.code === 0) { return Promise.resolve(data) } else if (data.code === 10004 || data.code === 10005 || data.code === 10007 || data.code === 10006) { // 跳转到公共登录 window.location.href = `${systemUrl}/login?companyId=1&sysCode=iot-partner` message.destroy() message.error(data.message || t('hdl.networkError')) return Promise.resolve(data) } else { message.destroy() if (data & data.code === 0 & data.message & data.message === t('homePage.noData')) { console.log(t('hdl.noPrompt')) } else { if (data.message === t('hdl.CannotBeEmpty')) { message.error(t('hdl.pleaseLoginAgain')) } else { message.error(data.message || t('hdl.networkError')) } } return Promise.resolve(data) } } else { // console.log(data) message.destroy() message.error(data.message || t('hdl.networkError')) return Promise.reject(response) } } // 拦截 respose 进行状态判断 xhr.interceptors.response.use(responseInterceptor) request.interceptors.response.use(responseInterceptor) export { xhr, request } export default request
const editor = require('./editor.js'); const storage = require('./storage.js'); const gateway = require('./gateway.js'); const flash = msg => { const dialog = document.getElementById('message'); dialog.innerHTML = `${new Date()} ${JSON.stringify(msg)}`; }; const convertButton = document.getElementById('convert'); convertButton.onclick = e => { editor.convertToYAML(storage.editor.item.data, document.getElementById('console'), storage.editor.itemType.path.ext); }; const searchInput = document.getElementById('search'); searchInput.onkeyup = e => { storage.menu.search.query = e.target.value; window.dispatchEvent(new CustomEvent('search-query-updated', { detail: 'e.target.value' })); }; window.addEventListener('item-data-changed', e => { storage.editor.item.data[e.detail.name] = e.detail.value; }); const saveButton = document.getElementById('save-item'); saveButton.onclick = event => { const body = editor.convertToYAML( storage.editor.item.data, document.getElementById('console'), storage.editor.itemType.path.ext ); const formData = new FormData(); formData.append('marketplace_builder_file_body', new Blob([body])); const path = storage.editor.itemType.path; const filename = storage.editor.item.data.path || 'FILENAME'; formData.append('path', `${path.base}/${filename}.${path.ext}`); gateway .sync(formData) .then(response => { // console.log(storage.editor); // const name = storage.editor.item.data.name || storage.editor.item.data.slug; // storage.editor.item.name = name; flash(response.data); window.dispatchEvent(new CustomEvent('items-loaded', { detail: storage.editor.itemType.name })); }) .catch(error => flash(error.data)); }; const reloadItemTypesData = () => { return new Promise((resolve, reject) => { gateway.getItemTypes().then(response => { storage.itemTypes = []; storage.itemTypes = [...response.data.data.itemTypes.results] .filter(t => t.name != 'Asset') .filter(t => t.name != 'ActivityStreamsHandler') .filter(t => t.name != 'ActivityStreamsGroupingHandler') .filter(t => t.name != 'Translation'); window.dispatchEvent(new Event('item-types-loaded')); resolve('OK'); }, flash); }); }; const loadItemsData = e => { if (storage.items.byType(e.detail).length > 0) { window.dispatchEvent(new CustomEvent('items-loaded', { detail: e.detail })); return; } gateway.getItems(e.detail).then(response => { storage.items.load(response.data.data.items.results); window.dispatchEvent(new CustomEvent('items-loaded', { detail: e.detail })); }); }; const renderItemTypeList = () => { const container = document.getElementById('item-type-list'); while (container.firstChild) { container.removeChild(container.firstChild); } for (i in storage.itemTypes) { let type = storage.itemTypes[i]; let div = document.createElement('div'); let label = document.createElement('label'); let option = document.createElement('input'); option.type = 'checkbox'; option.name = `chb-${type.name}`; option.value = type.name; option.checked = storage.menu.search.itemTypes.has(type.name); option.onchange = e => { if (e.target.checked) window.dispatchEvent(new CustomEvent('item-type-selected', { detail: type.name })); else window.dispatchEvent(new CustomEvent('item-type-deselected', { detail: type.name })); }; const newItemButton = document.createElement('button'); newItemButton.onclick = event => { const name = `new-${type.name.toLowerCase()}`; const newItem = { name: name, type: type.name, data: { name: name } }; storage.items.add(newItem); window.dispatchEvent(new CustomEvent('item-selected', { detail: { name: name, type: type.name } })); }; newItemButton.appendChild(document.createTextNode('new')); div.appendChild(newItemButton); let itemList = document.createElement('div'); itemList.id = `${type.name}-item-list`; label.appendChild(option); label.appendChild(document.createTextNode(type.name)); div.appendChild(label); div.appendChild(itemList); container.appendChild(div); } }; const renderItemList = ({ detail }) => { const list = document.getElementById(`${detail}-item-list`); if (!list) return; while (list.firstChild) { list.removeChild(list.firstChild); } for (i in storage.items.byType(detail)) { let item = storage.items.byType(detail)[i]; if (storage.menu.search.matches(item)) { let selected = item.name == storage.editor.item.name; list.appendChild(renderMenuItem(item, selected)); } } }; window.addEventListener('item-types-loaded', renderItemTypeList); window.addEventListener('items-loaded', renderItemList); // window.addEventListener('items-loaded', console.log); window.addEventListener('item-selected', ({ detail }) => { const item = storage.items.byType(detail.type).find(x => x.name == detail.name); storage.editor.item = item; }); window.addEventListener('item-selected', ({ detail }) => { const item = storage.itemTypes.find(x => x.name == detail.type); storage.editor.itemType = item; }); window.addEventListener('item-selected', ({ detail }) => { renderEditor(); }); const renderMenuItem = ({ name, type, data }, selected = false) => { let block = document.createElement('div'); let label = document.createElement('label'); let small = document.createElement('div'); small.classList.add('hint'); let item = document.createElement('input'); item.id = `list-item-${type}-${name}`; item.type = 'radio'; item.name = 'menu-item'; item.value = name; item.checked = selected; item.onclick = event => { window.dispatchEvent(new CustomEvent('item-selected', { detail: { name, type } })); }; label.appendChild(item); label.appendChild(document.createTextNode(name)); small.appendChild(document.createTextNode(type)); label.appendChild(small); block.appendChild(label); return block; }; const button = document.getElementById('reload'); button.onclick = reloadItemTypesData; window.addEventListener('item-type-selected', ({ detail }) => { storage.menu.search.itemTypes = new Set([...storage.menu.search.itemTypes, detail]); }); window.addEventListener('item-type-deselected', ({ detail }) => { storage.menu.search.itemTypes.delete(detail); }); window.addEventListener('item-type-selected', loadItemsData); window.addEventListener('item-type-deselected', loadItemsData); window.addEventListener('search-query-updated', () => { storage.menu.search.itemTypes.forEach(type => loadItemsData({ detail: type })); }); const renderEditor = () => { if (storage.editor.item.data) { editor.createForm( storage.editor.item.data, storage.editor.itemType, storage.editor.settings, document.getElementById('editor-fields') ); } }; const render = () => { reloadItemTypesData().then(() => { loadItemsData({ detail: 'EmailNotification' }); loadItemsData({ detail: 'SmsNotification' }); loadItemsData({ detail: 'ApiCallNotification' }); loadItemsData({ detail: 'AuthorizationPolicy' }); loadItemsData({ detail: 'FormConfiguration' }); loadItemsData({ detail: 'TransactableType' }); }); }; render();
import * as Graphs from "/imports/api/graphs/graphs.js"; import {insertNewChart} from "/imports/api/charts/methods.js"; import {insertGraph} from "/imports/api/graphs/methods.js"; import {Random} from "meteor/random"; export const createNewGuide = new ValidatedMethod({ name: "misc.createNewGuide", validate: new SimpleSchema({ name: { type: String, min: 4, regEx: /^[A-Z a-z0-9]+$/ }, description: { type: String } }).validator(), run({name: name, description: description}) { let firstNode = {}; let midNode = {}; let lastNode = {}; let firstEdge = {}; let secondEdge = {}; firstNode[Graphs.NODE_ID] = Random.id(); firstNode[Graphs.NODE_NAME] = "First Step"; firstNode[Graphs.NODE_DETAILS] = "The user will see this step first."; midNode[Graphs.NODE_ID] = Random.id(); midNode[Graphs.NODE_NAME] = "Next Step"; midNode[Graphs.NODE_DETAILS] = "The user will see this after pressing Next."; lastNode[Graphs.NODE_ID] = Random.id(); lastNode[Graphs.NODE_NAME] = "Done"; firstEdge[Graphs.EDGE_ID] = Random.id(); firstEdge[Graphs.EDGE_NAME] = "Next"; firstEdge[Graphs.EDGE_SOURCE] = firstNode[Graphs.NODE_ID]; firstEdge[Graphs.EDGE_TARGET] = midNode[Graphs.NODE_ID]; secondEdge[Graphs.EDGE_ID] = Random.id(); secondEdge[Graphs.EDGE_NAME] = "Next"; secondEdge[Graphs.EDGE_SOURCE] = midNode[Graphs.NODE_ID]; secondEdge[Graphs.EDGE_TARGET] = lastNode[Graphs.NODE_ID]; let graph = {}; graph[Graphs.NODES] = [firstNode, midNode, lastNode]; graph[Graphs.EDGES] = [firstEdge, secondEdge]; graph[Graphs.FIRST_NODE] = firstNode[Graphs.NODE_ID]; graph[Graphs.OWNER] = Meteor.userId(); let graphId = insertGraph.call(graph); return insertNewChart.call({name: name, description: description, graph: graphId}); } });
import * as flags from "../repository/FlagsRepository"; import {Country} from "../model/Country"; let countries = { "Albania": new Country("Albania", flags.albaniaFlag, "AL"), "Andorra": new Country("Andora", flags.andorraFlag), "Austria": new Country("Austria", flags.austriaFlag, "AT"), "Belarus": new Country("Białoruś", flags.belarusFlag, "BY"), "Belgium": new Country("Belgia", flags.belgiumFlag, "BE"), "BosniaAndHerzegovina": new Country("Bośnia i Hercegowina", flags.bosniaAndHerzegovinaFlag, "BA"), "Bulgaria": new Country("Bułgaria", flags.bulgariaFlag, "BG"), "Croatia": new Country("Chorwacja", flags.croatiaFlag, "HR"), "Cyprus": new Country("Cypr", flags.cyprusFlag, "CY"), "CzechRepublic": new Country("Czechy", flags.czechFlag, "CZ"), "Denmark": new Country("Dania", flags.denmarkFlag, "DK"), "Estonia": new Country("Estonia", flags.estoniaFlag, "EE"), "Finland": new Country("Finlandia", flags.finlandFlag, "FI"), "Macedonia": new Country("Macedonia", flags.macedoniaFlag, "MK"), "France": new Country("Francja", flags.franceFlag, "FR"), "Germany": new Country("Niemcy", flags.germanyFlag, "DE"), "Greece": new Country("Grecja", flags.greeceFlag, "GR"), "Hungary": new Country("Węgry", flags.hungaryFlag, "HU"), "Iceland": new Country("Islandia", flags.icelandFlag, "IS"), "Ireland": new Country("Irlandia", flags.irelandFlag, "IE"), "Italy": new Country("Włochy", flags.italyFlag, "IT"), "Latvia": new Country("Łotwa", flags.latviaFlag, "LV"), "Liechtenstein": new Country("Liechtenstein", flags.liechtensteinFlag), "Lithuania": new Country("Litwa", flags.lithuaniaFlag, "LT"), "Luxembourg": new Country("Luksemburg", flags.luxembourgFlag, "LU"), "Malta": new Country("Malta", flags.maltaFlag, "ML"), "Moldova": new Country("Mołdawia", flags.moldovaFlag, "MD"), "Monaco": new Country("Monako", flags.monacoFlag), "Montenegro": new Country("Czarnogóra", flags.montenegroFlag, "ME"), "Netherlands": new Country("Holandia", flags.netherlandsFlag, "NL"), "Norway": new Country("Norwegia", flags.norwayFlag, "NO"), "Poland": new Country("Polska", flags.polandFlag, "PL"), "Portugal": new Country("Portugalia", flags.portugalFlag, "PT"), "Romania": new Country("Rumunia", flags.romaniaFlag, "RO"), "Russia": new Country("Rosja", flags.russiaFlag, "RU"), "SanMarino": new Country("San Marino", flags.sanMarinoFlag), "Serbia": new Country("Serbia", flags.serbiaFlag, "RS"), "Slovakia": new Country("Słowacja", flags.slovakiaFlag, "SK"), "Slovenia": new Country("Słowenia", flags.sloveniaFlag, "SI"), "Spain": new Country("Hiszpania", flags.spainFlag, "ES"), "Sweden": new Country("Szwecja", flags.swedenFlag, "SE"), "Switzerland": new Country("Szwajcaria", flags.switzerlandFlag, "CH"), "Ukraine": new Country("Ukraina", flags.ukraineFlag, "UA"), "UnitedKingdom": new Country("Wielka Brytania", flags.ukFlag, "GB") }; function findAll() { let result = []; for (let country in countries) { if (Object.prototype.hasOwnProperty.call(countries, country)) { result.push({ code: country, country: countries[country] }); } } return result; } let allCountries = findAll(); export {countries, allCountries};
const INITIAL_STATE = { "_id":"", "Location":"", "Product":"", "Subject":"", "AlertPriority":"", "AlertType":"", "__v":0, "AlertStatus":"" }; export default (state = INITIAL_STATE, action) => { switch (action.type) { case 'LOGIN': return {...state}; default: return state; } };
var pgpkey_8c = [ [ "PgpCache", "structPgpCache.html", "structPgpCache" ], [ "PGP_KV_NO_FLAGS", "pgpkey_8c.html#a0bfe8fe961efecdedbf5f47cd0c75500", null ], [ "PGP_KV_VALID", "pgpkey_8c.html#a5403e07f6af4309818f8f3c470116833", null ], [ "PGP_KV_ADDR", "pgpkey_8c.html#a6e39bb3b1a46448f00f6591543553baf", null ], [ "PGP_KV_STRING", "pgpkey_8c.html#a6def4a22eecb2b0aadca924b534f71c7", null ], [ "PGP_KV_STRONGID", "pgpkey_8c.html#a3834779d4fa65b6cd9afc052e8dcc723", null ], [ "PGP_KV_MATCH", "pgpkey_8c.html#a40d5acd8017ff315f8840d04c56cc8ca", null ], [ "PgpKeyValidFlags", "pgpkey_8c.html#afa1aa4d0dec2040afc7e3d72d3ffc6b3", null ], [ "pgp_principal_key", "pgpkey_8c.html#a47196af4db1ab1d993f214b457140acb", null ], [ "pgp_key_is_valid", "pgpkey_8c.html#aad0a99e470d5d329e7cfa07f703d64b7", null ], [ "pgp_id_is_strong", "pgpkey_8c.html#a87be30a9047f2566816892e7ffc68b88", null ], [ "pgp_id_is_valid", "pgpkey_8c.html#a0a2d46a37ed92125eed6c9cea5543909", null ], [ "pgp_id_matches_addr", "pgpkey_8c.html#a4fe2cc5b3f19da4aeb934e2c781664c1", null ], [ "pgp_ask_for_key", "pgpkey_8c.html#a9a20d6887d1cb8c32cc689a85d6e7b7e", null ], [ "pgp_class_make_key_attachment", "pgpkey_8c.html#a2bdd0471e577ef56ced7214b5ab6c328", null ], [ "pgp_add_string_to_hints", "pgpkey_8c.html#a40177845326ba43e7b01949fa290a368", null ], [ "pgp_get_lastp", "pgpkey_8c.html#aa827774d3b566c1da76a2cf31bf09923", null ], [ "pgp_getkeybyaddr", "pgpkey_8c.html#a92767494b293bba80f3981e5a3bc72c0", null ], [ "pgp_getkeybystr", "pgpkey_8c.html#a56650c6cb5f5e19c4edee7736c385eaa", null ], [ "id_defaults", "pgpkey_8c.html#a51d9d35e23421cb468d976c61d257e3c", null ] ];
import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col, Card, CardText, CardBody, CardHeader, CardTitle, Form, Label, Alert, Input, Button, FormGroup, CardFooter } from 'reactstrap'; import Error from '../UI/Error'; class CardAjoutProduit extends React.Component { static propTypes = { error: PropTypes.array, loading: PropTypes.bool.isRequired, produits: PropTypes.arrayOf(PropTypes.shape()).isRequired, onFormSubmit: PropTypes.func.isRequired, recipeId:PropTypes.string, success:PropTypes.string, } static defaultProps = { error: null, success:null, } state = { nom: '', quantite: '', prix: '', } constructor(props) { super(props); } handleChange = e => this.setState({ [e.target.name]: e.target.value }); render() { const { loading, error, success ,recipeId} = this.props; const { nom, quantite, prix } = this.state; // Show Listing return ( <Card key="ajout"> <CardHeader>Ajout d'un produit</CardHeader> <Form onSubmit={(evt)=>{this.props.ajoutProduit(evt,this.state)}}> <CardBody > {!!error && <Alert color="danger"> {error.map((item, idx) => <Row key={item.field+idx.toString()} >{item.message}</Row> )} </Alert>} {!!success && <Alert color="success">{success}</Alert>} <FormGroup> <Label for="nom">Nom</Label> <Input type="text" name="nom" id="nom" placeholder="Carotte" disabled={loading} value={nom} onChange={this.handleChange} /> </FormGroup> <FormGroup> <Label for="prix">Prix</Label> <Input type="text" pattern="[0-9]*" name="prix" id="prix" placeholder="120" disabled={loading} value={prix} onChange={this.handleChange} /> </FormGroup> <FormGroup> <Label for="quantite">Quantite</Label> <Input type="text" pattern="[0-9]*" name="quantite" id="quantite" placeholder="30" disabled={loading} value={quantite} onChange={this.handleChange} /> </FormGroup> </CardBody> <CardFooter> <Button color="primary" disabled={loading} className="btn btn-primary"> {loading ? 'Loading' : 'Ajouter un produit'} </Button> </CardFooter> </Form> </Card> ); } } export default CardAjoutProduit;
const algorithm = 'aes192'; const password = '1qaZxsw2@3edcVfr4'; module.exports = { algorithm, password };
import React from 'react'; // Button to select a term export default class ButtonSelector extends React.Component { render() { var btnModifier = this.props.active ? "btn-primary" : "btn-outline-primary"; return ( <button type="button" className={"btn btn-lg " + btnModifier} onClick={this.props.onClick}>{this.props.name}</button> ) } }
/* 本地缓存 */ const loacalStorage = window.localStorage export default { set(key,value) { if(value === undefined) { return ; } loacalStorage.setItem(key,JSON.stringify(value)); }, get(key,def) {//def默认值 const value = parseVal(localStorage.getItem(key)); return value === undefined ? def : value; }, remove(key) { localStorage.removeItem(key); }, clear() { localStorage.clear(); } } function parseVal(val) { if(typeof val !== 'string') { return undefined; } try { return JSON.parse(val); } catch (err) { return val || undefined; } }
import ImgUpload from './src/index.vue' ImgUpload.install = (vue) => { vue.component(ImgUpload.name, ImgUpload) } export default ImgUpload
var mongoose = require('mongoose'); // var db = mongoose.connect('mongodb://localhost:27017/webdev', {useMongoClient: true}); var db = mongoose.connect('mongodb://adminWeb:adminWeb@ds263707.mlab.com:63707/heroku_f1xvv3gp', {useMongoClient: true}); module.exports = db;
import React, { useMemo } from "react"; import { useTable, useGlobalFilter, useSortBy, useFilters } from "react-table"; import DATA from "./DATA.json"; //how to get from db???? import { COLUMNS } from "./columns"; import "./table.css"; import "../App.css"; import { ColumnFilter } from "./ColumnFilter"; import { GlobalFilter } from "./GlobalFilter"; import { Link } from "react-router-dom"; export const FilteringTable = () => { //added props here const columns = useMemo(() => COLUMNS, []); //const article = props.article; const data = useMemo(() => DATA, []); const defaultColumn = useMemo(() => { return { Filter: ColumnFilter, }; }, []); const tableInstance = useTable( { columns, data, defaultColumn, initialState: { // eslint-disable-next-line array-callback-return hiddenColumns: columns.map((column) => { if (column.show === false) return column.accessor; }), }, }, useFilters, useGlobalFilter, useSortBy ); const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, state, setGlobalFilter, } = tableInstance; const { globalFilter } = state; return ( <> <div className="Table"> <h2 className="display-4 text-center"> SEEDs</h2> <div className="dropDown"> <GlobalFilter filter={globalFilter} setFilter={setGlobalFilter} /> </div> <table className="table table-hover table-dark" {...getTableProps()}> <thead> {headerGroups.map((headerGroup) => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map((column) => { return column.hideHeader === true ? null : ( <th {...column.getHeaderProps(column.getSortByToggleProps())} > {" "} {column.render("Header")} <div className="dateFilter"> {column.canFilter ? column.render("Filter") : null}{" "} </div> <span> {column.isSorted ? column.isSortedDesc ? "Descending" : "Ascending" : "Sort"} </span> </th> ); })} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {rows.map((row) => { prepareRow(row); return ( <tr {...row.getRowProps()}> {row.cells.map((cell) => { return ( <td {...cell.getCellProps()}>{cell.render("Cell")}</td> ); })} </tr> ); })} </tbody> </table> <div className="col-md-11"> <Link to="/create-article" className="btn btn-outline-warning" > + Request New Article </Link> <br /> <br /> <hr /> </div> </div> </> ); };
import React from 'react'; import {Link, NavLink} from "react-router-dom"; class Navbar extends React.Component { render() { return ( <nav className="navbar navbar-expand-lg navbar-dark bg-primary"> <Link className="navbar-brand" to="/">React</Link> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav mr-auto"> <li className="nav-item"> <NavLink className="nav-link" activeClassName="active" to="/inicio">Inicio</NavLink> </li> <li className="nav-item"> <NavLink className="nav-link" activeClassName="active" to="/articulos">Articulos</NavLink> </li> <li className="nav-item"> <NavLink activeClassName="active" className="nav-link" to="/contacto">Contacto</NavLink> </li> </ul> </div> </nav> ); } } export default Navbar;
const m = require('.'); console.log(m('unicorns')); console.log(m({ happiness: true }));
import Vue from 'vue' import VueRouter from 'vue-router' // import Home from '../views/Home.vue' Vue.use(VueRouter) const routes = [{ path: '/', redirect: '/general/homepage' // name: 'Home', // component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import( /* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/login', name: 'Login', component: () => import('../views/login/index.vue') }, { path: '/general', name: 'General', component: () => import('../views/general/index.vue'), children:[ { path:'homepage', component: () => import('../views/homepage/index.vue'), }, { path: 'book/:id', name:'Book', component: () => import('../views/book/index.vue') }, { path: 'mall', name:'Mall', component: () => import('../views/mall/index.vue') }, { path: 'trolley', component: () => import('../views/trolley/index.vue') }, { path: 'pay', name: 'Pay', component: () => import('../views/pay/index.vue'), // props: {books:} }, ] }, { path: '/customer', name: 'Customer', component: () => import('../views/customer/index.vue'), children:[ { path:'history', name:'History', component: () => import('../views/history/index.vue') }, { path: 'information', name: 'Information', component: () => import('../views/information/index.vue') } ] }, { path: '/admin', name: 'Admin', component: () => import('../views/admin/index.vue'), children:[ { path: 'manage', name: 'Manage', component: () => import('../views/manage/index.vue') }, { path: 'statistics', name: 'Statistics', component: () => import('../views/statistics/index.vue') }, ] }, ] const router = new VueRouter({ routes }) export default router
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module('actorFinderApp').controller('ActorFinderController', ['$scope', 'Resource', '$filter', function ($scope, Resource, $filter) { $scope.suggestActors = function(){ console.log('searching for '+$scope.searchTerm); Resource.search.find({data: $scope.searchTerm}, function (data) { console.log('sucess'); console.log(data); $scope.suggestedActors = data.results; console.log($scope.suggestedActors); }, function (data) { console.log('fail'); console.log(data); }); }; $scope.showItem = function(item){ console.log('show item'); switch(item.media_type){ case 'person':{ Resource.actors.get({id: item.id}, function(data){ console.log(data); $scope.selectedPerson = data; //hide search panel $('#search-panel').hide('slow'); $('#person-detail-panel').show('slow'); $('#person-detail-panel').css({'display': 'flex'}); }, function(data){ console.log('something bad happened'); console.log(data); }); }break; case 'movie':{ Resource.movies.get({id: item.id}, function(data){ console.log(data); $scope.selectedMovie = data; //hide search panel $('#search-panel').hide('slow'); $('#movie-detail-panel').show('slow'); $('#movie-detail-panel').css({'display': 'flex'}); }, function(data){ console.log('something bad happened'); console.log(data); }); }break; case 'tv':{ Resource.tvShow.get({id: item.id}, function(data){ console.log(data); $scope.selectedTv = data; //hide search panel $('#search-panel').hide('slow'); $('#tv-detail-panel').show('slow'); $('#tv-detail-panel').css({'display': 'flex'}); }, function(data){ console.log('something bad happened'); console.log(data); }); }break; } //animate transition }; $scope.goBack = function(){ console.log('return to new search'); $scope.searchTerm = null; $scope.suggestedActors = []; $('#person-detail-panel').hide('slow'); $('#movie-detail-panel').hide('slow'); $('#tv-detail-panel').hide('slow'); $('#search-panel').show('slow'); }; }]);
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const deepPopulate = require('mongoose-deep-populate')(mongoose); const AttendanceSchema = new Schema({ day:{ type: Date, default: Date.now }, workingHours: { type: Number }, employee: { type: Schema.Types.ObjectId, ref:'Employee' }, status: { type: Schema.Types.ObjectId, ref: 'Status' } }); AttendanceSchema.plugin(deepPopulate); module.exports = mongoose.model('Attendance', AttendanceSchema);
import { Box, Dialog, DialogContent, Grid, Typography, Button, } from "@material-ui/core"; import React from "react"; import PropTypes from "prop-types"; import githubLogo from "../assets/githubLogo.png"; import TechAvatar from "./TechAvatar"; function ProjectDialog(props) { const { onClose, open } = props; const handleClose = () => { onClose(); }; return ( <Dialog onClose={handleClose} aria-labelledby="simple-dialog-title" open={open} fullWidth={true} maxWidth={"lg"} > <DialogContent> <Grid container direction="column" style={{ height: "80vh" }}> <Grid item style={{ alignItems: "center", backgroundColor: "#86b3fc", height: "250px", width: "100%", }} > {/* <img src={props.data.image} alt="" height="250px" width="100%" /> */} {/* <Container style={{ backgroundColor: "black", width: "100%", height: "100%", }} ></Container> */} </Grid> <Box height="30px" /> <Grid item container direction="row"> <Grid item sm={6}> <Typography variant="h2">{props.data.title}</Typography> <Box height="30px" /> <Typography variant="body1">{props.data.desc}</Typography> </Grid> <Grid item container sm={6}> <Grid item container direction="row" style={{ paddingLeft: "100px", height: "40%" }} > <Grid item style={{ paddingTop: "10px" }}> <Typography variant="h5"> <u>Tech Stack:</u> </Typography> </Grid> <Box width="30px" /> {/* // Here we will add a map of tech img and tech name and map them as avatars */} {props.data.techstack ? props.data.techstack.map((item) => { return <TechAvatar title={item.title} logo={item.logo} />; }) : null} </Grid> <Box height="80%" /> <Grid item style={{ paddingLeft: "20%", width: "100%", }} > <Button style={{ backgroundColor: "black", width: "400px", height: "80px", outline: "none", }} onClick={() => window.open(props.data.githubLink, "_blank")} > <img src={githubLogo} alt="" width="60px" height="60px" /> </Button> </Grid> </Grid> </Grid> </Grid> </DialogContent> </Dialog> ); } ProjectDialog.propTypes = { onClose: PropTypes.func.isRequired, open: PropTypes.bool.isRequired, data: PropTypes.object.isRequired, }; export default ProjectDialog;
import React from "react"; import classNames from "classnames"; import Events from "events"; import Header from "../../components/Header/Header"; import Footer from "../../components/Footer/Footer"; // sections for this page import Stage from "./Sections/Stage"; import { PageLoader } from "../../components/PageLoader/PageLoader"; import { getProductsById } from "../../actions/actions_product_kind"; import LandingPageMobile from "../../components/Header/LandingPageMobile"; import LandingPageLinks from "../../components/Header/LandingPageLinks"; import CartObject from "../../helpers/customerOperations"; import Slider from "../../components/Parallax/Slider"; import CART1 from "../../assets/img/CART1.jpg"; import CART2 from "../../assets/img/CART2.jpg"; class Cart extends React.Component { constructor(props) { super(props); this.state = { loader: "block", products: {}, }; this.events = new Events(); } componentWillMount() { try { const { dispatch } = this.props; const cart = []; CartObject.getCart().map(item => cart.push(item.product)); if (cart.length > 0) { dispatch(getProductsById(cart)) .then(() => { const { shoppingCart } = this.props; const products = shoppingCart; this.setState({ loader: "none", products }); }); } else { this.setState({ loader: "none" }); } } catch (ex) { console.log(ex.message); this.setState({ loader: "none" }); } } render() { const { classes, location, ...rest } = this.props; const { loader, products } = this.state; document.title = "Shopping Cart @ Bezop Marketplace || Worlds First Decentralized Marketplace"; return ( <div> <PageLoader display={loader} /> <Header brand="" color="transparent" absolute rightLinks={<LandingPageMobile events={this.events} user="customer" />} leftLinks={<LandingPageLinks events={this.events} user="customer" />} {...rest} /> <Slider classes={classes} images={[CART1, CART2]} /> <div className={classNames(classes.main, classes.mainRaised)}> <Stage products={products} events={this.events} shop={location} /> </div> <Footer /> </div> ); } } export default Cart;