text
stringlengths
7
3.69M
import React from "react"; import { makeStyles } from "@material-ui/styles"; import { Grid, Typography } from "@material-ui/core"; import GitHubIcon from "@material-ui/icons/GitHub"; import LinkedInIcon from "@material-ui/icons/LinkedIn"; import TwitterIcon from "@material-ui/icons/Twitter"; import brandLogo from "../assets/brandLogo.png"; const useStyles = makeStyles((theme) => ({ footerContainer: { padding: "3rem 0 0 0", height: "40rem", }, spanText: { fontStyle: "italic", fontWeight: 500, }, socialIcon: { border: "1px solid #127eb1", borderRadius: "50%", padding: "7px", color: "#000", "&:hover": { backgroundColor: "#127eb1", }, }, })); const footer = (props) => { const classes = useStyles(); return ( <footer> <Grid container direction="column" alignItems="center" justify="space-evenly" className={classes.footerContainer} > <Grid item> <Grid container direction="column" alignItems="center"> <Grid item> <Typography style={{ color: "#127eb1", fontSize: "1.5rem", fontWeight: "400", marginBottom: "1rem", }} > CONTACT ME </Typography> </Grid> <Grid item> <Typography style={{ fontSize: "1.2rem", fontWeight: "300", color: "#575757", }} > If you want to <span className={classes.spanText}>talk</span>, you can <span className={classes.spanText}>find me</span> at: </Typography> </Grid> </Grid> </Grid> <Grid item> <Grid container direction="column"> <Grid item style={{ marginBottom: "1rem" }}> <Typography style={{ fontSize: "1.2rem", color: "#575757" }}> anshumank72@gmail.com </Typography> </Grid> <Grid item> <Grid container justify="space-between"> <Grid item component={"a"} href="https://github.com/anshumank72" > <GitHubIcon className={classes.socialIcon} /> </Grid> <Grid item component={"a"} href="https://www.linkedin.com/in/anshuman-kashyap-29ba58201/" > <LinkedInIcon className={classes.socialIcon} /> </Grid> <Grid item component={"a"} href="https://github.com/anshumank72" > <TwitterIcon className={classes.socialIcon} /> </Grid> </Grid> </Grid> </Grid> </Grid> <Grid item> <Grid container direction="column" alignItems="center"> <Grid item> <img src={brandLogo} alt="footerLogo" style={{ width: "13rem" }} /> </Grid> <Grid item> <Typography style={{ fontSize: "0.9rem", color: "#575757" }}> copyright@2021,ANSHUMAN </Typography> </Grid> </Grid> </Grid> </Grid> </footer> ); }; export default footer;
import Ember from 'ember'; export function isEqualDay([d1, d2]) { if (Ember.typeOf(d2) === 'array') { return d2.find((d2) => { if (Ember.typeOf(d1) !== 'instance' || Ember.typeOf(d2) !== 'instance') { return false; } return d1.format('YYYY-MM-DD') === d2.format('YYYY-MM-DD'); }); } if (Ember.typeOf(d1) !== 'instance' || Ember.typeOf(d2) !== 'instance') { return false; } return d1.format('YYYY-MM-DD') === d2.format('YYYY-MM-DD'); } export default Ember.Helper.helper(isEqualDay);
import CookieDetail from "./CookieDetail" export default function CookieSlide({cookies}) { return( <div> {cookies.map(cookie =>( <CookieDetail cookie={cookie}/> ))} </div> ); }
function runner (generatorFun) { const args = [].slice.call(arguments, 1) const it = generatorFun.apply(this, args) return Promise.resolve() .then(function handleNext (value) { const next = it.next(value) return (function handleResult (next){ if (next.done) { return next.value } else { return Promise.resolve(next.value) .then(handleNext, function handleError (err) { return Promise.resolve(it.throw(err)) }) } })(next) }) }
import logo from './logo.svg'; import './App.css'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import ListFriendsComponent from './components/ListFriendsComponent'; import HeaderComponent from './components/HeaderComponent'; import FooterComponent from './components/FooterComponent'; import CreateFriendComponent from './components/CreateFriendComponent'; import ViewFriendComponent from './components/ViewFriendComponent'; function App() { return ( <div> <Router> <HeaderComponent /> <div className="container"> <Switch> <Route path="/" exact component={ListFriendsComponent}></Route> <Route path="/friends" component={ListFriendsComponent}></Route> <Route path="/add-friend/:id" component={CreateFriendComponent}></Route> <Route path="/view-friend/:id" component={ViewFriendComponent}></Route> </Switch> </div> <FooterComponent /> </Router> </div> ); } export default App;
var WATCHER_SERVER_LISTENING_PORT = 8080; var path = require('path'); var extractModuleName = function(module) { if (module.resource) { var parts = module.resource.split(path.sep); return parts[parts.length - 1]; } if (module.regExp) { return module.regExp; } return 'unknown module'; }; module.exports = function(please) { var createConfig = require('./webpack.config.creator'); var config = createConfig(please); var remove = require('rimraf'); remove.sync(config.output.path); var fs = require('fs-extra'); fs.mkdirsSync(config.output.path); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var compiler = webpack(config); compiler.plugin('invalid', function(invalidDependencies) { if (invalidDependencies) { console.log(JSON.stringify(invalidDependencies, null, 4)); } }); var compilationId = 0; compiler.plugin('compilation', function(compilation) { if (compilation.compiler.isChild()) { return; } ++compilationId; if (compilationId === 1) { return; } compilation.plugin('build-module', function(module) { console.log('...', extractModuleName(module)); }); compilation.plugin('succeed-module', function(module) { console.log(' OK', extractModuleName(module)); }); compilation.plugin('failed-module', function(module) { console.error('ERR', extractModuleName(module)); }); }); compiler.plugin('done', function(stats) { process.title = stats.hasErrors() ? '╯°□°)╯' : ':)'; }); var server = new WebpackDevServer(compiler, { contentBase: 'non-existing-dir', watchOptions: { aggregateTimeout: 200, poll: false }, stats: require('./webpack.stats.console'), historyApiFallback: false }); server.listen(WATCHER_SERVER_LISTENING_PORT); };
/* gulpfile.js * Originally created 3/11/2017 by DaAwesomeP * This is the main build/task file of the extension * https://github.com/DaAwesomeP/tab-counter * * Copyright 2017-present DaAwesomeP * * 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. */ const gulp = require('gulp') const del = require('del') const lec = require('gulp-line-ending-corrector') const bro = require('gulp-bro') const babelify = require('babelify') const eslint = require('gulp-eslint') const sourcemaps = require('gulp-sourcemaps') const zip = require('gulp-zip') gulp.task('check', () => { return gulp.src(['src/**/*.js', 'gulpfile.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) }) gulp.task('checkSafe', () => { return gulp.src(['src/**/*.js', 'gulpfile.js']) .pipe(eslint()) .pipe(eslint.format()) }) gulp.task('static', () => { return gulp.src('src/**/*.js') .pipe(lec()) .pipe(gulp.dest('src')) }) gulp.task('clean', (callback) => { del(['dist/*', 'build/*']).then(() => { callback() }) }) gulp.task('compile', gulp.parallel(() => { return gulp.src('src/**/*.js') .pipe(sourcemaps.init()) .pipe(bro({ transform: [ babelify.configure() ] })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')) }, () => { return gulp.src(['src/**/*', '!src/**/*.js']) .pipe(gulp.dest('dist')) })) gulp.task('pack', () => { return gulp.src(['dist/**/*', '!dist/**/*.map', 'node_modules/lodash/**/*', 'icons/**/clear-*.png', 'icons/**/*.min.svg', 'manifest.json', 'LICENSE'], { base: '.' }) .pipe(zip('tab-counter.firefox.zip')) .pipe(gulp.dest('build')) }) gulp.task('watch', gulp.series('checkSafe', 'compile', () => { return gulp.watch(['src/**/*', 'node_modules/webextension-polyfill/**/*', 'node_modules/lodash/**/*', 'icons/**/*', 'manifest.json', 'package.json'], gulp.parallel('checkSafe', 'compile')) })) gulp.task('dist', gulp.series('static', 'check', 'clean', 'compile')) gulp.task('build', gulp.series('dist', 'pack')) gulp.task('default', gulp.series('build'))
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('tbl_chat_rooms', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, from_user_id: { type: Sequelize.INTEGER }, to_user_id: { type: Sequelize.INTEGER }, item_id: { type: Sequelize.INTEGER }, room_unique: { type: Sequelize.STRING, allowNull:false, }, updateDateStr:{ type: Sequelize.STRING, }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('tbl_chat_rooms'); } };
/** * Created by gavin on 16/4/8. */ 'use strict'; var events = require('../utils/events.js').events; var windows = require('../utils/window.js'); var tk = require('../utils/token.js'); module.exports.init = function (settings) { events.on('auth level changed', function (oldAuthLevel, newAuthLevel) { console.log('用户登录级别变化', oldAuthLevel, '==>', newAuthLevel); if (newAuthLevel == 0) { windows.open('home', 'home.html', true, { width: 1100, height: 600 }); //windows.open('test', 'test.html', true, { width: 1100, height: 600 }); windows.destroy('account'); } else if (newAuthLevel == 1) { windows.open('account', 'set_password.html'); } else if (newAuthLevel == 2) { windows.open('account', 'set_profile.html'); } else { windows.open('account', 'sign_in.html'); } }); events.on('start', function () { tk.checkToken(); // 15s一次的token检查 setInterval(tk.heartBeat, 15 * 1000); }); };
const { penName, footerTitle } = require("../common/info"); module.exports = { // 页脚信息 createYear: 2022, // 博客创建年份 copyrightInfo: penName + " | " + footerTitle + '<br> <a href="http://beian.miit.gov.cn/" target="_blank"></a><a href="/sitemap.xml">sitemap</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a>', // 博客版权信息,支持a标签 };
import { request } from './request'; //订阅列表 export const getSubscribeList = data => { return request({ url: `/push/subscripList`, method: 'GET', params: data }) } //推送列表 export const getpassList= data => { return request({ url: `/push/passList`, method: 'GET', params: data }) } // /push/smartPush 智能推送列表 export const getsmartPush= data => { return request({ url: `/push/smartPush`, method: 'GET', params: data }) } // 已办列表 /push/alreadyHandle export const getalreadyHandle= data => { return request({ url: `/push/alreadyHandle`, method: 'GET', params: data }) } // 待办列表 /push/waitHandle export const getwaitHandle= data => { return request({ url: `/push/waitHandle`, method: 'GET', params: data }) } // 查询推送方式的接口 /push/sendTypeList export function getSendlist(){ return request({ url: `/push/sendTypeList`, method: 'GET', }) } // 点击查询立即录入 /push/label/{policyId} export function getLable(id){ return request({ url: `/push/label/${id}`, method: 'GET', }) } // 修改通知名单 /push/update export const updatePush= data => { return request({ url: `/push/update`, method: 'GET', params: data }) } // 匹配记录 // push/match/{mattersId} // 待办事项-匹配 export const twoPPrecording = (mattersId ,data) => { return request({ url: `/push/match/${mattersId}`, method: 'post', data: data }) }
(function() { var app = angular.module('mongodb-gis'); app.component('apiError', { template: ` <div class='alert clearfix' ng-class='{"alert-danger": ctrl.error.status != 501, "alert-warning": ctrl.error.status == 501}'> <button type='button' class='btn btn-default btn-xs pull-right' ng-if='ctrl.error.status != 501' ng-click='ctrl.showDetails()'>Details</button> <span ng-if='ctrl.error.status == 501'>{{ ctrl.error.data }}</span> <span ng-if='ctrl.error.status != 501'> An unexpected error occurred. </span> </div> `, controller: 'ApiErrorCtrl', controllerAs: 'ctrl', bindings: { error: '<' } }); app.controller('ApiErrorCtrl', function($sce, $scope, $uibModal) { var ctrl = this; ctrl.errorBody = $sce.trustAsHtml(ctrl.error.data.replace(/^.*<body>/, '').replace(/<\/body>.*$/, '')); ctrl.showDetails = function() { $uibModal.open({ scope: $scope, template: ` <div class='modal-header'> <h3 class='modal-title' id='modal-title'>API Error</h3> </div> <div class='modal-body' id='modal-body'> <div ng-bind-html='ctrl.errorBody'></div> </div> <div class='modal-footer'> <button class='btn btn-primary pull-right' type='button' ng-click='$close()'>Close</button> </div> ` }); }; }); })();
var resultCollection = [1,2,3,4,5]; resultBlock = document.getElementById('result'); resultBlock.innerHTML += resultCollection.reduce(function(result, value){ return result + value; }, '');
var mongoose = require("mongoose"); var Schema = mongoose.Schema; var categorySchema = Schema({ categoryName: String, categoryImage: String, categoryDescription: String, }); module.export = mongoose.model('Category', categorySchema);
import { root } from '../root.js' // CLASS for keyboard and joystick // key map // 0 : axe L | left:right -1>1 // 1 : axe L | top:down -1>1 // 2 : axe R | left:right -1>1 // 3 : axe R | top:down -1>1 // 4 : bouton A 0-1 jump / space // 5 : bouton B 0-1 // 6 : bouton X 0-1 // 7 : bouton Y 0-1 // 8 : gachette L up 0-1 // 9 : gachette R up 0-1 // 10 : gachette L down 0>1 // 11 : gachette R down 0>1 // 12 : bouton setup 0-1 // 13 : bouton menu 0-1 // 14 : axe button left 0-1 // 15 : axe button right 0-1 // 16 : Xcross axe top 0-1 // 17 : Xcross axe down 0-1 // 18 : Xcross axe left 0-1 // 19 : Xcross axe right 0-1 // 20 : Keyboard or Gamepad 0-1 export class User { constructor( dom = window ) { this.key = [0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0 ] this.pad = new Gamepad( this.key ) dom.addEventListener( 'keydown', this ) dom.addEventListener( 'keyup', this ) } handleEvent( e ) { e = e || window.event switch( e.type ) { case 'keydown': this.keydown( e ); break; case 'keyup': this.keyup( e ); break; } //e.preventDefault() } update() { this.pad.update() if( this.pad.ready ) this.pad.getValue() root.key = this.key } keydown( e ) { switch ( e.which ) { // axe case 65: case 81: case 37: this.key[0] = -1; break; // left, A, Q case 68: case 39: this.key[0] = 1; break; // right, D case 87: case 90: case 38: this.key[1] = -1; break; // up, W, Z case 83: case 40: this.key[1] = 1; break; // down, S // other case 17: case 67: this.key[5] = 1; break; // ctrl, C case 69: this.key[5] = 1; break; // E case 32: this.key[4] = 1; break; // space case 16: this.key[7] = 1; break; // shift } this.pad.reset(); } keyup( e ) { switch( e.which ) { // axe case 65: case 81: case 37: this.key[0] = this.key[0]<0 ? 0:this.key[0]; break; // left, A, Q case 68: case 39: this.key[0] = this.key[0]>0 ? 0:this.key[0]; break; // right, D case 87: case 90: case 38: this.key[1] = this.key[1]<0 ? 0:this.key[1]; break; // up, W, Z case 83: case 40: this.key[1] = this.key[1]>0 ? 0:this.key[1]; break; // down, S // other case 17: case 67: this.key[5] = 0; break; // ctrl, C case 69: this.key[5] = 0; break; // E case 32: this.key[4] = 0; break; // space case 16: this.key[7] = 0; break; // shift } } }; //-------------------------------------- // // GAMEPAD // //-------------------------------------- export class Gamepad { constructor( key ) { this.values = []; this.key = key; this.ready = 0; this.current = -1; } update() { this.current = -1; var i, j, k, l, v, pad; var fix = this.fix; var gamepads = navigator.getGamepads(); for (i = 0; i < gamepads.length; i++) { pad = gamepads[i]; if(pad){ this.current = i; k = pad.axes.length; l = pad.buttons.length; if(l){ if(!this.values[i]) this.values[i] = []; // axe for (j = 0; j < k; j++) { v = fix( pad.axes[j], 0.5, true ); if( this.ready === 0 && v !== 0 ) this.ready = 1; this.values[i][j] = v; //if(i==0) this.key[j] = fix( pad.axes[j], 0.08 ); } // button for (j = 0; j < l; j++) { v = fix(pad.buttons[j].value); if(this.ready === 0 && v !== 0 ) this.ready = 1; this.values[i][k+j] = v; //if(i==0) this.key[k+j] = fix( pad.buttons[j].value ); } //info += 'gamepad '+i+'| ' + this.values[i]+ '<br>'; } else { if(this.values[i]) this.values[i] = null; } } } } getValue() { var n = this.current; if( n < 0 ) return; var i = 19, v; while(i--){ v = this.values[n][i]; if( this.ready === 0 && v !== 0 ) this.ready = 1; this.key[i] = v; } } reset() { this.ready = 0; } fix( v, dead, force ) { var n = Number((v.toString()).substring(0, 5)); if(dead && n<dead && n>-dead) n = 0; if(force){ if(n>dead) n = 1 if(n<-dead) n = -1 } return n; } }
const mongoose = require('../db/connection.js') const Schema = mongoose.Schema const LunchTopic = new Schema({ content: String }) module.exports = mongoose.model('LunchTopic', LunchTopic)
"use strict"; //header hamburger.onclick = function () { if (navHamburger.style.display === "") { navHamburger.style.display = "block"; navHamburger.style.animationName = "hamburgerOpen"; } else { navHamburger.style.animationName = "hamburgerClosed"; setTimeout(() => navHamburger.style.display = "", 400); } }; //footer const mediaQuery = window.matchMedia('(max-width: 768px)'); function handleTabletChange(e) { if (e.matches) { let heading = document.querySelectorAll("footer .heading"); let menu = document.querySelectorAll("footer .link-site"); let item = document.querySelectorAll("footer .link-site li a"); let item2 = document.querySelectorAll("footer .link-site li"); heading.forEach(element => { element.classList.add("dropdown-toggle"); }); menu.forEach(element => { element.classList.add("dropdown-menu"); }); item.forEach(element => { element.classList.add("dropdown-item"); }); item2.forEach(element => { element.classList.add("dropdown-item"); }); } }; mediaQuery.addListener(handleTabletChange); handleTabletChange(mediaQuery);
function validarn(e){ var teclado = (document.all)?e.keyCode:e.which; if(teclado == 8)return true; var patron = /[0-9\d .]/; var prueba = String.fromCharCode(teclado); return patron.test(prueba); } function validars(e){ var teclado = (document.all)?e.keyCode:e.which; if(teclado == 8)return true; var patron = "si" + "no" var prueba = String.fromCharCode(teclado); return patron.test(prueba); } function año(){ var añoN = document.formulario.año_nacimiento.value; var añoA = document.formulario.año_actual.value; var cumpleaños=document.formulario.cumpleaños.value; var edad if (cumpleaños=="si") edad= parseFloat(añoA)-parseFloat(añoN)+1 if (cumpleaños=="no") edad= parseFloat(añoA)-parseFloat(añoN) document.formulario.edad.value = edad; } function borrar(){ document.formulario.año_nacimiento.value= " "; document.formulario.año_actual.value= " "; document.formulario.cumpleaños.value = " "; document.formulario.edad.value =""; }
import React from 'react' import {makeStyles} from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; const useStyles = makeStyles(theme => ({ root: { flexGrow: 1 }, standardBasic: { backgroundColor: '#fff', borderRadius: '10px', marginBottom: '15px', display: 'flex', width: '317px', height: '36px', padding: '0 10px', border: 0 }, auth__box: { display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', marginTop: 70, width: '392px', height: '463px', backgroundColor: '#482945', borderRadius: '10px', position: 'relative' }, auth__input: { position: 'absolute', top: 130 }, auth__title: { color: '#fff', position: 'absolute', top: 2, left: '34px' }, enterBtn: { color: '#CC00FF', backgroundColor: '#2D083A', marginTop: 41, padding: '10px 30px', borderRadius: '10px', position: 'absolute', bottom: '20px' }, container: { margin: '0 auto', display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', maxWidth: '1100px', width: '100%' } })) export const Home = () => { const classes = useStyles(); return ( <div className={classes.container}> <div className={classes.auth__box}> <div className={classes.auth__title}> <h1>Вход</h1> </div> <div className={classes.auth__input}> <form className={classes.root}> <TextField className={classes.standardBasic} placeholder="Ваш логин" /> <TextField className={classes.standardBasic} placeholder="Ваш пароль" /> </form> </div> <Button variant="primary" className={classes.enterBtn}>Войти</Button> </div> </div> ) }
import Enum from './enum.js'; //处理状态 const handleStatus = new Enum({ unOrder: { value: 1, label: '未生成报关订单' }, partOrder: { value: 2, label: '部分生成报关订单' }, allOrder: { value: 3, label: '全部生成报关订单' }, partDeclare: { value: 4, label: '部分报关' }, declareFinished: { value: 5, label: '报关完成' }, clearFinished: { value: 6, label: '清关完成' } }); // simpleQuery let simpleQuery = [ { 'value': 'packPlanCode', 'label': '装箱计划编码', 'placeholder': '请输入装箱计划编码' }, { 'value': 'masterWaybillCode', 'label': '主提运单号', 'placeholder': '请输入主提运单号' } ] let comboQuery = [ { 'key': 'packPlanCode', 'line': true, 'label': '装箱计划编码', 'type': 'input' }, { key: 'createTime', label: '创建时间', type: 'timequery' }, { key: 'shipPeriod', label: '船期', type: 'timequery' }, { 'key': 'startPort', 'line': true, 'label': '起运港', 'type': 'input' }, { 'key': 'destintionPort', 'line': true, 'label': '目的港', 'type': 'input' }, { //下拉选项 如果options数据需要从服务器获取,需要vue组件route之前就得到 key: 'transportType', label: '运输方式', line: true, options: [], type: 'select' }, { //下拉选项 如果options数据需要从服务器获取,需要vue组件route之前就得到 key: 'state', label: '处理状态', line: true, options: [], type: 'select' }, { 'key': 'masterWaybillCode', 'line': true, 'label': '主提运单号', 'type': 'input' }, { 'key': 'customOrderCodes', 'line': true, 'label': '报关订单', 'type': 'input' } ] // quickFilter let quickFilter = [ { 'key': 'state', 'label': '处理状态', 'options': [ //{'value': '', 'label': '审核状态' } ].concat(handleStatus.array()) } ] // 运输方式 let transportWay = new Enum({ sea:{ value: 1, label: "海运" }, air:{ value: 2, label: "空运" } }) // 是否 let isOrNot = [ {'value': '1', 'label': '全部' }, {'value': '2', 'label': '是' }, {'value': '3', 'label': '否' } ] export { Enum, isOrNot, handleStatus, simpleQuery, comboQuery, quickFilter, transportWay };
var express = require('express'); var router = express.Router(); var User = require('../db/user.js'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); /* 登录/注册 页面 */ router.get('/login',function(req,res,next){ res.render('login',{title:'登录/注册'}); }); /* 登录提交 */ router.post('/login',function(req,res,next){ var uid = req.body.phone; var password = req.body.password; res.redirect('/'); // User.findOne({uid:uid},{fields:{_id:1,password:1,isactive:1}},function(err,r){ // console.log(err); // if(r!=null){ // if(r.isactive){ // if(r.password==password){ // res.redirect('/'); // }else{ // res.redirect('/login'); // } // }else{ // res.redirect('/login'); // } // }else{ // res.redirect('/login'); // } // }); }); /* 注册提交 */ router.post('/sign',function(req,res,next){ var uid = req.body.phone; var nick= req.body.user; var password = req.body.password; User.count({uid:uid},function(err,n){ if(n==0){ var time = parseInt(new Date().getTime()/1000); var user = new User({ uid:uid, nick:nick, password:password, ctime:time, ltime:time }); user.save(function(err,u){ if(!err){ res.redirect('/'); }else{ res.redirect('/login'); } }); }else{ res.redirect('/'); } }); }); module.exports = router;
import React from 'react'; import SelectList from './SelectList.jsx'; import Button from './Button.jsx'; import timeUnits from '../constants/timeUnits.js'; let cronPattern = '%minute% %hour% * * %day%'; class CronSetter extends React.Component { constructor() { super(); this.state = { day : timeUnits.dayList[0].value, hour : timeUnits.hourList[0].value, minute : timeUnits.minuteList[0].value, showSelectTime: false, showSelectDay: false, selectClassName : '' }; this.selectDay = this.selectDay.bind(this); this.setDay = this.setDay.bind(this); this.setHour = this.setHour.bind(this); this.setMinute = this.setMinute.bind(this); this.createCron = this.createCron.bind(this); this.selectEveryWeekDay = this.selectEveryWeekDay.bind(this); } selectDay() { this.setState({ showSelectTime: true, showSelectDay: true, showSelectEveryWeekDay: false, selectClassName: 'select-day' }); } setDay(event) { this.setState({day: event.target.value}); } setHour(event) { this.setState({hour: event.target.value}); } setMinute(event) { this.setState({minute: event.target.value}); } selectEveryWeekDay() { this.setState({ day : '1-5', showSelectEveryWeekDay: true, showSelectTime: true, showSelectDay: false, selectClassName: 'select-every-week-day' }); } createCron() { let cron = { expression: cronPattern.replace('%minute%', this.state.minute).replace('%hour%', this.state.hour).replace('%day%', this.state.day) }; this.props.onCreateCronHandler(cron); } renderTime(){ if (this.state.showSelectTime === true) { return ( <div className="select-time-at"> <h1>At...</h1> <SelectList data={timeUnits.hourList} onChange={this.setHour}/> <span>:</span> <SelectList data={timeUnits.minuteList} onChange={this.setMinute}/> </div> ); } } renderCalendar(){ if (this.state.showSelectDay === true) { return ( <SelectList data={timeUnits.dayList} onChange={this.setDay}/> ); } } renderCreate(){ if (this.state.showSelectTime === true) { return ( <div className="create-cron"> <Button onClick={this.createCron}>Create cron</Button> </div> ); } } render() { let selectEveryWeekDayClass = this.state.showSelectEveryWeekDay === true ? 'active' : ''; let selectDayClass = this.state.showSelectDay === true ? 'active' : ''; return ( <div> <h1>On...</h1> <Button className={selectEveryWeekDayClass} onClick={this.selectEveryWeekDay}> Every weekday </Button> <Button className={selectDayClass} onClick={this.selectDay}> Every... </Button> {this.renderCalendar()} {this.renderTime()} {this.renderCreate()} </div> ); } } export default CronSetter;
import React, {Component} from 'react'; import { Dimensions, Platform, StyleSheet, Text, View, TouchableWithoutFeedback, PermissionsAndroid } from 'react-native'; import Header from "./CommonModules/Header"; import BlePackage from './pass/BlePackage'; import VisitorPackage from './pass/VisitorPackage'; import QrcodePackage from './pass/QrcodePackage'; import px2dp from "./tools/px2dp"; var {width,height} = Dimensions.get('window'); import Icon from "react-native-vector-icons/AntDesign"; export default class PassPage extends Component{ static navigationOptions = { header: null }; constructor(props){ super(props); this.state = { pageShow:'ble' } } //tab切换 changeTab(page){ this.setState({ pageShow:page }) } //页面显示 pageShow(){ if(this.state.pageShow=='ble'){ return( <BlePackage /> ) }else if(this.state.pageShow=='qrcode'){ return( <QrcodePackage /> ) }else { return( <VisitorPackage /> ) } } render(){ const { navigate } = this.props.navigation; return( <View style={{flex:1,backgroundColor: '#fcfcfc'}}> <Header title={'通行'} navigate={this.props.navigation} left={true}/> <View style={[styles.flex_space_between,styles.tab_wrap]}> <TouchableWithoutFeedback onPress={()=>{this.changeTab('ble')}}> <View style={styles.tab_item}> <Icon name="key" size={28} color="#32bbff" /> <Text style={styles.tab_font}>我的钥匙</Text> </View> </TouchableWithoutFeedback> <View style={styles.gap_line}></View> <TouchableWithoutFeedback onPress={()=>{this.changeTab('qrcode')}}> <View style={styles.tab_item}> <Icon name="qrcode" size={28} color="#32bbff" /> <Text style={styles.tab_font}>二维码</Text> </View> </TouchableWithoutFeedback> <View style={styles.gap_line}></View> <TouchableWithoutFeedback onPress={()=>{this.changeTab('visitor')}}> <View style={styles.tab_item}> <Icon name="addusergroup" size={28} color="#32bbff" /> <Text style={styles.tab_font}>邀请好友</Text> </View> </TouchableWithoutFeedback> </View> {this.pageShow()} </View> ) } } const styles = StyleSheet.create({ tab_item:{ flex:1, alignItems:'center', paddingVertical:px2dp(20) }, flex_space_between:{ flexDirection: 'row', alignItems:'center' }, tab_font:{ marginTop:px2dp(10) }, tab_wrap:{ borderBottomWidth:px2dp(1), borderBottomColor:'#e0e0e0' }, gap_line:{ width:px2dp(1), height:px2dp(35), backgroundColor:'#e0e0e0' } });
sap.ui.define([ "com/pkr/table/controller/BaseController" ], function(BaseController) { "use strict"; return BaseController.extend("com.pkr.table.controller.S2", { onLinkPress: function(oEvent) { sap.m.URLHelper.redirect("http://" + oEvent.getSource().getText(), true); } }); });
"use strict" function generateScarchLocation(countryData) { var newLocation = countryData.cityName + ',' + countryData.cityInCountry; weatherAPI(newLocation); }
(function () { var app = angular.module('splits-module', []); app.controller('SplitController', function () { this.selection = 0; this.selectTab = function (selection) { this.selection = selection; }; this.showSplits = function () { return this.selection == 0; }; this.showAgeGrade = function () { return this.selection == 1; }; this.showWeather = function () { return this.selection == 2; }; this.showAbout = function () { return this.selection == 3; }; this.padTime = function (time, digits) { var s = ("000000000" + time); return s.substr(s.length - digits); }; this.generateHtmlBoilerplate = function () { return "<div class='container'>"; }; this.dumpPaceTable = function (pace_distance, pr_hours, pr_minutes, pr_seconds) { console.log("dumpPaceTable"); console.log("pace_distance: " + pace_distance); console.log("pr_hours: " + pr_hours); console.log("pr_minutes: " + pr_minutes); console.log("pr_seconds: " + pr_seconds); var distance = 0; var distances = new Array(100, 200, 300, 400, 500, 600, 800, 1000, 1200, 1600, 1609); var pace_distance_km = (pace_distance / 1000).toFixed(2); var pace_distance_miles = (pace_distance / 1609).toFixed(2); var pace_distance_string = pace_distance + " meters"; //.toFixed(2) var pace_distance_string_short = pace_distance_string; if (pace_distance > 1000) { pace_distance_string = pace_distance_km + " km (" + pace_distance_miles + " miles)"; pace_distance_string_short = pace_distance_km + "k"; } if (pace_distance > 10000) { pace_distance_string = pace_distance_km + " km (" + pace_distance_miles + " miles)"; pace_distance_string_short = pace_distance_miles + "m"; } var str_hours = this.padTime(pr_hours, 2); var str_minutes = this.padTime(pr_minutes, 2); var str_seconds = this.padTime(pr_seconds, 2); var html = "<h5>Splits Based on " + pace_distance_string + " of " + str_hours + ":" + str_minutes + ":" + str_seconds + "</h5>"; var total_seconds = (pr_hours * 3600 + pr_minutes * 60 + pr_seconds); html += "<table class=\"table table-striped table-condensed table-bordered table-hover \">"; html += "<tr><th>meters</th><th>split</th></tr>"; for (i = 0; i < distances.length; i++) { distance = distances[i]; var split = (total_seconds / pace_distance) * distance; var sec_remainder = Math.floor(split % 60); var split_min_sec = Math.floor(split / 60) + ":" + ("0" + sec_remainder).slice(-2); html += "<tr><td>" + distance + "</td><td>" + split_min_sec + "</td></tr>"; } html += "</table>"; return html; }; this.prs = [ { "event": "800", "text": "800m (Min:Sec)", "distance": 800.0, "showHours": false, "hours": "", "minutes": "", "seconds": "" }, { "event": "Mile", "text": "Mile (Min:Sec)", "distance": 1609.0, "showHours": false, "hours": "", "minutes": "", "seconds": "" }, { "event": "3000", "text": "3k", "distance": 3000.0, "showHours": false, "hours": "", "minutes": "", "seconds": "" }, { "event": "5k", "text": "5k", "distance": 5000.0, "showHours": false, "hours": "", "minutes": "", "seconds": "" }, { "event": "10k", "text": "10k", "distance": 10000.0, "showHours": false, "hours": "", "minutes": "", "seconds": "" }, { "event": "Half", "text": "Half (Hour:Min)", "distance": 13.1 * 1609, "showHours": true, "hours": "", "minutes": "", "seconds": "" }, { "event": "Marathon", "text": "Marathon (Hour:Min)", "distance": 26.2 * 1609, "showHours": true, "hours": "", "minutes": "", "seconds": "" } ]; this.splitTableHtml = ""; this.showResults = function () { return this.splitTableHtml != ""; }; this.resetSplits = function () { this.splitTableHtml = ""; }; this.calculateSplits = function () { console.log("calculateSplits"); this.splitTableHtml = ""; this.splitTableHtml += this.generateHtmlBoilerplate(); for (var i = 0; i < this.prs.length; i++) { if (this.prs[i].showHours) { this.prs[i].seconds = 0; } if (!isNaN(parseInt(this.prs[i].minutes)) && !isNaN(parseInt(this.prs[i].seconds))) { if (isNaN(parseInt(this.prs[i].hours))) { this.prs[i].hours = 0; } this.splitTableHtml += this.dumpPaceTable(this.prs[i].distance, parseInt(this.prs[i].hours), parseInt(this.prs[i].minutes), parseInt(this.prs[i].seconds)); } } this.splitTableHtml += "</div>"; console.log("splitTableHtml" + this.splitTableHtml); }; }); }) ();
// Firebase import * as firebase from 'firebase'; const firebaseConfig = { apiKey: "AIzaSyC9WpJ8YES3GzQLxkX-gbFS2v4Ot8-T2ug", authDomain: "heaveneye-ace6a.firebaseapp.com", databaseURL: "https://heaveneye-ace6a.firebaseio.com", projectId: "heaveneye-ace6a", storageBucket: "heaveneye-ace6a.appspot.com", messagingSenderId: "377871605720" }; firebase.initializeApp(firebaseConfig); const database = firebase.database(); export default database;
import React from 'react'; import { Link } from 'react-router-dom'; class HomePage extends React.Component{ router(event){ console.log('here') this.props.history.push(`/${event.target.id}`); } render(){ return( <div class="w-75 text-center mr-auto ml-auto"> <div class="card-body w-75 mr-auto ml-auto"> <h4 class="card-title">Welcome to the PAG Vendor Portal</h4> <h6 class="card-text" style={{fontSize:18}}>Here you can view invoices on file, view payments, submit invoices, and find invoice information. Try selecting one of the options below or searching for an invoice or PO number in the search box above.</h6> </div> <div class="card-body col-10 mr-auto ml-auto"> <div class="card-deck"> <Link to={`/invoices`} style={{textDecoration: 'none',color:'black'}} className="card hvr-fade pointer"> <div class="card-body"> <h5 class="card-title">Invoices</h5> <p class="card-text">View invoice status, payment date, or update invoice information.</p> </div> </Link> <Link to={`/payments`} style={{textDecoration: 'none',color:'black'}} className="card hvr-fade pointer"> <div class="card-body"> <h5 class="card-title">Payment Information</h5> <p class="card-text">View recent payments and remittance information.</p> </div> </Link> <Link to={`/submit`} style={{textDecoration: 'none',color:'black'}} className="card hvr-fade pointer"> <div class="card-body"> <h5 class="card-title">Submit Invoices</h5> <p class="card-text">Submit invoice copies, statements, or vendor documentation</p> </div> </Link> <Link to={`/info`} style={{textDecoration: 'none',color:'black'}} className="card hvr-fade pointer"> <div class="card-body"> <h5 class="card-title">Update Information</h5> <p class="card-text">Update address, contact, W9, or payment information</p> </div> </Link> </div> </div> </div> ); } } export default HomePage;
$(document).ready(function(){ $('.untitledList li').click(function() { $(this).css("background-color", "purple"); }); $('.untitledList li').css("width", "200px"); $('.untitledList li').css("height", "50px"); });
import React, { useEffect, useState } from "react"; import "./Loading.css"; import { useHistory } from "react-router-dom"; import axios from "axios"; import { useStateValue } from "./StateProvider"; import { Link } from "react-router-dom"; function Loading() { const [{ user }, dispatch] = useStateValue(); const [rend, setrend] = useState(""); const [noinput, setnoinput] = useState(""); const history = useHistory(); const [verify, setverify] = useState(""); // useEffect(() => { // axios.get("http://localhost:9000/submitted").then((res) => { // // eslint-disable-next-line no-unused-expressions // // eslint-disable-next-line no-restricted-globals // res.data ? history.push("/qpaper") : setrend(false); // }); // console.log(user); // }, [user]); const handleProceed = (e) => { e.preventDefault(); axios .post("https://fathomless-sands-42436.herokuapp.com/verify", { em: user, code: noinput, }) .then((res) => { console.log(res.data); // eslint-disable-next-line no-restricted-globals res.data ? history.push("/qpaper") : alert("Incorrect! Verification Code"); }); }; return ( <div className="bodyver"> <h5 className="heading"> Please Check your Email and Enter The Verification Code. </h5> <div className="center"> <div className="lds-hourglass"></div> </div> <div className="input" style={{ marginLeft: "21%", paddingTop: "5vh" }}> <input style={{ border: "1px solid black", margin: "2px" }} className="ip" type="text" onChange={(e) => setnoinput(e.target.value)} /> {noinput.length == 6 ? ( <Link to="/qpaper"> <button onClick={handleProceed} className="btn btn-primary"> Proceed </button> </Link> ) : ( <button className="btn btn-primary" disabled> Proceed </button> )} </div> <div className="refresh"> Please recheck your Code again if not logged in </div> </div> ); } export default Loading;
import React from "react"; const ProductInfoVariation = props => { let productInfoVariationOne; let productInfoVariationTwo; if (props.productInfoVariationProp.options === "[null]") { productInfoVariationOne = null; } else { productInfoVariationOne = ( <div className="product-info-variations"> <div className="product-info-variations-header">Available Options:</div> <label className="product-info-variations-label"> <select className="product-info-variations-drop-down"> <option>None</option> {props.selectedProductOptions.map((option, key) => ( <option value={option} key={key}> {option} </option> ))} </select> </label> </div> ); } if (props.productInfoVariationProp.onHand < 1) { productInfoVariationTwo = ( <div className="product-info-variations"> <div className="product-info-variations-header-two-b"> Out of Stock! </div> </div> ); } else { productInfoVariationTwo = ( <div className="product-info-variations"> <div className="product-info-variations-header-two-c">In Stock!</div> </div> ); } return ( <div> {productInfoVariationOne} {productInfoVariationTwo} </div> ); }; export default ProductInfoVariation;
(function() { 'use strict'; angular .module('app.catalArtManufSupp') .factory('CatalArtManufSupp', CatalArtManufSupp); CatalArtManufSupp.$inject = ['$resource', 'API_BASE_URL']; /* @ngInject */ function CatalArtManufSupp($resource, API_BASE_URL) { var params = { catalArtManufSuppId: '@id' }; var actions = { update: { method: 'PUT' }, findBy: { method: 'POST', url: API_BASE_URL + '/catalartmanufsupps/findBy' } }; var API_URL = API_BASE_URL + '/catalartmanufsupps/:catalArtManufSuppId'; return $resource(API_URL, params, actions); } })();
export default { items: [ { name: 'Dashboard', url: '/dashboard', icon: 'icon-speedometer' }, { title: true, name: 'AQI Monitoring & Forecast', wrapper: { // optional wrapper object element: '', // required valid HTML5 element tag attributes: {} // optional valid JS object with JS API naming ex: { className: "my-class", style: { fontFamily: "Verdana" }, id: "my-id"} }, class: '' // optional class names space delimited list for title item ex: "text-center" }, { name: 'AQ Stations', url: '/map', icon: 'fa fa-mixcloud', }, { name: 'Forecast', url: '/aqiForecasts', icon: 'fa fa-crosshairs' }, { title: true, name: 'Pollution Sources', wrapper: { element: '', attributes: {}, }, }, { name: 'Traffic', url: '/traffic', icon: 'fa fa-car', children: [ { name: 'Levels', url: '/traffic', icon: 'icon-cursor', }, // { // name: 'Button dropdowns', // url: '/buttons/button-dropdowns', // icon: 'icon-cursor', // }, // { // name: 'Button groups', // url: '/buttons/button-groups', // icon: 'icon-cursor', // }, // { // name: 'Brand Buttons', // url: '/buttons/brand-buttons', // icon: 'icon-cursor', // }, ], }, { name: 'Bushfires', url: '/fires', icon: 'fa fa-fire', children: [ { name: 'Live', url: '/fires', icon: 'icon-fire' }, { name: 'Historical', url: '/historical-fires', icon: 'fa fa-history' } ], }, { divider: true, }, { title: true, name: 'Extras', }, // { // name: 'Pages', // url: '/pages', // icon: 'fa fa-desktop', // disable: true, // children: [ // { // name: 'Login', // url: '/login', // icon: 'fa fa-desktop', // }, // { // name: 'Register', // url: '/register', // icon: 'fa fa-desktop', // }, // { // name: 'Error 404', // url: '/404', // icon: 'fa fa-desktop', // }, // { // name: 'Error 500', // url: '/500', // icon: 'fa fa-desktop', // }, // ], // }, { name: 'Tesis Progress', url: '/tesis-progress', icon: 'fa fa-edit', disable: true, children: [ { name: 'Current Progress', url: '/tesis-progress/current', icon: 'fa fa-users', } ], } ], };
/** * Created by Administrator on 2019/04/26. */ <!--ajax 请求地址--> //var apiurl = "192.168.5.21:53801"; var apiurl = "218.108.45.6:1112"; <!--判断token是否为空--> var token = sessionStorage.getItem("token"); if(token == "" || token == null){ window.location.href = "../Index/index.html"; } <!--注销按钮--> function exit(){ sessionStorage.removeItem("token"); window.location.reload(); } <!--页面长时间未操作自动退出--> //var lastTime = new Date().getTime(); //var currentTime = new Date().getTime(); //var timeOut = 10 * 60 * 1000; //设置超时时间: 10分 //$(function(){ // /* 鼠标移动事件 */ // $(document).mouseover(function(){ // lastTime = new Date().getTime(); //更新操作时间 // }); //}); //function testTime(){ // currentTime = new Date().getTime(); //更新当前时间 // if(currentTime - lastTime > timeOut){ //判断是否超时 // sessionStorage.removeItem("token"); // alert("您已超过十分钟未操作,请重新登录"); // window.location.reload(); // } //} /* 定时器 间隔1秒检测是否长时间未操作页面 */ //window.setInterval(testTime(), 1000); <!--解析通过url传过来的参数--> function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } <!--去除输入框前后空格--> function tim(s){ return s.replace(/(^\s*)|(\s*$)/g, "").replace(/(^\s*)|(\s*$)/g, ""); } function nbsp(n){ //去除前后空白直接调用此方法即可。 n:为输入框的id名 $("#"+n).val(tim($("#"+n).val())); } //维修 -> 维修记录查询:物料管理 function QueryErrCode(name,no,page,per){ var ret; var url = "http://"+apiurl+"/api/Repair/QueryErrCode?name="+name+"&no="+no+"&page="+page+"&per="+per+""; var xhr = new XMLHttpRequest(); xhr.open('GET',url,false); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //必须写在open和send中间 xhr.send(); xhr.onreadystatechange = function(data){ return xhr = data.responseText; }; return xhr } //获取维修记录 function QueryRepair(page,per,prodNo,stateNo,errCode,Date1,Date2){ //"MoID":"WKT-18071000000001",//工单id // "Bel_NO":"01090411",//产线,从获取产线接口获取 // "RepairDate":"2018-07-25 09:00:00",//维修时间 // "Sta_NO":"113",//维修点,工位no // "RepairName":"陈雪",//维修人,员工名称 // "Pro_barcode":"PRO-00000001",//产品条码,从获取对应产品接口获取 // "Pro_NO":"PRO-00000001",//产品no,从获取对应产品获取 // "StateNo":"01",//维修状态,01:待修02:已维修03:无法维修 // "Err_code":"2-1",//错误编码 // "Err_name":"Error2"//错误名称 //必传项:Err_code:错误编码 page 当前页 per:每页显示数据 Pro_NO:产品no Date1:开始时间 repairDate2:结束时间 if(errCode == 'undefined'){ errCode ='' } if(stateNo == 'undefined'){ stateNo = '' } var ret; var url = "http://"+apiurl+"/api/Repair/QueryRepair?page="+page+"&per="+per+"&prodNo="+prodNo+"&stateNo="+stateNo+"&errCode="+errCode+"&repairDate1="+Date1+"&repairDate2="+Date2+""; var xhr = new XMLHttpRequest(); xhr.open('GET',url,false); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //必须写在open和send中间 xhr.send(); xhr.onreadystatechange = function(data){ return xhr = data.responseText; }; return xhr } //维修录入->获取树状信息 function getErrCodes(){ var ret; $.ajax({ url:"http://"+ apiurl +"/api/Repair/getErrCodes", header:"Content-Type: application/json", //data:{"page":pages,"per":count,"plinenub":text}, type:"GET", dataType:"json", async:false, success:function(data){ ret = data } }); return ret; } //获取维修记录列表 function getReplays(pages,count,code){ var ret; $.ajax({ url:"http://"+ apiurl +"/api/Repair/getReplays", header:"Content-Type: application/json", data:{"page":pages,"per":count,"code":code}, type:"GET", dataType:"json", async:false, success:function(data){ ret = data } }); return ret; } //获取工单 function Manufacture(page,per){ var ret; $.ajax({ url:"http://"+ apiurl +"/api/Manufacture/Query", header:"Content-Type: application/json", data:{"page":page,"per":per,"teamNo":''}, type:"GET", dataType:"json", async:false, success:function(data){ ret = data } }); return ret; } //获取所有用户 function getuserinfo(page,per){ //api/Userinfo/Query?badgenumber=&name=&no=&page=1&pager=&per=500 var ret; $.ajax({ url:"http://"+ apiurl +"/api/Userinfo/Query?", header:"Content-Type: application/json", data:{badgenumber:'',name:'',no:'',page:page,pager:'',per:per}, type:"GET", dataType:"json", async:false, success:function(data){ ret = data } }); return ret; } //获取维修点 function getStation(page,per){ var ret; $.ajax({ url:"http://"+ apiurl +"/api/Station/Query?content=&lineNo=&no=&page=1&per=500&workshopNo=", data:{content:'',lineNo:'',no:'',page:page,per:per,workshopNo:''}, type:"get", dataType:"json", async:false, success:function(data){ ret = data; } }); return ret; } //修改维修记录 function modifyRepairs(Rp_ID,MoID,Pro_NO,Pro_barcode,Sta_NO,Err_code,Err_name,Bel_NO,RepairName,RepairDate,StateNo){ var ret; $.ajax({ url:"http://"+ apiurl +"/api/Repair/ModifyRepair", type:"PUT", data:JSON.stringify({Rp_ID:Rp_ID,MoID:MoID,Pro_NO:Pro_NO,Pro_barcode:Pro_barcode,Sta_NO:Sta_NO,Err_code:Err_code, Err_name:Err_name,Bel_NO:Bel_NO,RepairName:RepairName,RepairDate:RepairDate,StateNo:StateNo,_method:'PUT'}), dataType:"json", contentType:"application/json; charset=utf-8", async:false, success:function(data){ //console.log(data.data) ret = data; //console.log(data) } }); return ret; } //新增维修 function AddRepair(MoID,Bel_NO,RepairDate,Sta_NO,RepairName,Pro_barcode,Pro_NO,StateNo,Err_code,Err_name){ /* "MoID":"WKT-18071000000001",//工单id "Bel_NO":"01090411",//产线,从获取产线接口获取 "RepairDate":"2018-07-25 09:00:00",//维修时间 "Sta_NO":"113",//维修点,工位no "RepairName":"陈雪",//维修人,员工名称 "Pro_barcode":"PRO-00000001",//产品条码,从获取对应产品接口获取 "Pro_NO":"PRO-00000001",//产品no,从获取对应产品获取 "StateNo":"01",//维修状态,01:待修02:已维修03:无法维修 "Err_code":"2-1",//错误编码 "Err_name":"Error2"//错误名称 */ var ret; $.ajax({ url:"http://"+apiurl+"/api/Repair/AddRepair", //data:JSON.stringify(result), data: {"MoID":MoID,"Bel_NO":Bel_NO,"RepairDate":RepairDate,"Sta_NO":Sta_NO,"RepairName":RepairName, "Pro_barcode":Pro_barcode,"Pro_NO":Pro_NO,"StateNo":StateNo,"Err_code":Err_code,"Err_name":Err_name}, type:"post", //contentType: 'application/json;charset=utf-8', dataType:"json", async:false, cache:true, success:function(data){ ret = data }, error:function(jqXHR){ alert("错误"+jqXHR.status) } }); return ret; } //删除维修记录 function DeleteRepair(id){ var url = "http://"+ apiurl +"/api/Repair/DeleteRepair?id="+id+""; var xhr = new XMLHttpRequest(); xhr.open('delete',url,false); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //必须写在open和send中间 xhr.send(); xhr.onreadystatechange=function(data) { return xhr = data.responseText; }; return xhr; } <!-- 生产时间计划->查询生产时间->查询 --> function manualPlan(pages,count,text){ var ret; $.ajax({ url:"http://"+apiurl+"/api/manualPlan/getPlineTime", header:"Content-Type: application/json", data:{"page":pages,"per":count,"plinenub":text}, type:"GET", dataType:"json", async:false, success:function(data){ ret = data } }); return ret; } // 生产时间计划->查询生产时间->删除 function removePlineTime(no,time_s,time_e,liine_nub,plan_date){ var ret; var result = {timeList:[{ "no":no, "time_s": time_s, "time_e": time_e,"pline_nub": liine_nub, "plan_date": plan_date }]}; $.ajax({ url:"http://"+apiurl+"/api/manualPlan/removePlineTime", data:JSON.stringify(result), type:"post", contentType: 'application/json;charset=utf-8', dataType:"json", async:false, cache:true, success:function(data){ ret = data },error:function(jqXHR){ alert("错误"+jqXHR.status) } }); return ret; } <!--生产时间计划->查询生产时间->新增 --> function savePlineTime(no,startTime,endTime,productNbm,planDate,count){ //开始时间、结束时间、车间、时间、数量 //获取原来数据,在原来的序号上增加1 var result = { timeList: [{"no":no, "time_s": startTime, "time_e": endTime, "pline_nub": productNbm, "plan_date": planDate}], "count": count //记录条数 }; var ret; $.ajax({ header:"Content-Type: application/json", url:"http://"+ apiurl +"/api/manualPlan/savePlineTime", contentType: 'application/json;charset=utf-8', data:JSON.stringify(result), type:"POST", dataType:"json", async:false, cache:true, success:function(data){ ret = data; } }); return ret; } //手工录入 -> 产品数量计划:新增 function saveQuantityPlan(pdate,orderno,pcode,pname,ptype,pdatetime,stdjp,ordernub,type,workers,workers_real,pnum,plinenub,team){ //pdate 开始时间 var result = { pplanList: [{ pdate: pdate,orderno: orderno, pcode: pcode, pname: pname, ptype: ptype, pdatetime: pdatetime, stdjp: stdjp, ordernub: ordernub, type: type, workers: workers, workers_real: workers_real, pnum: pnum, plinenub: plinenub, team: team}]}; var ret; $.ajax({ url:"http://" + apiurl + "/api/manualPlan/saveQuantityPlan", type:'POST', contentType: 'application/json; charset=UTF-8', async:false, dataType:'json', data:JSON.stringify(result), success: function (data) { ret = data; } }); return ret; } <!--分页--> function paging (currentpage,count,mtd,murl,mtotalcount,list){ //currentpage:当前页 count:当前页显示的笔数 mtb:拼接的标签名 murl:拼接的URL地址 mtotalcount:总count条记录 list:每个表有多少列 var totalCount = mtotalcount; var prepage = parseInt(currentpage)-1; var nextpage = parseInt(currentpage)+1; var bootpage = parseInt(Math.ceil(totalCount/count));//( 总数据条数 - 1 )/每页显示数据 + 1 var totalPages = bootpage; mtd += "<tr style='text-align: center'>"+ "<td colspan='"+list+"'>" + '<a href=\"'+ murl +'page=1\">首页</a>'; if(currentpage == 1){ mtd += "<span style='padding-left: 30px;'>上一页</span>" }else { mtd += '<a style="padding-left: 30px;" href="'+ murl +'page='+ prepage +'">上一页</a>'; } if(currentpage == bootpage){ mtd += "<span style='padding-left: 30px;'>下一页</span>" }else { mtd += '<a style="padding-left: 30px;" href="'+ murl +'page='+ nextpage +'">下一页</a>'; } mtd +='<a style="padding-left: 30px;" href="'+ murl +'page='+ bootpage +'">尾页</a>'+ '<apan style="padding-left: 30px;">&nbsp;&nbsp;共'+ totalPages +'页</apan>'+ '<span style="padding-left: 30px;" href="">&nbsp;&nbsp;合计:'+ totalCount +'条数据</span>'+ "</td>"+ "</tr>"; return mtd; } //查询和搜索人员 function getuserlist(apiurl,currentpage,count,like) { //必传参数:搜索框id var ret; var start = (currentpage-1)*count; if (typeof(like) == "undefined") { var mydata = {"access_token": sessionStorage.getItem("token"),"start":start,"count":count}; } else { var mydata = {"access_token": sessionStorage.getItem("token"),"start":start,"count":count, "like": like}; } $.ajax({ url: "http://" + apiurl + "/Open/App/getusers", data: mydata, type: "post", async:false, dataType: "json", success: function (data) { ret = data } }); return ret; } //数组之间相减 function arrChange(a,b){ for (var i = 0; i < b.length; i++) { for (var j = 0; j < a.length; j++) { if (a[j].user_name == b[i].user_name) { //如果是id相同的,那么a[ j ].id == b[ i ].id a.splice(j,1); j = j - 1; } } } return a; }
import React from "react"; import Counter from "../../CommonModule/Counter"; import { Link } from "react-router-dom"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { addToCart, removeFromCart } from "../../CardsList/actions/actionCreator"; function SummaryCard({ items, addToCart, removeFromCart }) { return ( <div className="card pt-4 pb-4 pl-2 pr-2 bg-light w-100"> <div className="card-body"> <div className="card-title"> <div className="row mb-2 text-uppercase font-weight-bold pl-2 pr-2"> <div className="col-3 text-center">S.No.</div> <div className="col-5">Items</div> <div className="col-4 text-center">Qty</div> </div> </div> <hr /> {items.map((item, index) => ( <div className="row pt-3 pb-3 d-flex align-items-center" key={item.id} > <div className="col-3 text-center">{index + 1}.</div> <div className="col-5 text-capitalize">{item.name}</div> <div className="col-4 text-center"> <Counter current={item.quantity} onDecrement={() => removeFromCart(item.id)} onIncrement={() => addToCart(item.id)} color="#4C5363" /> </div> </div> ))} <hr /> <div className="row"> <div className="col-12"> <Link to="/"> <button className="btn btn-link font-weight-bold">+ Add more items</button> </Link> </div> </div> </div> </div> ); } const mapDispatchToProps = dispatch => ({ ...bindActionCreators({ addToCart, removeFromCart }, dispatch) }); export default connect(null, mapDispatchToProps)(SummaryCard);
const { nextISSTimesForMyLocation } = require('./iss_promised'); const printFlyOverTime = (passTimes) => { for (const pass of passTimes) { const unix_timestamp = pass.risetime; const date = new Date(unix_timestamp * 1000); console.log(`Next pass at ${date} for ${pass.duration} seconds!`); } }; nextISSTimesForMyLocation() .then((passTimes) => { printFlyOverTime(passTimes); }) .catch((err) => { console.log(`It didn't work: `, err.message); });
define(['frame'], function (ngApp) { 'use strict' ngApp.provider.controller('ctrlMain', [ '$scope', 'http2', 'srvSigninApp', 'srvTag', function ($scope, http2, srvSigApp, srvTag) { $scope.$on('xxt.tms-datepicker.change', function (event, data) { $scope.app[data.state] = data.value srvSigApp.update(data.state) }) $scope.assignMission = function () { srvSigApp.assignMission() } $scope.quitMission = function () { srvSigApp.quitMission() } $scope.remove = function () { if (window.confirm('确定删除?')) { http2 .get( '/rest/pl/fe/matter/signin/remove?site=' + $scope.app.siteid + '&app=' + $scope.app.id ) .then(function (rsp) { if ($scope.app.mission) { location = '/rest/pl/fe/matter/mission?site=' + $scope.app.siteid + '&id=' + $scope.app.mission.id } else { location = '/rest/pl/fe/site/console?site=' + $scope.app.siteid } }) } } $scope.tagMatter = function (subType) { var oTags oTags = $scope.oTag srvTag._tagMatter($scope.app, oTags, subType) } srvSigApp.get().then(function (oApp) { $scope.defaultTime = { start_at: oApp.start_at > 0 ? oApp.start_at : (function () { var t t = new Date() t.setHours(8) t.setMinutes(0) t.setMilliseconds(0) t.setSeconds(0) t = parseInt(t / 1000) return t })(), } }) }, ]) ngApp.provider.controller('ctrlAccess', [ '$scope', 'srvSigninApp', 'tkEntryRule', function ($scope, srvSigApp, tkEntryRule) { srvSigApp.get().then(function (oApp) { $scope.jumpPages = srvSigApp.jumpPages() $scope.rule = oApp.entryRule $scope.tkEntryRule = new tkEntryRule(oApp, $scope.sns) }, true) $scope.$watch('app.entryRule', function (nv, ov) { if (nv && nv !== ov) { srvSigApp.renew(['enrollApp', 'groupApp']) } }) }, ]) })
// Basic import React, { Component } from 'react'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; // Theme import 'bootstrap/dist/css/bootstrap.min.css'; // Styles import './App.css'; // Screens import Home from './screens/Home/Home'; import Category from './screens/Category/Category'; import Post from './screens/Post/Post'; import StorePost from './screens/StorePost/StorePost'; import PageNotFound from './screens/PageNotFound/PageNotFound'; // Prepare store import reducers from './store/reducers'; import middlewares from './store/middlewares'; // Init Store const store = createStore(reducers, middlewares); class App extends Component { // @lifecycle componentWillMount() { // Get user let user = localStorage.getItem('user') || null; if (user !== null) { user = JSON.parse(user) } else { // Define initial user user = { id: Math.random().toString(36).substr(-8), name: 'Udacity Student', login: 'udacityStudent', template: 'cerulean' } // Save user on local Storage localStorage.setItem('user', JSON.stringify(user)) } const head = document.getElementsByTagName('head')[0]; let link = document.createElement('link'); link.id = 'theme'; link.rel = 'stylesheet'; link.type = 'text/css'; link.href = `./themes/bootstrap.${user.template}.min.css`; head.appendChild(link); } render() { return ( <Provider store={store}> <BrowserRouter basename={process.env.PUBLIC_URL}> <Switch> <Route path='/' exact={true} component={Home} /> <Route path="/page-not-found" component={PageNotFound} /> <Route path="/new-post" component={StorePost} /> <Route path="/:categoryName" exact={true} component={Category} /> <Route path="/:categoryName/:postId" exact={true} component={Post} /> <Route path="/:categoryName/:postId/edit" exact={true} component={StorePost} /> <Route path="*" component={PageNotFound} /> </Switch> </BrowserRouter> </Provider> ); } } export default App;
/** * Created by elie. */ /** * Requests two Json objects from the server, the world map and the data, then call the function to draw the map. * @param div {Object} D3 encapsulated parent div element. * @param svg {Object} D3 encapsulated parent svg element, direct child of div parameter. * @param mydiv {String} Div identifier. * @param urlJson {String} Url to request the data to the server. */ function createChoroplethDirection(div, svg, mydiv, urlJson){ d3.queue() .defer(d3.json,"javascripts/D3JSCharts/worldmap.json") // .defer(d3.json, "worldmap.json") .defer(d3.json, urlJson) .await(function(error,worldmap,json){ createMapDirection(error, div, svg, mydiv, urlJson, worldmap, json); }) } /** * Create a map with resize and zoom features. * @param error {Object} A Javascript error returned by d3.json * @param div {Object} D3 encapsulated parent div element. * @param svg {Object} D3 encapsulated parent svg element, direct child of div parameter. * @param mydiv {String} Div identifier. * @param urlJson {String} Url to request the data to the server. * @param worldmap {Object} The Json object containing the information to create a map of the world. * @param json {Object} The Json object containing the data sent by the server. */ function createMapDirection(error,div,svg,mydiv, urlJson, worldmap,json){ svg.style("margin", "auto").classed("diagram",false).style("display","block"); var colorBottomStart = "#ffccff", colorBottomEnd = "#ff0000"; var colorTopStart = "#66ffcc", colorTopEnd = "#0066ff"; svg.margin.offsetLegend = 5; svg.margin.legendWidth = 10; svg.margin.right = svg.margin.offsetLegend * 2 + svg.margin.legendWidth + 60; svg.margin.left = 5; svg.margin.top = 20; svg.margin.bottom = 15; if(error || typeof json === "undefined" || json.result != "true" || typeof json.response.data === "undefined"){ noData(div,svg,mydiv,"error json conformity"); return; } var button = div.append("button").text("Switch to histogram").classed("buttonMap", true).remove(); div.node().insertBefore(button.node(), svg.node()); button.on("click",function(){ myLastHourHistory.unsubscribe(urlJson, svg.id); drawChartFromInterface(urlJson, mydiv); }); json = json.response; var jsonContent = json.content; svg.jsonData = json.data; var minuteArray; var itemValue = searchItemValue(jsonContent); var amountValue = searchAmountValue(jsonContent); var directionValue = searchDirectionValue(jsonContent); svg.amountByCountryCodeBottom = new Map(); svg.amountByCountryCodeTop = new Map(); if(!(itemValue && amountValue && directionValue)){ noData(div,svg,mydiv,"error no value found"); return; } var elemAmount; var elemItem; var i; for(i = svg.jsonData.length - 1; i >=0; i--){ minuteArray = svg.jsonData[i][1]; minuteArray.forEach(function(elem){ elemItem = elem[itemValue]; elemAmount = +elem[amountValue]; if(elemItem === "--" || elemItem === ""){ return; } switch(elem[directionValue]){ case "OUT": if(svg.amountByCountryCodeBottom.has(elem[itemValue])){ svg.amountByCountryCodeBottom.set(elem[itemValue], elemAmount + svg.amountByCountryCodeBottom.get(elem[itemValue])); }else{ svg.amountByCountryCodeBottom.set(elem[itemValue], elemAmount); } break; case "IN": if(svg.amountByCountryCodeTop.has(elem[itemValue])){ svg.amountByCountryCodeTop.set(elem[itemValue], elemAmount + svg.amountByCountryCodeTop.get(elem[itemValue])); }else{ svg.amountByCountryCodeTop.set(elem[itemValue], elemAmount); } break; default: console.log("inconsistent direction value"); break; } }); } console.log(svg.amountByCountryCodeTop); console.log(svg.amountByCountryCodeBottom); var bottomMax = 0; var bottomMin = Infinity; var topMax = 0; var topMin = Infinity; svg.amountByCountryCodeBottom.forEach(function(value){ bottomMax = Math.max(bottomMax,value); bottomMin = Math.min(bottomMin,value); }); svg.amountByCountryCodeTop.forEach(function(value){ topMax = Math.max(topMax,value); topMin = Math.min(topMin,value); }); if(svg.amountByCountryCodeBottom.size === 0){ bottomMin = 0; bottomMax = 1; } if(svg.amountByCountryCodeTop.size === 0){ topMin = 0; topMax = 1; } svg.lastMinute = json.data[0][0]; svg.units = json.units; //finding/computing the div dimensions var clientRect = div.node().getBoundingClientRect(); var divWidth = Math.max(svg.margin.left + svg.margin.right + 1,clientRect.width), divHeight = Math.max(svg.margin.bottom + svg.margin.top + svg.margin.zero + 1,clientRect.height); //Some pre-computation to find the dimensions of the map (with a determined height/width ratio // for a given standard latitude) //Maximum potential width & height the map will have svg.width = divWidth - svg.margin.left - svg.margin.right; svg.height = divHeight - svg.margin.bottom - svg.margin.top; svg.mapHeight = (svg.height - svg.margin.zero)*0.5 ; //The wished standard latitude for a cylindrical equal-area projection (in degree) //37.5: Hobo-Dyer projection, 45: Gall-Peters projection var standardParallelDeg = 37.5; //Conversion in radians and cosinus precomputation var standardParallelRad = standardParallelDeg*2*Math.PI/360; var cosStdPar = Math.cos(standardParallelRad); //evaluation of the map width & height if the projection scale = 1, then homothetic zooming. svg.mapDefaultWidth = 2*Math.PI*cosStdPar; svg.mapDefaultHeight = 2/cosStdPar; //evaluation of the optimal scale coefficient for the chosen format var projectionScale = Math.min(svg.width/svg.mapDefaultWidth,svg.mapHeight/svg.mapDefaultHeight); //update of the correct width & height svg.width = projectionScale*svg.mapDefaultWidth; svg.mapHeight = projectionScale*svg.mapDefaultHeight; svg.height = svg.mapHeight * 2 + svg.margin.zero; //dimensions of the root svg (= with margins) svg.attr("width", svg.width + svg.margin.left + svg.margin.right + "px") .attr("height", svg.height + svg.margin.bottom + svg.margin.top + "px"); //dimensions of the svg map container (= without margins) svg.svg = svg.append("svg").attr("x",svg.margin.left).attr("y",svg.margin.top).attr("width",svg.width) .attr("height", svg.mapHeight).classed("geometricPrecision",true); //A rect is appended first (= background) with the size of svg.svg as a sea representation svg.backgroundRect = svg.svg.append("rect") .attr("width",svg.width) .attr("height",svg.mapHeight) .attr("y",0) .classed("backgroundSea sizeMap",true); //Computation of the cylindrical equal-area projection with the given standard latitude and // the precomputed scale projectionScale var projection = d3.geoProjection(function(lambda,phi){ return [lambda*cosStdPar,Math.sin(phi)/cosStdPar]; }) .translate([svg.width/2,svg.mapHeight/2]) .scale(projectionScale); //The corresponding path function creation for this projection var path = d3.geoPath().projection(projection); //svg.maps will contain the 2 maps for rotation svg.svg.maps = svg.svg.append("g"); //svg.map will contain the first initial map svg.map = svg.svg.maps.append("g").classed("gMap",true); //stroke-width controlled by javascript to adapt it to the current scale //0.3 when map scale = 100 svg.strokeWidth = 0.003*projectionScale; svg.svg.maps.style("stroke-width", svg.strokeWidth); //test json conformity if (typeof worldmap === "undefined" || error) { noData(div, svg,mydiv, "error json conformity"); return false; } svg.scaleLogBottom = d3.scaleLog().range([0,1]); var colorInterpolatorBottom = d3.interpolateRgb(colorBottomStart,colorBottomEnd); svg.scaleLogTop = d3.scaleLog().range([0,1]); var colorInterpolatorTop = d3.interpolateRgb(colorTopStart,colorTopEnd); //Axes svg.scaleBottomDisplay = d3.scaleLog().range([svg.mapHeight,0]); svg.axisBottom = svg.append("g") .attr("class", "axisGraph"); svg.labelGradientBottom = svg.append("text") .classed("labelChoropleth",true) .attr("x",svg.margin.top + 1.5 * svg.mapHeight + svg.margin.zero) .attr("y",-svg.margin.left - svg.width - svg.margin.right) .attr("dy","1.3em") .attr("transform", "rotate(90)"); svg.scaleTopDisplay = d3.scaleLog().range([svg.mapHeight,0]); svg.axisTop = svg.append("g").attr("class", "axisGraph"); svg.labelGradientTop = svg.append("text") .classed("labelChoropleth",true) .attr("x",svg.margin.top + 0.5 * svg.mapHeight) .attr("y",-svg.margin.left - svg.width - svg.margin.right) .attr("dy","1.3em") .attr("transform", "rotate(90)"); updateDataAxesMap(svg,bottomMin,bottomMax,topMin,topMax); svg.scaleColorBottom = function(countryCode){ var value = svg.amountByCountryCodeBottom.get(countryCode); if(!value){ return "#ffffff"; } return colorInterpolatorBottom(svg.scaleLogBottom(value)); }; svg.scaleColorTop = function(countryCode){ var value = svg.amountByCountryCodeTop.get(countryCode); if(!value){ return "#ffffff"; } return colorInterpolatorTop(svg.scaleLogTop(value)); }; //the binded data, containing the countries info and topology var data = topojson.feature(worldmap,worldmap.objects.countries).features; console.log(data); svg.titleTop = mapCountryTitleTop(svg); //Creation of the countries svg.map.selectAll(".countries") .data(data) .enter().append("path") .style("fill",function(d){return svg.scaleColorTop(d.id)}) .attr("d",path) .classed("countries",true) .append("svg:title").text(svg.titleTop); //stroke-dasharray controlled by javascript to adapt it to the current scale // value 2,2 when map scale = 100 svg.strokeDash = 0.02*projectionScale; //Interior boundaries creation svg.map.append("path") .datum(topojson.mesh(worldmap,worldmap.objects.countries,function(a,b){ return a !==b; })) .attr("d",path) .classed("countries_boundaries interior",true) //zoom dependant, javascript controlled style property with precalculed svg.strokeDash .style("stroke-dasharray", svg.strokeDash + "," + svg.strokeDash); //Exterior boundaries creation svg.map.append("path") .datum(topojson.mesh(worldmap,worldmap.objects.countries,function(a,b){ return a ===b; })) .attr("d",path) .classed("countries_boundaries exterior",true); //map border. svg.svg.append("rect") .attr("width",svg.width) .attr("height",svg.mapHeight) .attr("y",0) .classed("rectBorder sizeMap",true); //A duplicate map is created and translated next to the other, outside viewport //The .99991 operation avoid a little cut to be too visible where the 2 maps meet. svg.map2 = d3.select(svg.svg.maps.node().appendChild(svg.map.node().cloneNode(true))) .attr("transform","matrix(1, 0, 0,1," + (0.99991*svg.width) + ", 0)"); //the data are binded to the second map (may be useful later) svg.map2.selectAll(".countries").data(data); //Maps out svg.svg2 = d3.select(svg.node().appendChild(svg.svg.node().cloneNode(true))) .attr("y",svg.margin.top + svg.margin.zero + svg.mapHeight); svg.svg2.maps = svg.svg2.select("g"); svg.titleBottom = mapCountryTitleBottom(svg); svg.countriesBottom = svg.svg2.maps.selectAll(".gMap").selectAll(".countries"); svg.countriesBottom.data(data) .style("fill",function(d){return svg.scaleColorBottom(d.id)}) .select("title").text(svg.titleBottom); svg.countriesTop = svg.svg.maps.selectAll(".gMap").selectAll(".countries"); //titles svg.label1 = svg.append("text") .classed("labelChoropleth",true) .attr("x", svg.margin.left + svg.width/2) .attr("dy", "-0.5em") .attr("y",svg.margin.top) .text("Ingress"); svg.label2 = svg.append("text") .classed("labelChoropleth",true) .attr("x", svg.margin.left + svg.width/2) .attr("dy", "-0.5em") .attr("y",svg.margin.top + svg.mapHeight + svg.margin.zero) .text("Egress"); //legend //Definition of the colors gradient appendVerticalLinearGradientDefs(svg,"linearTop",colorTopStart,colorTopEnd); svg.legendTop = svg.append("rect").attr("x",svg.width + svg.margin.left + svg.margin.offsetLegend) .attr("y",svg.margin.top) .attr("width",svg.margin.legendWidth) .attr("height",svg.mapHeight) .attr("fill", "url(#linearTop)"); appendVerticalLinearGradientDefs(svg,"linearBottom",colorBottomStart,colorBottomEnd); svg.legendBottom = svg.append("rect").attr("x",svg.width + svg.margin.left + svg.margin.offsetLegend) .attr("y",svg.margin.top + svg.mapHeight + svg.margin.zero) .attr("width",svg.margin.legendWidth) .attr("height",svg.mapHeight) .attr("fill", "url(#linearBottom)"); //added functionalities addZoomMapDirection(svg,svg.svg); addZoomMapDirection(svg,svg.svg2); addResizeMapDirection(div,svg,mydiv); autoUpdateMapDirection(svg, urlJson); } /** * Updates the maps with new data on websocket's notification. * @param svg {Object} D3 encapsulated parent svg element. * @param urlJson {String} Url to request the data to the server. */ function autoUpdateMapDirection(svg,urlJson){ var duration = 800; svg.id = myLastHourHistory.addMinuteRequest(urlJson,function(json){ console.log(json); if(typeof json === "undefined" || typeof json.data === "undefined"){ console.warn("map update: no data"); return; } var llm = svg.lastMinute; var gapMinute = trueModulo(json.data[0][0] - svg.lastMinute, 60); console.log(gapMinute); svg.lastMinute = json.data[0][0]; var jsonContent = json.content; var jsonDataUpdate = json.data; var itemValue = searchItemValue(jsonContent); var amountValue = searchAmountValue(jsonContent); var directionValue = searchDirectionValue(jsonContent); if(!(itemValue && amountValue && directionValue)){ return; } var elemAmount; var elemItem; // - for(var i = svg.jsonData.length - 1; trueModulo(llm - svg.jsonData[i][0], 60) + gapMinute > 59; i --){ console.log(trueModulo(llm - svg.jsonData[i][0], 60) + gapMinute); svg.jsonData[i][1].forEach(function(elem){ elemItem = elem[itemValue]; elemAmount = +elem[amountValue]; if(elemItem === "--" || elemItem === ""){ return; } console.log(elemItem); switch(elem[directionValue]){ case "OUT": var subtraction = svg.amountByCountryCodeBottom.get(elemItem) - elemAmount; console.log(svg.amountByCountryCodeBottom.get(elemItem)); if(subtraction <= 0){ svg.amountByCountryCodeBottom.delete(elemItem); }else{ svg.amountByCountryCodeBottom.set(elemItem, subtraction); } break; case "IN": subtraction = svg.amountByCountryCodeTop.get(elemItem) - elemAmount; console.log(svg.amountByCountryCodeTop.get(elemItem)); if(subtraction <= 0){ svg.amountByCountryCodeTop.delete(elemItem); }else{ svg.amountByCountryCodeTop.set(elemItem, subtraction); } break; } }); // end svg.jsonData[i][1].forEach console.log(svg.jsonData.splice(i,1)); } // end main for loop console.log(trueModulo(llm - svg.jsonData[i][0], 60) + gapMinute); console.log(svg.jsonData.length); // + for(i = jsonDataUpdate.length - 1; i >= 0; i --){ jsonDataUpdate[i][1].forEach(function(elem){ elemItem = elem[itemValue]; elemAmount = +elem[amountValue]; if(elemItem === "--" || elemItem === ""){ return; } switch(elem[directionValue]){ case "OUT": if(svg.amountByCountryCodeBottom.has(elemItem)){ svg.amountByCountryCodeBottom.set(elemItem, elemAmount + svg.amountByCountryCodeBottom.get(elem[itemValue])); }else{ svg.amountByCountryCodeBottom.set(elemItem, elemAmount); } break; case "IN": if(svg.amountByCountryCodeTop.has(elemItem)){ svg.amountByCountryCodeTop.set(elemItem, elemAmount + svg.amountByCountryCodeTop.get(elem[itemValue])); }else{ svg.amountByCountryCodeTop.set(elemItem, elemAmount); } break; default: console.log("inconsistent direction value"); break; } }); // end jsonDataUpdate forEach svg.jsonData.unshift(jsonDataUpdate[i]); } // end jsonDataUpdate main for loop console.log(svg.jsonData); var bottomMax = 0; var bottomMin = Infinity; var topMax = 0; var topMin = Infinity; svg.amountByCountryCodeBottom.forEach(function(value){ bottomMax = Math.max(bottomMax,value); bottomMin = Math.min(bottomMin,value); }); svg.amountByCountryCodeTop.forEach(function(value){ topMax = Math.max(topMax,value); topMin = Math.min(topMin,value); }); if(svg.amountByCountryCodeBottom.size === 0){ bottomMin = 0; bottomMax = 1; } if(svg.amountByCountryCodeTop.size === 0){ topMin = 0; topMax = 1; } console.log(svg.amountByCountryCodeTop); console.log(svg.amountByCountryCodeBottom); updateDataAxesMap(svg,bottomMin,bottomMax,topMin,topMax); svg.countriesBottom.style("fill",function(d){return svg.scaleColorBottom(d.id)}) .select("title").text(svg.titleBottom); svg.countriesTop.style("fill",function(d){ return svg.scaleColorTop(d.id)}) .select("title").text(svg.titleTop); },svg.lastMinute); console.log(svg.id); } /** * Updates internal variables and redraw the maps on resize event. * @param div {Object} D3 encapsulated parent div element. * @param svg {Object} D3 encapsulated parent svg element, direct child of div parameter. * @param mydiv {String} Div identifier. */ function addResizeMapDirection(div,svg,mydiv){ var oldMapHeight, divWidth,divHeight,coefScaling,scaleTotal1,scaleTotal2,projectionScale; //the total ratio alteration since the beginning if(typeof svg.ratioProjectionScale === "undefined"){ svg.ratioProjectionScale = 1; } d3.select(window).on("resize."+mydiv,function(){ //initial height kept for future computation of the resize augmentation oldMapHeight = svg.mapHeight; //finding/computing the div dimensions var clientRect = div.node().getBoundingClientRect(); divWidth = Math.max(svg.margin.left + svg.margin.right + 1,clientRect.width); divHeight = Math.max(svg.margin.bottom + svg.margin.top + 1,clientRect.height); //Some computation to find the new dimensions of the map (with a constant height/width ratio) svg.width = divWidth - svg.margin.left - svg.margin.right; svg.height = divHeight - svg.margin.bottom - svg.margin.top; svg.mapHeight = (svg.height - svg.margin.zero)*0.5 ; projectionScale = Math.min(svg.width/svg.mapDefaultWidth,svg.mapHeight/svg.mapDefaultHeight); svg.width = projectionScale*svg.mapDefaultWidth; svg.mapHeight = projectionScale*svg.mapDefaultHeight; svg.height = svg.mapHeight * 2 + svg.margin.zero; //svg and svg.svg dimensions are accordingly updated svg.attr("width", svg.width + svg.margin.left + svg.margin.right + "px") .attr("height", svg.height + svg.margin.bottom + svg.margin.top + "px"); svg.svg.attr("width",svg.width).attr("height",svg.mapHeight); svg.svg2.attr("width",svg.width).attr("height",svg.mapHeight) .attr("y",svg.margin.top + svg.margin.zero + svg.mapHeight); //Evaluation of the resize ratio augmentation coefScaling = svg.mapHeight/oldMapHeight; //update of svg.ratioProjectionScale and computation of the map total effective scaling svg.ratioProjectionScale *= coefScaling; scaleTotal1 = svg.ratioProjectionScale * svg.svg.transform.k; scaleTotal2 = svg.ratioProjectionScale * svg.svg2.transform.k; //update of the translation vector svg.svg.transform.x *= coefScaling; svg.svg.transform.y *= coefScaling; svg.svg2.transform.x *= coefScaling; svg.svg2.transform.y *= coefScaling; //update of the internal zoom translation vector updateTransform(svg.svg,svg.svg.transform); updateTransform(svg.svg2,svg.svg2.transform); //the modifications are performed svg.svg.maps.attr("transform","matrix(" + scaleTotal1 + ", 0, 0, " + scaleTotal1 + ", " + svg.svg.transform.x + ", " + svg.svg.transform.y + ")"); svg.svg2.maps.attr("transform","matrix(" + scaleTotal2 + ", 0, 0, " + scaleTotal2 + ", " + svg.svg2.transform.x + ", " + svg.svg2.transform.y + ")"); //update of the sea rect svg.selectAll(".sizeMap").attr("width",svg.width).attr("height",svg.mapHeight); //update of some styling variables. svg.strokeDash *= coefScaling; svg.strokeWidth *= coefScaling; //update of labels position svg.label1.attr("x", svg.margin.left + svg.width/2); svg.label2.attr("x", svg.margin.left + svg.width/2) .attr("y",svg.margin.top + svg.mapHeight + svg.margin.zero); svg.legendBottom .attr("x",svg.width + svg.margin.left + svg.margin.offsetLegend) .attr("y",svg.margin.top + svg.mapHeight + svg.margin.zero) .attr("height",svg.mapHeight); svg.legendTop .attr("x",svg.width + svg.margin.left + svg.margin.offsetLegend) .attr("height",svg.mapHeight); resizeAxesMap(svg); }) } /** * Add zoom feature to one map. * @param parentSvg {Object} D3 encapsulated parent svg element. * @param svg {Object} D3 encapsulated svg element, which contains one map. */ function addZoomMapDirection(parentSvg,svg){ if(typeof parentSvg.ratioProjectionScale === "undefined"){ parentSvg.ratioProjectionScale = 1; } svg.transform = {k:1,x:0,y:0}; var widthScale, scaleTotal, dashValue; svg.zoom = d3.zoom().scaleExtent([1,100]).on("zoom",function(){ //computation of useful values svg.transform = d3.event.transform; widthScale = parentSvg.width*svg.transform.k; scaleTotal = svg.transform.k*parentSvg.ratioProjectionScale; dashValue = parentSvg.strokeDash/scaleTotal; //Evaluation of effective translation vectors //for "rotation" of the planisphere, svg.transform.x should always be in the [0,-widthScale] range. svg.transform.x = svg.transform.x - Math.ceil(svg.transform.x/widthScale)*widthScale; svg.transform.y = Math.min(0, Math.max(svg.transform.y,parentSvg.mapHeight - svg.transform.k*parentSvg.mapHeight)); //zoom and translation are performed svg.maps.attr("transform","matrix(" + scaleTotal + ", 0, 0, " + scaleTotal + ", " + svg.transform.x + ", " + svg.transform.y + ")"); //styling update, for keeping the same visual effect svg.maps.style("stroke-width",parentSvg.strokeWidth/scaleTotal); svg.maps.selectAll(".interior").style("stroke-dasharray",dashValue + "," + dashValue); }) .on("start",function(){ svg.on("contextmenu.zoomReset",null); }) .on("end",function(){ svg._groups[0][0].__zoom.k =svg.transform.k; svg._groups[0][0].__zoom.x =svg.transform.x; svg._groups[0][0].__zoom.y =svg.transform.y; svg.on("contextmenu.zoomReset",function(){ svg._groups[0][0].__zoom.k = 1; svg._groups[0][0].__zoom.x = 0; svg._groups[0][0].__zoom.y = 0; svg.transform.k = 1; svg.transform.x = 0; svg.transform.y = 0; scaleTotal = parentSvg.ratioProjectionScale; dashValue = parentSvg.strokeDash/scaleTotal; svg.maps.attr("transform","matrix(" + scaleTotal + ", 0, 0, " + scaleTotal + ",0,0)"); svg.maps.style("stroke-width",parentSvg.strokeWidth/scaleTotal); svg.maps.selectAll(".interior").style("stroke-dasharray",dashValue + "," + dashValue); }); }); //the listener is finally created on the svg element used as the map container. svg.call(svg.zoom); //A fresh start... svg._groups[0][0].__zoom.k =svg.transform.k; svg._groups[0][0].__zoom.x =svg.transform.x; svg._groups[0][0].__zoom.y =svg.transform.y; }
/** Hide and show responsive menu on click and window resize **/ $(document).ready(function(){ $("#viewmenu").click(function(){ $("#menu-main-menu").slideToggle(500); }); }); $(window).resize(function() { if ($(window).width() < 768) { $("#menu-main-menu").hide(); $("#viewmenu").show(); } else { $("#menu-main-menu").show(); $("#viewmenu").hide(); } });
var container = $("<div>"); var dragElement = $("<div class='fc-event' data-lan='' data-type=''>"); //the types of the languages var languages = ["anglais", "chinois", "français", "allemand", "espagnol", "portugal", "japonais"]; // shorten the expression of languages var languages_short = ["en", "zh", "fr", "de", "es", "pt", "jp"]; // the two types of activities var type = ["Apprendre", "Enseigner"]; var i, j; //listen the events of adding events by drag and poser document.addEventListener('DOMContentLoaded', function() { for(i in languages) { for (j in type) { var d = dragElement.clone() .html(type[j] + " " + languages[i]) .data("type",j) .data("language", languages[i]); $("p").after(d); } } var Draggable = FullCalendarInteraction.Draggable; var containerEl = document.getElementById('external-events'); var calendarEl = document.getElementById('calendar'); // initialize the external events // ----------------------------------------------------------------- new Draggable(containerEl, { itemSelector: '.fc-event', eventData: function(eventEl) { return { title: eventEl.innerText }; } }); // initialize the calendar // ----------------------------------------------------------------- var calendar = new FullCalendar.Calendar(calendarEl, { //ajuste the head header: { left: 'dayGridMonth,timeGridWeek', // buttons for switching between views }, //add the plugins plugins: [ 'dayGrid', 'timeGrid', 'interaction' ], //set View default defaultView: 'timeGridWeek', //set the period of the time slotDuration: '00:30', businessHours: { // days of week. an array of zero-based day of week integers (0=Sunday) daysOfWeek: [ 1, 2, 3, 4 , 5, 6, 0], startTime: '8:00', // a start time endTime: '18:00', // an end time }, //shut the allDay events allDaySlot: false, nowIndicator: true, //set editable editable:true, //set selectable selectable:true, selectHelper:true, //set droppable droppable:true, //load the events from the database events: function(info, successCallback, failureCallback){ $.ajax({ url:'load_event', method: 'POST', error:function(){ alert("error"); }, success: function(res){ var events = []; var i=0; if(res!=null){ for (i in res){ var time = new Date(res[i].time.replace(" ", "T")); var lan = res[i].language; for(var j in languages) { if (lan === languages_short[j]){ lan = languages[j]; } } if(res[i].status==1){ Color='#278006'; } else { Color='#064780'; } events.push({ id:res[i].id, start: time, description:res[i].status + "", title: type[res[i].type] + " " + lan, color: Color, }); } successCallback(events); } } }); }, //delete the event by click the events eventClick: function(info) { if(confirm("Supprimer la réservation/le cours?")) { var id = info.event.id; console.log(info.event.extendedProps.description); if(info.event.extendedProps.description === "1"){ $.ajax({ url: 'cancel_ref_event', type: 'POST', data:{ id:info.event.id, }, error: function () { alert("error"); }, success: function (res) { calendar.refetchEvents(); } }); } else{ $.ajax({ url:"delete_event", type:"POST", data:{id:id}, success:function() { // calendar.fullCalendar('refetchEvents'); calendar.refetchEvents(); alert("Event Removed"); } }) } } }, //add the event by drop the event drop: function(info) { var choice = info.draggedEl.innerHTML.split(" "); var i,j; for (i in type) { if (choice[0] === type[i]){ choice[0] = i; } } for(j in languages) { if (choice[1] === languages[j]){ choice[1] = languages_short[j]; } } var time = info.dateStr.replace(/T/, " "); time = time.substr(0, 19); $.ajax({ url:"drag_insert_event", type:"POST", data:{ time: time, language: choice[1], type: choice[0] }, error:function(){ alert("error"); }, success:function() { // alert("Added Successfully"); } }) }, }); calendar.render(); });
/////////////////////////////////////////////////////////////////////////////////////////// /////////////变量定义!//////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// let M1S11addIns; let M1S12addIns; let tabledataS1 = []; //用于接收表格数据源 let searchdataM1; //每个查询条件form的数据 let searchdataFormM1; //每个查询条件form的实例var contextMenuItems = [ { text: '选择', icon: 'dx-icon-add' }, ]; let adddata = {}; //添加按钮需要的数据源 let addIns; //增加操作时候的模态框实例 //设置模态框的属性 if (addIns == null) { addIns = $('#addmotai ').dxPopup({ 'visible': false, //设置属性不可见 height: 300, //设置高度 width: 450, //设置宽度 }).dxPopup('instance'); } let change = ''; //区分增加和修改的状态,1为增加;2为修改 //查询区域数据 let validationGroupName = 'validationGroupName'; //当存在不需要与后台通信的数据框,且需要自行添加的选择框 /////////////////////////////////////////////////////////////////////////////////////////// /////////////$function!//////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// $(function() { start() //调用初始化函数//websocket开始 /*var userId='DZ_08_websocket'; var websocket; if('WebSocket' in window) { console.log('此浏览器支持websocket'); websocket = new WebSocket('ws://192.168.1.114:8480/webSocketServer/chats/'+userId); } else if('MozWebSocket' in window) { alert('此浏览器只支持MozWebSocket'); websocket = new WebSocket('ws://192.168.1.114:8480/webSocketServer/chats/'+userId); } else { alert('此浏览器只支持SockJS'); websocket = new WebSocket('ws://192.168.1.114:8480/webSocketServer/chats/'+userId); } websocket.onopen = function(evnt) { console.log('链接服务器成功!') var data = ['[{"objId":"DZ_08_websocket","funName":"DZ_08","funType":"M1S11","tbName":"TB_SUPPLIER","dataId":"A"},]'] send(data) }; websocket.onmessage = function(evnt) { var jsons = eval('(' + evnt.data + ')'); var result = DevExpress.ui.dialog.confirm(jsons.dataType+'数据有更新,需要刷新吗?','T1温馨提示:DZ_08'); result.done(function (dialogResult) { if (dialogResult) { var json = eval('(' + evnt.data + ')'); eval(json.dataType) console.log(json) } }) }; websocket.onerror = function(evnt) {}; websocket.onclose = function(evnt) { console.log('与服务器断开了链接!') } function send(data) { if(websocket != null) { websocket.send(data); } else { alert('未与服务器链接.'); } }*/ //websocket结束 //////////////////////////////////// //////查询Form属性生成/////////////////) //////////////////////////////////// //以下为查询form的代码 searchdataFormM1 = $('#searchFormM1').dxForm({ deferRendering: false, formData: searchdataM1, ////当参数小于三个时为五个,大于等于三时统一乘二 ////王晶晶给改为自适应编码 colCountByScreen: { lg: 6, md: 4, sm: 2, xs: 1, }, //所有查询条件为一组的代码段 itemType: 'group', items: [ // { // dataField:'cIdTbSupplier', // label:{ // text:'主键' // }, // editorOptions: { // showClearButton: true, // } // }, // { dataField: 'cSupplierTbSupplier', label: { text: '公司名称' }, editorOptions: { showClearButton: true, } } ] }).dxForm('instance') //完成对查询条件的自动生成 //////////////////////////////////////////////////// ////生成按钮层////////////////////////////////////// //////////////////////////////////////////////////// $('#operateFormM1S1').dxForm({ width: '100%', colCount: 200, items: [{ name: 'M1S11Q', itemType: 'button', buttonOptions: { height: "auto", width: "auto", icon: "search", text: '查询', onClick: function() { M1S11_serDel(); } } }, { name: 'M1S11A', itemType: 'button', buttonOptions: { height: "auto", width: "auto", name: 'M1S11Q', icon: 'plus', text: '新增', onClick: function() { change = '1'; $('#addmotai').show() addIns = $('#addmotai').dxPopup({ width: 1000, //为了规范限制模态框大小//用脚本标识模态框的标题 height: 450, //为了规范限制模态框大小//用脚本标识模态框的标题 }).dxPopup('instance') addIns.option('title', 'DZ_08') addIns.show(); M1S11_addfun(); M1S11addIns.option('formData', new Object()) } } }, { name: 'M1S11_U', itemType: 'button', buttonOptions: { height: "auto", width: "auto", icon: 'save', text: '修改', onClick: function() { change = '2' let grid = $('#dataGridS1').dxDataGrid('instance'); let rowsData = grid.getSelectedRowsData()[0] let selectedRowKeys = grid.getSelectedRowKeys() if (selectedRowKeys.length < 1) { // Cake.Ui.Toast.showInfo('请选择一条要修改的数据。') DevExpress.ui.notify('请选择一条要修改的数据。', 'info', 3000); return; } if (selectedRowKeys.length > 1) { Cake.Ui.Toast.showInfo('一次只能选择一条要修改的数据。') DevExpress.ui.notify('一次只能选择一条要修改的数据。', 'info', 3000); return; } addIns = $('#addmotai').dxPopup({ //模态框增加name width: 1000, height: 450 }).dxPopup('instance') addIns.option('title', 'DZ_08'); addIns.show(); // 调用模态框函数 // updatafun() M1S11_Updatefun() M1S11addIns.option('formData', rowsData) } } }, // { // name: 'M1S11D', // itemType: 'button', // buttonOptions: { // height: "auto", // width: "auto", // // icon: 'remove', // text: '删除', // onClick: function() { // let grid1 = $('#dataGridS1').dxDataGrid('instance'); // let selectedRowKeys = grid1.getSelectedRowKeys() // let rowsData = grid1.getSelectedRowsData() // //脚本执行 // if (selectedRowKeys.length < 1) { // DevExpress.ui.notify('请选择一条要删除的数据。', 'info', 3000); // return; // } // msg = { // ver: '53cc62f6122a436083ec083eed1dc03d', // session: '42f5c0d7178148938f4fda29460b815a', // tag: {}, // data: {} // }; // //前后端统一叫'tscLtrawbin' // // msg.data.dz08M1s1 = $('#dataGridS1').dxDataGrid('instance').getSelectedRowsData(); // console.log(msg) // M1S11D_serDel_Judgment(); // if (M1S11D_serDel_mark != 'M1S11D_success') {} else { // // var result = DevExpress.ui.dialog.confirm("您确定要删除吗?", "删除确认"); // result.done(function (dialogResult) { // if (dialogResult) { // cake.Ui.LoadPanel.show() // // $.ajax({ // url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/M1S11D'), // dataType: 'json', //返回格式为json // async: true, //请求是否异步,默认为异步,这也是ajax重要特性 // data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名 // type: 'post', //请求方式 get 或者post , // contentType: 'application/json', // success: function(data) { // let select = data.msg // if (data.errcode == 0) { // DevExpress.ui.notify(data.msg, 'success', 3000); // M1S11_serDel(); //// var websocketData = ['[{"objId":"DZ_08_websocket","funName":"DZ_08","funType":"M1S11","tbName":"TB_SUPPLIER","dataId":"AUD"}]'] //// send(websocketData) // // } else { // DevExpress.ui.notify(data.msg, 'warning', 120000); // } // }, // error: function() { // DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000); // } // }) // // } // cake.Ui.LoadPanel.close() // }) // // } // } // } // }, { itemType: 'button', buttonOptions: { height: "auto", width: "auto", icon: "add", text: "导入", onClick: function(e) { importPopup.show(); }, } }, ] }) //////////////////////////////////// //////表格属性生成/////////////////) //////////////////////////////////// var dataGridS1columns = [ /* { dataField: 'cIdTbSupplier', caption: '主键', },*/ { dataField: 'number', caption: '序号', // width: 50, alignment: 'left' }, { dataField: 'cSupplierTbSupplier', caption: '公司名称', width: "auto", }, { dataField: 'cSupaddressTbSupplier', caption: '公司地址', width: "auto", }, { dataField: 'cTaxnumberTbSupplier', caption: '税号', width: "auto", }, { dataField: 'cBanknameTbSupplier', caption: '电汇开户银行', width: "auto", }, { dataField: 'cSw05TbSupplier', caption: '电汇行号', width: "auto", }, { dataField: 'cAccountnoTbSupplier', caption: '电汇账号', width: "auto", }, { dataField: 'cSupphoneTbSupplier', caption: '电话', width: "auto", }, { dataField: 'cFaxnoTbSupplier', caption: '传真', width: "auto", }, { dataField: 'cSw06TbSupplier', caption: '承兑开户银行', width: "auto", }, { dataField: 'cSw01TbSupplier', caption: '承兑行号', width: "auto", }, { dataField: 'cSw02TbSupplier', caption: '承兑账号', width: "auto", }, { dataField: 'cSw07TbSupplier', caption: '电汇开户银行2', width: "auto", }, { dataField: 'cSw08TbSupplier', caption: '电汇行号2', width: "auto", }, { dataField: 'cSw09TbSupplier', caption: '电汇账号2', width: "auto", }, { dataField: 'cRemarkTbSupplier', caption: '备注', width: "auto", }, ] $('#dataGridS1').dxDataGrid({ deferRendering: false, columnResizingMode: "widget", dataSource: tabledataS1, editing: { mode: 'popup', //allowUpdating: false }, // keyExpr: 'ID', columnAutoWidth: true, showBorders: true, allowColumnResizing: true, showColumnLines: true, showRowLines: true, onCellHoverChanged: '#888', hoverStateEnabled: true, noDataText: '无数据', //允许脚本编写 height: '100% ', paging: { enabled: false }, /* scrolling: { mode: 'virtual' },*/ paging: { pageSize: 100, enabled: true, }, pager: { // showPageSizeSelector: true, // allowedPageSizes: [5, 10, 20 , 25 ,30], PageNavigator: true, showInfo: true, showNavigationButtons: true, infoText: "{0}/{1} " }, selection: { // mode: 'multiple' mode: 'single' }, columns: dataGridS1columns, // onToolbarPreparing: function(e) { // operateFormS1buts.forEach(item => e.toolbarOptions.items.push(item)); // } }).dxDataGrid('instance'); /////////////////////////////////////////////////////// //Star()请求下拉框、多选框数据、通过请求网址的后缀生成代码 /////////////////////////////////////////////////////// function start() { //ajax传参用 msg = { ver: '53cc62f6122a436083ec083eed1dc03d', session: '42f5c0d7178148938f4fda29460b815a', tag: {}, data: {} }; console.log(msg) //////////////////////////////////////////////////////////////////////////////// //寻找查询条件的所有字段,带有后缀请求的,并且尾号为零的,所有下来框的循环生成, //////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////////////////////// //功能类代码(与button生成代码对应) ///////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// function M1S11_serDel() { msg = { ver: '53cc62f6122a436083ec083eed1dc03d', session: '42f5c0d7178148938f4fda29460b815a', tag: {}, data: {} }; let searchtiao = searchdataFormM1.option('formData') msg.data.dz08M1s1 = [searchdataFormM1.option('formData')]; M1S11Q_serDel_Judgment(); if (M1S11Q_serDel_mark != 'M1S11Q_success') {} else { $.ajax({ url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/M1S11Q'), dataType: 'json', //返回格式为json async: true, //请求是否异步,默认为异步,这也是ajax重要特性 data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名 type: 'post', //请求方式 get 或者post , contentType: 'application/json', success: function(data) { if (data.data == null) { tabledataS1.splice(0, tabledataS1.length); $('#dataGridS1').dxDataGrid('instance').option('dataSource', tabledataS1) return } let select; select = data.data.dz08M1s1 tabledataS1.splice(0, tabledataS1.length); select.forEach(item => tabledataS1.push(item)); $('#dataGridS1').dxDataGrid('instance').deselectAll() $('#dataGridS1').dxDataGrid('instance').refresh() DevExpress.ui.notify(data.msg, 'success', 1000); }, error: function() { DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000); // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。') //e.cancel=true; } }) } } function M1S11_addfun() { M1S11addIns = $('#addForm').dxForm({ formData: adddata, validationGroup: validationGroupName, colCount: 3, items: [ /*{ dataField: 'cIdTbSupplier', label: { text: '主键' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 40, min: 0, message: '长度超限,最长为40!' }, ] },*/ { dataField: 'cSupplierTbSupplier', label: { text: '公司名称' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSupaddressTbSupplier', label: { text: '公司地址' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cTaxnumberTbSupplier', label: { text: '税号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 50, min: 0, message: '长度超限,最长为50!' }, ] }, { dataField: 'cBanknameTbSupplier', label: { text: '电汇开户银行' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw05TbSupplier', label: { text: '电汇行号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cAccountnoTbSupplier', label: { text: '电汇账号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw06TbSupplier', label: { text: '承兑开户银行' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw01TbSupplier', label: { text: '承兑行号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw02TbSupplier', label: { text: '承兑账号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw07TbSupplier', label: { text: '电汇开户银行2' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSw08TbSupplier', label: { text: '电汇行号2' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSw09TbSupplier', label: { text: '电汇账号2' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, ] }, { dataField: 'cSupphoneTbSupplier', label: { text: '电话' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, ] }, { dataField: 'cFaxnoTbSupplier', label: { text: '传真' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 50, min: 0, message: '长度超限,最长为50!' }, ] }, { dataField: 'cRemarkTbSupplier', label: { text: '备注' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] } ] }).dxForm('instance') $('#addsure').dxButton({ text: '确定', icon: 'todo', validationGroup: validationGroupName, onClick: function(e) { // let validateResult = e.validationGroup.validate(); // if (!validateResult.isValid) { // DevExpress.ui.notify('数据不符合规范', 'info', 3000); // return; // } msg = { ver: '53cc62f6122a436083ec083eed1dc03d', session: '42f5c0d7178148938f4fda29460b815a', tag: {}, data: {}, }; let cBanknameTbSupplier = $('#addForm').dxForm('instance').option('formData').cBanknameTbSupplier; if (cBanknameTbSupplier == "" || cBanknameTbSupplier == undefined || cBanknameTbSupplier == null) { DevExpress.ui.notify('电汇开户银行不能为空!!', 'error', 3000); return } let cSw05TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw05TbSupplier; if (cSw05TbSupplier == "" || cSw05TbSupplier == undefined || cSw05TbSupplier == null) { DevExpress.ui.notify('电汇行行号不能为空!!', 'error', 3000); return } let cAccountnoTbSupplier = $('#addForm').dxForm('instance').option('formData').cAccountnoTbSupplier; if (cAccountnoTbSupplier == "" || cAccountnoTbSupplier == undefined || cAccountnoTbSupplier == null) { DevExpress.ui.notify('电汇账号不能为空!!', 'error', 3000); return } let cSw06TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw06TbSupplier; if (cSw06TbSupplier == "" || cSw06TbSupplier == undefined || cSw06TbSupplier == null) { DevExpress.ui.notify('承兑开户银行不能为空!!', 'error', 3000); return } let cSw01TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw01TbSupplier; if (cSw01TbSupplier == "" || cSw01TbSupplier == undefined || cSw01TbSupplier == null) { DevExpress.ui.notify('承兑行号不能为空!!', 'error', 3000); return } let cSw02TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw02TbSupplier; if (cSw02TbSupplier == "" || cSw02TbSupplier == undefined || cSw02TbSupplier == null) { DevExpress.ui.notify('承兑账号不能为空!!', 'error', 3000); return } msg.data.dz08M1s1 = [M1S11addIns.option('formData')]; //change等于1为添加 M1S11A_serDel_Judgment(); if (M1S11A_serDel_mark != 'M1S11A_success') {} else { var result = DevExpress.ui.dialog.confirm("您确定要添加吗?", "确认添加"); result.done(function(dialogResult) { if (dialogResult) { cake.Ui.LoadPanel.show() $.ajax({ url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/M1S11A'), dataType: 'json', //返回格式为json async: true, //请求是否异步,默认为异步,这也是ajax重要特性 data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名 type: 'post', //请求方式 get 或者post , contentType: 'application/json', success: function(data) { let select = data.msg if (data.errcode == 0) { DevExpress.ui.notify(data.msg, 'success', 3000) /* var websocketData = ['[{"objId":"DZ_08_websocket","funName":"DZ_08","funType":"M1S11","tbName":"TB_SUPPLIER","dataId":"AUD"}]'] send(websocketData)*/ } else { DevExpress.ui.notify(data.msg, 'error', 120000) return; } M1S11_serDel(); addIns.hide(); }, error: function() { DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000); // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。') //e.cancel=true; } }) } cake.Ui.LoadPanel.close(); }) } } }) $('#addcansel').dxButton({ text: '取消', icon: 'remove', onClick: function() { addIns.hide() } }) } function M1S11_Updatefun() { M1S11addIns = $('#addForm').dxForm({ formData: adddata, validationGroup: validationGroupName, colCount: 3, items: [ /*{ dataField: 'cIdTbSupplier', label: { text: '主键' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 40, min: 0, message: '长度超限,最长为40!' }, ] },*/ { dataField: 'cSupplierTbSupplier', label: { text: '公司名称' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSupaddressTbSupplier', label: { text: '公司地址' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cTaxnumberTbSupplier', label: { text: '税号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 50, min: 0, message: '长度超限,最长为50!' }, ] }, { dataField: 'cBanknameTbSupplier', label: { text: '电汇开户银行' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw05TbSupplier', label: { text: '电汇行号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cAccountnoTbSupplier', label: { text: '电汇账号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw06TbSupplier', label: { text: '承兑开户银行' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw01TbSupplier', label: { text: '承兑行号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw02TbSupplier', label: { text: '承兑账号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, { type: 'required', message: '必填!' }, ] }, { dataField: 'cSw07TbSupplier', label: { text: '电汇开户银行2' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSw08TbSupplier', label: { text: '电汇行号2' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSw09TbSupplier', label: { text: '电汇账号2' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, ] }, { dataField: 'cSupphoneTbSupplier', label: { text: '电话' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, ] }, { dataField: 'cFaxnoTbSupplier', label: { text: '传真' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 100, min: 0, message: '长度超限,最长为100!' }, ] }, { dataField: 'cRemarkTbSupplier', label: { text: '备注' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] } ] }).dxForm('instance') $('#addsure').dxButton({ text: '确定', icon: 'todo', validationGroup: validationGroupName, onClick: function(e) { // let validateResult = e.validationGroup.validate(); // if (!validateResult.isValid) { // DevExpress.ui.notify('数据不符合规范', 'info', 3000); // return; // } msg = { ver: '53cc62f6122a436083ec083eed1dc03d', session: '42f5c0d7178148938f4fda29460b815a', tag: {}, data: {}, }; let cBanknameTbSupplier = $('#addForm').dxForm('instance').option('formData').cBanknameTbSupplier; if (cBanknameTbSupplier == "" || cBanknameTbSupplier == undefined || cBanknameTbSupplier == null) { DevExpress.ui.notify('电汇开户银行不能为空!!', 'error', 3000); return } let cSw05TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw05TbSupplier; if (cSw05TbSupplier == "" || cSw05TbSupplier == undefined || cSw05TbSupplier == null) { DevExpress.ui.notify('电汇行行号不能为空!!', 'error', 3000); return } let cAccountnoTbSupplier = $('#addForm').dxForm('instance').option('formData').cAccountnoTbSupplier; if (cAccountnoTbSupplier == "" || cAccountnoTbSupplier == undefined || cAccountnoTbSupplier == null) { DevExpress.ui.notify('电汇账号不能为空!!', 'error', 3000); return } let cSw06TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw06TbSupplier; if (cSw06TbSupplier == "" || cSw06TbSupplier == undefined || cSw06TbSupplier == null) { DevExpress.ui.notify('承兑开户银行不能为空!!', 'error', 3000); return } let cSw01TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw01TbSupplier; if (cSw01TbSupplier == "" || cSw01TbSupplier == undefined || cSw01TbSupplier == null) { DevExpress.ui.notify('承兑行号不能为空!!', 'error', 3000); return } let cSw02TbSupplier = $('#addForm').dxForm('instance').option('formData').cSw02TbSupplier; if (cSw02TbSupplier == "" || cSw02TbSupplier == undefined || cSw02TbSupplier == null) { DevExpress.ui.notify('承兑账号不能为空!!', 'error', 3000); return } msg.data.dz08M1s1 = [M1S11addIns.option('formData')]; //change等于1为添加 M1S11U_serDel_Judgment(); if (M1S11U_serDel_mark != 'M1S11U_success') {} else { var result = DevExpress.ui.dialog.confirm("您确定要修改吗?", "修改确认"); result.done(function(dialogResult) { if (dialogResult) { cake.Ui.LoadPanel.show() $.ajax({ url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/M1S11U'), dataType: 'json', //返回格式为json async: true, //请求是否异步,默认为异步,这也是ajax重要特性 data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名 type: 'post', //请求方式 get 或者post , contentType: 'application/json', success: function(data) { let select = data.msg if (data.errcode == 0) { DevExpress.ui.notify(data.msg, 'success', 3000) // var websocketData = ['[{"objId":"DZ_08_websocket","funName":"DZ_08","funType":"M1S11","tbName":"TB_SUPPLIER","dataId":"AUD"}]'] // send(websocketData) } else { DevExpress.ui.notify(data.msg, 'error', 120000) return; } M1S11_serDel(); addIns.hide(); }, error: function() { DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000); // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。') //e.cancel=true; } }) } cake.Ui.LoadPanel.close() }) } } }) $('#addcansel').dxButton({ text: '取消', icon: 'remove', onClick: function() { addIns.hide() } }) } function M1S11_UpdatefunA() { M1S11addIns = $('#addForm').dxForm({ formData: adddata, validationGroup: validationGroupName, colCount: 3, items: [ /*{ dataField: 'cIdTbSupplier', label: { text: '主键' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 40, min: 0, message: '长度超限,最长为40!' }, ] },*/ { dataField: 'cSupplierTbSupplier', label: { text: '公司名称' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cSupaddressTbSupplier', label: { text: '公司地址' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cBanknameTbSupplier', label: { text: '开户银行' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] }, { dataField: 'cAccountnoTbSupplier', label: { text: '账号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, ] }, { dataField: 'cTaxnumberTbSupplier', label: { text: '税号' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 50, min: 0, message: '长度超限,最长为50!' }, ] }, { dataField: 'cSupphoneTbSupplier', label: { text: '电话' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 1000, min: 0, message: '长度超限,最长为1000!' }, ] }, { dataField: 'cFaxnoTbSupplier', label: { text: '传真' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 50, min: 0, message: '长度超限,最长为50!' }, ] }, { dataField: 'cRemarkTbSupplier', label: { text: '备注' }, editorOptions: { showClearButton: true, }, validationRules: [{ type: 'stringLength', max: 4000, min: 0, message: '长度超限,最长为4000!' }, ] } ] }).dxForm('instance') $('#addsure').dxButton({ text: '确定', icon: 'todo', validationGroup: validationGroupName, onClick: function(e) { let validateResult = e.validationGroup.validate(); if (!validateResult.isValid) { DevExpress.ui.notify('数据不符合规范', 'info', 3000); return; } msg = { ver: '53cc62f6122a436083ec083eed1dc03d', session: '42f5c0d7178148938f4fda29460b815a', tag: {}, data: {}, }; msg.data.dz08M1s1 = [M1S11addIns.option('formData')]; //change等于1为添加 M1S11U_serDel_Judgment(); if (M1S11U_serDel_mark != 'M1S11U_success') {} else { var result = DevExpress.ui.dialog.confirm("您确定要修改添加吗?", "修改添加确认"); result.done(function(dialogResult) { if (dialogResult) { cake.Ui.LoadPanel.show() $.ajax({ url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/M1S11A'), dataType: 'json', //返回格式为json async: true, //请求是否异步,默认为异步,这也是ajax重要特性 data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名 type: 'post', //请求方式 get 或者post , contentType: 'application/json', success: function(data) { let select = data.msg if (data.errcode == 0) { DevExpress.ui.notify(data.msg, 'success', 3000) // var websocketData = ['[{"objId":"DZ_08_websocket","funName":"DZ_08","funType":"M1S11","tbName":"TB_SUPPLIER","dataId":"AUD"}]'] // send(websocketData) } else { DevExpress.ui.notify(data.msg, 'error', 120000) return; } M1S11_serDel(); addIns.hide(); }, error: function() { DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000); // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。') //e.cancel=true; } }) } cake.Ui.LoadPanel.close() }) } } }) $('#addcansel').dxButton({ text: '取消', icon: 'remove', onClick: function() { addIns.hide() } }) } //代码需要重新定义 function M1S12_Msgfun() { msg = { ver: '53cc62f6122a436083ec083eed1dc03d', session: '42f5c0d7178148938f4fda29460b815a', tag: {}, data: {} }; msg.data.dz08M1s1 = $('#dataGridS1').dxDataGrid('instance').getSelectedRowsData(); M1S12MSG_serDel_Judgment(); if (M1S12MSG_serDel_mark != 'M1S12MSG_success') {} else { $.ajax({ url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/M1S12MSG'), dataType: 'json', //返回格式为json async: true, //请求是否异步,默认为异步,这也是ajax重要特性 data: JSON.stringify(msg), //下拉框的参数值 queryCondition 上面有定义 cStlCla 后台给的固定的名 type: 'post', //请求方式 get 或者post , contentType: 'application/json', success: function(data) { if (data.errcode == "0") { DevExpress.ui.notify(data.msg, 'success', 3000) var websocketData = ['[{"objId":"DZ_08_websocket","funName":"DZ_08","funType":"M1S12","tbName":"TB_SUPPLIER","dataId":"AUD"}]'] send(websocketData) } else { DevExpress.ui.notify(data.msg, 'error', 120000) return; } M1S11_serDel(); }, error: function() { DevExpress.ui.notify('网络或服务器故障,请稍后再试。', 'error', 3000); // Cake.Ui.Toast.showError('网络或服务器故障,请稍后再试。') //e.cancel=true; } }) } } //Script ------------------------------------ // ==========================导入============================== let importPopup = $('#import-content').dxPopup({ deferRendering: false, height: 200, width: 600, }).dxPopup('instance'); $('#import_btn').dxForm({ width: "100%", items: [{ itemType: "group", colCount: 6, items: [{ colSpan: 4, itemType: "empty" }, { itemType: "button", buttonOptions: { icon: "todo", text: "确定", onClick: function() { DevExpress.ui.notify('正在导入,请稍等。。。', "success", 3000); console.log(localStorage.getItem('updata')); console.log(localStorage.getItem('updata')) $.ajax({ url: Cake.Piper.getAuthUrl('../../tdhc_cgsys/DZ_08/Import_SuppExcel'), type: 'POST', dataType: 'json', contentType: "application/json; charset=utf-8", data: localStorage.getItem('updata'), success: function(data) { importPopup.hide(); $("#upInput").val(""); localStorage.clear('updata'); DevExpress.ui.notify(data.msg, "success", 3000); M1S11_serDel() }, error: function(err) { DevExpress.ui.notify('导入失败', "error", 3000); $("#upInput").val(""); localStorage.clear('updata'); } }) } } }, { itemType: "button", buttonOptions: { icon: "close", text: "取消", onClick: function() { importPopup.hide(); } } }, ] }, ] }); }) function importf(obj) { /* FileReader共有4种读取方法: 1.readAsArrayBuffer(file):将文件读取为ArrayBuffer。 2.readAsBinaryString(file):将文件读取为二进制字符串 3.readAsDataURL(file):将文件读取为Data URL 4.readAsText(file, [encoding]):将文件读取为文本,encoding缺省值为'UTF-8' */ if (!obj.files) { return; } var wb; //读取完成的数据 var rABS = false; //是否将文件读取为二进制字符串 var updata = {}; //储存读取出来的数据 function fixdata(data) { //文件流转BinaryString var o = "", l = 0, w = 10240; for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w))); o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w))); return o; } var f = obj.files[0]; var reader = new FileReader(); reader.onload = function(e) { var data = e.target.result; if (rABS) { wb = XLSX.read(btoa(fixdata(data)), { //手动转化 type: 'base64' }); } else { wb = XLSX.read(data, { type: 'binary' }); } //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字 //wb.Sheets[Sheet名]获取第一个Sheet的数据 var tables = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); // // 拼接两段数据 tables = JSON.stringify(tables); tables = tables.replace(/公司名称/g, 'cSupplier'); tables = tables.replace(/公司地址/g, 'cSupaddress'); tables = tables.replace(/开户银行/g, 'cBankname'); tables = tables.replace(/账号/g, 'cAccountno'); tables = tables.replace(/税号/g, 'cTaxnumber'); tables = tables.replace(/电话/g, 'cSupphone'); tables = tables.replace(/传真/g, 'cFaxno'); updata.data = {} updata.data.tbSupplier = JSON.parse(tables); console.log(updata); localStorage.setItem('updata', JSON.stringify(updata)); }; if (rABS) { reader.readAsArrayBuffer(f); } else { reader.readAsBinaryString(f); } }
import React, { Component } from "react"; import Book from "./Book"; class ListBooks extends Component { render() { return ( <ol className="books-grid"> {this.props.books.map((book, index) => ( <li key={index}> <Book changeBookStatus={this.props.changeBookStatus} book={book} /> </li> ))} </ol> ); } } export default ListBooks;
const phoneNumVal = (number) => { regExp = /\(?\+?([44]{2}|[0])?\)\s?\d{3}\s?\d{3}\s?\d\s?\d{4,6}/g; return regExp.test(number); }; console.log(phoneNumVal("07856766543")); console.log(phoneNumVal("0785 676 6543")); console.log(phoneNumVal("+447856766543")); console.log(phoneNumVal("+44 7856766543")); console.log(phoneNumVal("(44) 7856766543")); console.log(phoneNumVal("Apple"));
import Vue from 'vue'; document.addEventListener('DOMContentLoaded', () => { new Vue({ el: "#app", data: { tasks: [ { chore: "Tidy", isCompleted: false, priority: 0}, { chore: "Food Shop", isCompleted: true, priority: 2}, { chore: "pay bills", isCompleted: false, priority: 7}, ], newTask: "" }, methods: { saveNewTask: function() { this.tasks.push({ chore: this.newTask, isCompleted: false, }); this.newTask = ""; }, doTask: function(index) { this.tasks[index].isCompleted = true; } } }); });
/** * @author a */ var xWidth = screen.availWidth; var xHeight = screen.availHeight; var beforeWidth = $(window).width(); var browser_val = true; var elements = $('.title').find(".items"); var elements_width; setFirstElementsWidth(); $('.title').css('width' , $(window).width()); $('.scroll-img').css('width' , $(window).width()); function get_height() { var top_area_height = $(window).height(); if (top_area_height < 780) { top_area_height = 780; }; return top_area_height; } $('.top-area').css('height' , get_height()); function setFirstElementsWidth() { var percent = $(window).width()/1920; elements_width = new Array(elements.length); for(var i=0;i<=elements.length;i++) { elements_width[i]=$(elements[i]).width(); $(elements[i]).css("width",elements_width[i]*percent); } } function small_item() { var percent = $(window).width()/1920; for(var i = 0 ; i <= elements.length ; i ++ ) { $(elements[i]).css("width" , elements_width[i]*percent); } if (browser_val == true) { adjust_gallery(); }; beforeWidth=$(window).width(); } function adjust_gallery() { if($(window).width()>beforeWidth) { var move_speed = 0; var width_gap = $(window).width() - beforeWidth; console.log(move_speed); for(var i=1;i<get_title_cnt();i++) { move_speed+=width_gap; } $(".move-title").animate({ left: "-="+move_speed+"" }, 300); } else if($(window).width()<beforeWidth) { // && get_title_cnt()!=get_title_length() && get_title_cnt()!=1 var move_speed = 0; var width_gap = beforeWidth - $(window).width(); for(var i=get_title_cnt();i>1;i--) { move_speed+=width_gap; } $(".move-title").animate({ left: "+="+move_speed+"" }, 300); } } $(window).resize(function() { $('.title').css('width' , $(window).width()); $('.scroll-img').css('width' , $(window).width()); resize_event(); menu_build(); }); var lock = false; function resize_event() { if(!lock) { lock=true; setTimeout(function() { small_item(); lock=false; },250); } } function checkBrowser() { $.browser.chrome = $.browser.webkit && !!window.chrome; $.browser.safari = $.browser.webkit && !window.chrome; if($.browser.chrome || $.browser.mozilla || $.browser.safari || $.browser.opera== true) { small_item(true); } else if($.browser.msie == true) { userAgent = $.browser.version; userAgent = userAgent.substring(0,userAgent.indexOf('.')); version = userAgent; if(version == 6 && 7) { alert("당신의 브라우져는 IE" + version + "입니다. \n 본사이트는 IE9 이상 및 기타 브라우져에 최적화 되어있습니다."); } else if(version == 8 && 9 ) { browser_val = false; resize_item(); } else if(version == 10){ small_item(true); } } } var mobileKeyWords = new Array('iPhone', 'iPod', 'BlackBerry', 'Android', 'Windows CE', 'LG', 'MOT', 'SAMSUNG', 'SonyEricsson'); for (var word in mobileKeyWords){ if (navigator.userAgent.match(mobileKeyWords[word]) != null) { /*$(".title-box").hide();*/ break; } } checkBrowser(); function menu_build() { //if ($(window).width() > 1200) {$(".top-menu > ul > li > p").css({"font-size" : "14px"});} //else if ($(window).width() < 1200) {$(".top-menu > ul > li > p").css({"font-size" : "10px"});} } function pages_check(val) { $('body,html').animate({scrollTop:val.top - 80},300); } $(".goto-01").click(function() { var val = $('body').offset(); pages_check(val); }); $(".goto-02").click(function() { var val = $('#cate-02').offset(); pages_check(val); }); $(".goto-03").click(function() { var val = $('#cate-03').offset(); pages_check(val); }); $(".goto-04").click(function() { var val = $('#cate-04').offset(); pages_check(val); }); $(".goto-05").click(function() { var val = $('#cate-05').offset(); pages_check(val); }); $(".goto-06").click(function() { var val = $('#cate-06').offset(); pages_check(val); }); $(".goto-07").click(function() { var val = $('#cate-07').offset(); pages_check(val); }); $(".banner-go01").click(function() { location.href = "http://pianohakwon.cafe24.com/"; }); $(".banner-go02").click(function() { location.href = "http://www.catalook.co.kr/"; }); $(".top-button").click(function() { var val = $("body").offset(); $('body,html').animate({scrollTop:val.top},1000); }); var trans_menu = false; $(window).scroll(function () { var horizontalScroll = window.pageYOffset; var sector = $(".container").find(".sector"); //new Seprate; if (horizontalScroll > get_height() - 0 && trans_menu == false) { trans_menu = true; //$(".menu-containner").hide("blind",500); $(".top-menu").css({"position" : "fixed", "background-color" : "#FFFFFF" , "top" : "0px"}); $(".logo").animate({"top" : "5px"} , 200); $(".top-menu > ul").animate({"top" : "20px"} , 200); $(".top-menu").animate({"height" : "65px"} , 500); $(".menu-containner > ul").animate({"top" : "-0px"} , 400); $(".top-bar").hide(500); //$(".menu-containner02").show("blind" , 500); //스크롤 이벤트 첨부 return false; } else if(horizontalScroll < get_height() - 0 && trans_menu == true) { trans_menu = false; //$(".menu-containner02").hide("blind" , 500); $(".top-menu").css({"position" : "relative", "background-color" : "#FFFFFF"}); $(".logo").animate({"top" : "20px"} , 400); $(".top-menu > ul").animate({"top" : "70px"} , 700); $(".top-menu").animate({"height" : "90px"} , 300); $(".menu-containner > ul").animate({"top" : "10px"} , 400); $(".top-bar").show(500); //$(".menu-containner").show("blind" , 500); //스크롤 이벤트 첨부 return false; } //(horizontalScroll > 500) == true ? $(".banner").fadeIn(700) : $(".banner").fadeOut(700); (horizontalScroll < 100) == true ? $(".top-button").fadeOut(400) : $(".top-button").fadeIn(400); }); $(".banner-close").click(function() { $(".banner").fadeOut(400); }); /* hover effect */ var animate_val = false; $(".top-menu > ul > li").hover(function() { if(animate_val == false){ animate_val = true; $(this).children(".pointer").fadeIn(300); setTimeout(function(){animate_val = false;},100); } }, function() { $(this).children(".pointer").fadeOut(300); }); // var animate_val = false; var selected ; $(".pf-menu-li").hover(function() { selected = this; if(animate_val == false){ animate_val = true; $(this).animate({ "background-color" : "#554ad7" } , 400); setTimeout(function(){animate_val = false;},50); } }, function() { $(this).animate({ "background-color" : "#222", opacity: 1 } , 400); }); $(".slide-li01").hover(function() { selected = this; if(animate_val == false){ animate_val = true; $(this).animate({ "background-color" : "#554ad7" } , 400); setTimeout(function(){animate_val = false;},50); } }, function() { $(this).animate({ "background-color" : "#222", opacity: 1 } , 400); }); $(".slide-li02").hover(function() { selected = this; if(animate_val == false){ animate_val = true; $(this).animate({ "background-color" : "#554ad7" } , 400); setTimeout(function(){animate_val = false;},50); } }, function() { $(this).animate({ "background-color" : "#222", opacity: 1 } , 400); }); var hover_idx = new Array( "/Hyuneum/resources/img/icon/icon_header01/icon_header_01.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_02.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_03.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_04.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_05.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_06.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_07.png" ); var hover_idx_after = new Array( "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_01.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_02.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_03.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_04.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_05.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_06.png", "/Hyuneum/resources/img/icon/icon_header01/icon_header_t_07.png" ); /* * 로컬용 var hover_idx = new Array( "/hyuneum/resources/img/icon/icon_header01/icon_header_01.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_02.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_03.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_04.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_05.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_06.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_07.png" ); var hover_idx_after = new Array( "/hyuneum/resources/img/icon/icon_header01/icon_header_t_01.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_t_02.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_t_03.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_t_04.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_t_05.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_t_06.png", "/hyuneum/resources/img/icon/icon_header01/icon_header_t_07.png" );*/ var selected_menu = 0; var before_cnt = false; $(".main-menu-container > li").hover(function() { var aim = $(this).index(); if(animate_val == false && aim != selected_menu) { animate_val = true; $(this).animate({ "background-color" : "#554ad7" } , 400); $(this).children().find("img").attr("src" ,""+hover_idx_after[aim]+""); $(this).find("p").css({ "color" : "#fff" }); setTimeout(function(){animate_val = false;},0); } /* 이미지 경로 난리남 var aim = $(this).children().find("img").attr("src"); var aim1 = aim.substring(0,34); var aim2 = aim.substring(34,41); */ }, function() { var aim2 = $(this).index(); if(aim2 != selected_menu) { $(this).animate({ "background-color" : "#fff", opacity: 1 } , 400); $(this).children().find("img").attr("src" , ""+hover_idx[aim2]+""); $(this).find("p").css({ "color" : "#555" }); } }); $(".main-menu-container > li").bind("click" , function() { var aim = $(this).index(); var before_num = $(".before-menu").index(); selected_menu = aim; $(".main-menu-container > li").css({"background-color" : "#fff" }); $(".before-menu").children().find("img").attr("src" ,""+hover_idx[before_num]+""); $(".main-menu-container > li").find("p").css({ "color" : "#555"}); $(".before-menu").removeClass("before-menu"); $(this).css({"background-color" : "#554ad7" }); $(this).children().find("img").attr("src" ,""+hover_idx_after[aim]+""); $(this).find("p").css({ "color" : "#fff"}); $(this).addClass("before-menu"); }); function Init_menu() { $(".before-menu").css({"background-color" : "#554ad7" }); $(".before-menu").children().find("img").attr("src" ,""+hover_idx_after[0]+""); $(".before-menu").find("p").css({ "color" : "#fff"}); } Init_menu(); var now_sector = 1; //obj-sector01 //now_position > sector_num01 && now_position < sector_num02 /* $(document).scroll(function() { var sector_num01 = $(".container").position(); var sector_num02 = $(".obj-sector01").position(); var sector_num03 = $(".obj-sector02").position(); var sector_num04 = $(".obj-sector03").position(); var sector_num05 = $(".obj-sector04").position(); var sector_num06 = $(".obj-sector05").position(); var sector_num07 = $(".obj-sector06").position(); var now_position = $(window).scrollTop(); console.log(now_position); //0<=x<=10 if (0 <= now_position && now_position < sector_num01.top) { now_sector = 1; console.log("nowsector:" + now_sector); } else if(sector_num01.top <= now_position && now_position < sector_num02.top) { now_sector = 2; console.log("nowsector:" + now_sector); } else if(sector_num02.top <= now_position && now_position < sector_num03.top) { now_sector = 3; console.log("nowsector:" + now_sector); } else if(sector_num03.top <= now_position && now_position < sector_num04.top) { now_sector = 4; console.log("nowsector:" + now_sector); } else if(sector_num04.top <= now_position && now_position < sector_num05.top) { now_sector = 5; console.log("nowsector:" + now_sector); } else if(sector_num05.top <= now_position && now_position < sector_num06.top) { now_sector = 6; console.log("nowsector:" + now_sector); } else if(sector_num06.top <= now_position && now_position < sector_num07.top) { now_sector = 7; console.log("nowsector:" + now_sector); } }); */
import React from "react"; import MediaCard from "./MediaCard"; const StyleField={ GameField:{ backgroundColor: 'rgba(89, 174, 194, 0.43)', border: '1px solid rgb(204, 204, 204)', borderRadius:5, width:648, height:300, marginBottom:10, display:'inline-block', }, mediaCard:{ marginTop:20, display:'inline-block', float:'left' }, resultBlock:{ marginTop:90, marginLeft:25, display:'inline-block', width:50, height: 50, backgroundImage:'url(https://cdn2.iconfinder.com/data/icons/bold-ui/100/reload-512.png)', backgroundColor:'rgba(0, 187, 255, 0.46)', backgroundSize: 'cover', borderRadius: 20, border: '1px solid rgb(204, 204, 204)', float:'left' }, waitBlock:{ // marginBottom:80, // marginLeft:25, // display:'inline-block', // width:50, // height: 50, // borderRadius: 20, marginTop:90, marginLeft:25, display:'inline-block', width:50, height: 50, //backgroundImage:'url(https://cdn2.iconfinder.com/data/icons/bold-ui/100/reload-512.png)', backgroundColor:'rgba(0, 187, 255, 0.46)', backgroundSize: 'cover', borderRadius: 20, border: '1px solid rgb(204, 204, 204)', float:'left' }, eventsMess:{ marginTop:20, marginLeft:25, marginRight:25, backgroundColor:'rgba(0, 187, 255, 0.46)', display: 'inline-block', border: '1px solid rgb(204, 204, 204)', borderRadius:5, float:'left' }, video:{ marginTop:20, marginRight:20, display: 'inline-block', width:270, height:190, borderRadius:5, backgroundColor:'rgba(0, 187, 255, 0.46)', border: '1px solid rgb(204, 204, 204)', float:'right', marginBottom:20, }, score:{ marginLeft:25, marginRight:25, backgroundColor:'rgba(0, 187, 255, 0.46)', display: 'inline-block', border: '1px solid rgb(204, 204, 204)', borderRadius:5, float:'right' } } export default function GameField(prop){ //Карта этого пользователя const myCard =prop.obj.state.myCard; // Карта противника const victimCard =prop.obj.state.victimCard; // показывает в каком состоянии на данный момент находится игра- // 1) wait - ожидание (Противники еще не выбрали свои карточки на этом ходу // 2) yea - этот пользователь победил // 3) no - этот пользователь проиграл let win = prop.obj.state.win; let resBlock; // если пользователь проиграл, появляется кнопка для предложения реваша switch(win){ case 'wait':resBlock=<div style={StyleField.waitBlock }> </div> ;break; case 'Yes':resBlock=<div onClick ={()=>prop.obj.again()} style={StyleField.resultBlock }> </div> ;break; case 'No':resBlock=<div onClick ={()=>prop.obj.again()} style={StyleField.resultBlock }> </div> ;break; } return( <div className="GameField" style={StyleField.GameField}> {/*//Карта этого пользователя*/} <div style={StyleField.mediaCard}> <MediaCard card ={myCard} key = {"MyCard"} /> </div> {/*//Кнопка реванша*/} {resBlock} {/*//Карта противника*/} <div style={StyleField.mediaCard}> <MediaCard card ={victimCard} key = {"MyCard"} /> </div> {/*//Видео с веб-камеры*/} <div id="video" style={StyleField.video}> </div> {/*// поле с пояснительным текстом - что требуется делать дальше*/} <div style={StyleField.eventsMess}> <div> {prop.obj.state.textForEvent} </div> </div> {/*// текущий счет с этим противником*/} <div style={StyleField.score}> <div> {prop.obj.state.score} </div> </div> </div> ) }
import React from 'react'; import {injectIntl} from 'react-intl'; import {Confirm} from 'semantic-ui-react'; export default injectIntl(props => ( <Confirm {...props} content={props.intl.formatMessage({id: props.content})} cancelButton={props.intl.formatMessage({id: props.cancelButton})} confirmButton={props.intl.formatMessage({id: props.confirmButton})} /> ));
var _ = require('lodash'); module.exports = function Console(window, exec) { window.console = { log: delegate('log'), info: delegate('info'), error: delegate('error'), warn: delegate('warn'), time: delegate('time'), timeEnd: delegate('timeEnd') }; function delegate( name) { return function() { console[name].apply(console, ['id_' + window._id, process.hrtime(window._start)[1]/1e6].concat(mapArgs(arguments))); }; } function mapArgs(args) { return _.map(args, function(arg) { if (arg && arg.split) { arg = exec.rewriteStack(arg); } return arg; }); } return { dispose: function() { window = window.console = undefined; } }; };
/** * The MIT License (MIT) * Copyright (c) 2016, Jeff Jenkins @jeffj. */ const React = require('react'); const Markdown = require('react-remarkable'); const ReactCSSTransitionGroup = require('react-addons-css-transition-group'); const ToolTip = React.createClass({ propTypes: { location: React.PropTypes.array.isRequired, onClick: React.PropTypes.func.isRequired }, render: function() { const postionStyle = { display:'block', top:this.props.location[1], left:this.props.location[0] }; return <ReactCSSTransitionGroup transitionAppear={true} transitionName="fall" transitionAppearTimeout={200} transitionEnterTimeout={200} transitionLeaveTimeout={200} > <div style={postionStyle} className="popover top main-popover"> <div className="arrow arrow-link"></div> <div className="btn-group"> <button onClick={this.props.onClick} className="btn btn-primary"> <span className="glyphicon glyphicon-link" aria-hidden="true"></span> </button> </div> </div> </ReactCSSTransitionGroup> } }) module.exports = ToolTip;
Zotero.Idb = function(){ var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; this.indexedDB = indexedDB; // Now we can open our database var request = indexedDB.open("Zotero"); request.onerror = function(e){ Zotero.debug("ERROR OPENING INDEXED DB", 1); }; request.onupgradeneeded = function(event){ var db = event.target.result; Zotero.Idb.db = db; // Create an objectStore to hold information about our customers. We're // going to use "ssn" as our key path because it's guaranteed to be // unique. var itemStore = db.createObjectStore("items", { keyPath: "itemKey" }); var collectionStore = db.createObjectStore("collections", { keyPath: "itemKey" }); var tagStore = db.createObjectStore("tags", { keyPath: "itemKey" }); // Create an index to search customers by name. We may have duplicates // so we can't use a unique index. itemStore.createIndex("itemKey", "itemKey", { unique: false }); itemStore.createIndex("itemType", "itemType", { unique: false }); itemStore.createIndex("parentKey", "parentKey", { unique: false }); itemStore.createIndex("libraryKey", "libraryKey", { unique: false }); collectionStore.createIndex("name", "name", { unique: false }); collectionStore.createIndex("title", "title", { unique: false }); collectionStore.createIndex("collectionKey", "collectionKey", { unique: false }); collectionStore.createIndex("parentCollectionKey", "parentCollectionKey", { unique: false }); collectionStore.createIndex("libraryKey", "libraryKey", { unique: false }); tagStore.createIndex("name", "name", { unique: false }); tagStore.createIndex("title", "title", { unique: false }); tagStore.createIndex("libraryKey", "libraryKey", { unique: false }); //Zotero.Idb.itemStore = itemStore; //Zotero.Idb.collectionStore = collectionStore; //Zotero.Idb.tagStore = tagStore; /* // Store values in the newly created objectStore. for (var i in customerData) { objectStore.add(customerData[i]); } */ }; }; Zotero.Idb.addItems = function(items){ var transaction = db.transaction(["items"], IDBTransaction.READ_WRITE); transaction.oncomplete = function(event){ Zotero.debug("Add Items transaction completed.", 3); }; transaction.onerror = function(event){ Zotero.debug("Add Items transaction failed.", 1); }; var itemStore = transaction.objectStore("items"); for (var i in items) { var request = itemStore.add(items[i]); request.onsuccess = function(event){ Zotero.debug("Added Item " + event.target.result, 4); }; } }; Zotero.Idb.getItem = function(itemKey, callback){ Zotero.Idb.db.transaction("items").objectStore("items").get(itemKey).onsuccess = function(event) { callback(null, event.target.result); }; }; Zotero.Idb.getAllItems = function(callback){ var items = []; var objectStore = Zotero.Idb.db.transaction('items').objectStore('items'); objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { items.push(cursor.value); cursor.continue(); } else { callback(null, items); } }; };
/** * Showdown's Extension boilerplate * * A boilerplate from where you can easily build extensions * for showdown */ import showdown from 'showdown'; // This is the extension code per se // Here you have a safe sandboxed environment where you can use "static code" // that is, code and data that is used accros instances of the extension itself // If you have regexes or some piece of calculation that is immutable // this is the best place to put them. // The following method will register the extension with showdown showdown.extension('<%= pluginName %>', () => ({ type: 'lang', // or output filter(text, converter, options) { // your code here // ... // text is the text being parsed // converter is an instance of the converter // ... // don't forget to return the altered text. If you don't, nothing will appear in the output return text; }, regex: /foo/g, // if filter is present, both regex and replace properties will be ignored replace: 'bar', }));
import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' import firebase from 'firebase' Vue.use(Vuex) export default new Vuex.Store({ state: { current_user: null, questions: [], categories: [] }, mutations: { SET_CURRENT_USER: (state, user) => state.current_user = user, SET_QUESTIONS: (state, questions) => state.questions = questions.results, SET_CATEGORIES: (state, categories) => { for(var i = 0; i < categories.trivia_categories.length; i++){ var value = categories.trivia_categories[i].id var text = categories.trivia_categories[i].name state.categories.push({value, text}) } } }, actions: { set_current_user({ commit }){ if(firebase.auth().currentUser){ const currentUser = firebase.auth().currentUser commit('SET_CURRENT_USER', currentUser) } }, set_random_questions({ commit }){ axios.get('https://opentdb.com/api.php?amount=10') .then(response => { commit('SET_QUESTIONS', response.data) }) }, set_category_questions({commit}, category){ axios.get(`https://opentdb.com/api.php?amount=10&category=${category}`) .then(response => { commit('SET_QUESTIONS', response.data) }) }, get_categories({ commit }){ axios.get(`https://opentdb.com/api_category.php`) .then(response => { commit('SET_CATEGORIES', response.data) }) } }, getters: { } })
import { useState } from "react"; import Link from "next/link"; export default function Home() { const [contar, setContar] = useState(5); function somar() { setContar(contar + 1); } return ( <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", }} > <h1>Home</h1> <Link href="/sobre"> <a>Ir para sobre</a> </Link> </div> ); }
//server layer for setting up api and routes var express = require('express'); var app = express(); var serv = require('http').Server(app); var data = require('./data.js'); //static resource routing app.use('/client', express.static(__dirname + '/client')); //api routes for requesting data as json or csv app.get('/api/show', function(req, res) { //retrieve json data from data access layer data.getJsonData() .then(data => res.json(data)) .catch(err => res.send(err)); }); app.get('/api/download', function(req, res) { //retrieve csv data from data access layer data.getCsvData() .then(data => res.send(data)) .catch(err => res.send(err)); }); //route to index page app.get('/',function(req, res) { res.sendFile(__dirname + '/client/index.html'); }); //start server var port = process.env.PORT || 8080; serv.listen(port); console.log('Server listening on port', port);
function generateIntegers(m, n) { let array = [m]; let length = n - m; for ( var i = 1; i < length+1;i++){ array.push(m+i); } return array; console.log(array); }
import { Meteor } from 'meteor/meteor' import SitemapModel from 'utils/sitemap' Meteor.startup(() => { SitemapModel.update() })
var mongoose = require('mongoose'); //define schema of a work module.exports = mongoose.model('Education', { userId: String, institute: String, degree: String, startDate: String, endDate: String, description: String });
export default { API_HOST: 'https://dev.example.com/' };
function send(nomeFilme) { sessionStorage.setItem("filme", nomeFilme); window.location.href = "filme.html"; } function sendGenero(genero) { sessionStorage.setItem("genero", genero); window.location.href = "genero.html"; }
if(document.getElementById('article-ckeditor')){ CKEDITOR.replace('article-ckeditor'); }
const redis = require("redis") module.exports = { createConnection : () => { return new Promise((resolve, reject) => { // const client = redis.createClient() var client = require('redis').createClient(process.env.REDIS_URL); client.on('connect', () => { resolve(client) }) client.on('error', () => { reject("Error: Failed to connect") }) }).catch(err => console.log(err)); } } var myfunc = module.exports.createConnection(); myfunc.then(function () { console.log("Promise Resolved"); }).catch(function () { console.log("Promise Rejected"); });
'use strict'; define(['jquery', 'infobox', 'app/google-map', 'app/tpl/map/tooltip', 'markerClusterer', 'app/functions'], function ($, InfoBox, google, tpl) { /*** * Данные карты * @param {Object} $map - jQuery объект - карта * @constructor */ var Map = function Map($map) { this.isMobile = $(window).width() < 768; if ($map.data('noinit') !== undefined && this.isMobile) { return; } var attributData = $map.data(); var scriptData = window.map[$map[0].id]; var data = $.extend(scriptData, attributData); this.$map = $map; this.data = data || {}; this.markers = []; this.markerOpen = -1; this.data.fit = data.fit; this.data.minZoom = data.minzoom || 10; this.data.maxZoom = data.maxzoom || 18; if (data.center) { this.data.center = new google.maps.LatLng(data.center[0], data.center[1]); } this.options = { center: { lat: 59.939552, lng: 30.423428 }, zoom: 12, zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER }, streetViewControl: false, mapTypeControl: false, styles: false }; this.options = $.extend(this.options, this.data); this.initCustomZoomControls($map); this.initMap(); this.clickCustomZoomControls(); this.initBounds(); this.initMarkers(); this.imageBoundsInit(); this.initInfoWindow(); this.editor(); this.initTabs(); // this.initCluster(); }; /** * Инициализация карты */ Map.prototype.initMap = function () { this.map = new google.maps.Map(this.$map[0], this.options); }; /** * Сбор данных маркеров */ Map.prototype.initMarkers = function () { var that = this; if (!this.data.markers) { return; } $.each(this.data.markers, function (index, marker) { that.initMarker(index, marker); }); }; /** * Инициализация маркера на карте * @param {Number} index - номер маркера * @param {Object} data - данные маркера */ Map.prototype.initMarker = function (index, data) { var coords = new google.maps.LatLng(data.coords[0], data.coords[1]); var options = { map: this.map, position: coords, animation: google.maps.Animation.DROP, icon: data.image, type: data.type }; var marker = new google.maps.Marker(options); this.markers.push(marker); marker.setMap(this.map); if (this.data.zoom === undefined || this.data.fit !== undefined) { this.bounds.extend(coords); } this.bindMarkerClick(index, marker, data); }; /** * Клик по маркеру * @param {Number} index - номер маркера * @param {Object} marker - google marker * @param {Object} data - данные маркера */ Map.prototype.bindMarkerClick = function (index, marker, data) { var that = this; if (!data.title && !data.text && !data.url) { marker.setOptions({ clickable: false }); return; } google.maps.event.addListener(marker, 'click', function () { if (data.url) { that.markerLink(data.url); return; } that.infoWindow.setContent(tpl(data)); that.infoWindow.open(that.map, this); if (that.markerOpen !== -1) { that.markerShow(that.markerOpen); } that.markerOpen = index; that.markerHide(index); }); }; /** * Скрыть маркер * @param {Number} index - порядковый номер маркера */ Map.prototype.markerHide = function (index) { this.markers[index].setVisible(false); }; /** * Показать маркер * @param {Number} index - порядковый номер маркера */ Map.prototype.markerShow = function (index) { this.markers[index].setVisible(true); }; Map.prototype.markerToggle = function (type) { $.each(this.markers, function (index, marker) { if (!marker.type) { return; } var isVisible = type === 0 || marker.type === type; marker.setVisible(isVisible); }); }; /** * Балун */ Map.prototype.initInfoWindow = function () { var that = this; this.infoWindow = new InfoBox({ content: '', disableAutoPan: false, maxWidth: 0, pixelOffset: new google.maps.Size(-55, -83), zIndex: null, closeBoxMargin: '0px 0px 0px 0px', closeBoxURL: '', infoBoxClearance: new google.maps.Size(10, 10), isHidden: false, pane: 'floatPane', enableEventPropagation: false, boxStyle: { width: 'auto' } }); google.maps.event.addListener(this.map, 'click', function () { that.closeInfoWindow(); }); this.infoWindow.addListener('domready', function () { var $infoBox = $('.infoBox'); var $width; var $height; var $arrow = $infoBox.find('.b-map-tooltip__arrow'); var $closeInfoWindow = $('.b-map-tooltip__close'); var $image = $infoBox.find('img'); if ($image.length) { $image.load(function () { $width = $infoBox.width(); $height = $infoBox.height() + $arrow.outerHeight(); that.infoWindow.setOptions({ pixelOffset: new google.maps.Size(-$width / 2, -$height) }); }); } else { $width = $infoBox.width(); $height = $infoBox.height() + $arrow.outerHeight(); that.infoWindow.setOptions({ pixelOffset: new google.maps.Size(-$width / 2, -$height) }); } $closeInfoWindow.click(function () { that.closeInfoWindow(); }); }); }; /** * Закрытие балуна */ Map.prototype.closeInfoWindow = function () { if (this.markerOpen !== -1) { this.markerShow(this.markerOpen); } this.markerOpen = -1; this.infoWindow.close(); }; /** * Маркер с ссылкой * @param {String} url - ссыллка */ Map.prototype.markerLink = function (url) { var isLocalLink = url.indexOf(window.location.origin) + 1; if (isLocalLink) { window.location.href = url; } else { window.open(url); } }; /** * Инициализация картинки на карте */ Map.prototype.imageBoundsInit = function () { var data = this.data.imageBounds; if (!data) { return; } var coords = new google.maps.LatLng(data.coords[0], data.coords[1]); var options = { map: this.map, position: coords, icon: data.icon }; var marker = new google.maps.Marker(options); this.markers.push(marker); var imageBounds = this.data.imageBounds; this.imageBounds = { north: imageBounds.north, west: imageBounds.west, south: imageBounds.south, east: imageBounds.east }; this.historicalOverlay = new google.maps.GroundOverlay(imageBounds.image, this.imageBounds); this.historicalOverlay.setMap(this.map); this.imageBoundsZoomChange(); }; Map.prototype.imageBoundsZoomChange = function () { var that = this; var currentZoom = this.map.getZoom(); var changeView = 14; function toggleView(zoom) { if (zoom <= changeView) { that.historicalOverlay.setMap(null); that.markerShow(that.markers.length - 1); } else { that.historicalOverlay.setMap(that.map); that.markerHide(that.markers.length - 1); } } toggleView(currentZoom); this.map.addListener('zoom_changed', function () { currentZoom = that.map.getZoom(); toggleView(currentZoom); }); }; /** * Определение крайних позиций маркеров на карте */ Map.prototype.initBounds = function () { if (this.data.zoom !== undefined && this.data.fit === undefined) { return; } this.bounds = new google.maps.LatLngBounds(); this.fitBounds(this.bounds); }; /** * Изменение области отображения карты, так чтобы были видны все маркеры */ Map.prototype.fitBounds = function (bounds) { this.map.fitBounds(bounds); }; /** * Инициализация кастомного зума * @param {Object} $map - jQuery Object - разметка карты */ Map.prototype.initCustomZoomControls = function ($map) { this.$zoomIn = $map.siblings('.b-map__zoom-in'); this.$zoomOut = $map.siblings('.b-map__zoom-out'); if (this.$zoomIn.length && this.$zoomOut.length) { this.options.zoomControl = false; } }; /** * Клики по кастомным контролам зума */ Map.prototype.clickCustomZoomControls = function () { var that = this; this.map.addListener('zoom_changed', function () { var currentZoom = that.map.getZoom(); if (currentZoom === that.options.maxZoom) { that.$zoomIn.hide(); } else { that.$zoomIn.show(); } if (currentZoom === that.options.minZoom) { that.$zoomOut.hide(); } else { that.$zoomOut.show(); } }); this.$zoomIn.click(function () { that.map.setZoom(that.map.getZoom() + 1); if (that.map.getZoom() === that.options.maxZoom) { that.$zoomIn.hide(); } else { that.$zoomOut.show(); } }); this.$zoomOut.click(function () { that.map.setZoom(that.map.getZoom() - 1); if (that.map.getZoom() === that.options.minZoom) { that.$zoomOut.hide(); } else { that.$zoomIn.show(); } }); }; Map.prototype.initTabs = function () { var $tabsWrapper = this.$map.parents('.b-map__cnt').find('.b-map-tabs'); if (!$tabsWrapper.length) { return; } var that = this; var $tabItems = $tabsWrapper.find('.b-map-tabs__item'); var active = 'is-active'; var $tabBtnToggleContent = $tabsWrapper.find('.b-map-tabs__btn'); var $tabContent = $tabsWrapper.find('.b-map-tabs__list'); $tabItems.click(function (e) { e.preventDefault(); $tabItems.removeClass(active); $(this).addClass(active); that.closeInfoWindow(); that.markerToggle($(this).find('a').data('type')); $tabContent.removeClass(active); }); $tabBtnToggleContent.click(function (e) { e.preventDefault(); $tabContent.toggleClass(active); }); if (this.isMobile) { google.maps.event.addListener(this.map, 'click', function () { $tabContent.removeClass(active); }); } }; /** * Режим создания/редактирования карты */ Map.prototype.editor = function () { if (!this.data.editor) { return; } google.maps.event.addListener(this.map, 'click', function (e) { console.log('[' + e.latLng.lat().toFixed(6) + ',' + e.latLng.lng().toFixed(6) + ']'); }); }; return Map; });
const express = require('express') const Papers = require('./../models/paper') const router = express.Router() router.get('/new', (req, res) => { res.render('papers/new', { papers: new Papers() }) }) router.get('/edit/:id', async (req, res) => { const papers = await Papers.findById(req.params.id) res.render('papers/edit', { papers: papers }) }) router.get('/:slug', async (req, res) => { const papers = await Papers.findOne({ slug: req.params.slug }) if (papers == null) res.redirect('/') res.render('papers/show', { papers: papers }) }) router.post('/', async (req, res, next) => { req.papers = new Papers() next() }, saveArticleAndRedirect('new')) router.put('/:id', async (req, res, next) => { req.papers = await Papers.findById(req.params.id) next() }, saveArticleAndRedirect('edit')) router.delete('/:id', async (req, res) => { await Papers.findByIdAndDelete(req.params.id) res.redirect('/papers') }) function saveArticleAndRedirect(path) { return async (req, res) => { let papers = req.papers papers.title = req.body.title papers.author = req.body.author papers.description = req.body.description papers.markdown = req.body.markdown try { papers = await papers.save() res.redirect(`/papers/${papers.slug}`) } catch (e) { res.render(`papers/${path}`, { papers: papers }) } } } module.exports = router
const { gql } = require("apollo-server"); // TODO - extend external type Review with Booking -- DONE // TODO - extend external type User with Review (recieved -- as coach) -- NOT NECESSARY // TODO - extend external type User with Review (given -- as reviewer) -- NOT NECESSARY const typeDefs = gql` # The Query type lists all the different queries (Retrieve operations) that front-end can make from this Endpoint # We can name these whatever we want. "Banana" words extend type Query { interviewQinfo: String! posts( industry: String price: String orderBy: String tags: String ids: [String] ): [Post!]! post(id: String!): Post! postByCoach(coach_id: String!): Post! industries: [Industry]! industry(name: String!): [Post!]! availabilities: [Availability] availabilitiesByCoach(coach_id: String!): [Availability] availabilityByUniquecheck(uniquecheck: String!): Availability! bookings: [Booking] bookingsByCoach(coach_id: String!): [Booking] bookingsBySeeker(seeker_id: String!): [Booking] bookingByUniquecheck(uniquecheck: String!): Booking! # responseByBooking(uniqueBooking: String!): Response reports: [Report] reportsByCoach(coach_id: String!): [Report] reportsBySeeker(seeker_id: String!): [Report] reportByBooking(uniqueBooking: String!): Report } # *************************************************** # The Mutation type lists all the different CUD (Create, Update, Delete) operations that front-end can make from this Endpoint type Mutation { createPost( price: Int position: String industryName: String description: String tagString: String company: String isPublished: Boolean! ): Post! deletePost: Post! updatePost( id: ID! price: Int position: String industryName: String description: String tagString: String company: String isPublished: Boolean ): Post! removeTagFromPost(id: ID!, tagID: String): Post! createAvailability( hour: Int! minute: Int! # coach: String! # bookingId: String year: Int! month: Int! day: Int! recurring: Boolean! ): Availability! deleteAvailability(uniquecheck: String!): Availability! createBooking( year: Int! month: Int! day: Int! hour: Int! minute: Int! coach: String! # seeker: String! availabilityA: String! availabilityB: String! pending: Boolean confirmed: Boolean interviewGoals: String interviewQuestions: String resumeURL: String price: Int! ): Booking! deleteBooking(uniquecheck: String!): Booking! createReport( # coach: String! # seeker: String! uniqueBooking: String! firstImpression_rating: Int! firstImpression_comment: String! resume_rating: Int! resume_comment: String! professionalism_rating: Int! professionalism_comment: String! generalAttitude_rating: Int! generalAttitude_comment: String! technicalProficiency_rating: Int! technicalProficiency_comment: String! contentOfAnswers_rating: Int! contentOfAnswers_comment: String! communication_rating: Int! communication_comment: String! ): Report! updateReport(id: String!): Report! createCoachReport( # coach: String! # seeker: String! uniqueBooking: String! firstImpression_rating: Int! firstImpression_comment: String! resume_rating: Int! resume_comment: String! professionalism_rating: Int! professionalism_comment: String! generalAttitude_rating: Int! generalAttitude_comment: String! technicalProficiency_rating: Int! technicalProficiency_comment: String! contentOfAnswers_rating: Int! contentOfAnswers_comment: String! communication_rating: Int! communication_comment: String! ): CoachReport! } # *************************************************** # All of the types below are ones that we create and are what make up the different tables in our Prisma database. # Every created type needs an ID, which will be a random string of characters generated by Prisma #The datamodel.prisma file should match this part, although that file includes @id for every primary key ID scalar DateTime type Post { id: ID! price: Int! position: String! industry: Industry! description: String! tags: [Tag]! coach: User! company: String! isPublished: Boolean! createdAt: DateTime! lastUpdated: DateTime! } # Associates posts, availability, bookings, etc with User extend type User @key(fields: "authId") { authId: String! @external post: Post availability: [Availability] coach_bookings: [Booking] seeker_bookings: [Booking] } type Industry { id: ID! name: String! posts: [Post]! } type Tag { id: ID! name: String! posts: [Post]! } type Availability { id: ID! hour: Int! minute: Int! coach: User! bookingID: String year: Int! month: Int! day: Int! uniquecheck: String! isOpen: Boolean! recurring: Boolean! } type Booking @key(fields: "id") { id: ID! year: Int! month: Int! day: Int! hour: Int! minute: Int! coach: User! seeker: User! uniquecheck: String! availability: [Availability]! pending: Boolean confirmed: Boolean interviewGoals: String interviewQuestions: String resumeURL: String report: Report price: Int! review: Review # response: Response } extend type Review @key(fields: "job") { job: String! @external } type Report { id: ID! coach: User! seeker: User! booking: Booking! firstImpression_rating: Int! firstImpression_comment: String! resume_rating: Int! resume_comment: String! professionalism_rating: Int! professionalism_comment: String! generalAttitude_rating: Int! generalAttitude_comment: String! technicalProficiency_rating: Int! technicalProficiency_comment: String! contentOfAnswers_rating: Int! contentOfAnswers_comment: String! communication_rating: Int! communication_comment: String! createdAt: DateTime! isSent: Boolean } type CoachReport { id: ID! coach: User! seeker: User! booking: Booking! firstImpression_rating: Int! firstImpression_comment: String! resume_rating: Int! resume_comment: String! professionalism_rating: Int! professionalism_comment: String! generalAttitude_rating: Int! generalAttitude_comment: String! technicalProficiency_rating: Int! technicalProficiency_comment: String! contentOfAnswers_rating: Int! contentOfAnswers_comment: String! communication_rating: Int! communication_comment: String! createdAt: DateTime! isSent: Boolean } `; module.exports = typeDefs;
$("#loginBtn .form input[name='businessDbId']").attr("dbId",dbid);
import React from 'react' import classes from './PlanPage.module.css' import {Link} from 'react-router-dom' import axios from 'axios' const PlanPage=(props)=>{ const [state,setState]=React.useState({}) React.useEffect(()=>{ if(props.location.session==undefined && Object.keys(state)==0){ axios.get("https://5f89f1c718c33c0016b3146e.mockapi.io/session") .then(resp =>{ console.log(resp.data) resp.data.map(item=>{ if(item.id==props.match.params.id){ console.log(item.id) setState({...item}) } }) }) .catch(err =>{ console.log("Call Failed"); }) } }) return( <div className={classes.MainDiv}> <h1>Session Plan</h1> <h3 className={classes.PlanHeading}>Topics:</h3> { props.location.session!=undefined?props.location.session.topics.map(item=>{ return <p>{`- ${item}`}</p> }): state.topics!=undefined?state.topics.map(item=>{ return <p>{`- ${item}`}</p> }):null } <h3 className={classes.PlanHeading}>Session Link:</h3> <p>{props.location.session!=undefined?props.location.session.link:state.link!=undefined?state.link:null}</p> <h3 className={classes.PlanHeading}>Meeting Password</h3> <p>{props.location.session!=undefined?props.location.session.password:state.password!=undefined?state.password:null}</p> </div> ) } export default PlanPage;
const Create = () => { return ( <p>Hello this is create age</p> ); } export default Create;
import React from 'react'; import './animate.css'; import Navbar from './components/Navbar'; import Sidebar from './components/sidebar/Sidebar'; import Map from './components/Map'; import Api from './components/Api'; import Form from './components/Form'; import SignInForm from './components/SignInForm'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import './App.css'; // import Backdrop from './components/sidebar/Backdrop'; class App extends React.Component { state = { sidebarOpen: false, }; ToggleClickHandler = () => { this.setState((prevState) => { return { sidebarOpen: !prevState.sidebarOpen }; }); }; backdropClickHandler = () => { this.setState({ sidebarOpen: false }); }; render() { let sidebar; // let backdrop; if (this.state.sidebarOpen) { sidebar = <Sidebar />; // backdrop = <Backdrop click={this.backdropClickHandler} />; } return ( <Router> <div style={{height: '100%'}}> <Navbar drawerClickHandler={this.ToggleClickHandler} /> {sidebar} <Switch> <Route path="/travel-plug/stations" exact component={Api}/> <Route path="/travel-plug/login" exact component={SignInForm}/> <Route exact path="/travel-plug/register" component={Form}/> <Route exact path="/travel-plug/" component={Map}/> {/* <Route path="/" component={} /> */} {/* {backdrop} */} {/* <Map /> */} </Switch> </div> </Router> ); } } export default App;
const express = require('express'); const db = require('./mongoDB-connection/dbConnection'); const app = express(); const cors = require('cors'); const patientRoute = require('./routes/patient'); const doctorRoute = require('./routes/doctor'); const nurseRoute = require('./routes/nurse'); const appointmentRoute = require('./routes/appointment'); const visitRoute = require('./routes/visit'); const invoiceRoute = require('./routes/invoice'); const paymentRoute = require('./routes/payment'); const adminRoute = require('./routes/admin'); const loginRoute = require('./routes/login'); app.use(cors()); app.use(express.json()); app.use(patientRoute.app); app.use(doctorRoute.app); app.use(nurseRoute.app); app.use(appointmentRoute.app); app.use(visitRoute.app); app.use(invoiceRoute.app); app.use(paymentRoute.app); app.use(adminRoute.app); app.use(loginRoute.app); // PORT const port = process.env.PORT || 3001; db.getDBConnection().then(err => { if (!err) { app.listen(port, () => { console.log(`server is running on port number ${port}...`); }); } });
const express = require('express'); const path = require('path'); const app = express(); const port = process.env.PORT || 8080; app.use(express.static('build')); app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization'); next(); }); app.listen(port, function(){ console.log(`Server started on port ${port}`) });
import logo from './logo.svg'; import './App.css'; import { Typography } from '@material-ui/core'; import Navbar from './components/Navbar' import Slider from './components/slider' import Products from './components/Products' import {React,Fragment, useState, useEffect} from 'react' import {BrowserRouter,Route,Switch} from 'react-router-dom' import Cart from './components/Cart' import Chekout from './components/Chekout' const cartFromStorage = JSON.parse(localStorage.getItem('cart') || "[]"); function App() { const [cart,setCart] =useState(cartFromStorage); const [search, setSearch] = useState(""); useEffect(() => { localStorage.setItem("cart",JSON.stringify(cart)); }, [cart]) const [show, setShow] = useState(true); const [products,setProducts] =useState([ { id : 1, name : 'Toy Car', price:2000, description:"Ver Good Product", image:"https://images.unsplash.com/photo-1581235720704-06d3acfcb36f?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fHByb2R1Y3R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { id : 2, name : 'Bicycle', price:15990, description:"Ver Good Product", image:'https://images.unsplash.com/photo-1532298229144-0ec0c57515c7?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzF8fHByb2R1Y3R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' }, { id : 3, name : 'Soda', price:1000, description:"Ver Good Product", image:"https://images.unsplash.com/photo-1570831739435-6601aa3fa4fb?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MjJ8fHByb2R1Y3R8ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" } ]); const addToCart = (product) => { let newCart = [...cart]; let itemInCart = newCart.find((item) => product.name === item.name); if(itemInCart){ itemInCart.quantity++; } else{ itemInCart = { ...product, quantity:1 } newCart.push(itemInCart); } // setCart([...cart,{...product}]); setCart(newCart); } const removeFromCart = (productRemove) => { setCart(cart.filter((product) => product !== productRemove)) } const clearCart = () => { console.log("cleared"); setCart([]); } const getProductsTotal = () => { return cart.reduce((sum , {price,quantity}) => sum + price * quantity ,0); } const getTotalCart = () => { return cart.reduce((sum , {quantity}) => sum + quantity ,0); } const setQuantity = (product,amount) => { const newCart = [...cart]; newCart.find((item) => product.name === item.name ).quantity = amount; if (product.quantity == 0) { setCart(newCart.filter((x) => x.id !== product.id)); } else { setCart(newCart) } } return ( <BrowserRouter> <Fragment> <Route path="/" exact component={Products}> <Navbar totalItems= {getTotalCart()} /> <Slider /> <Products products ={products} addToCart={addToCart} /> </Route> <Route path="/cart" exact component={Cart}> <Navbar totalItems= {getTotalCart()} /> <br></br> <br></br> <br></br> <br></br> <Cart cart ={cart} removeFromCart={removeFromCart} clearCart={clearCart} getProductsTotal={getProductsTotal} setQuantity={setQuantity} /> </Route> <Route path="/checkout" exact component={Chekout}> <Chekout totalItems= {getTotalCart()} cart ={cart} getProductsTotal={getProductsTotal}/> </Route> </Fragment> </BrowserRouter> ); } export default App;
import React from 'react'; import Layout from '@theme/Layout'; import GuideItems from '@theme/GuideItems'; import Link from '@docusaurus/Link'; function GuideCategoryPage(props) { const { metadata: { category }, items } = props; return ( <Layout title={`${category.title} Guides`} description={`All ${category.title} guides`} > <header className="hero hero--clean"> <div className="container"> <h1>{category.title} Guides</h1> {category.description && ( <div className="hero--subtitle">{category.description}</div> )} <div> <Link to="/guides">View All Guides</Link> </div> </div> </header> <main className="container container--s"> <GuideItems items={items} staggered={items[0].content.metadata.seriesPosition != null} /> </main> </Layout> ); } export default GuideCategoryPage;
module.exports = function(app) { var MongoDB = app.dataSources.MongoDB; MongoDB.automigrate('Role', function(err) { if (err) throw (err); var Role = app.models.Role; //create the admin role Role.create({ name: 'admin' }, function(err, originalRole) { if (err) throw (err); //make admin console.log('Admin role created.'); MongoDB.automigrate('Customer', function(err) { if (err) throw (err); var Customer = app.models.Customer; Customer.create([ {username: 'admin', email: 'sm8a76@gmail.com', password: 'abcdef'}, {username: 'smendoza', email: 'sm8a76@gmail.com', password: 'abcdef'}, {username: 'jsmith', email: 'sm8a76@gmail.com', password: 'abcdef'} ], function(err, users) { if (err) throw (err); var Role = app.models.Role; var RoleMapping = app.models.RoleMapping; console.log('Admin, smendoza and jsmith users created.'); Role.find({name: 'Admin'}, function(err, role){ if (err) throw (err); //make admin originalRole.principals.create({ principalType: RoleMapping.USER, principalId: users[0].id }, function(err, principal) { if (err) throw (err); console.log('Role principal for admin created.'); MongoDB.automigrate('Supermarket', function(err) { if (err) throw (err); var Supermarket = app.models.Supermarket; Supermarket.create([ {name: 'HEB Puerta de Hierro'}, {name: 'Walmart Cumbres'}, {name: 'Soriana Lincoln'} ], function(err, supermarkets) { if (err) throw (err); console.log('Supermarket created and populated.'); MongoDB.automigrate('Grocery', function(err) { if (err) throw (err); var Grocery = app.models.Grocery; Grocery.create([ {name: 'Leche Entera Santa Clara', description: 'Leche Entera Santa Clara', image: 'images/leche-entera-santaclara.png', unit: 'Litros', madeBy: 'Santa Clara'}, {name: 'Leche Entera Lala', description: 'Leche Entera Lala', image: 'images/leche-entera-lala.jpeg', unit: 'Litros', madeBy: 'Lala'}, {name: 'Leche Deslactosada Santa Clara', description: 'Leche Deslactosada Santa Clara', image: 'images/leche-deslactosada-santaclara.jpg', unit: 'Litros', madeBy: 'Santa Clara'}, {name: 'Leche Deslactosada Parmalat', description: 'Leche Deslactosada Parmalat', image: 'images/leche-deslactosada-parmalat.jpg', unit: 'Litros', madeBy: 'Parmalat'}, {name: 'Azucar Mascabado BlackSugar', description: 'Azucar Mascabado BlackSugar', image: 'images/Azucar_mascabado_grande.jpg', unit: 'Kg', madeBy: ''}, {name: 'Tomates Rojos', description: 'Tomates Rojos', image: 'images/tomates.jpg', unit: 'Kg', madeBy: ''}, {name: 'Limones', description: 'Limones', image: 'images/limones.jpg', unit: 'Kg', madeBy: ''} ], function(err, groceries) { if (err) throw (err); console.log('Groceries created and populated.'); }); // Grocery.create([ }); // MongoDB.automigrate('Grocery', function(err) { }); //Supermarket.create([ }); //MongoDB.automigrate('Supermarket', function(err) { }); // role.principals.create({ }); //Role.find({name: 'Admin'}, function(err, role){ }); //Customer.create([ }); //MongoDB.automigrate('Customer', function(err) { }); //Role.create({ }); //MongoDB.automigrate('Role', function(err) { };
import React, {Component} from 'react' import {AsideNav} from '../../components/AsideNav/AsideNav' import {Header} from '../../components/Header/Header' import {Track} from '../../components/Track/Track' import firebase from 'firebase'; import {store} from "../../store/index"; import NavLink from "react-router-dom/es/NavLink"; export class Playlist extends React.Component { componentWillUnmount(){ clearTimeout(this.timeout1); } constructor(props){ super(props); let title = props.location.search.toString().substr(1, props.location.search.toString().length-1); title = title.replace(/%20/g, " "); this.state = { playlist: [], title: props.location.search.toString().substr(1, props.location.search.toString().length-1).replace(/%20/g, " ") }; let currentUser = {uid: store.getState().auth.uid}; let playlist = []; if(currentUser.uid){ firebase.database().ref(`users/${currentUser.uid}/playlist/${title}/items`).once("value", function (snapshot) { snapshot.forEach(function (snap) { if(snap.val().id){ firebase.database().ref(`podcasts/${snap.val().id}`).once("value", function (podcast) { if(podcast.val()){ let profileImage = ''; let podcastURL = ''; let favorited = false; if(currentUser){ firebase.database().ref(`users/${currentUser.uid}/favorites/${podcast.val().id}`).once('value', function (fav) { if(fav.val()){ favorited = true; } }) } if(podcast.val().rss){ firebase.database().ref(`users/${podcast.val().podcastArtist}/profileImage`).once("value", function (image) { if(image.val().profileImage){ profileImage = image.val().profileImage; } }); podcastURL = podcast.val().podcastURL; } else{ const storageRef = firebase.storage().ref(`/users/${podcast.val().podcastArtist}/image-profile-uploaded`); storageRef.getDownloadURL() .then(function(url) { profileImage = url; }).catch(function(error) { // }); firebase.storage().ref(`/users/${podcast.val().podcastArtist}/${podcast.val().id}`).getDownloadURL().catch(() => {console.log("file not found")}) .then(function(url){ podcastURL = url; }); } let username = ''; firebase.database().ref(`users/${podcast.val().podcastArtist}/username`).once("value", function (name) { if(name.val().username){ username = name.val().username } }); setTimeout(() => { let ep = {podcastTitle: podcast.val().podcastTitle, podcastArtist: podcast.val().podcastArtist, id: podcast.val().id, username: username, profileImage: profileImage, podcastURL: podcastURL, favorited: favorited}; playlist.push(ep); }, 1000); } }) } }); }); } this.timeout1 = setTimeout(() => {this.setState({playlist: playlist, title: title })}, 2000); } render() { return ( <div> <Header props={this.props}/> <div className="tcontent"> <AsideNav/> <div className="tsscrollwrap"> <div className="tsscrollcontent"> <div className="container"> <div className="trow-header"> <div className={"tsHeaderTitles"}> <h2>{store.getState().auth.loggedIn ? this.state.title : 'Log in to see your playlists!'}</h2> </div> <div className={"tsHeaderTitles"}> <NavLink to={`/playlists`}> <a onClick={() => { let currentUser = {uid: store.getState().auth.uid}; if(currentUser.uid){ let title = this.state.title; firebase.database().ref(`users/${currentUser.uid}/playlist/${title}`).remove() } }}>delete</a> </NavLink> </div> </div> <div className="row"> {this.state.playlist.map((_, i) => ( <div key={i} className="col-xs-4 col-sm-4 col-md-3 col-lg-2"> <Track menukey={i} podcast={_}/> </div> ))} </div> </div> </div> </div> </div> </div> ) } }
const Conference = {}; Conference.attendee = function (firstName = 'None', lastName = 'None') { let checkedIn = false; let checkInNumber; return { getFullName: function () { return `${firstName} ${lastName}`; }, isCheckedIn: function () { return checkedIn; }, checkIn: function () { checkedIn = true; }, getCheckInNumber: function () { return checkInNumber; }, setCheckInNumber: function (number) { checkInNumber = number; }, undoCheckIn: function () { checkedIn = false; checkInNumber = undefined; }, }; }; Conference.attendeeCollection = function () { let attendees = []; return { contains: function (attendee) { return attendees.some((_attendee) => _attendee.getFullName() === attendee.getFullName()); }, add: function (attendee) { if (!this.contains(attendee)) { attendees.push(attendee); } }, remove: function (attendee) { if (this.contains(attendee)) { attendees = attendees.filter((_attendee) => _attendee !== attendee); } }, iterate: function (callback) { // attendees의 각 attendee에 대해 콜백을 실행한다. attendees.forEach((attendee) => callback(attendee)); }, }; }; Conference.checkInRecorder = function () { const messages = { mustBeCheckedIn: '참가자는 체크인 된 것으로 표시되어야 합니다.', }; return { recordCheckIn(attendee) { return new Promise((resolve, reject) => { if (attendee.isCheckedIn()) { resolve(4444); } else { reject(new Error(messages.mustBeCheckedIn)); } }); }, getMessages() { return messages; }, }; }; Conference.checkInService = function (recorder) { return { checkIn(attendee) { return new Promise((resolve, reject) => { attendee.checkIn(); recorder.recordCheckIn(attendee).then( function onRecordCheckInSucceeded(checkInNumber) { attendee.setCheckInNumber(checkInNumber); resolve(checkInNumber); }, function onRecordCheckInFailed(reason) { attendee.undoCheckIn(); reject(reason); }, ); }); }, }; }; Conference.checkedInAttendeeCounter = function () { let checkedInAttendeesCount = 0; const self = { getCount() { return checkedInAttendeesCount; }, increment() { checkedInAttendeesCount++; }, countIfCheckedIn(attendee) { if (attendee.isCheckedIn()) { self.increment(); } }, }; return self; }; const checkInService = Conference.checkInService(Conference.checkInRecorder); const attendees = Conference.attendeeCollection(); attendees.iterate(checkInService.checkIn); export { Conference };
import React, { Fragment } from 'react'; import useSWR from "swr"; import client from '../lib/sanity'; import IntroModule from '../components/introModule.js'; import '../styles/app.scss'; import SocialModule from '../components/socialModule.js'; import FeatureModule from '../components/featureModule.js'; import SupportModule from '../components/supportModule.js'; import Footer from '../components/footer.js'; import NavBar from '../components/navbar.js' const query = ` { "introModule": *[_type == "introModule"][0], "featureModule": *[_type == "featureModule"][0], "socialModule": *[_type == "socialModule"][0], "supportModule": *[_type == "supportModule"][0], "footerModule": *[_type == "footerModule"][0], }`; function LandingPage(props) { const { data: moduleData, error } = useSWR(query, query => client.fetch(query) ) if (error) { return <div className="App">We're sorry, something wrong happened. <a href="mailto:contact@wemunity.org">Let us know about it.</a></div> } return ( <div className="App"> <NavBar {...props} theme="dark" /> { /* Suspense can't come soon enough */ moduleData ? <Fragment> <IntroModule m={moduleData.introModule} /> <SocialModule m={moduleData.socialModule} /> <FeatureModule m={moduleData.featureModule} /> <SupportModule m={moduleData.supportModule} /> <Footer m={moduleData.footerModule} /> </Fragment> : <div className="App">Loading</div> } </div> ); } export default LandingPage;
/** 2. * System configuration for Angular samples 3. * Adjust as necessary for your application needs. 4. */ 5.(function (global) { 6. System.config({ 7. paths: { 8. // paths serve as alias 9. 'npm:': 'node_modules/' 10. }, 11. // map tells the System loader where to look for things 12. map: { 13. // our app is within the app folder 14. app: 'app', 15. 16. // angular bundles 17. '@angular/core': 'npm:@angular/core/bundles/core.umd.js', 18. '@angular/common': 'npm:@angular/common/bundles/common.umd.js', 19. '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', 20. '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', 21. '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', 22. '@angular/http': 'npm:@angular/http/bundles/http.umd.js', 23. '@angular/router': 'npm:@angular/router/bundles/router.umd.js', 24. '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', 25. 26. // other libraries 27. 'rxjs': 'npm:rxjs', 28. 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api', 29. }, 30. // packages tells the System loader how to load when no filename and/or no extension 31. packages: { 32. app: { 33. main: './main.js', 34. defaultExtension: 'js' 35. }, 36. rxjs: { 37. defaultExtension: 'js' 38. }, 39. 'angular-in-memory-web-api': { 40. main: './index.js', 41. defaultExtension: 'js' 42. } 43. } 44. }); 45.})(this);
import React, { Component } from 'react'; // import Img from '../images/code-cloud-v6.png'; // import Img from '../images/simple-shapes-feat-img.png'; class FeaturedImg extends Component { static defaultProps = { pageTitle: "" } render(){ return( <div> <div className="Featured-img-container Fade-in"> <div className="Page-title-container"> <h1 className="Page-title">{this.props.pageTitle}</h1> </div> </div> </div> ); } } export default FeaturedImg;
let shelljs = require('shelljs') console.log('entry client directory') shelljs.cd('./client') console.log('run `npm run build`') shelljs.exec('npm run build') console.log('return root category`') shelljs.cd('..') console.log('remove old static`') shelljs.rm('-rf', './dist/client') shelljs.mkdir('-p', './dist/client/dist') console.log('copy new static`') shelljs.cp('./client/dist/*', './dist/client/dist/') console.log('client 构建完毕')
import { handleActions } from 'redux-actions' import { RECEIVE_AGGREGATIONS, } from 'actions/search' const initialState = {}; export default handleActions({ RECEIVE_AGGREGATIONS: (state, action) => { const { term } = action.data.entities return Object.assign({}, state, term) }, }, initialState);
import { combineReducers } from 'redux'; import collectionReducer from './collectionReducer'; export default combineReducers({ collections: collectionReducer, });
import { BASE_URL, apiFetch } from "./api_fetch.js"; export function listCategories() { return apiFetch(`${BASE_URL}/categories`, { method: 'GET', headers: { Authorization: `Token token=${sessionStorage.getItem('token')}` } }) } export function createCategory(name, transaction_type) { return apiFetch(`${BASE_URL}/categories`, { method: 'POST', headers: { "Content-Type": "application/json", Authorization: `Token token=${sessionStorage.getItem('token')}` }, body: JSON.stringify({ name, transaction_type }) }) } export function showCategory(categoryId) { return apiFetch(`${BASE_URL}/categories/${categoryId}`, { method: 'GET', headers: { Authorization: `Token token=${sessionStorage.getItem('token')}` } }) } export function deleteCategory(categoryId) { return apiFetch(`${BASE_URL}/categories/${categoryId}`, { method: 'DELETE', headers: { Authorization: `Token token=${sessionStorage.getItem('token')}` } }) }
// test_setSampleDataGeneralLighting_3.js // 2017.08.17 let properties = { "On" : false, "Brightness" : 70, "OperatingMode": "normal", "RGB": {"r":100, "g":200, "b":150} }; global.set("GeneralLighting_3", properties); return msg;
import { FILTER_EDITABLE_DATASETS, EDIT_DATASET, FIND_AND_REPLACE_DATASETS, DELETE_DATASETS, TOGGLE_TABLE_FILTERS, CLEAR_DATASETS } from './datasets'; // Actions of both (editable_datasets and waiting_datasets) are found in their respective file const INITIAL_STATE = { datasets: [], pages: 0, count: 0, filter: {}, sortings: [], filterable: false }; export default function(state = INITIAL_STATE, action) { const { type, payload } = action; switch (type) { case FILTER_EDITABLE_DATASETS: return { ...state, datasets: payload.datasets, pages: payload.pages, count: payload.count, filter: action.filter, sortings: action.sortings }; case EDIT_DATASET: return { ...state, datasets: editDatasetHelper(state.datasets, payload) }; case FIND_AND_REPLACE_DATASETS: return { ...state, datasets: findAndReplaceHelper(state.datasets, payload) }; case DELETE_DATASETS: return { ...state, datasets: findAndDelete(state.datasets, payload) }; case TOGGLE_TABLE_FILTERS: return { ...state, filterable: !state.filterable }; case CLEAR_DATASETS: return INITIAL_STATE; default: return state; } } const findId = (array, run_number, dataset_name) => { for (let i = 0; i < array.length; i++) { if (array[i].run_number === run_number && array[i].name === dataset_name) { return i; } } return null; }; const editDatasetHelper = (datasets, new_dataset) => { const index = findId(datasets, new_dataset.run_number, new_dataset.name); if (index !== null) { return [ ...datasets.slice(0, index), new_dataset, ...datasets.slice(index + 1) ]; } // If it didn't find it, it means it was just created: return [new_dataset, ...datasets]; }; const findAndReplaceHelper = (datasets, new_datasets) => { new_datasets.forEach(new_dataset => { datasets = editDatasetHelper(datasets, new_dataset); }); return datasets; }; const findAndDelete = (datasets, deleted_datasets) => { const new_datasets = datasets.filter(dataset => { const { run_number, name } = dataset; let dataset_deleted = deleted_datasets.some(dataset => { return dataset.run_number === run_number && dataset.name === name; }); return !dataset_deleted; }); return new_datasets; };
import { faSortNumericUpAlt } from "@fortawesome/free-solid-svg-icons"; import { yellow } from "@material-ui/core/colors"; import React, { Component } from "react"; import Loader from "react-loader-spinner"; import { DIV_HIGHT } from "../../constants/chart"; import ProductService from "../../services/productService"; export class Chart extends Component { constructor(props) { super(props); } productService = new ProductService(); state = { chartData: [], maxProductsValue: 0, products: [], }; priceData = []; maxProducts = 0; async componentWillReceiveProps(nextProps) { await this.setState({ products: nextProps.productsProp == null ? [] : nextProps.productsProp, }); this.loadData(); } componentDidMount = async () => { await this.setState({ products: this.props.productsProp == null ? [] : this.props.productsProp, }); this.loadData(); }; loadData = async () => { this.maxProducts = 0; this.setState({ maxProductsValue: 0 }); const { products } = this.state; this.priceData = await this.productService.getPriceFilterData(); var chartDataArray = []; var min = this.priceData == null ? 0 : this.priceData.minPrice; var max = this.priceData == null ? 0 : this.priceData.maxPrice; var incrementValue = 20; while (min < max) { min = min + incrementValue; chartDataArray.push({ groupTopValue: min, productsArray: [] }); } var lastGroupTopValue = this.priceData == null ? 0 : this.priceData.minPrice - 1; for (let i = 0; i < chartDataArray.length; i++) { var groupTopValue = chartDataArray[i].groupTopValue; for (let j = 0; j < products.length; j++) { if ( products[j].startPrice > lastGroupTopValue && products[j].startPrice <= groupTopValue ) { chartDataArray[i].productsArray.push(products[j]); if (chartDataArray[i].productsArray.length > this.maxProducts) { this.maxProducts = chartDataArray[i].productsArray.length; } } } lastGroupTopValue = groupTopValue; } this.setState({ chartData: chartDataArray, maxProductsValue: this.maxProducts, }); }; render() { return ( <div style={{ display: "flex", borderBottom: "2px solid #D8D8D8", borderRadius: "1px", }} key={this.props.productsProp} > {this.state.chartData !== undefined && this.state.chartData !== null && this.state.chartData.map( function (chartData, index) { return ( <div key={index} style={{ width: "50px" }}> <div style={{ height: `${chartData.productsArray.length * DIV_HIGHT}px`, backgroundColor: "#E4E5EC", marginRight: "0px", marginLeft: "0px", position: "relative", top: `${ this.state.maxProductsValue * DIV_HIGHT - chartData.productsArray.length * DIV_HIGHT }px`, }} ></div> </div> ); }.bind(this) )} </div> ); } } export default Chart;
var StopValidationException = function(message){ this.message = message; }; StopValidationException.prototype.constructor = StopValidationException; module.exports = StopValidationException;
$(document).ready(function () { $('#idPassword').on('keyup', function () { let textElement = $(this).val() let strength = 0 //===========Business rules================== $('#typepass').find('h4').html(`Your Password: ${textElement}`) if (textElement.length > 0) { let sizeElements = textElement.length if (sizeElements > 10) { strength += 30 } else { let calcMath = (sizeElements * 2) strength += calcMath } } let lowerCase = new RegExp(/[a-z]/) if (lowerCase.test(textElement)) { strength += 16 } let upperCase = new RegExp(/[A-Z]/) if (upperCase.test(textElement)) { strength += 18 } let regularNumber = new RegExp(/[0-9]/i) if (regularNumber.test(textElement)) { strength += 16 } let specialChars = new RegExp(/[^a-z0-9]/i) if (specialChars.test(textElement)) { strength += 20 } //============end Business rules============== //======Results Rendering===================== if (strength < 21) { //red very weak password $('#strengthResult').html( ` <h5>Password Strength:</h5> <h5>${strength}% = Very Weak</h5> <div class="progress" style="height: 40px;"> <div class="progress-bar bg-danger" role="progressbar" style="width: ${strength}%" aria-valuenow="${strength}" aria-valuemin="0" aria-valuemax="100"><strong style="font-size: 30px">${strength}%</strong></div> </div>` ) } else if (strength > 20 && strength < 41) { //orange weak password $('#strengthResult').html( ` <h5>Strength Analyses:</h5> <h5>${strength}% = Weak</h5> <div class="progress" style="height: 40px;"> <div class="progress-bar bg-warning" role="progressbar" style="width: ${strength}%" aria-valuenow="${strength}" aria-valuemin="0" aria-valuemax="100"><strong style="font-size: 30px">${strength}%</strong></div> </div>` ) } else if (strength > 40 && strength < 61) { //medium password $('#strengthResult').html( ` <h5>Strength Analyses:</h5> <h5>${strength}% = Medium </h5> <div class="progress" style="height: 40px;"> <div class="progress-bar bg-secondary" role="progressbar" style="width: ${strength}%" aria-valuenow="${strength}" aria-valuemin="0" aria-valuemax="100"><strong style="font-size: 30px">${strength}%</strong></div> </div>` ) } else if (strength > 60 && strength < 81) { // strong password $('#strengthResult').html( ` <h5>Strength Analyses:</h5> <h5>${strength}% = Strong </h5> <div class="progress" style="height: 40px;"> <div class="progress-bar bg-info" role="progressbar" style="width: ${strength}%" aria-valuenow="${strength}" aria-valuemin="0" aria-valuemax="100"><strong style="font-size: 30px">${strength}%</strong></div> </div>` ) } else { //very strong password $('#strengthResult').html( ` <h5>Strength Analyses:</h5> <h5>${strength}% = Very Strong </h5> <div class="progress" style="height: 40px;"> <div class="progress-bar bg-success" role="progressbar" style="width: ${strength}%" aria-valuenow="${strength}" aria-valuemin="0" aria-valuemax="100"><strong style="font-size: 30px">${strength}%</strong></div> </div>` ) } //======Results Rendering===================== //======Hide the div containing the result==== if (strength == 0) { $('#typepass').addClass('showHidden') } else { $('#typepass').removeClass('showHidden') } }); });
define(function () { return function (app) { // write some extensions }; });
$(function() { Parse.$ = jQuery; // Replace this line with the one on your Quickstart Guide Page Parse.initialize("0p5WZtJHlZM3ERJYSBfnokM7KWbVgmdiaB0fO9HV", "sITcgQ6IuklhwPMG52wcy5CybyNweH7iO7aXorLh"); var BeanieBoosView = Parse.View.extend({ template: Handlebars.compile($('#bb-tpl').html()), render: function() { var collection = {beanieBoo: this.collection.toJSON() }; this.$el.html(this.template(collection)); } }); var BeanieBoo = Parse.Object.extend("BeanieBoo"); var BeanieBoos = Parse.Collection.extend({ model: BeanieBoo, query: (new Parse.Query(BeanieBoo)).limit(1000) }); var beanieBoos = new BeanieBoos(); beanieBoos.comparator = function(object) { return object.get("name"); }; beanieBoos.fetch({ success: function(beanieBoos) { var beanieBoosView = new BeanieBoosView({ collection: beanieBoos }); beanieBoosView.render(); $('.bb-main-table').html(beanieBoosView.el); }, error: function(beanieBoos, error) { console.log(error); } }); });
import Circle from '../es6_getter_setter'; const circle = new Circle(10); radius = circle.radius; circle.draw();
'use strict'; var express = require('express'); var cors = require('cors'); var path = require('path'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var jwt = require('jsonwebtoken'); var config = require('./config'); mongoose.connect(config.database); const log = require('./utils/Logger'); var apiEndpoint = require('./routes/api'); log.info('Starting the express app'); var app = express(); //Setup DB Data, remove it later //var dbSetup = require('./dataSetup/setup'); //Setup end // view engine setup app.set('view engine', 'hbs'); app.set('views', path.join(__dirname, 'views')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); var originsWhitelist = [ 'http://localhost:4200' ]; var corsOptions = { origin: function (origin, callback) { var isWhitelisted = originsWhitelist.indexOf(origin) !== -1; callback(null, isWhitelisted); }, credentials: true } app.use(cors(corsOptions)); app.use(cookieParser()); app.use('/', express.static(path.join(__dirname, 'public/swagger-ui'))); app.use('/api', apiEndpoint); var allowCrossDomain = function (req, res, next) { res.header('Access-Control-Allow-Origin', "*"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); } app.use(allowCrossDomain); app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); app.listen(process.env.PORT || 5200, function () { log.info('Started the express microservice.'); // Setup DB Data, remove it later // Comment below when not needed // dbSetup.init(); // Setup end }); module.exports = app;
import React from "react"; import "./AccommodationHeader.css"; import homeImage from "../../../assets/home.jpg"; function AccommodationHeader() { return ( <div className="accHeader container mt-3"> <h3>Place</h3> <a href="/" className="accHeader__location"> Mansoura Qism 2, Dakahlia Governorate, Egypt </a> <img className="accHeader__image img-fluid .max-width: 100% rounded-lg" src={homeImage} /> </div> ); } export default AccommodationHeader;
import typescript from 'rollup-plugin-typescript2' import filesize from 'rollup-plugin-filesize' import { terser } from "rollup-plugin-terser"; import { join } from 'path' export default { input: join(__dirname, './src/main.ts'), output: [ { file: 'dist/simpleWorker.iife.js', format: 'iife', name: 'SimpleWorker', }, { file: 'dist/simpleWorker.es.js', format: 'es' } ], plugins: [ typescript(), terser(), filesize() ] }
// ==UserScript== // @name Salesforce - Autolink in comments // @description Discover links in comments // @namespace https://github.com/nobuto-m/greasemonkey-scripts/tree/master/salesforce // @updateURL https://github.com/nobuto-m/greasemonkey-scripts/raw/master/salesforce/autolinkInComments.user.js // @match https://*.salesforce.com/* // @version 1.8 // @grant none // @require https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js // @require https://raw.githubusercontent.com/nfrasser/linkify-shim/67ecf680a10e3ed029e4bfd62e8217e27326a6ae/linkify.min.js // @require https://raw.githubusercontent.com/nfrasser/linkify-shim/67ecf680a10e3ed029e4bfd62e8217e27326a6ae/linkify-string.min.js // @require https://raw.githubusercontent.com/nfrasser/linkify-shim/67ecf680a10e3ed029e4bfd62e8217e27326a6ae/linkify-jquery.min.js // ==/UserScript== var comments = $('div[id$=\'_RelatedCommentsList_body\']').find('td.dataCell'); $(comments).linkify();
import SignInPage from './SignInPage.component.jsx'; export default SignInPage;
import RestfulDomainModel from '../base/RestfulDomainModel' class Model extends RestfulDomainModel { async page(pageNo, pageSize, filter, sort) { // console.log(this.baseUrl); // var filter = {"deleted":{"NE":1}}; // var pageNo = 1; // var pageSize = 1; // var sort = []; // return await this.post(`/search-srv/im_profile_views/page`, { pageNo, pageSize, filter, sort }) return {"gg":"dw"} } } export default new Model([ ], '/rootmenu/test')
/** * A bare bones Sprite and sprite Group example. * * We move a lot of Ship sprites across the screen with varying speed. The sprites * rotate themselves randomly. The sprites bounce back from the bottom of the * screen. */ var gamejs = require('gamejs'); /** * The ship Sprite has a randomly rotated image und moves with random speed (upwards). */ var Ship = function(rect) { // call superconstructor Ship.superConstructor.apply(this, arguments); this.speed = 20 + (40 * Math.random()); // ever ship has its own scale this.originalImage = gamejs.image.load("images/ship.png"); var dims = this.originalImage.getSize(); this.originalImage = gamejs.transform.scale( this.originalImage, [dims[0] * (0.5 + Math.random()), dims[1] * (0.5 + Math.random())] ); this.rotation = 50 + parseInt(120*Math.random()); this.image = gamejs.transform.rotate(this.originalImage, this.rotation); this.rect = new gamejs.Rect(rect); return this; }; // inherit (actually: set prototype) gamejs.utils.objects.extend(Ship, gamejs.sprite.Sprite); Ship.prototype.update = function(msDuration) { // moveIp = move in place this.rect.moveIp(0, this.speed * (msDuration/1000)); if (this.rect.top > 600) { this.speed *= -1; this.image = gamejs.transform.rotate(this.originalImage, this.rotation + 180); } else if (this.rect.top < 0 ) { this.speed *= -1; this.image = gamejs.transform.rotate(this.originalImage, this.rotation); } }; function main() { // screen setup gamejs.display.setMode([800, 600]); gamejs.display.setCaption("Example Sprites"); // create some ship sprites and put them in a group var ship = new Ship([100, 100]); var gShips = new gamejs.sprite.Group(); for (var j=0;j<4;j++) { for (var i=0; i<25; i++) { gShips.add(new Ship([10 + i*20, j * 20])); } } // game loop var mainSurface = gamejs.display.getSurface(); // msDuration = time since last tick() call var tick = function(msDuration) { mainSurface.fill("#FFFFFF"); // update and draw the ships gShips.update(msDuration); gShips.draw(mainSurface); }; gamejs.time.fpsCallback(tick, this, 60); } /** * M A I N */ gamejs.preload(['images/ship.png']); gamejs.ready(main);
//Fade in welcome message window.onload = function () { var elem = document.getElementsByClassName("split-screen"); var opacity = 0; var fadeRate = 0.01; elem[0].style.opacity = opacity; elem[0].style.visibility = "visible"; var interval; var startDelay = setTimeout(startAnim, 667); function startAnim() { interval = setInterval(stepFade, 10); } function stepFade() { if (opacity >= 1) { clearInterval(interval); } else { opacity += fadeRate; elem[0].style.opacity = opacity; } } }
console.log(process.argv[2]); const MidiParse = require("midiconvert"); const fs = require('fs'); var dir = "./" + process.argv[2]; var dirJson = dir + "JSON" if (!fs.existsSync(dirJson)){ fs.mkdirSync(dirJson); } // const fs = require('fs'); const MidiConvert = require('midiconvert'); fs.readdirSync(`${dir}`).forEach(file => { let midiBlob = fs.readFileSync(`${dir}/${file}`, "binary"); let json = MidiConvert.parse(midiBlob); fs.writeFileSync(`${dirJson}/${file}.json`, JSON.stringify(json, null, 4)); });