text
stringlengths
7
3.69M
//import { Demand } from './demand'; export const DEMANDS = [ {id: 1, time: "2017-10-20 00:00:00", value: 44, meter: 1 }, {id: 2, time: "2017-10-20 01:00:00", value: 48, meter: 1 }, {id: 3, time: "2017-10-20 02:00:00", value: 57, meter: 1 }, {id: 4, time: "2017-10-20 03:00:00", value: 66, meter: 1 }, {id: 5, time: "2017-10-20 04:00:00", value: 55, meter: 1 }, {id: 6, time: "2017-10-20 05:00:00", value: 44, meter: 1 }, {id: 7, time: "2017-10-20 06:00:00", value: 37, meter: 1 }, {id: 8, time: "2017-10-20 00:00:00", value: 15, meter: 2 }, {id: 9, time: "2017-10-20 01:00:00", value: 25, meter: 2 }, {id: 10, time: "2017-10-20 02:00:00", value: 16, meter: 2 }, {id: 11, time: "2017-10-20 03:00:00", value: 18, meter: 2 }, {id: 12, time: "2017-10-20 04:00:00", value: 33, meter: 2 }, {id: 13, time: "2017-10-20 00:00:00", value: 70, meter: 3 }, {id: 14, time: "2017-10-20 01:00:00", value: 44, meter: 3 }, {id: 15, time: "2017-10-20 02:00:00", value: 55, meter: 3 }, {id: 16, time: "2017-10-20 03:00:00", value: 57, meter: 3 }, {id: 17, time: "2017-10-20 04:00:00", value: 42, meter: 3 }, {id: 18, time: "2017-10-20 05:00:00", value: 69, meter: 3 } ]
import Vue from 'vue' import './plugins/vuetify' import router from './router' import store from "@vue/cli-service/generator/vuex/template/src/store"; import BootstrapVue from "bootstrap-vue" import App from './App' import Default from './Layout/Wrappers/baseLayout.vue'; import Pages from './Layout/Wrappers/pagesLayout.vue'; import Apps from './Layout/Wrappers/appLayout.vue'; import {empty} from "leaflet/src/dom/DomUtil"; import {VM} from './managers/VocabularyManager.js'; import qs from "qs"; // or './module' var VocabularyManager = new VM(); Vue.config.productionTip = false; Vue.use(BootstrapVue); Vue.component('default-layout', Default); Vue.component('userpages-layout', Pages); Vue.component('apps-layout', Apps); new Vue({ el: '#app', router, store, template: '<App/>', components: { App }, created: function() { this.$store.state.t = (string) => { var currentInterfaceVocabulary = JSON.parse(localStorage.getItem('currentInterfaceVocabulary')); if (typeof this.$store.state.currentInterfaceVocabulary == 'undefined' && currentInterfaceVocabulary !== null){ this.$store.state.currentInterfaceVocabulary = currentInterfaceVocabulary; } if ( typeof this.$store.state.currentInterfaceVocabulary != 'undefined' && typeof this.$store.state.currentInterfaceVocabulary[''+string] != 'undefined' && this.$store.state.currentInterfaceVocabulary[''+string] !== '' && this.$store.state.currentInterfaceVocabulary[''+string] !== null ){ return this.$store.state.currentInterfaceVocabulary[''+string]; } else if ( typeof this.$store.state.currentInterfaceVocabulary != 'undefined' && typeof this.$store.state.currentInterfaceVocabulary[''+string] == 'undefined' ) { VocabularyManager.create(string) .then( (response) => { if (response.data !== false){ this.$store.state.currentInterfaceVocabulary[''+string] = ''; this.$forceUpdate(); this.$eventHub.$emit('updateList:vocabularies'); } }) .catch(function (error) { console.log(error); }); } return string; } }, methods: { } }); Vue.prototype.$eventHub = new Vue({ props: { }, data: function () { return { } }, created: function () { }, beforeMount: function() { }, mounted() { }, computed: { }, updated: function () { }, methods: { }, template: ``, });
module.exports = { "database" : "mongodb://localhost/agendalegale", // process.env tratta le variabili di ambiente definite nel sistema operativo "port" : process.env.PORT || 3000 }
/** * Created by az on 2017/7/28. */ import React, {Component} from 'react'; import RateStar from '../common/RateStar'; /*eslint-disable*/ class QbCard extends Component { render() { const {cardStyle, avatarSrc, rate} = this.props; return ( <div style={{...style.card, ...cardStyle}}> <div style={style.leftFrame}> <img src={avatarSrc}/> </div> <div style={style.rightFrame}> <div className="box-font-narrow" style={style.classTitle}>asdasmd koamo kmo jm osdjonqc dqwj dncpian apdijcn pdj pfidf n</div> <div style={style.priceAndTime}> <div style={style.time}>120912321</div> <div style={style.price}>$666</div> </div> <div style={style.ratingAndName}> <div style={style.tutorName}>asda joisdd</div> <div style={style.rating}> <RateStar rate={rate * 20}/> </div> </div> </div> </div> ) } } const style = { card: { display: 'flex', flexDirection: 'row', borderRadius: 4, boxShadow: '0 2px 20px 0 rgba(25, 34, 48, 0.27)', }, leftFrame: { height: '100%', width: 68, border: 0, }, rightFrame: { flex: 1, display: 'flex', flexDirection: 'column', padding: '9px 15px 9px 12px', }, classTitle: { fontSize: 21, fontWeight: 'bold', lineHeight: 1.2, color: '#192230', }, priceAndTime: { display: 'flex', flexDirection: 'row', }, price: { fontFamily: 'Gotham-Book', fontSize: 14.4, lineHeight: 1.5, color: '#5d90e3', marginLeft: 10, }, time: { fontFamily: 'Gotham-Book', fontSize: 14.4, lineHeight: 1.5, color: '#5d90e3', }, ratingAndName: { display: 'flex', flexDirection: 'row', alignItems: 'center', }, rating: { marginLeft: 10, }, tutorName: { fontFamily: 'Gotham-Book', fontSize: 14.4, lineHeight: 1.5, color: '#192230', }, } export default QbCard;
module.exports = require('./src/index'); module.exports.parse_newick = require('biojs-io-newick').newick;
/** * * @authors zx.wang (zx.wang1991@gmail.com) * @date 2016-06-21 17:18:15 * @version $Id$ */ /** * Q:Find the contiguous subarray within an array (containing at least one number) which has the largest product. * For example, given the array [2,3,-2,4], * the contiguous subarray [2,3] has the largest product = 6. */ /** * [maxProduct 新建两个数组,一个max存储最大数,一个min存储最小数,循环数组,将相邻数相乘的最大最小数分别存入max及min数组中, * 然后再来比较默认值与获取到的最大数组中的最大值的比较,最后获取到最大值。相邻数相乘的时候正负数的大小按照符号取值相反。] * @param {[type]} nums [输入一个数组] * @return {[type]} [返回相邻数相乘的最大值] */ let maxProduct = function(nums) { let max = [], min = [], result = nums[0]; max[0] = min[0] = nums[0]; for (let i = 1; i < nums.length; i++) { if (nums[i] > 0) { max[i] = Math.max(nums[i], max[i - 1] * nums[i]); min[i] = Math.min(nums[i], min[i - 1] * nums[i]); } else { max[i] = Math.max(nums[i], min[i - 1] * nums[i]); min[i] = Math.min(nums[i], max[i - 1] * nums[i]); } result = Math.max(result, max[i]); } return result; };
// fs是node中的一个模块 是文件系统的一个模块 // 可以使得node可以操作文件 // 首先是创建一个变量来建立模块 let fs = require('fs')
system = ["btI", "bc", "bf", "bd", "brI", "bf", "bc", "btI", "bpI", "bpI", "bpI", "bpI", "bpI", "bpI", "bpI", "bpI", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "wpI", "wpI", "wpI", "wpI", "wpI", "wpI", "wpI", "wpI", "wtI", "wc", "wf", "wd", "wrI", "wf", "wc", "wtI"] statute = 0 piece = 0 tour = "w" finDePartie = false bAutoplay = true copyOfSystem = [] excludesPlays = [] profunderMax = 3 testResult = [] initSystem() function systemPrint() { //rapidly transfer this system graphically for(x=0;x<8;x++) { chaine = [x] for(y=0;y<8;y++) { chaine += " " + system[x*8+y] } } } function deplace(whereIs, whereGo) { //really basic, but essentially type = system[whereIs] system[whereIs] = "x" system[whereGo] = type actuSystem() } function initSystem() { table = document.getElementsByTagName('table') lineList = table[0].firstElementChild.childNodes for(x=0;x<8;x++) { lineToComplete = lineList[x*2] for(y=0;y<8;y++) { lineToComplete.childNodes[y*2+1].id = x*8+y img = document.createElement('img') if(system[x*8+y] != "x") { img.src = "img/" + system[x*8+y][0] + system[x*8+y][1] + ".png" } else { img.src = "img/" + system[x*8+y] + ".png" } img.onclick = function lol(){ imgclick(this) } lineToComplete.childNodes[y*2+1].appendChild(img) } } } function actuSystem() { table = document.getElementsByTagName('table') lineList = table[0].firstElementChild.childNodes for(x=0;x<8;x++) { lineToComplete = lineList[x*2] for(y=0;y<8;y++) { lineToComplete.childNodes[y*2+1].id = x*8+y img = lineToComplete.childNodes[y*2+1].firstChild if(system[x*8+y] != "x") { img.src = "img/" + system[x*8+y][0] + system[x*8+y][1] + ".png" } else { img.src = "img/" + system[x*8+y] + ".png" } img.onclick = function lol(){ imgclick(this) } } } } colorMemory = "" function imgclick(x) { if(statute == 0) { statute = 1 piece = x colorMemory = x.parentNode.style.background x.parentNode.style.background = "red" } else { statute = 0 piece.parentNode.style.background = colorMemory if(verify(piece.parentNode.id, x.parentNode.id) == true) { whereIs = piece.parentNode.id whereGo = x.parentNode.id deplace(whereIs, whereGo) changeTour() if(tour=="b" && bAutoplay==true) { cocoSystem = system.concat() bestBlack = testAutoplay(system) system = cocoSystem.concat() deplace(bestBlack[1], bestBlack[2]) changeTour() } } } } function verify(whereIs, whereGo) { //principal topic to verify if play in rules if(finDePartie == true) { return false } if(tour == system[whereIs][0]) { if(system[whereIs][1] == "x") { return false } if(system[whereIs][1] == "p") { if(pRules(whereIs, whereGo) == true) { return true } else { return false } } if(system[whereIs][1] == "t") { if(tRules(whereIs, whereGo) == true) { system[whereIs] = system[whereIs][0] + "t" return true } else { return false } } if(system[whereIs][1] == "c") { if(cRules(whereIs, whereGo) == true) { return true } else { return false } } if(system[whereIs][1] == "f") { if(fRules(whereIs, whereGo) == true) { return true } else { return false } } if(system[whereIs][1] == "r") { if(rRules(whereIs, whereGo) == true) { system[whereIs] = system[whereIs][0] + "r" return true } else { roque(whereIs, whereGo) return false } } if(system[whereIs][1] == "d") { if(dRules(whereIs, whereGo) == true) { return true } else { return false } } } } function changeTour() { if(tour=="w") { tour = "b" document.getElementById('tour').innerHTML = "Aux noirs de jouer" document.getElementById('tour').style.color = "black" } else { tour = "w" document.getElementById('tour').innerHTML = "Aux blancs de jouer" document.getElementById('tour').style.color = "white" } wrPresence = false brPresence = false for(x=0;x<64;x++) { if(system[x]=="wr" || system[x]=="wrI") { wrPresence = true } if(system[x]=="br" || system[x]=="brI") { brPresence = true } } if(brPresence==false) { document.getElementById('tour').innerHTML = "Les blancs ont gagné" document.getElementById('tour').style.color = "yellow" finDePartie = true } if(wrPresence==false) { document.getElementById('tour').innerHTML = "Les noirs ont gagné" document.getElementById('tour').style.color = "yellow" finDePartie = true } } function newGame() { tour = "w" document.getElementById('tour').innerHTML = "Aux blancs de jouer" document.getElementById('tour').style.color = "white" system = ["btI", "bc", "bf", "bd", "brI", "bf", "bc", "btI", "bpI", "bpI", "bpI", "bpI", "bpI", "bpI", "bpI", "bpI", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "wpI", "wpI", "wpI", "wpI", "wpI", "wpI", "wpI", "wpI", "wtI", "wc", "wf", "wd", "wrI", "wf", "wc", "wtI"] actuSystem() finDePartie = false }
// Business logic var add = function(num1, num2, num3, num4, num5) { return num1 + num2+ num3 + num4 + num5; }; // Front end logic $(document).ready(function() { $("form#survey").submit(function(event) { var userName = $("input#userName").val(); var companySize = parseInt($("#companySize").val()); var productType = parseInt($("#productType").val()); var gameDev = parseInt($("#gameDev").val()); var uxDesign = parseInt($("#uxDesign").val()); var crossPlatform = parseInt($("#crossPlatform").val()); var userInput = add(companySize, productType, gameDev, uxDesign, crossPlatform); // Allows results directly on page event.preventDefault(); if (userInput <= 10) { $("#initial-showing").hide(); $("#frontEnd").fadeIn(1000); $(".userName").text(userName); } else if (userInput === 11 || userInput <= 13) { $("#initial-showing").hide(); $("#mobileDev").fadeIn(1000); $(".userName").text(userName); } else if (userInput === 14 || userInput <= 16) { $("#initial-showing").hide(); $("#gameDevelopment").fadeIn(1000); $(".userName").text(userName); } else { $("#initial-showing").hide(); $("#backEnd").fadeIn(1000); $(".userName").text(userName); } }); });
import React,{Component} from 'react'; import {getDetail,AddToCart,increase} from '../actions' import {connect} from 'react-redux' import { Jumbotron, Button , Breadcrumb , BreadcrumbItem } from 'reactstrap'; import { NavLink } from 'react-router-dom' const mapStateToProps = (state)=>{ return { ...state.detailpro,/* detailList: [{…}] totalPro: 0 */ } } class DetailPro extends Component{ componentDidMount(){ this.props.getDetail(this.props.match.params.id); } addtocart(item){ this.props.AddToCart(item); this.props.increase(); } details(){ var jsx=[]; var id=0; this.props.detailList.map((item,index)=>{ jsx.push( <div key={index}> <div key={index} > <div className="thumbnail" style={{backgroundColor:"#f5f5f5",padding:"10px"}}> <img src={item.img} style={{width:"500px",display:"table",margin:"0 auto 0 auto"}}/><br/><br/> <div className="caption" > <h2 className="display-5" style={{margin:"0 0 20px 0",fontSize:"3rem"}}>{item.name}</h2> <hr className="my-2" /> <p className="lead">{item.content}</p> <p>价格 :¥{item.price}</p><br/> <p className="lead" style={{position:"relative"}}> <Button color="danger" onClick={()=>this.addtocart(item)} style={{fontSize:"1.5rem"}}>加入购物车</Button> <span className="badge" style={{width:"20px",height:"20px",backgroundColor:"#dc3545",position:"absolute",left:"90px",top:"-7px"}}>{this.props.totalPro}</span> </p> </div> </div> </div> </div> ) id=item.id+1; }) return [jsx,id]; } render(){ return ( <div style={{fontSize:"1.5rem"}}> <div className="panel panel-success" style={{fontSize:"1.5rem",width:"80%",margin:"50px auto"}}> <div className="panel-body"> {this.details()[0]} </div> </div> </div> ) } } export default connect(mapStateToProps,{getDetail,AddToCart,increase})(DetailPro);
const express=require('express'); const router=express.Router(); const ctrlApp=require('../controller/ctrlApp') const multer = require('multer'); const path = require('path'); const upload = multer( { storage: multer.diskStorage({ destination:function (req, file, cb) { // set uploads directory cb(null, 'photo/post/') }, filename: function(req, file, cb) { // save file with current timestamp + user email + file extension cb(null, Date.now() + path.extname(file.originalname)); } }) } ); const uploadProfilePic = multer({storage: multer.diskStorage({ destination:function (req, file, cb) { // set uploads directory cb(null, 'photo/user/') }, filename: function(req, file, cb) { // save file with current timestamp + user email + file extension cb(null, req.user._id+ path.extname(file.originalname)); } })}); router.get('/settings',isLoggedIn,ctrlApp.settings); router.post('/settings/profile',isLoggedIn,uploadProfilePic.single('photo'),ctrlApp.profileSettings); router.post('/settings/password',isLoggedIn,ctrlApp.passwordSettings); router.post('/settings/account',isLoggedIn,ctrlApp.accountSettings); router.get('/settings/delete',isLoggedIn,ctrlApp.userBlock); router.get('/u/:id',ctrlApp.user); router.get('/u/:id/posts',ctrlApp.userPosts); router.get('/u/:id/likes',ctrlApp.userUpVotes); router.get('/u/:id/comments',ctrlApp.userComments); router.get('/',ctrlApp.home); router.get('/hot',ctrlApp.hot); router.get('/trending',ctrlApp.trending); router.get('/fresh',ctrlApp.fresh); router.get('/gag/:id',ctrlApp.gag); router.get('/aftergag/:id',ctrlApp.afterGag); router.post('/report/:id',ctrlApp.report); router.post('/postImgUrl',isLoggedIn, upload.single('photo'),ctrlApp.post); router.get('/tag/:tag',ctrlApp.tag); router.get('/search/:searchText',ctrlApp.searchTag); router.get('/upVote/:id',ctrlApp.upVote); router.get('/downVote/:id',ctrlApp.downVote); router.get('/:data',ctrlApp.section); module.exports=router; function isLoggedIn(req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }
/** * Created by Sora on 3/22/2017. */
/* Step 3. In this_file, access the newly created environment variables Lambda environment variables are accessible on the `process.env` object in node. `process.env.[YourEnvKeyName]` Return the environment variable in the `foo` function response */ module.exports.foo = (event, context, callback) => { const response = { statusCode: 200, body: JSON.stringify({ headers: { /* Required for CORS support to work */ "Access-Control-Allow-Origin" : "*", /* Required for cookies, authorization headers with HTTPS */ "Access-Control-Allow-Credentials" : true }, message: 'return env variable here' }), } return callback(null, response) } /* Step 4. In this_file, access the newly created scoped `bar` environment variables `process.env.[YourEnvKeyName]` Return the environment variable in the `bar` function response */ module.exports.bar = (event, context, callback) => { const response = { statusCode: 200, body: JSON.stringify({ headers: { /* Required for CORS support to work */ "Access-Control-Allow-Origin" : "*", /* Required for cookies, authorization headers with HTTPS */ "Access-Control-Allow-Credentials" : true }, message: 'return env variable here' }), } return callback(null, response) }
module.exports = { "extends": "airbnb", "parser": "babel-eslint", "plugins": [ "flowtype" ], "rules": { "linebreak-style": 0, "max-len": [2, 160, 2, {ignoreComments: true}], "indent": 0, "object-curly-spacing": 0, "object-curly-newline": 0, "arrow-parens": 0, "react/jsx-indent": 0, "react/jsx-filename-extension": 0, "react/jsx-tag-spacing": 0, "react/jsx-indent-props": 0, "react/prop-types": 0, "comma-dangle": 0, "no-confusing-arrow": 0, "import/no-named-as-default": 0, "import/no-named-as-default-member": 0, "import/named": 0, "spaced-comment": 0, "lines-between-class-members": 0, "react/sort-comp": 0, }, "globals": { "window": true, "EventSource": true, "localStorage": true, "WebSocket": true, "fetch": true } };
'use strict'; module.exports = async (email, password, {userRepository, accessTokenManager}) => { const user = await userRepository.getByEmail(email); console.log(user); if (!user || user.password !== password) { throw new Error('Bad credentials'); } return { token: accessTokenManager.generate({uid: user.id}), user: { id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email, rut: user.firstName, phone: user.firstName, role: user.role, crated_at: user.created_at } }; };
'use strict'; // global.$ = { // package: require('./package.json'), // config: require('./gulp/config.js'), // path: { // task: require('./gulp/path/tasks.js'), // app: require('./gulp/path/app.js') // }, // gulp: require('gulp'), // browsersync: require('browser-sync').create(), // gp: require('gulp-load-plugins')() // }; // $.path.task.forEach(function(taskPath) { // require(taskPath)(); // }); require('./gulp/tasks/watch.js'); require('./gulp/tasks/browsersync.js'); require('./gulp/tasks/pug.js'); require('./gulp/tasks/styles.js'); require('./gulp/tasks/scripts.js');
export { default as CalendarDateItem } from './CalendarDateItem';
var mysql= require('mysql'); var mysqlConnection = mysql.createConnection({ host : 'localhost', user : 'root', password : '', database : 'nodedb', debug : true, }); //mysqlConnection.connect(function(err) { // if ( !err ) //}); //var query = mysqlConnection.query('select * from account', function(err, result) { // console.log(result); //}); var app = require('express')() , server = require('http').createServer(app) , io = require('socket.io').listen(server); server.listen(3000); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); io.sockets.on('connection', function (socket) { socket.on('send-msg', function(data) { // var query = mysqlConnection.query('select * from account where acc_username = "'+data+'"', function(err, result) { // io.sockets.emit('new-msg', result); // }); io.sockets.emit('new-msg', data); }); });
import React from 'react'; import background from './../Medias/frame1.png' import './../Stylesheets/Landingpage.scss' function Landingpage() { return ( <div className="landingpage_main"> <img className='bg' src={background} alt="img"/> </div> ); } export default Landingpage;
var $ = require('jquery'); var Vue = require('vue'); var remodal = require('remodal'); var howler = require('howler'); // var dragula = require('dragula'); var siteData = require('./siteData.js'); var pageData = require('./pageData.js'); require('jquery-ui/draggable'); require('jquery-ui/droppable'); require('jquery-ui/position'); Vue.config.debug = true; function blurAll(){ var tmp = document.createElement("input"); document.body.appendChild(tmp); tmp.focus(); document.body.removeChild(tmp); } window.staticSound = new Howl({ urls: ['assets/audio/img_zoom.mp3'], loop: true, volume: 0.1 }); window.staticSoundTrue = new Howl({ urls: ['assets/audio/true.mp3'], volume: 0.2 }); window.staticSoundFalse = new Howl({ urls: ['assets/audio/false.mp3'], volume: 0.2 }); new Vue({ el: '#app', data: { jumpPage: '', leftpage: -2, rightpage: -1, staticpage: false, currentModalContent: '', pages: pageData(), site: siteData(), selectedPageObject: {}, selected: '', sandboxContent: '', dropzoneContent: '', staticSound: '' }, computed: { canGoBack: function() { if (this.leftpage.length != 0) { if (this.leftpage - 2 > -3) { return true } else { return false } } }, canGoForward: function() { if (this.rightpage.length != 0) { if (this.rightpage + 2 < 90) { return true } else { return false } } }, leftPageObject: function() { for (var i = 0; i < this.pages.length; i++) { if (this.pages[i].no == this.leftpage) { // Check to see if there is media on the page if (!this.pages[i].video && !this.pages[i].static && !this.pages[i].ex && !this.pages[i].ex2) { this.pages[i].hasMedia = false; } else { this.pages[i].hasMedia = true; } // Return page object with added info ^ return this.pages[i]; } } }, rightPageObject: function() { for (var i = 0; i < this.pages.length; i++) { if (this.pages[i].no == this.rightpage) { // Check to see if there is media on the page if (!this.pages[i].video && !this.pages[i].static && !this.pages[i].ex && !this.pages[i].ex2) { this.pages[i].hasMedia = false; } else { this.pages[i].hasMedia = true; } // Return page object with added info ^ return this.pages[i]; } } }, typerTrue: function(a, b) { var parsedA = a.replace(/\s+/g, '').toLowerCase(); if (parsedA.length == b.length && parsedA == b) { window.staticSoundTrue.play(); console.log('true'); return true; } }, typerFalse: function(a, b) { var parsedA = a.replace(/\s+/g, '').toLowerCase(); if (parsedA.length == b.length && parsedA != b) { window.staticSoundFalse.play(); console.log('false'); return true; } } }, methods: { prevPages: function() { this.leftpage = this.leftpage - 2; this.rightpage = this.rightpage - 2; blurAll(); }, nextPages: function() { this.leftpage = this.leftpage + 2; this.rightpage = this.rightpage + 2; blurAll(); }, showLeftModal: function() { this.selectedPageObject = this.leftPageObject; this.selectModalContent(); }, showLeftStaticModal: function() { this.selectedPageObject = this.leftPageObject; this.selectModalContent(); window.staticSound.play(); }, showRightModal: function() { this.selectedPageObject = this.rightPageObject; this.selectModalContent(); }, showRightStaticModal: function() { this.selectedPageObject = this.rightPageObject; this.selectModalContent(); window.staticSound.play(); }, muteStaticSound: function() { window.staticSound.stop(); }, jumpToPage: function(event) { event.preventDefault(); if (! this.jumpPage) { return false; } else { this.staticpage = false; if (this.jumpPage > 1 && this.jumpPage < 87) { if (this.jumpPage % 2 == 0) { this.leftpage = parseInt(this.jumpPage); this.rightpage = parseInt(this.jumpPage) + 1; } else { this.leftpage = parseInt(this.jumpPage) - 1; this.rightpage = parseInt(this.jumpPage); } } else { return false; } } }, jumpToToc: function(page) { if (page % 2 == 0) { this.leftpage = page; this.rightpage = page + 1; } else { this.leftpage = page - 1; this.rightpage = page; } }, selectModalContent: function() { if (this.selectedPageObject.hasMedia) { if (this.selectedPageObject.video) { this.currentModalContent = 'video'; } else if (this.selectedPageObject.static) { this.currentModalContent = 'static'; this.selected = this.selectedPageObject.static[0]; } else if (this.selectedPageObject.ex) { this.currentModalContent = 'ex'; } else { this.currentModalContent = 'ex2'; } } }, resetForm: function() { for (var i = 0; i < this.selectedPageObject.ex.data.length; i++) { this.selectedPageObject.ex.data[i].model = '' } for (var i = 0; i < this.selectedPageObject.ex2.data.length; i++) { this.selectedPageObject.ex2.data[i].model = '' } }, solveForm: function() { if (this.selectedPageObject.ex.name != 'mediumselect') { for (var i = 0; i < this.selectedPageObject.ex.data.length; i++) { this.selectedPageObject.ex.data[i].model = this.selectedPageObject.ex.data[i].solution; } } if (this.selectedPageObject.ex2.name != 'mediumselect') { for (var i = 0; i < this.selectedPageObject.ex2.data.length; i++) { this.selectedPageObject.ex2.data[i].model = this.selectedPageObject.ex2.data[i].solution; } } }, solveCheck: function() { if (this.selectedPageObject.ex.name == 'mediumselect') { for (var i = 0; i < this.selectedPageObject.ex.data.length; i++) { this.selectedPageObject.ex.data[i].model = 'true'; } } if (this.selectedPageObject.ex2.name == 'mediumselect') { for (var i = 0; i < this.selectedPageObject.ex2.data.length; i++) { this.selectedPageObject.ex2.data[i].model = 'true'; } } }, interactNow: function() { this.sandboxContent = this.$$.sandbox.innerHTML; this.dropzoneContent = this.$$.dropzone.innerHTML; this.$$.startButton.setAttribute('disabled', 'disabled'); for (var i = 0; i < this.selectedPageObject.ex.data.length; i++) { // dragula([document.querySelector('.launch--' + this.selectedPageObject.ex.data[i].rowID), document.querySelector('.target--' + this.selectedPageObject.ex.data[i].rowID)]); var launch = '.launch--' + this.selectedPageObject.ex.data[i].rowID;console.log(launch); var target = '.target--' + this.selectedPageObject.ex.data[i].rowID;console.log(target); var targetScope = this.selectedPageObject.ex.data[i].rowID; $(launch).addClass('hvr-wobble-horizontal-custom'); $(launch).draggable({ stack: '.dnd__answer-container', scope: targetScope, revert: true, start: function( event, ui ) { if ($(this).hasClass('hvr-wobble-horizontal-custom')) { $(this).removeClass('hvr-wobble-horizontal-custom'); } ui.helper.addClass('on-drag'); }, stop: function( event, ui ) { ui.helper.removeClass('on-drag'); } }); $(target).droppable({ accept: launch, scope: targetScope, hoverClass: 'drop-hover', drop: function( event, ui ) { var self = $(this); self.addClass( "dropped"); ui.draggable.draggable( 'disable' ); $(this).droppable( 'disable' ); ui.draggable.position( { of: self, my: 'center', at: 'center' } ); ui.draggable.draggable( 'option', 'revert', false ); window.staticSoundTrue.play(); } }); } }, resetDnd: function() { if (this.sandboxContent) { this.$$.sandbox.innerHTML = this.sandboxContent; } if (this.dropzoneContent) { this.$$.dropzone.innerHTML = this.dropzoneContent; } this.$$.startButton.removeAttribute('disabled'); }, goStatic: function(page) { this.leftpage = ''; this.rightpage = ''; this.staticpage = page; }, goToPage: function(page) { this.staticpage = false; if (page % 2 == 0) { this.leftpage = parseInt(page); this.rightpage = parseInt(page) + 1; } else { this.leftpage = parseInt(page) - 1; this.rightpage = parseInt(page); } }, checkSolution: function(model, solution) { if (model.length == solution.length && model.toLowerCase() == solution) { window.staticSoundTrue.play(); } if (model.length == solution.length && model.toLowerCase() != solution) { window.staticSoundFalse.play(); } }, playStaticSound: function(bool) { if (bool == 'true') { console.log(bool + 'should be true'); window.staticSoundTrue.play(); } else if (bool == 'false') { console.log(bool + 'should be false'); window.staticSoundFalse.play(); } }, stopVideo: function(id) { console.log(id); $('#' + id).trigger('pause'); $('#' + id).prop("currentTime", 0); } } });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { getAllTags, createAd, updateField, } from '../actions/index'; import CreateNewAd from '../components/createAd'; class CreateAd extends Component { componentDidMount() { this.getTags(); } getTags = () => { this.props.getAllTags(); } sendAd = async values => { values.photo = values.photo.length ? values.photo : 'https://static.thenounproject.com/png/220984-200.png'; const success = await this.props.createAd({ name: values.name, price: values.price, description: values.description, photo: values.photo, tags: [values.tag1, values.tag2], type: values.type }); if (success.payload._id) { this.props.updateField({ target: { name: 'backhome', value: true, } }) } } render() { if(this.props.backhome){ return <Redirect to='/ads'/> } return ( <CreateNewAd valid_tags={ this.props.valid_tags } onSubmit={ this.sendAd } /> ) } } const mapStateToProps = state => { return state.ads } const mapDispatchToProps = { getAllTags, createAd, updateField, } export default connect( mapStateToProps, mapDispatchToProps )(CreateAd);
'use strict'; (function () { var ESC_KEY = 27; var modal = document.querySelector('.modal'); var form = modal.querySelector('form'); var overlay = document.querySelector('.overlay'); var callBtn = document.querySelector('.page-header__call-btn'); var closeBtn = modal.querySelector('.modal__button-close'); var userName = modal.querySelector('input[name=user-name]'); var userPhone = modal.querySelector('input[name=user-phone-number]'); var userQuestion = modal.querySelector('textarea[name=user-question]'); var isStorageSupport = true; var storageName = ''; var storagePhone = ''; var closePopUp = function () { modal.classList.remove('modal--active'); overlay.classList.remove('overlay--active'); }; try { storageName = localStorage.getItem('userName'); storagePhone = localStorage.getItem('userPhone'); } catch (err) { isStorageSupport = false; } callBtn.addEventListener('click', function (evt) { evt.preventDefault(); modal.classList.add('modal--active'); overlay.classList.add('overlay--active'); if (storageName && storagePhone) { userName.value = storageName; userPhone.value = storagePhone; userQuestion.focus(); } else { userName.focus(); } }); closeBtn.addEventListener('click', function (evt) { evt.preventDefault(); closePopUp(); }); overlay.addEventListener('click', function () { closePopUp(); }); document.addEventListener('keyup', function (e) { if (e.keyCode === ESC_KEY) { closePopUp(); } }); form.addEventListener('submit', function () { if (isStorageSupport) { localStorage.setItem('userName', userName.value); localStorage.setItem('userPhone', userPhone.value); } }); })();
var searchData= [ ['trackingfailed',['trackingFailed',['../classlsd__slam_1_1_frame.html#a71811be54c6d349c9f13e50361b14718',1,'lsd_slam::Frame']]] ];
import { ADD_TO_CART, SAVE_TO_STORAGE, REMOVE_ITEM_CART, REMOVE_FROM_STORAGE, EMPTY_CART, SAVE_SHIPPING_INFO, } from '../constants/cartConstants'; export const cartReducer = ( state = { cartItems: [], shippingInfo: {} }, action ) => { switch (action.type) { case ADD_TO_CART: const item = action.payload; const isItemExists = state.cartItems.find( (i) => i.product === item.product ); if (isItemExists) { return { ...state, cartItems: state.cartItems.map((i) => i.product === isItemExists.product ? item : i ), }; } else { return { ...state, cartItems: [...state.cartItems, item], }; } case SAVE_TO_STORAGE: const storedItem = action.payload; const isStoredItem = state.storedItems.find( (item) => item.id === storedItem.id ); if (isStoredItem) { return { ...state, storedItems: state.storedItems.map((i) => i.id === isStoredItem.id ? storedItem : i ), }; } else { return { ...state, storedItems: [...state.storedItems, storedItem], }; } case REMOVE_ITEM_CART: return { ...state, cartItems: state.cartItems.filter((i) => i.product !== action.payload), }; case REMOVE_FROM_STORAGE: return { ...state, storedItems: state.storedItems.filter((i) => i.id !== action.payload), }; case EMPTY_CART: localStorage.removeItem('cartItems'); return { cart: {}, }; case SAVE_SHIPPING_INFO: return { ...state, sgippingInfo: action.payload, }; default: return state; } };
describe('Javabuzz', function() { var javabuzz; beforeEach(function() { javabuzz = new Javabuzz(); }); describe('knows what a number is', function() { it('divisible by 3', function() { expect(javabuzz._isDivisibleByThree(3)).toBe(true); }); it('divisible by 5', function() { expect(javabuzz._isDivisibleByFive(5)).toBe(true); }); it('divisible by 3 and 5', function() { expect(javabuzz._isDivisibleByFifteen(15)).toBe(true); }) }); describe('knows when a number is NOT', function() { it('divisible by 3', function() { expect(javabuzz._isDivisibleByThree(1)).toBe(false); }); it('divisible by 5', function() { expect(javabuzz._isDivisibleByFive(6)).toBe(false); }) it('divisible by 3 and 5', function() { expect(javabuzz._isDivisibleByFifteen(12)).toBe(false); }) }); describe('when playing, says', function(){ it('"Java" when a number is divisible by 3', function() { expect(javabuzz.says(6)).toEqual("Java"); }); it('"Buzz" when a number is divisible by 5', function() { expect(javabuzz.says(10)).toEqual("Buzz"); }); it('"JavaBuzz" when a number is divisible by 3 and 5', function() { expect(javabuzz.says(30)).toEqual("JavaBuzz"); }) it('"Number" when a number is not divisible by 3 or 5', function() { expect(javabuzz.says(1)).toEqual(1) }) }); });
const express = require('express') const rpc_client = require('../rpc_client/rpc_client'); const router = express.Router(); router.get('/userId/:userId/requestId/:requestId', function(req, res, next) { console.log('Get Request Detail...'); user_id = req.params['userId']; request_id = req.params['requestId']; rpc_client.getRequestDetail(user_id,request_id, function(response) { res.json(response); }); }); module.exports = router;
"use strict"; var express = require("express"); var app = express(); var cors = require("cors"); var https = require("https"); var fs = require("fs"); require("dotenv").config(); const { MongoClient } = require("mongodb"); const { OAuth2Client } = require("google-auth-library"); const fetch = require("node-fetch"); const convert = require("xml-js"); const bodyParser = require("body-parser"); var jsonParser = bodyParser.json(); const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID); let options = { useNewUrlParser: true, useUnifiedTopology: true, }; const MONGO_URI = process.env.MONGO_URI; let url = require("url"); const { openFilePromise, openTextFilePromise } = require("./filelibs.js"); const data = require("./data"); const searchForPodcasts = async (req, response) => { const { search_term } = req.params; const search_url = `https://itunes.apple.com/search?media=podcast&term=${search_term}`; fetch(search_url) .then((res) => res.json()) .then((json) => { return response.json({ json, }); }) .catch((error) => { console.log(error); return response.json({ error, }); }); }; const getTopPodcastsFromItunes = async (req, response) => { const apiUrl = "https://rss.itunes.apple.com/api/v1/ca/podcasts/top-podcasts/all/25/explicit.json"; fetch(apiUrl) .then((res) => res.json()) .then((json) => { return response.json({ json, }); }) .catch((error) => { console.log(error); return response.json({ error, }); }); // let english_text = JSON.parse(get_english); // return res.json({ // english_text, // }); }; const returnEnglishText = async (req, res) => { // const allFlights = Object.keys(flights); const get_english = await openFilePromise("sorted_combined.json"); let english_text = JSON.parse(get_english); return res.json({ english_text, }); }; const returnTraslatedText = async (req, res) => { // const allFlights = Object.keys(flights); const get_translations = await openFilePromise( "combined_speakers_and_translations.json" ); let translations = JSON.parse(get_translations); return res.json({ translations, }); }; const returnCombined = async (req, res) => { // const allFlights = Object.keys(flights); const get_translations = await openFilePromise( "translations_with_aligned_timing.json" ); let translations = JSON.parse(get_translations); return res.json({ translations, }); }; const returnCombined2 = async (req, res) => { // const allFlights = Object.keys(flights); const get_translations = await openFilePromise( "healthish__translations_with_aligned_timing.json" ); let translations = JSON.parse(get_translations); return res.json({ translations, }); }; const returnCombined3 = async (req, res) => { // const allFlights = Object.keys(flights); const get_translations = await openFilePromise( "healthish_V2__translations_with_aligned_timing.json" ); let translations = JSON.parse(get_translations); return res.json({ translations, }); }; const returnMP3Translationrecords = async (req, res) => { // const allFlights = Object.keys(flights); const records_data = await openFilePromise("records.json"); let records = JSON.parse(records_data); return res.json({ records, }); }; const returnMP3Translationrecords2 = async (req, res) => { // const allFlights = Object.keys(flights); const records_data = await openFilePromise("records_new_2.json"); let records = JSON.parse(records_data); return res.json({ records, }); }; const returnMP3Translationrecords3 = async (req, res) => { // const allFlights = Object.keys(flights); const records_data = await openFilePromise("healthish_v3_records.json"); let records = JSON.parse(records_data); return res.json({ records, }); }; const verifyToken = async (req, res) => { const { token } = req.params; async function verify() { const ticket = await client.verifyIdToken({ idToken: token, audience: "NOPE.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3] }); const payload = ticket.getPayload(); const userid = payload["sub"]; return res.json({ payload, userid }); // If request specified a G Suite domain: // const domain = payload['hd']; } verify().catch(console.error); }; const verifyTokenAndSlapItIntoDatabase = async (req, res) => { const { token } = req.params; console.log(MONGO_URI); console.log(token); let oneUpdated, userid, payload, db, mongoClient; try { const ticket = await client.verifyIdToken({ idToken: token, audience: GOOGLE_AUTH, // Specify the CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3] }); payload = ticket.getPayload(); userid = payload["sub"]; console.info(payload); options = { ...options, upsert: true }; mongoClient = await MongoClient(MONGO_URI, options); await mongoClient.connect(); db = mongoClient.db("users"); oneUpdated = await db .collection("user_records") .updateOne({ _id: userid }, { $set: { payload: payload } }); // console.info(oneUpdated); mongoClient.close(); return res.status(200).json({ oneUpdated, userid, payload, }); } catch (err) { console.error(err); mongoClient.close(); let errorMessage = Error(err); console.log(errorMessage.message); return res.status(404).json({ oneUpdated, userid, payload, error: { name: errorMessage.name, message: errorMessage.message }, }); } finally { client.close(); } }; app.use(cors()); app.get("/", function (req, res) { res.send("Hello Woddddddddrld0011"); }); app.get("/englishText", returnEnglishText); app.get("/translatedText", returnTraslatedText); app.get("/returnCombined", returnCombined); app.get("/returnCombined2", returnCombined2); app.get("/returnCombined3", returnCombined3); app.get("/returntranslationrecords", returnMP3Translationrecords); app.get("/returntranslationrecords2", returnMP3Translationrecords2); app.get("/returntranslationrecords3", returnMP3Translationrecords3); app.get("/verifyToken/:token", verifyToken); app.get( "/verifyTokenAndSlapItIntoDatabase/:token", verifyTokenAndSlapItIntoDatabase ); app.get("/searchForPodcasts/:search_term", searchForPodcasts); app.get("/getTopPodcastsFromItunes", getTopPodcastsFromItunes); app.post("/getEpisodes", jsonParser, function (req, res) { console.log(req.body.url); let dataAsJson = {}; fetch(req.body.url) .then((response) => response.text()) .then((str) => { dataAsJson = JSON.parse(convert.xml2json(str)); }) .then(() => { return res.json({ dataAsJson, }); }) .catch((error) => { console.log(error); return res.json({ error, }); }); }); https .createServer( { key: fs.readFileSync( "/etc/letsencrypt/live/www.justheard.ca/privkey.pem" ), cert: fs.readFileSync( "/etc/letsencrypt/live/www.justheard.ca/fullchain.pem" ), }, app ) .listen(8000, function () { console.log( "Example app listening on port 3000! Go to https://localhost:8000/" ); });
define([], function () { return { "PropertyPaneDescription": "Configure the leaderboard.", "ConnectivityGroupName": "Connectivity", "ApiUrlFieldLabel": "API-Url", "ValidateApiUrlNotNull": "The API-Url must not be empty.", "ValidateApiUrlValidUrl": "The API-Url must be a valid URL.", "VisibilityGroupName": "Visibility", "ShowPointSystemLabel": "Show Point system", "ShowRankSystemLabel": "Show rank system", "UITitle": "Point-System", "UIDescription": "Shows, for which actions, how much points you get.", "UITableDescription": "Description", "UITablePoints": "Points", "UITableRank": "Rank", "UITableBadge": "Badge", "UITableRequiredPoints": "Required Points" } });
const path = require("path"); const env = process.env.NODE_ENV; // Get all entry points from Scripts/Editors const glob = require('glob'); const entryArray = glob.sync('Scripts/Editors/*.js'); const entryObject = entryArray.reduce((acc, item) => { const name = item.replace('Scripts/Editors/', '').replace('.js', ''); acc[name] = path.resolve(__dirname, item); return acc; }, {}); module.exports = { mode: env || 'development', entry: entryObject, output: { filename: "[name].js", libraryTarget: "amd", libraryExport: "default", path: path.resolve(__dirname, "ClientResources/scripts/") }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ['@babel/preset-react', '@babel/preset-env', "@babel/preset-typescript"] }, } } ] }, externals: [ "dojo/_base/declare", "dijit/_WidgetBase" ] };
const natural = require('natural'); const wordnet = new natural.WordNet(); function getDef(word, synonym, callback) { wordnet.lookup(word, function(results) { var data = []; for (let i = 0; i < results.length; i++) { if (results[i].synonyms.indexOf(synonym) != -1) { data.push(results[i]); } } if (data.length > 0) callback(null, data); else callback(null, results); }) } exports.getDef = getDef;
import styled from "styled-components"; import PaprikaInput from "@paprika/input"; import stylers from "@paprika/stylers"; import tokens from "@paprika/tokens"; export const Input = styled(PaprikaInput)` input[data-pka-anchor="input"] { border: none; border-bottom: 1px solid ${tokens.color.black}; border-radius: 0; height: 100%; left: 0; position: absolute; top: 0; width: 100%; &:focus { ${stylers.focusRing()} border-bottom-color: transparent; border-radius: ${tokens.border.radius}; } } `; export const Wrapper = styled.div` height: ${stylers.spacer(4)}; padding: 0 ${stylers.spacer(3)} 0 ${tokens.spaceSm}; position: relative; `; export const Trigger = styled.div` max-width: 280px; min-width: 80px; overflow: hidden; padding: 0 ${tokens.spaceLg}; `;
import React from "react"; const CurrentUserContext = React.createContext(undefined); const CurrentUserDispatchContext = React.createContext(undefined); const HasAppliedToJobContext = React.createContext(undefined); const HasAppliedToJobDispatchContext = React.createContext(undefined) const CompaniesContext = React.createContext(undefined); const CompaniesDispatchContext = React.createContext(undefined); const JobsContext = React.createContext(undefined); const JobsDispatchContext = React.createContext(undefined); export { CurrentUserContext, CurrentUserDispatchContext, HasAppliedToJobContext, HasAppliedToJobDispatchContext, CompaniesContext, CompaniesDispatchContext, JobsContext, JobsDispatchContext };
const thesaurus = require('thesaurus'); /* based on wordnet.princeton.edu */ function makeChain(query, allSynonyms, callback) { const startWord = query.start.toLowerCase(); const endWord = query.end.toLowerCase(); const reg = /^[a-z]+$/; /* eliminate words with non-alpha chars */ const nodeNumberLimit = 20; // no chains more than this number of nodes const synonymLevel = query.synonymLevel; // cut list of synonyms for each word off at this limit let currentNodeNumber = query.nodeLimit; // this is original node limit, up to nodeNumberLimit let foundChain = false; let attemptCount = 0; /* test for missing words, words not in db */ if (!startWord || !endWord) { callback("Please enter two search words."); } else if (!reg.test(startWord) || !reg.test(endWord)) { callback("Please enter single words with no spaces or special characters."); } else if (startWord == endWord) { callback("Please enter different words."); } else if (getSynonyms(startWord, []).length == 0) { callback("The first word was not found."); } else if (getSynonyms(endWord, []).length == 0) { callback("The second word was not found."); } else { getChain(); } function getChain() { if (currentNodeNumber < nodeNumberLimit) { currentNodeNumber++; // for next chain if (!foundChain) { buildChain( [{word:startWord}], [{ word:endWord, synonyms: getSynonyms(endWord, allSynonyms.slice(0)) }], allSynonyms.slice(0) ); if (!foundChain) getChain(); } } else { callback(`Your search was not able to be performed with the current parameters. ${attemptCount} attempts.`); } } /* get synonyms of word up to synonym limit except synonyms already used */ function getSynonyms(word, allSynsCopy) { const temp = thesaurus.find(word); const synonyms = []; for (let i = 0; i < temp.length; i++) { const syn = temp[i]; if ( // various tests, play w these reg.test(syn) && !syn.includes(word) && !word.includes(syn) && allSynsCopy.indexOf(syn) == -1 && allSynsCopy.indexOf(syn + "s") == -1 && synonyms.length < 10 ) { synonyms.push({ word: syn }); } } return synonyms; } /* recursively builds chains one node at a time uses one chain starting with start and one with end advances each one at a time until meets in the middle */ function buildChain(startChain, endChain, allSyns) { const startIndex = startChain.length - 1; const endIndex = endChain.length - 1; let allSynsCopy = allSyns.slice(0); // get synonyms of last word in start chain startChain[startIndex].synonyms = getSynonyms(startChain[startIndex].word, allSynsCopy); // add new syns to all syns for (let i = 0; i < startChain[startIndex].synonyms.length; i++) { allSynsCopy.push(startChain[startIndex].synonyms[i].word); } // test each new syn again the syns of last word in end chain for (let i = 0; i < startChain[startIndex].synonyms.length; i++) { const startCopy = startChain.slice(0); // object values will be refs, won't push new ones const startSyn = startChain[startIndex].synonyms[i]; startCopy.push(startSyn); // endchain already has syns bc it was previous start chain for (let j = 0; j < endChain[endIndex].synonyms.length; j++) { const endSyn = endChain[endIndex].synonyms[j]; attemptCount++; if (startSyn.word == endSyn.word && !foundChain) { foundChain = true; // if chain is found, add endchain to start chain in reverse order for (let k = endChain.length - 1; k >= 0; k--) { startCopy.push( endChain[k] ); } // format data for front end const chain = []; chain[0] = { word: startWord }; chain[startCopy.length - 1] = { word: endWord }; let nextIndex = -1; for (let k = 1; k < startCopy.length - 1; k++) { chain[k] = {}; chain[k].word = startCopy[k].word; chain[k].alts = []; // save synonym alternatives for swapping syns const alts = startCopy[k + (k > startCopy.length - 2 ? 1 : -1)].synonyms; for (let l = 0; l < alts.length; l++) { // syndex is the synonym "level", index in syn list if (alts[l].word == chain[k].word) chain[k].syndex = l; chain[k].alts.push(alts[l].word); } } callback(null, chain); // send data back to app.js return; } } // if chain hasn't been found keep building chains if (startCopy.length + endChain.length < currentNodeNumber && !foundChain) { buildChain(startCopy, endChain, allSynsCopy); /* fastest ?*/ } /* current version no longer swaps start and end start just builds to end syns better performance, perhaps because fewer for loops per attempt? */ } if (attemptCount > 1000000) { if (!foundChain) { callback(`Your search was aborted after ${attemptCount} attempts.`); foundChain = true; } return; } } } exports.makeChain = makeChain;
// import { checkA11yIssues } from "../../../helpers/jest-a11y/storybookPage"; // describe("Spinner", () => { // it("should be accessible", () => { // const result = checkA11yIssues({ // kind: "Spinner/Automation Tests/Accessibility", // story: "Default", // }); // return result.then(component => { // expect(component).toBeAccessible(); // }); // }); // });
import { FETCH_ALL, CREATE, UPDATE, DELETE, FILTER_ALL } from '../constants/actionTypes'; import * as api from '../api'; import swal from 'sweetalert'; import Swal from 'sweetalert2'; export const getPosts = () => async (dispatch) => { try { const { data } = await api.fetchPosts(); dispatch({ type: FETCH_ALL, payload: data.sort(function compare(a, b) { var dateA = new Date(a.createdAt); var dateB = new Date(b.createdAt); return dateB - dateA; }) }) } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong! Check your connection and try again!' }) } } export const filterPosts = (text) => async (dispatch) => { try { const { data } = await api.fetchPosts(); dispatch({ type: FETCH_ALL, payload: data.sort(function compare(a, b) { var dateA = new Date(a.createdAt); var dateB = new Date(b.createdAt); return dateB - dateA; }) }) dispatch({ type: FILTER_ALL, payload: text }) } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong! Please try again later!' }) } } export const getUserPosts = () => async (dispatch) => { const user = JSON.parse(localStorage.getItem('profile')); const userName = user?.result?.name; try { const { data } = await api.fetchUserPosts(userName); console.log(data); } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong!' }) } } export const createPost = (post) => async (dispatch) => { try { const { data } = await api.createPost(post); dispatch({ type: CREATE, payload: data }); swal("Published!", "The post was successfully published!", "success"); } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong! Make sure you selected .gif file smaller than 70Kb!' }) } } export const updatePost = (id, post) => async (dispatch) => { try { const { data } = await api.updatePost(id, post); dispatch({ type: UPDATE, payload: data }); swal("Updated!", "The post was updated successfully!", "success"); } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong! Check post data and try again!' }) } } export const deletePost = (id) => async (dispatch) => { try { await api.deletePost(id); dispatch({ type: DELETE, payload: id }); swal("Deleted!", "The post was successfully deleted!", "success"); } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong!' }) } } export const likePost = (id) => async (dispatch) => { try { const { data } = await api.likePost(id); dispatch({ type: UPDATE, payload: data }); } catch (error) { Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong! Make sure post is still published' }) } }
var imgObj = null; var animate ; var speed = 25; function init() { imgObj = document.getElementById('myImage'); imgObj.style.position= 'relative'; imgObj.style.left = '0px'; imgObj.style.top = '0px' } function moveRight(){ clearTimeout(animate); imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px'; animate = setTimeout(moveRight,speed); // call moveRight in 20msec } function moveLeft(){ clearTimeout(animate); imgObj.style.left = parseInt(imgObj.style.left) - 10 + 'px'; animate = setTimeout(moveLeft,speed); // call moveRight in 20msec } function moveUp(){ clearTimeout(animate); imgObj.style.top = parseInt(imgObj.style.top) - 10 + 'px'; animate = setTimeout(moveUp,speed); // call moveRight in 20msec } function moveDown(){ clearTimeout(animate); imgObj.style.top = parseInt(imgObj.style.top) + 10 + 'px'; animate = setTimeout(moveDown,speed); // call moveRight in 20msec } function stop(){ clearTimeout(animate); imgObj.style.left = '0px'; } document.onkeydown = checkKey; function checkKey(e) { e = e || window.event; if (e.keyCode == '38') { moveUp(); } else if (e.keyCode == '40') { moveDown(); } else if (e.keyCode == '37') { moveLeft(); } else if (e.keyCode == '39') { moveRight(); } } window.onload = init;
function selectionSort(arr) { for (let i = 0; i < arr.length; i++) { let indexMin = i; for (let j = i + 1; j < arr.length; j++) { if (arr[j] < arr[indexMin]) { indexMin = j; } } [arr[i], arr[indexMin]] = [arr[indexMin], arr[i]]; } return arr; } let array = [2, 3, 5, 4, 12, 14, 123, 54, 1]; console.log(selectionSort(array));
/*####################################################### Klasse Timelinescroll ###################################################*/ //********************** Attribute ************************** //************************************************************ var Divs = new Array(); var Toggles = new Array(); //********************** Methoden *************************** //************************************************************ function slide(num, flag){ obj = Divs[num]; window.clearTimeout(obj.motion); var step=32; uobj = obj.getElementsByTagName('TABLE')[0]; oht = obj.style.height; oht = oht.substring(0, oht.indexOf('px')); oht = parseInt(oht); uht = uobj.offsetHeight; if(flag>0){ step*=(1-oht/uht); step = Math.ceil(step); while ((step-1) > (uht-oht)) step--; oht+=step; obj.style.height= oht + 'px'; uobj.style.top = oht-uht; if(oht!=uht) obj.motion = window.setTimeout("slide("+ num +","+ flag +")", 83); else window.clearTimeout(obj.motion); } else { step*=(oht/uht); step = Math.ceil(step); while (step-1 > oht) step--; oht-=step; obj.style.height= oht + 'px'; uobj.style.top = oht-uht; if(oht!=0){ obj.motion = window.setTimeout("slide("+ num +","+ flag +")", 83); } else { window.clearTimeout(obj.motion); } } } function init_timeline () { var j = 0; for (i=0; i<document.getElementsByTagName('DIV').length; i++ ) { if(document.getElementsByTagName('DIV')[i].className=="dyn"){ Divs[j] = document.getElementsByTagName('DIV')[i]; Divs[j].motion=false; Divs[j].style.height="0px"; Table = Divs[j].getElementsByTagName('TABLE')[0]; //Table.style.top = -1*(Table.offsetHeight+Table.offsetTop) + 'px'; j++; } } j = 0; for (i=0; i<document.getElementsByTagName('A').length; i++ ) { if(document.getElementsByTagName('A')[i].className=="dyn"){ Toggles[j] = document.getElementsByTagName('A')[i]; Toggles[j].flag = 1; Toggles[j].j=j; Toggles[j].onclick = function () { slide(this.j, this.flag); this.flag*=-1; } j++; } } }
var divCustomer = "<tr><td>%CustomerID</td><td>%CustomerLevel</td><td>%CustomerName</td><td>%Gender</td><td>%Birthday</td><td>%SkinType</td><td>%Points</td><td>%Mobile</td><td>%ActiveStatus</td></tr>" var searchhtml = " <em>%add</em><span>“%value”</span><em></em>"; var btnclearhtml = "<button class=\"btn-clear darkbg\">清空</button>"; var searchlist = $(".selectedCondition")[0]; var customerList = JSON.parse(sourceDataList.customerList); var search = JSON.parse('{"CustomerName":"","Mobile":"","CustomerLevel":{"text":"","value":""},"Birthday1":"","Birthday2":"","RegisterDate1":"","RegisterDate2":"","ActiveStatus":{"text":"","value":""},"Points1":"","Points2":"","StoreID":{"text":"","value":""},"Valid":"True"}') AddData(); curBirthday(); LoadSearch(); LoadData(); AddSearchList(); $(function () { $(".btn-low-search.qingbg").click(function () { StartSearch(); }) $(".queresult.clearfix .check-box").click(function () { if ($(this).attr("class").indexOf("select") > -1) { $(this).removeClass("select"); $("#tbBirthday1").val(""); $("#tbBirthday2").val(""); StartSearch(); } else { $(".queresult.clearfix .check-box").removeClass("select"); $(this).addClass("select"); if ($(this).attr("btnIndex") == 0) { curBirthday(); search.RegisterDate1 = ""; search.RegisterDate2 = ""; StartSearch(); } if ($(this).attr("btnIndex") == 1) { $("#tbBirthday1").val(""); $("#tbBirthday2").val(""); search.RegisterDate1 = GetDate(6); search.RegisterDate2 = GetDate(-1); StartSearch(); } } }) $(".borderTop.memLevel .check-box").click(function () { if ($(this).attr("class").indexOf("select") > -1) { $(this).removeClass("select"); ClearSearch(); StartSearch(false); } else { $(".borderTop.memLevel .check-box").removeClass("select"); $(this).addClass("select"); var level = 0; if ($(this).attr("class").indexOf("basicCard") > -1) { level = 1; } if ($(this).attr("class").indexOf("goldenCard") > -1) { level = 2; } if ($(this).attr("class").indexOf("platCard") > -1) { level = 3; } setSelect("sltCustomerLevel", level); StartSearch(); } }); }) function randomDate(i, year) { var d = new Date(); var year = d.getYear() + 1900; var month = 12 - i % 11; return year + "-" + month + "-05"; } function GetDate(day) { var zdate = new Date(); var sdate = zdate.getTime() - (1 * 24 * 60 * 60 * 1000); var edate = new Date(sdate - (day * 24 * 60 * 60 * 1000)).Format("yyyy-MM-dd"); return edate; } function curBirthday() { var d = new Date(); var year = d.getYear() + 1900; var month = d.getMonth() + 1; var lastday = new Date(year, month + 1, 0) var daylast = lastday.getDate(); $("#tbBirthday1").val(month + "-1"); $("#tbBirthday2").val(month + "-" + daylast); } function setSelect(id, value) { $("#" + id).attr("value", value); var count = $("#" + id).get(0).options.length; for (var i = 0; i < count; i++) { if ($("#" + id).get(0).options[i].value == value) { $("#" + id).get(0).options[i].selected = true; break; } else $("#" + id).get(0).options[i].selected = false; } $("#" + id).parent().find(".value")[0].innerText = $("#" + id + " :selected").text(); } function StartSearch(needsearch) { //if (needsearch == false) // search.Valid = false; //else // search.Valid = true; LoadSearch(); AddSearchList(); LoadData(); } function ClearSearch() { $("#tbCustomerName").val(""); $("#tbMobile").val(""); setSelect("sltCustomerLevel", ""); $("#tbBirthday1").val(""); $("#tbBirthday2").val(""); setSelect("sltActiveStatus", ""); $("#tbPoints1").val(""); $("#tbPoints2").val(""); setSelect("sltStoreID", ""); $(".borderTop.memLevel .check-box").removeClass("select"); $(".queresult.clearfix .check-box").removeClass("select"); } function AddData() { customerList = JSON.parse('[{"CustomerID":"9000200","CustomerName":"Kate","CustomerLevel":"白金卡","UserName":"Kate","Gender":"女","Birthday":"1983-12-03","SkinType":"","Points":"2500","Mobile":"18601234567","ActiveStatus":"冻结","StoreID":"101","Brand":"","SkinProblem":"","Email":"","ZipCode":"200001","Address":"上海市闵行区","RegisterDate":"2013-01-01","AddUser":"admin"}]'); for (var i = 0; i < 19; i++) { var level; if (i < 15) level = "普通卡"; else if (i < 18) level = "金卡"; else level = "白金卡"; var status; if (i < 4) status = "无效"; else if (i < 8) status = "活跃"; else status = "冻结"; customerList.push({ "CustomerID": "900000" + i, "CustomerName": "Kate" + i, "CustomerLevel": level, "UserName": "Kate" + i, "Gender": "女", "Birthday": randomDate(i, 1987), "SkinType": "", "Points": "2500" + i * 10, "Mobile": "18601234" + i, "ActiveStatus": status, "StoreID": "10" + i % 2, "Brand": "", "SkinProblem": "", "Email": "", "ZipCode": "200001", "Address": "上海市闵行区", "RegisterDate": randomDate(i, 2013), "AddUser": "admin" }); } setSelect("sltCustomerLevel", 1); } function LoadData() { var table = $(".table-scroll .tableTh.tablemember")[0]; table.innerHTML = "<tr><td>Loading...</td></tr>"; setTimeout(loaddata); } function loaddata() { var table = $(".table-scroll .tableTh.tablemember")[0]; table.innerHTML = ""; var count = 0; for (var x = 0; x < customerList.length; x++) { var customer = customerList[x]; if (search != null && search != undefined) { if (search.CustomerName != "" && search.CustomerName != undefined && customer.CustomerName.indexOf(search.CustomerName) == -1) continue; if (search.Mobile != "" && search.Mobile != undefined && customer.Mobile.indexOf(search.Mobile) == -1) continue; if (search.CustomerLevel.text != "" && search.CustomerLevel != undefined && customer.CustomerLevel != search.CustomerLevel.text) continue; if (search.Birthday1 != "" && search.Birthday1 != undefined) { if (customer.Birthday.split('-')[1] != search.Birthday1.split('-')[0]) continue; else if (customer.Birthday.split('-')[1] < search.Birthday1.split('-')[1]) continue; } if (search.Birthday2 != "" && search.Birthday2 != undefined) { if (customer.Birthday.split('-')[1] != search.Birthday2.split('-')[0]) continue; else if (customer.Birthday.split('-')[1] > search.Birthday2.split('-')[1]) continue; } if (search.RegisterDate1 != "" && search.RegisterDate1 != undefined) { if (customer.RegisterDate.split('-')[0] != search.RegisterDate1.split('-')[0] || customer.RegisterDate.split('-')[1] != search.RegisterDate1.split('-')[1]) continue; else if (customer.RegisterDate.split('-')[2] < search.RegisterDate1.split('-')[2]) continue; } if (search.RegisterDate2 != "" && search.RegisterDate2 != undefined) { if (customer.RegisterDate.split('-')[0] != search.RegisterDate2.split('-')[0] || customer.RegisterDate.split('-')[1] != search.RegisterDate2.split('-')[1]) continue; else if (customer.RegisterDate.split('-')[2] > search.RegisterDate2.split('-')[2]) continue; } if (search.ActiveStatus.text != "" && search.ActiveStatus != undefined && customer.ActiveStatus != search.ActiveStatus.text) continue; if (search.Points1 != "" && search.Points1 != undefined && customer.Points < search.Points1) continue; if (search.Points2 != "" && search.Points2 != undefined && customer.Points > search.Points2) continue; if (search.StoreID.text != "" && search.StoreID != undefined && customer.StoreID != search.StoreID.value) continue; //if (search.Valid == false ) // continue; } count++; var divhtml = divCustomer; divhtml = ProcessData(divhtml, "CustomerID", customer.CustomerID); divhtml = ProcessData(divhtml, "CustomerLevel", customer.CustomerLevel); divhtml = ProcessData(divhtml, "CustomerName", customer.CustomerName); divhtml = ProcessData(divhtml, "Gender", customer.Gender); divhtml = ProcessData(divhtml, "Birthday", customer.Birthday); divhtml = ProcessData(divhtml, "SkinType", customer.SkinType); divhtml = ProcessData(divhtml, "Points", customer.Points); divhtml = ProcessData(divhtml, "Mobile", customer.Mobile); divhtml = ProcessData(divhtml, "ActiveStatus", customer.ActiveStatus); table.innerHTML += divhtml; } $(".queresult.clearfix .fr .h")[0].innerHTML = "\"" + count + "\""; } function LoadSearch() { search.CustomerName = $("#tbCustomerName").val(); search.Mobile = $("#tbMobile").val(); search.CustomerLevel = { "value": $("#sltCustomerLevel").get(0).value, text: $("#sltCustomerLevel :selected").text() }; search.Birthday1 = $("#tbBirthday1").val(); search.Birthday2 = $("#tbBirthday2").val(); search.ActiveStatus = { "value": $("#sltActiveStatus :selected").attr("value"), text: $("#sltActiveStatus :selected").text() }; search.Points1 = $("#tbPoints1").val(); search.Points2 = $("#tbPoints2").val(); search.StoreID = { "value": $("#sltStoreID :selected").attr("value"), text: $("#sltStoreID :selected").text() }; } function AddSearchList() { searchlist.innerHTML = ""; if (search.CustomerName != "" && search.CustomerName != undefined) AddSearch(search.CustomerName); if (search.Mobile != "" && search.Mobile != undefined) AddSearch(search.Mobile); if (search.CustomerLevel.text != "" && search.CustomerLevel != undefined) AddSearch(search.CustomerLevel.text); if (search.Birthday1 != "" && search.Birthday1 != undefined) AddSearch("大于等于" + search.Birthday1); if (search.Birthday2 != "" && search.Birthday2 != undefined) AddSearch("小于等于" + search.Birthday2); if (search.ActiveStatus.text != "" && search.ActiveStatus != undefined) AddSearch(search.ActiveStatus.text); if (search.Points1 != "" && search.Points1 != undefined) AddSearch("大于等于" + search.Points1); if (search.Points2 != "" && search.Points2 != undefined) AddSearch("小于等于" + search.Points2); if (search.StoreID.text != "" && search.StoreID != undefined) AddSearch(search.StoreID.text); if (searchlist.innerHTML != "") { searchlist.innerHTML += btnclearhtml; $(".btn-clear.darkbg").bind("click", function () { ClearSearch(); StartSearch(); }) } } function AddSearch(value) { var html = searchhtml; if (searchlist.innerHTML == "") html = ProcessData(html, "add", ""); else html = ProcessData(html, "add", "+"); html = ProcessData(html, "value", value); searchlist.innerHTML += html; } function ProcessData(str, name, value) { return str.replace("%" + name, value); } Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }
import {ImmutablePropTypes, PropTypes} from 'src/App/helpers' import {pageRequestParamsModel} from 'src/App/models' import {immutableVideoItemModel} from 'src/generic/VideoItem/models' export const model = process.env.NODE_ENV === 'production' ? null : ImmutablePropTypes.exact({ isLoading: PropTypes.bool, isLoaded: PropTypes.bool, isFailed: PropTypes.bool, lastPageRequestParams: PropTypes.nullable(pageRequestParamsModel), videoList: ImmutablePropTypes.listOf(immutableVideoItemModel), })
import React, { Component } from "react"; import { connect } from "react-redux"; import { openModal, ATTENDANCE } from "ducks/Modals"; import { PARKING_LOT, PROJECTS, SUCCESSES, DESCRIPTION, setMeetingView } from "ducks/MeetingTimer"; import LoadingIndicator from "components/LoadingIndicator"; import { parseDate } from "utilities/dates"; import Button from "components/Button"; import peopleIcon from "images/people.png"; import parkingLotIcon from "images/ParkingLot-G.png"; import projectsIcon from "images/projectG.png"; import financialStatementsIcon from "images/financial-statement.png"; import successChallengeIcon from "images/Success-and-Challenge.png"; import Timer from "./containers/MeetingTimer"; import MeetingAgenda from "./containers/MeetingAgenda"; import MeetingSidebar from "./components/MeetingSidebar"; import ParkingLot from "./containers/ParkingLot"; import SuccessesChallenges from "./containers/SuccessesChallenges"; import ProjectsMilestones from "./containers/ProjectsMilestones"; import "./style.css"; class Meeting extends Component { constructor(props) { super(props); this.setCurrentView = this.setCurrentView.bind(this); this.state = { currentView: props.meetingView }; } setCurrentView(view) { return () => { /*if (this.props.meetingInProgress)*/ this.props.setMeetingView(view); this.setState({ currentView: view }); }; } componentWillReceiveProps(nextProps) { if (!this.props.meetingInProgress && nextProps.meetingInProgress) this.setState({ currentView: nextProps.meetingView }); } render() { let loading = false; for (let prop in this.props) { if (this.props[prop] === null) { loading = true; break; } } let date = {}; let heading = ""; if (!loading) { date = parseDate(this.props.meeting.date_time); heading = `${ this.props.meetingType.meeting_title } - ${date.fullMonthName.toUpperCase()} ${date.day}, ${date.year}`; } return ( <div> {loading && <LoadingIndicator />} {!loading && ( <div className="meeting"> <h3>{heading}</h3> <Button className="small-btn attendance" click={() => { this.props.openAttendanceModal(this.props.meeting.id); }} > <img src={peopleIcon} alt="" /> Attendance </Button> <div className="meeting-nav"> <Timer meeting={this.props.meeting} currentView={this.state.currentView} /> <div className="buttons"> <Button click={this.setCurrentView(PARKING_LOT)} className={ this.state.currentView === PARKING_LOT ? "active" : "" } > <img src={parkingLotIcon} alt="" /> Parking Lot<br /> {(this.props.meetingParkingLots.length || "no") + " issues"} </Button> <Button click={this.setCurrentView(PROJECTS)} className={ this.state.currentView === PROJECTS ? "active" : "" } > <img src={projectsIcon} alt="" /> Projects &amp;<br />Milestones </Button> <Button> <img src={financialStatementsIcon} alt="" /> Financial<br />Statements </Button> <Button click={this.setCurrentView(SUCCESSES)} className={ this.state.currentView === SUCCESSES ? "active" : "" } > <img src={successChallengeIcon} alt="" /> Successes &amp;<br />Challenges </Button> </div> <div className="clearfix" /> </div> <div> <MeetingAgenda sections={this.props.meetingSections} topics={this.props.meetingTopics} active={this.props.meetingInProgress} meeting={this.props.meeting} /> {this.state.currentView === DESCRIPTION && ( <MeetingSidebar description={this.props.meetingType.description} /> )} {this.state.currentView === PARKING_LOT && ( <ParkingLot meeting={this.props.meeting.id} /> )} {this.state.currentView === SUCCESSES && ( <SuccessesChallenges meeting={this.props.meeting.id} /> )} {this.state.currentView === PROJECTS && ( <ProjectsMilestones meeting={this.props.meeting.id} /> )} </div> </div> )} </div> ); } } // const mapStateToProps = (state, { match }) => { let meeting = state.meetings.items.find( ({ id }) => id === parseInt(match.params.meetingId, 10) ) || null; let meetingSections = state.meetingSections.items.filter( ({ meeting_type }) => meeting_type === meeting.meeting_type ) || null; let meetingTopics = state.meetingTopics.items.filter(({ section }) => meetingSections.find(({ id }) => id === section) ); let meetingType = state.meetingTypes.items.find( ({ id }) => (meeting ? id === meeting.meeting_type : false) ) || null; let meetingParkingLots = state.meetingParkingLots.items.filter( pl => pl.meeting === meeting.id ); let meetingView = state.meetingTimer.meeting_view; return { meeting, meetingSections, meetingTopics, meetingType, meetingInProgress: meeting ? state.meetingTimer.meeting_id === meeting.id : null, meetingParkingLots, meetingView }; }; const mapDispatchToProps = dispatch => ({ openAttendanceModal: meeting_id => { dispatch(openModal(ATTENDANCE, { meeting_id })); }, setMeetingView: meeting_view => { dispatch(setMeetingView(meeting_view)); } }); export default connect(mapStateToProps, mapDispatchToProps)(Meeting);
import React, { Component } from 'react'; import { Text, View, StyleSheet, Image, Dimensions, } from 'react-native'; import Card from '../../../../components/Card'; import { BCLE_ORDER_PAY_STATUS_DESCRIBE, ORDER_STATUS_ONLINE } from '../../../../const/order'; import { keepTwoDecimal } from '../../../../config/utils'; import math from '../../../../config/math'; import ImageView from '../../../../components/ImageView'; const exchangeFToY = fen => keepTwoDecimal(math.divide(fen, 100)); const green = require('../../../../images/account/xiaokebi.png'); const shiwuquan = require('../../../../images/account/shiwuquan.png'); const { width, height } = Dimensions.get('window'); function getwidth(val) { return width * val / 375; } export default class OrderGoodsCard extends Component { renderRefund(refund) { console.log('renderRefund', refund); return ( <View style={styles.refund}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <Image source={refund.payStatusInfo.noPay ? shiwuquan : green} /> { !refund.itemRefundId ? null : <Text style={[styles.c7f14, { marginLeft: 8 }]}>{`售后编号:${refund.itemRefundId}`}</Text> } </View> <Text style={!refund.pPurchaseRefundId ? styles.cgreenF14 : styles.cyellowF14}> {refund.payStatusInfo.name} </Text> </View> ); } render() { const { isShouhou, // 售后 orderDetail, // 订单详情 style, } = this.props; const { data = [], orderStatus, getSomeData = {}, price, resmoney, } = orderDetail || {}; const isPlatformPrice = [ORDER_STATUS_ONLINE.STAY_EVALUATE, ORDER_STATUS_ONLINE.COMPLETELY].includes(orderStatus); /** 商品信息 */ const goods = data.map(item => ({ refund: !isShouhou ? null : { itemRefundId: item.itemRefundId, // 售后编号 pPurchaseRefundId: item.pPurchaseRefundId, // 售后Id bcleOrderPayStatus: item.pBcleOrderPayStatus, // 售后商品支付状态 payStatusInfo: BCLE_ORDER_PAY_STATUS_DESCRIBE[item.pBcleOrderPayStatus] || {}, }, skuUrl: item.skuUrl, // 商品图片 goodsName: item.goodsName, // 商品名称 skuName: item.skuName, // 商品规格 platformPrice: exchangeFToY(isPlatformPrice ? item.platformShopPrice : item.platformPrice), // 商品实际价格 originalPrice: exchangeFToY(item.originalPrice), })); /** 订单商品价格统计信息 */ const priceInfo = [ { title: '总数:', value: `x${data.length}`, style: styles.c2f14 }, { title: '共计:', value: `¥${exchangeFToY(price)}` }, { title: '消费券支付:', value: exchangeFToY(getSomeData.voucher) }, { title: '商家券支付:', value: exchangeFToY(getSomeData.shopVoucher) }, { title: '现金支付:', value: `¥${exchangeFToY(resmoney)}` }, ]; return ( <Card style={style}> { goods.map((item, index) => ( <View key={item.id}> {item.refund ? this.renderRefund(item.refund) : null} <View style={[styles.serviceItem, index === data.length - 1 ? {} : styles.borderBt]}> <View style={styles.serviceItemimg}> <ImageView source={{ uri: item.skuUrl }} sourceWidth={getwidth(80)} sourceHeight={getwidth(80)} resizeMode='cover' /> </View> <View style={styles.goods}> <View style={styles.textItem}> <View style={{ flex: 1 }}> <Text style={styles.c2f14}>{item.goodsName}</Text> </View> </View> <View style={{ marginTop: 13 }}> <Text style={styles.c7f12}>{item.skuName}</Text> </View> <View style={styles.price}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <Text style={styles.credf14}>{`¥${item.platformPrice}`}</Text> <Text style={[styles.ccf10, { textDecorationLine: 'line-through' }]}>{` 市场价(¥${item.originalPrice})`}</Text> </View> </View> </View> </View> </View> )) } <View style={styles.serviceBottom}> { priceInfo.map(item => ( <View style={styles.serviceBottomItem}> <View><Text style={styles.c7f14}>{item.title}</Text></View> <View><Text style={[styles.credf14, item.style]}>{item.value}</Text></View> </View> )) } </View> </Card> ); } } const styles = StyleSheet.create({ refund: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 6, alignItems: 'center', }, serviceBottom: { width: getwidth(355), height: 170, borderTopColor: '#D7D7D7', borderTopWidth: 0.5, borderRadius: 6, overflow: 'hidden', }, serviceBottomItem: { width: getwidth(325), flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }, c2f14: { color: '#222', fontSize: 14, }, c7f14: { color: '#777', fontSize: 14, }, credf14: { color: '#EE6161', fontSize: 14, }, cgreenF14: { color: '#46D684', fontSize: 14, }, cyellowF14: { color: '#FA994A', fontSize: 14, }, price: { flexDirection: 'row', height: 44, alignItems: 'center', justifyContent: 'space-between', }, borderBt: { borderBottomColor: '#D7D7D7', borderBottomWidth: 0.5, }, goods: { flex: 1, height: 80, marginLeft: 15, alignSelf: 'center', }, serviceItem: { width: getwidth(325), height: 110, flexDirection: 'row', backgroundColor: '#fff', }, serviceItemimg: { width: getwidth(80), height: 110, justifyContent: 'center', alignItems: 'center', }, textItem: { width: '100%', flexDirection: 'row', justifyContent: 'space-between', }, ccf10: { color: '#CCCCCC', fontSize: 10, }, });
/* Author: Jacob Williams Purpose: these are functions that are use when users interact with index.html usage: click buttons and enter info in index.html */ // addUser takes information from the text fields and sends them to server.js to be added into the db function addUser(){ var httpRequest = new XMLHttpRequest(); if(!httpRequest){ return false; } // gets info from text inputes let u = document.getElementById('username').value; let p = document.getElementById('password').value; httpRequest.onreadystatechange = () => { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { console.log(httpRequest.responseText); } else { alert('ERROR'); } } } newUser = { 'username': u, 'password': p, 'listings':[], 'purchases':[]} dataString = JSON.stringify(newUser); let url = '/add/user/'; httpRequest.open('POST',url); httpRequest.setRequestHeader('Content-type', 'application/json'); httpRequest.send(dataString); } // addItem takes information from the text input fields and send them to server.js to be added into the db function addItem(){ var httpRequest = new XMLHttpRequest(); if(!httpRequest){ return false; } // get info let t = document.getElementById('title').value; let d = document.getElementById('desc').value; let i = document.getElementById('image').value; let p = document.getElementById('price').value; let s = document.getElementById('status').value; let u = document.getElementById('username_item').value; httpRequest.onreadystatechange = () => { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { console.log(httpRequest.responseText); } else { alert('ERROR'); } } } newItem = {'title':t,'description':d, 'image':i, 'price':p, 'status':s}; dataString = JSON.stringify(newItem); let url = '/add/item/'+u; httpRequest.open('POST',url); httpRequest.setRequestHeader('Content-type', 'application/json'); httpRequest.send(dataString); }
'use strict'; /** * Module dependencies. */ const mongoose = require('mongoose'), debug = require('debug'), _ = require('underscore'), placeSearch = require('../lib/place-search'), Message = mongoose.model('Message'), Query = mongoose.model('Query'), Choice = mongoose.model('Choice'); const log = debug('telegrambot-navermap:inline-query'); module.exports = exports = (bot) => { bot.on('inline_query', (msg) => { log('Got query: ', msg); if (!msg.query) { return bot.answerInlineQuery(msg.id, []); } placeSearch(msg.query).then((places) => { const inlineQueryResults = places.map((place, index) => { const payload = { type: 'article', id: `${msg.id}/${index}`, title: place.title, description: place.description || place.address, url: place.link || place.appLink, disable_web_page_preview: true, message_text: _.chain([ `<strong>[네이버 지도] ${place.title}</strong>`, place.telephone, place.address, place.description, '\n', place.link && `<a href="${place.link}">상세정보 바로가기</a>`, place.appLink && `<a href="${place.appLink}">네이버 지도 앱에서 열기</a>`, '\n', '<a href="https://www.lawtalk.co.kr/tg2">[광고] 개발자가 만든 좋은 변호사 찾는 로톡 바로가기</a>' ]).compact() .value() .join('\n'), parse_mode: 'HTML' }; if (place.thumb) { payload.thumb_url = place.thumb; } return payload; }); bot.answerInlineQuery(msg.id, inlineQueryResults, { cache_time: 86400 }); }).catch((e) => { log(e.stack); bot.answerInlineQuery(msg.id, [], { cache_time: 0 }); }); Query.create(msg, (e) => { if (e) { log(e.stack ? e.stack : e); } }); }); bot.on('chosen_inline_result', (msg) => { Choice.create(msg).exec((e) => { if (e) { log(e.stack ? e.stack : e); } }); }); };
var fs = require('fs'); var ids; fs.readFile('./names.csv', (err, data) => { var test = data .toString() .replace(/\r?\n|\r/g, ',') .split(',') .map(function(e){ return e.toString() }) .filter(function(e){ return e.indexOf(' ') !== -1 }) .map(function(e){ return e.replace(/ /g, '').trim().toLowerCase() }) .filter(function(e, i){ return (i !== 0 && i !== 1 && i !== 2) }); var all = {}; for(var index in test){ all[test[index]] = { answered: false, answer: null } } fs.writeFile('identification.json', JSON.stringify(all), (err) => { if (err) throw err; console.log('The file has been saved!'); }); });
import * as React from "react"; import {useEffect, useState} from "react"; import MoviesDAL from "../adapters/MoviesDAL"; import SubsDAL from "../adapters/SubsDAL"; import {AppBar, Box, Card, Tab, Tabs} from "@material-ui/core"; import CardMedia from "@material-ui/core/CardMedia"; import CardContent from "@material-ui/core/CardContent"; import Typography from "@material-ui/core/Typography"; import {makeStyles} from "@material-ui/core/styles"; import {Rating} from "@material-ui/lab"; import Divider from "@material-ui/core/Divider"; import Review from '../components/Movie/Review' import AddReview from "../components/Movie/AddReview"; import PropTypes from "prop-types"; import MemberList from "../components/Movies/Movie/MemberList"; const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper, }, card: { maxWidth: '700px', margin: "20px auto 50px", transition: "0.3s", boxShadow: "0 8px 40px -12px rgba(0,0,0,0.3)", "&:hover": { boxShadow: "0 16px 70px -12.125px rgba(0,0,0,0.3)" } }, media: { margin: "20px auto 0", width: "50%", height: "80%", borderRadius: "10px", boxShadow: "0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23)", position: "relative", zIndex: 1000 }, content: { textAlign: "left", padding: theme.spacing.unit * 3 }, divider: { margin: `${theme.spacing.unit * 3}px 0` }, heading: { fontWeight: "bold" }, subheading: { lineHeight: 1.8, textAlign: '' } })); function TabPanel(props) { const {children, value, index, ...other} = props; return ( <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && ( <Box p={3}> <Typography>{children}</Typography> </Box> )} </div> ); } TabPanel.propTypes = { children: PropTypes.node, index: PropTypes.any.isRequired, value: PropTypes.any.isRequired, }; function a11yProps(index) { return { id: `simple-tab-${index}`, 'aria-controls': `simple-tabpanel-${index}`, }; } function Movie(props) { const classes = useStyles(); const {match: {params}} = props; const {id} = params; const [movie, setMovie] = useState() const [memberList, setMemberList] = useState([]) const [value, setValue] = React.useState(0); const [toggleRerender, setToggleRerender] = useState(false) const handleChange = (event, newValue) => { setValue(newValue); }; useEffect(async () => { const respMovie = await MoviesDAL.getMovie(id) const memberList = await SubsDAL.getMemberList(id) setMovie(respMovie.data) setMemberList(memberList.data) }, [toggleRerender]) const handleReview = async (obj) => { await MoviesDAL.addReview(id, obj) setToggleRerender(!toggleRerender) } return ( <div> { movie && <Card className={classes.card}> <CardContent className={classes.content}> <AppBar position="static"> <Tabs value={value} onChange={handleChange} aria-label="tabs" > <Tab label="Summary" {...a11yProps(0)} /> <Tab label="Reviews" {...a11yProps(1)} /> { memberList.length > 0 && <Tab label="Subscribers" {...a11yProps(2)} /> } </Tabs> </AppBar> <TabPanel value={value} index={0}> <CardMedia className={classes.media} component="img" image={movie.image.original} alt="cover" /> <br/> <Typography gutterBottom variant="h4" component="div" className={"MuiTypography--heading"} > {movie.name}, {movie.premiered.substring(0, 4)} </Typography> <Divider className={classes.divider} light/> <Box component="fieldset" mb={3} borderColor="transparent"> <Typography component="legend">Rating {movie.rating}</Typography> <Rating name="read-only" value={movie.rating} readOnly/> </Box> Genres: {movie.genres.toString().replaceAll(",", "/ ")} <br/> Premiered: {movie.premiered} <br/> Language: {movie.language} <br/> Official site: <a href={movie.officialSite} target="_blank">{movie.officialSite}</a> <Divider className={classes.divider} light/> <Typography variant="body2" color="text.secondary"> <div dangerouslySetInnerHTML={{__html: movie.summary}}/> </Typography> </TabPanel> <TabPanel value={value} index={1}> { movie.comments.map((c, i) => { return <Review key={i} comments={c}/> }) } <AddReview rerenderParentCallback={() => setToggleRerender(!toggleRerender)} callBackAddReview={(obj) => handleReview(obj)} /> </TabPanel> <TabPanel value={value} index={2}> { memberList && <MemberList list={memberList}/> } </TabPanel> </CardContent> </Card> } </div> ); } export default Movie;
var revalidator = require('revalidator') module.exports = function schemaValidator (schema) { return function (value) { var results = revalidator.validate(value, schema) if (!results.valid) throw new Error(JSON.stringify(results.errors)) } }
var template = <p> change </p>; var appRoot = document.getElementById('app'); ReactDOM.render(template, appRoot);
import firebase from 'firebase'; const config = { apiKey: 'AIzaSyBvhiQan31wb2NstBcVplRFnCxw_QCexW0', authDomain: 'laarrc.firebaseapp.com', databaseURL: 'https://laarrc.firebaseio.com', projectId: 'laarrc', storageBucket: 'laarrc.appspot.com', // messagingSenderId: '587806808328', }; firebase.initializeApp(config); const version = 'v0'; class FireService { static db = firebase.database(); static addObserver(path, event, callback) { FireService .db .ref() .child(version) .child(path) .on(event, callback); } static removeObserver(path, event, callback) { FireService .db .ref() .child(version) .child(path) .off(event, callback); } static async readOnce(path) { return ( FireService .db .ref() .child(version) .child(path) .once('value') ); } } export default FireService;
import React, { useState, useEffect } from "react"; let born = false; function UseEffectHook() { const [growth, setGrowth] = useState(0); const [nirvana, setNirvana] = useState(false); useEffect(() => { if (born) { document.title = "nirvana attained"; } }, [nirvana]); // component mounted useEffect(() => { console.log(`I am born`); }, []); // component updated useEffect(() => { if (born) { console.log("learning"); } else { born = true; } if (growth > 70) { setNirvana(true); } return () => { console.log("cleanup"); }; }); const growHandle = () => { setGrowth(growth + 10); }; return ( <> <h2>Use Effect</h2> <h3>growth: {growth}</h3> <button onClick={growHandle}>learn and grow</button> </> ); } export default UseEffectHook;
/** * Created by xiaojiu on 2017/3/25. */ define(['../../../app','../../../services/platform/information/platformEquipmentManagementService'], function (app) { var app = angular.module('app'); app.controller('platformEquipmentManagementCtrl', ['$scope','$sce','platformEquipmentManagement', function ($scope,$sce,platformEquipmentManagement) { // query moudle setting $scope.querySeting = { items: [{ // type: 'select', // model: 'partyId', // selectedModel:'partyIdSelect', // title: '所属运营' type: 'text', model: 'equipmentName', title: '设备名称' }], btns: [{ text: $sce.trustAsHtml('查询'), click: 'searchClick' }] }; //theadr $scope.thHeader=platformEquipmentManagement.getThead(); //初始化查询数据 var pmsSearch = platformEquipmentManagement.getSearch(); pmsSearch.then(function (data) { $scope.searchModel=data.query; $scope.searchModel.partyIdSelect = -1; $scope.storageRDC = data.query.rdcId; $scope.storageCDC = data.query.cdcId; getTable(); }); //获取table function getTable(){ var opts = angular.extend({}, $scope.searchModel, {});//克隆出新的对象,防止影响scope中的对象 console.log(opts); opts.rdcId = $scope.storageSelectedRDC;//获取仓储选择第一个下拉框 opts.cdcId = $scope.storageSelectedCDC;//获取仓储选择第二个下拉框 opts.partyId=$scope.searchModel.partyIdSelect; opts.pageNo = $scope.paging.currentPage; opts.pageSize = $scope.paging.showRows; platformEquipmentManagement.getDataTable({param:{query:opts}},'/Ckequipment/queryPfEquipmentList') .then(function (data) { if(data.code==-1){ alert(data.message); $scope.result = []; $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows, }; return false; } $scope.result=data.grid; $scope.paging = { totalPage: data.total, currentPage: $scope.paging.currentPage, showRows: $scope.paging.showRows, }; }); } //查询 $scope.searchClick= function () { $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows }; getTable(); } $scope.goToPage= function () { getTable(); } //分页对象 $scope.paging = { totalPage: 1, currentPage: 1, showRows: 30, }; }]); });
$(function () { skinChanger(); activateNotificationAndTasksScroll(); setSkinListHeightAndScroll(true); setSettingListHeightAndScroll(true); $(window).resize(function () { setSkinListHeightAndScroll(false); setSettingListHeightAndScroll(false); }); }); //Skin changer function skinChanger() { $('.right-sidebar .demo-choose-skin li').on('click', function () { var $body = $('body'); var $this = $(this); var existTheme = $('.right-sidebar .demo-choose-skin li.active').data('theme'); $('.right-sidebar .demo-choose-skin li').removeClass('active'); $body.removeClass('theme-' + existTheme); $this.addClass('active'); $body.addClass('theme-' + $this.data('theme')); }); } //Skin tab content set height and show scroll function setSkinListHeightAndScroll(isFirstTime) { var height = $(window).height() - ($('.navbar').innerHeight() + $('.right-sidebar .nav-tabs').outerHeight()); var $el = $('.demo-choose-skin'); if (!isFirstTime){ $el.slimScroll({ destroy: true }).height('auto'); $el.parent().find('.slimScrollBar, .slimScrollRail').remove(); } $el.slimscroll({ height: height + 'px', color: 'rgba(0,0,0,0.5)', size: '6px', alwaysVisible: false, borderRadius: '0', railBorderRadius: '0' }); } //Setting tab content set height and show scroll function setSettingListHeightAndScroll(isFirstTime) { var height = $(window).height() - ($('.navbar').innerHeight() + $('.right-sidebar .nav-tabs').outerHeight()); var $el = $('.right-sidebar .demo-settings'); if (!isFirstTime){ $el.slimScroll({ destroy: true }).height('auto'); $el.parent().find('.slimScrollBar, .slimScrollRail').remove(); } $el.slimscroll({ height: height + 'px', color: 'rgba(0,0,0,0.5)', size: '6px', alwaysVisible: false, borderRadius: '0', railBorderRadius: '0' }); } //Activate notification and task dropdown on top right menu function activateNotificationAndTasksScroll() { $('.navbar-right .dropdown-menu .body .menu').slimscroll({ height: '254px', color: 'rgba(0,0,0,0.5)', size: '4px', alwaysVisible: false, borderRadius: '0', railBorderRadius: '0' }); } //Google Analiytics ====================================================================================== addLoadEvent(loadTracking); var trackingId = 'UA-30038099-6'; function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function () { oldonload(); func(); } } } function loadTracking() { (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', trackingId, 'auto'); ga('send', 'pageview'); } //======================================================================================================== function showNotification(colorName, text, placementFrom, placementAlign, animateEnter, animateExit, timer) { if (colorName === null || colorName === '') { colorName = 'bg-black'; } if (text === null || text === '') { text = 'Turning standard Bootstrap alerts'; } if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; } if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; } if (timer === null || timer === '') { timer = 1000; } var allowDismiss = true; $.notify({ message: text }, { type: colorName, allow_dismiss: allowDismiss, newest_on_top: true, timer: timer, placement: { from: placementFrom, align: placementAlign }, z_index: 999999, animate: { enter: animateEnter, exit: animateExit }, template: '<div data-notify="container" class="bootstrap-notify-container alert alert-dismissible {0} ' + (allowDismiss ? "p-r-35" : "") + '" role="alert">' + '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">&times;</button>' + '<span data-notify="icon"></span> ' + '<span data-notify="title">{1}</span> ' + '<span data-notify="message">{2}</span>' + '<div class="progress" data-notify="progressbar">' + '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' + '</div>' + '<a href="{3}" target="{4}" data-notify="url"></a>' + '</div>' }); }
/* eslint-env browser */ /* eslint-env jquery */ // BuildBook declared to build all books with help of Handlebars function buildBook(data) { const rawTemplate = document.getElementById('entry-template').innerHTML; const compiledTemplate = Handlebars.compile(rawTemplate); const builtbooks = compiledTemplate(data); const container = document.getElementById('books-container'); container.innerHTML = builtbooks; } // HTTP request function apiSearch() { $.ajax({ type: 'GET', url: 'script/booksCollection.json', success: buildBook, error(e) { console.log(e); }, }); } apiSearch();
import joi from 'joi' const weatherValidations = { // GET /weather weather: { headers: {}, query: { cityName: joi .string() .trim() .required() .description('name of the city whose weather is to be fetched') }, options: { allowUnknown: true } } } export { weatherValidations }
 angular .module("iCanHelp", ["ui.bootstrap", 'ngRoute']) .config(['$routeProvider',function ($routeProvider) { return [ $routeProvider.when('/', { templateUrl: 'app/home/index/index.html', controller: 'home.indexController', controllerAs: 'contr' }), $routeProvider.when('/account/login/:email?', { templateUrl: 'app/account/login/login.html', controller: "account.loginController" }), $routeProvider.when('/account/register', { templateUrl: 'app/account/register/register.html', controller: "account.registerController", controllerAs: 'contr' }) ]; }]);
/* * Author: Santhosh Nandhakumar * eMail ID: nsanthosh2409@gmail.com */ var gridTreeMap = {}; (function() { "use strict"; gridTreeMap.generate = function(){ var RIGHT = true; var LEFT = false; var DOWN = true; var UP = false; var SPLIT = true; var SLICE = false; var layout = SPLIT; /*var splitDirection = RIGHT; var sliceDirection = DOWN;*/ var numRows; var numCols; var idGrid =[]; var nextList; var idList = []; var treeName; function point(x,y){ var pt = {}; pt["x"] = x; pt["y"] = y; return pt; } function draw(data,tree){ treeName = tree; var area = sumMultidimensionalArray(data); numRows = Math.ceil(Math.sqrt(area)); /* //To manintain the number of rows always a odd number if(numRows%2 != 1){ numRows = numRows - 1; }*/ numCols = Math.ceil(area / numRows); data["rows"] = numRows; data["cols"] = numCols; for (var i=0; i<numRows; i++) { idGrid[i] = []; for (var j=0; j<numCols; j++) { idGrid[i][j] = { "parent" : "0"}; } } gridTreeMapMultiDimensional("0", data, layout); return [numRows,numCols]; } function gridTreeMapMultiDimensional(parent, data, fillLayout){ var layout = fillLayout; var mergeddata = []; if(isArray(data[0])) { // if we've got more dimensions of depth for(var i=0; i<data.length; i++) { mergeddata[i] = sumMultidimensionalArray(data[i]); } gridTreeSingleDimensional(parent,mergeddata,layout,false); layout = !layout for(var i=0; i<data.length;i++){ gridTreeMapMultiDimensional(parent+""+i,data[i],layout); } } else{ gridTreeSingleDimensional(parent,data,layout,true); } return idList; } function gridTreeSingleDimensional(parent,data, layout,isLeaf) { var pts = []; var startpt = {}; var i; for(i=0; i<data.length; i++) { startpt = findStartingPoint(parent,layout); if(isLeaf){ pts = fill(startpt, parent, i, Number(data[i].setSize),layout); } else{ pts = fill(startpt, parent, i, data[i],layout); } if(isLeaf){ if(treeName == "subsetTree"){ data[i]["coOrdinates"] = pts; } if(treeName == "degreeTree"){ data[i]["degreeCoOrdinates"] = pts; } if(treeName == "setTree"){ data[i]["setcoOrdinates"] = pts; } idList.push(pts); } } } function findStartingPoint(parent,layout){ var direction = true; var startPt = {}; var row, col; if(layout == SLICE){ endloop: for(col=0;col<numCols;col++){ if(direction == DOWN){ for(row=0;row<numRows;row++){ if(idGrid[row][col]["parent"] == parent){ startPt = point(col,row); startPt["direction"] = direction break endloop; } } } else{ for(row=numRows-1;row>-1;row--){ if(idGrid[row][col]["parent"] == parent){ startPt = point(col,row); startPt["direction"] = direction break endloop; } } } direction = !direction; } } else{ endloop: for(row=0;row<numRows;row++){ if(direction == RIGHT){ for(col=0;col<numCols;col++){ if(idGrid[row][col]["parent"] == parent){ startPt = point(col,row); startPt["direction"] = direction break endloop; } } } else{ for(col=numCols-1;col>-1;col--){ if(idGrid[row][col]["parent"] == parent){ startPt = point(col,row); startPt["direction"] = direction break endloop; } } } direction = !direction; } } return startPt; } function fill(startpt, parent, id, size,layout) { var row, col; var pt = {}; var pts = []; var direction = startpt.direction if(layout == SLICE){ endloop: for(col=startpt.x;col<numCols;col++){ if(direction == DOWN){ for(row=startpt.y;row<numRows;row++){ if(idGrid[row][col]["parent"] == parent){ idGrid[row][col]["parent"] = parent + "" + id; size--; pts[size] = point(col,row); if(size == 0){ break endloop; } } } startpt["y"] = numRows-1; } else{ for(row=startpt.y;row>-1;row--){ if(idGrid[row][col]["parent"] == parent){ idGrid[row][col]["parent"] = parent + "" + id; size--; pts[size] = point(col,row); if(size == 0){ break endloop; } } } startpt["y"] = 0; } direction = !direction; } } else{ endloop: for(row=startpt.y;row<numRows;row++){ if(direction == RIGHT){ for(col=startpt.x;col<numCols;col++){ if(idGrid[row][col]["parent"] == parent){ idGrid[row][col]["parent"] = parent + "" + id; size--; pts[size] = point(col,row); if(size == 0){ break endloop; } } } startpt["x"] = numCols -1; } else{ for(col=startpt.x;col>-1;col--){ if(idGrid[row][col]["parent"] == parent){ idGrid[row][col]["parent"] = parent + "" + id; size--; pts[size] = point(col,row); if(size == 0){ break endloop; } } } startpt["x"] = 0; } direction = !direction; } } return pts; } // isArray - checks if arr is an array function isArray(arr) { return arr && arr.constructor === Array; } // sumArray - sums a single dimensional array function sumArray(arr) { var sum = 0; var i; for (i = 0; i < arr.length; i++) { sum += arr[i].setSize; } return sum; } // sumMultidimensionalArray - sums the values in a nested array (aka [[0,1],[[2,3]]]) function sumMultidimensionalArray(arr) { var i, total = 0; if(isArray(arr[0])) { for(i=0; i<arr.length; i++) { total += sumMultidimensionalArray(arr[i]); } } else { total = sumArray(arr); } return total; } return draw; }(); })();
(function() { 'use strict'; angular .module('BlackSwanGitHub') .factory('githubFactory', ['$http', 'githubSearchDataService', function ($http, githubSearchDataService) { var githubFactory = {}; githubFactory.getRepos = function (_params) { var searchData = githubSearchDataService.getNew("repos", _params); return $http({ method: 'GET', url: searchData.url, params: searchData.object, }); }; githubFactory.getRepoIssues = function (_params) { var searchData = githubSearchDataService.getNew("repoIssues", _params); return $http({ method: 'GET', url: searchData.url, params: searchData.object, }); }; githubFactory.getRepoDetails = function (_params) { var searchData = githubSearchDataService.getNew("repoDetails", _params); return $http({ method: 'GET', url: searchData.url, params: searchData.object, }); }; return githubFactory; }]) .service('githubSearchDataService', function () { this.getApiBaseUrl = function (_params) { return "https://api.github.com/"; }; this.fillDataInObjectByList = function (_object, _params, _list) { angular.forEach(_list, function (value, key) { if (angular.isDefined(_params[value])) { _object.object[value] = _params[value]; } }); return _object; }; this.getNew = function (_type, _params) { var githubSearchData = { object: {}, url: "", }; if (angular.isDefined(_params.per_page)) { githubSearchData.object.per_page = _params.per_page; } switch (_type) { case "repos": githubSearchData = this.fillDataInObjectByList(githubSearchData, _params, [ 'sort', 'order', 'page', 'per_page' ]); githubSearchData.url = this.getApiBaseUrl() + "search/repositories?q=" + _params.q; break; case "repoIssues": githubSearchData = this.fillDataInObjectByList(githubSearchData, _params, ['page', 'per_page']); githubSearchData.url = this.getApiBaseUrl() + "search/issues?q=repo:" + _params.user + "/" + _params.repo; break; case "repoDetails": githubSearchData = this.fillDataInObjectByList(githubSearchData, _params, []); githubSearchData.url = this.getApiBaseUrl() + "repos/" + _params.user + "/" + _params.repo; break; } return githubSearchData; }; }); })();
/* Copyright 2016-2018 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Creates a prototype chain. * @param {Object[]} propsArray an array of properties for the prototype chain * @returns {Object} an object with a prototype chain. */ export default function protoChain(...propsArray) { let prev = Object.prototype; propsArray.forEach(props => { function F() { Object.keys(props).forEach(key => { this[key] = props[key]; }); } F.prototype = prev; prev = new F(); }); return prev; }
import React from "react"; import {Alert, Card} from "antd"; class SmoothlyUnmount extends React.Component { state = { visiable: true, }; handleClose = () => { this.setState({visiable: false}); }; render() { return ( <Card title="Smoothly Unmount" className="gx-card"> { this.state.visiable ? ( <Alert message="Alert Message Text" type="success" closable afterClose={this.handleClose} /> ) : null } <p>placeholder text here</p> </Card> ); } } export default SmoothlyUnmount;
const fs = require('fs'); const https = require('https'); const WebSocket = require('ws'); const server = https.createServer({ cert: fs.readFileSync('/Path'), key: fs.readFileSync('/Path') }); //var lookup = {}; const wss = new WebSocket.Server({ server }) //port: 8080 console.log(`ServerStarted`) wss.on('connection', function connection (ws,req) { console.log(`connection incomming`) ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0]; console.log(ip); ws.id = ip; //console.log(JSON.stringify(ws.ClientOptions.localAddress)); // var propValue; // for(var propName in ws) { // propValue = ws[propName] // console.log(propName,propValue); // } ws.send('Welcome To PierChat') // var EmotionMessage = {}; // EmotionMessage.type = "emotion"; // EmotionMessage.Emotion = currentEmotion; // ws.send(JSON.stringify(EmotionMessage)); ws.on('message', message => { console.log(`Received message => ${message}`) var countMessage = {}; // countMessage.test = "test2"; countMessage.clientNumber = wss.clients. size; ws.send(JSON.stringify(countMessage)); console.log(JSON.stringify(countMessage)); var msgTosend; try{ var JsonMessage = JSON.parse(message); JsonMessage.address = ws.id; msgTosend = JSON.stringify(JsonMessage); } catch{ msgTosend = message; } wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(msgTosend); } // ws.send("copy that sir") }) }) }) server.listen(8081); //lookup[0].send('message');
import React, { Component } from 'react' import Waypoint from 'react-waypoint' import classNames from 'classnames' import stylesheetHowItWorks from 'styles/how-it-works.scss' import { default as Layout } from '../components/layout/layout' import { guide, desc } from '../components/constants/how-it-works' import { Button } from '../components/button' import { Header } from '../components/header' import { MyBitFooter } from '../components/footer/footer' import Scroll from '../static/svgs/other/how-it-works-scroll1.svg' import { testAlphaUrl } from '../components/constants' class HowItWorks extends Component { constructor(props) { super(props) this.state = { animatedSteps: [ false, false, false, false, false, false, false, false, false, false, false ] } this.handleEnter = this.handleEnter.bind(this) } handleEnter(index) { const animatedSteps = this.state.animatedSteps animatedSteps[index] = true this.setState({ animatedSteps }) } render() { const { animatedSteps } = this.state const guideToRender = guide.map((step, index) => ( <Waypoint key={step.title} onEnter={() => this.handleEnter(index)} bottomOffset="300px" > <div key={step.title} className={classNames({ 'HowItWorks__guide-body-step': true, 'HowItWorks__guide-body-step--is-visible': animatedSteps[index], 'HowItWorks__guide-body-step--is-left': index % 2 === 0, 'HowItWorks__guide-svg-funding-ends': index === 4 && animatedSteps[4], 'HowItWorks__guide-svg-funding-starts': index === 3 && animatedSteps[3], 'HowItWorks__guide-svg-escrow': index === 2 && animatedSteps[2] })} > <div className="HowItWorks__guide-body-step-image">{step.image}</div> <div className="HowItWorks__guide-body-step-description-wrapper"> <b className="HowItWorks__guide-body-step-title">{step.title}</b> <div className="HowItWorks__guide-body-step-description" dangerouslySetInnerHTML={{ __html: step.desc }} /> </div> </div> </Waypoint> )) return ( <Layout> <div className="HowItWorks"> <style dangerouslySetInnerHTML={{ __html: stylesheetHowItWorks }} /> <div className="HowItWorks__header"> <Header isLight={false} /> </div> <div className="HowItWorks__guide"> <div className="HowItWorks__guide-header"> <h1 className="HowItWorks__guide-header-title"> Start your Journey </h1> <div className="HowItWorks__guide-header-description" dangerouslySetInnerHTML={{ __html: desc }} /> <p className="HowItWorks__guide-header-keep-scrolling"> Keep scrolling for a step by step walk through. </p> <Scroll className="HowItWorks__guide-header-img-sroll" /> </div> <div className="HowItWorks__guide-body">{guideToRender}</div> </div> <Waypoint key={'footer'} onEnter={() => this.handleEnter(8)} bottomOffset="250px" > <div className={classNames({ 'HowItWorks__guide-footer': true, 'HowItWorks__guide-footer--is-visible': animatedSteps[8] })} > <h2 className="HowItWorks__guide-footer-header"> Own your Future </h2> <p className="HowItWorks__guide-footer-description"> Be one of the first to test the future of investing. Sign up for the Alpha today. </p> <div className="HowItWorks__btn-test-alpha-wrapper"> <Button label={'Test Alpha'} url={testAlphaUrl} className="HowItWorks__btn-test-alpha" isLink isCentered newTab /> </div> </div> </Waypoint> <MyBitFooter /> </div> </Layout> ) } } export default HowItWorks
exports.JWT_SECRET = Buffer.from('semicolon-2018', 'hex')
// Copyright (c) 2019 - 2020, FHNW, Switzerland. All rights reserved. // Licensed under MIT License, see LICENSE for details. import React, {Component} from "react"; import {Button, Modal} from "react-bootstrap"; class DeleteModal extends Component { render() { return ( <> <Modal show={this.props.show} onHide={this.props.onHide}> <Modal.Header closeButton> <Modal.Title>Delete Item</Modal.Title> </Modal.Header> <Modal.Body>{this.props.body}</Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.props.onHide}> Close </Button> <Button className="btn-danger" variant="primary" onClick={this.props.onDeleteItem} > Delete </Button> </Modal.Footer> </Modal> </> ); } } export default DeleteModal;
import React from 'react' import CartItem from '../cart-item/cart-item.component' import {connect} from 'react-redux'; import {selectCartItems} from '../../redux/cart/cart.selector' import {createStructuredSelector} from 'reselect' // import {withRouter} from 'react-router-dom' // import Button from '../button/button.component' // import './cart-dropdown.styles.scss' import { hideCart } from '../../redux/cart/cart.action'; // import { products } from '../../redux/shop/shop.selector'; import { selectProducts } from '../../redux/user/user.selector'; import { useRouter } from 'next/dist/client/router'; const CartDropdown = ({cartItems, hideCart, products}) =>{ const route = useRouter() return( <div className='cart-dropdown'> <div className='cart-items'> { cartItems.length? cartItems.map( product => <CartItem className='cart-item' key={product.id} item={product}/>): <span className='empty-message'> Your cart is empty. </span> } </div> <button onClick={() => { route.push('/checkout'); hideCart() } } inverted>GO TO CHECKOUT</button> </div> )} const mapDispatchToProps = dispatch =>({ hideCart: () => dispatch(hideCart()) }) const mapStateToProps = createStructuredSelector({ cartItems: selectCartItems, products: selectProducts }); export default connect(mapStateToProps,mapDispatchToProps)(CartDropdown);
import { PROFILE_LIST_REQUEST, PROFILE_LIST_SUCCESS, PROFILE_LIST_FAIL, CLEAN_PROFILE_LIST, PROFILE_DETAILS_FAIL, PROFILE_DETAILS_SUCCESS, PROFILE_DETAILS_REQUEST, CLEAN_PROFILE_DETAILS, GET_MORE_PROJECTS_FAIL, GET_MORE_PROJECTS_REQUEST, GET_MORE_PROJECTS_SUCCESS, } from "../constants/profileConstants"; export const profileDetailsReducer = ( state = { profile: {}, starred: [], repos: [], loading: true, loading_projects: true, }, action ) => { switch (action.type) { case GET_MORE_PROJECTS_REQUEST: return { ...state, loading_projects: true, }; case GET_MORE_PROJECTS_SUCCESS: return { ...state, loading_projects: false, repos: action.payload, }; case GET_MORE_PROJECTS_FAIL: return { loading_projects: false, profile: {}, starred: [], repos: [], error: action.payload, }; case CLEAN_PROFILE_DETAILS: return { loading: true, profile: {}, starred: [], repos: [], }; case PROFILE_DETAILS_REQUEST: return { profile: {}, starred: [], repos: [], loading: true, }; case PROFILE_DETAILS_SUCCESS: return { loading: false, profile: action.payload.profile, starred: action.payload.starred, repos: action.payload.repos, }; case PROFILE_DETAILS_FAIL: return { loading: false, profile: {}, starred: [], repos: [], error: action.payload, }; default: return state; } }; export const profileListReducer = ( state = { profiles: [], totalCount: 0, loading: true, previousSearchTerm: "", }, action ) => { switch (action.type) { case CLEAN_PROFILE_LIST: return { profiles: [], totalCount: 0, loading: true, previousSearchTerm: "", }; case PROFILE_LIST_REQUEST: return { loading: true, }; case PROFILE_LIST_SUCCESS: return { loading: false, previousSearchTerm: action.payload.previousSearchTerm, profiles: action.payload.data, totalCount: action.payload.totalCount, }; case PROFILE_LIST_FAIL: return { loading: false, error: action.payload, profiles: {}, ...state, }; default: return state; } };
const basicController = {}; basicController.get = (req,res) => { res.json({ message: 'app.js > routes.js > basicController.js' }) }; module.exports = basicController
var qrc = require('./qrc'); var i = 0; qrc.Connect('10.0.0.11') .then(function() { console.log('Connected!'); setInterval(function() { i = (i+0.01)%1 qrc.Call('Control.Set', {"Name": "source_level", "Position": i }); }, 0.1); });
// 点击小图变大图 // 渲染数据 // 正则表达式来获取id let reg = /id=(\d+)/; let res = reg.test(location.search); if (!res) { location.href = '../html/goods_list.html' } let id = reg.exec(location.search)[1]; console.log(id); let login = $.cookie('login'); let container = document.querySelector('.container'); // 根据id获取数据 $.ajax({ url: '../api/getDetail.php', method: 'get', data: { id: id, }, dataType: 'json', async: true, success: function(res) { // console.log(res); if (res.code == 1) { console.log(res.detail); readData(res.detail); innerCar(); buy(); Simg() } } }) function readData(res) { let str = ""; let atr = ""; str += ` <!-- 图片部分 --> <div class="content_text_pic"> <div class="content_text_picMain"> <img src="${res.goods_img}" alt="" class="bigImg"> </div> <div class="content_text_picMore"> <p> <i> <img src="${res.goods_img}" alt="" class="selectImg"> </i> <i> <img src="${res.goods_img1}" alt="" class="selectImg"> </i> <i> <img src="${res.goods_img2}" alt="" class="selectImg"> </i> <i> <img src="${res.goods_img3}" alt="" class="selectImg"> </i> </p> </div> </div> <!-- 产品介绍 --> <div class="content_text_con"> <h3> ${res.goods_name} </h3> <!--价格打折 --> <div class="content_text_con_price"> <div class="content_text1"> <i>价格:</i> <span>¥${res.goods_money}</span> </div> <!-- 价格第二排 --> <div class="content_text2 clearFix"> <p class="content_textp"> <i>促销价:</i> <span>¥${res.goods_price}</span> </p> <p class="content_text2p"> <i>评价:524</i> <span>累计销量:${res.goods_sales}</span> </p> </div> <!-- 店铺优惠价 --> <p class="content_text3"> <i>店铺优惠:</i> <span> <img src="../img/youhui1_03.jpg" alt=""> </span> <span> <img src="../img/youhui2_03.jpg" alt=""> </span> </p> </div> <!-- 产品尺寸 --> <div class="content_prodect_detail"> <p> <i>客服:</i> <button><img src="../img/chat_03.jpg" alt=""> 联系客服</button> </p> <p> <i>颜色:</i> <span class="proColor selectColor">${res.goods_color}</span> <span class="proColor">${res.goods_color1}</span><span class="proColor">${res.goods_color2}</span> </p> <p> <i>尺寸:</i> <span class="proSize selectSize">${res.goods_size}</span> <span class="proSize">${res.goods_size1}</span><span class="proSize">${res.goods_size2}</span> <span class="proSize">${res.goods_size3}</span> </p> <div> <i>数量:</i> <span class="minus">-</span> <input type="text" value="1" class="num"> <span class="add">+</span> <i> 库存:1176件 </i> </div> <div class="buy"> <button class="buyNow">立即购买</button> <button class="addCar">加入购物车</button> </div> <div class="operation"> <span><img src="../img/star_03.jpg" alt="">3779</span> <span> <i>+</i> 分享 </span> <a href=""> 举报 </a> </div> <div class="server"> <i>服务说明:</i> <span><img src="../img/yes_03.jpg" alt="">72小时发货</span> <span><img src="../img/yes_03.jpg" alt="">7天无理由退货</span> <span><img src="../img/yes_03.jpg" alt="">延误必赔</span> <span><img src="../img/yes_03.jpg" alt="">退货补运费</span> <span><img src="../img/yes_03.jpg" alt="">全国包邮</span> </div> <div class="pay"> <i>支付方式:</i> <span><img src="../img/zhifubao_03.jpg" alt=""></span> <span><img src="../img/weixin_03.jpg" alt=""></span> </div> </div> </div> `; atr += `${res.introduce}`; $('.content_text').html(str); $('.content_Text').html(atr); // console.log(1); } // 页面处理 function Simg() { // 图片点击切换 $('.content_text_picMore').click(function() { let e = window.event; if (e.target.className == "selectImg") { // console.log(1); let url = e.target.src; // console.log(url); $(".bigImg").attr('src', url); } }) // 页面尺寸和颜色的挑选 $('.content_prodect_detail').click(function() { let e = window.event; if (e.target.classList.contains('proColor')) { console.log(1); $('.proColor').removeClass('selectColor'); $(e.target).addClass('selectColor'); } if (e.target.classList.contains('proSize')) { console.log(1); $('.proSize').removeClass('selectSize'); $(e.target).addClass('selectSize'); } }) } // 立即购买 function buy() { $('.buyNow').click(function() { location.href = '../html/car.html' }) } // 添加数据到购物车 function innerCar() { // 对数量的处理 $('.minus').click(function() { let num = $('.num').val(); if (num == 1) { num = 1; } else { num--; $('.num').val(num); } }) $('.add').click(function() { let num = $('.num').val(); num++; $('.num').val(num); }) $('.addCar').click(function() { let num = $('.num').val(); let goods_color = $('.selectColor').text(); let goods_size = $('.selectSize').text(); // console.log(num); if (!login) { location.href = '../html/login.html'; localStorage.setItem('url', './detail.html'); return; } $.ajax({ url: '../api/addCarData.php', method: 'get', data: { username: login, goods_id: id, num: num, goods_color: goods_color, goods_size: goods_size }, dataType: 'json', async: true, success: function(res) { if (res.code) { alert("加入购物车成功") } } }) }) }
const bcrypt = require('bcryptjs') const myFunction = async () => { // Create a password hash const password = 'Red12345!' const hashedPassword = await bcrypt.hash(password, 8) console.log(password) console.log(hashedPassword) // Hashed passwords cannot be decripted, instead, the plain text will be hashed again // then it will be compared to the hashed pass on the DB. const isMatch = await bcrypt.compare('Red12345!', hashedPassword) console.log(isMatch) } myFunction()
import React from 'react'; import { Title, TextBlock, InvasivePotential, Resources, Resource, Summary, SexualReproduction, AsexualReproduction, EcologicalNiche, PopulationDensity, EnvironmentImpact, ManagementMethod, ManagementApplication, OriginalArea, SecondaryArea, Introduction, Breeding, CaseImage, } from '../components'; import image from '../../../assets/caseDetails/rak-pruhovany.png'; //TODO change source const _template = (props) => ( <div> <Title name="" nameSynonyms="" latinName="" latinNameSynonyms="" /> <Summary> <OriginalArea text="" /> <SecondaryArea text="" /> <Introduction text="" /> <Breeding text="" /> </Summary> <CaseImage source={image} copyright="" /> <TextBlock> <p></p> <h5>Ekologie a způsob šíření</h5> <p></p> </TextBlock> <InvasivePotential> <SexualReproduction score={} /> <AsexualReproduction score={} /> <EcologicalNiche score={} /> <PopulationDensity score={} /> <EnvironmentImpact score={} /> <ManagementMethod text="" /> <ManagementApplication text="" /> </InvasivePotential> <Resources> <Resource></Resource> </Resources> </div> ); export default _template;
/** * Created by kingson·liu on 2017/3/9. */ goceanApp.controller('MainMallCtrl', function ($scope, $rootScope, $state, $timeout, $stateParams, mallService, mallDetailService, configService, localStorageService) { var params = configService.parseQueryString(window.location.href); if (params.passportId){ params.nickName = decodeURI(params.nickName); try { params.nickName = Base64.decode(params.nickName); }catch (e){ } localStorageService.set("passport",params); } $scope.passport = localStorageService.get("passport"); // 获取JSSDK configService.getJssdkInfo(window.location.href); // 隐藏右上角 configService.hideWXBtn(); // 底部tab选中 $("#mall").addClass('weui_active').siblings().removeClass('weui_active'); $rootScope.tabbar = "GOU";// YEZAI | GOU |MY | ORDER | GROUPON if ($rootScope.viewCatetoryId == null){ //后退的状态, FIXME 无法聚焦NAVBAR, TABBAR 也没选择, 需要封装个方法刷新BAR $rootScope.viewCatetoryId = 1; } $scope.page = 1; $scope.rows = 5; var obj = { viewCategoryId:$rootScope.viewCatetoryId, page:$scope.page, rows:$scope.rows }; mallService.getMallList(obj).then(function(data){ if (data.status == "OK"){ $scope.itemList = data.result; if(!$scope.$$phase){ $scope.$apply(); } } },function(err){ }); $rootScope.viewCateory = store.mall.viewCateory; var tabWidth = 20 * $scope.viewCateory.length; $("#cTab").css({"width":tabWidth+"%","height":"44px"}); setTimeout(function () { $('#tab1').tab({defaultIndex:0,activeClass:"tab-green"}); var selectViewId = localStorageService.get("selectViewId"); if (selectViewId){ $("#view"+ selectViewId).addClass("tab-green").siblings().removeClass('tab-green'); $scope.listItems(selectViewId); } }, 10); /* * DEMO 分页,没用, */ $scope.onScrollPagination = function (){ $scope.page += 1; var obj = { viewCategoryId:$rootScope.viewCatetoryId, page:$scope.page, rows:$scope.rows }; mallService.getMallList(obj).then(function(data){ if (data.status == "OK"){ $scope.itemList = data.result; for (i in data.result){ $scope.itemList.push(data.result[i]); } if(!$scope.$$phase){ $scope.$apply(); } } },function(err){ }); }; $scope.listItems = function (id) { $rootScope.viewCatetoryId = id; localStorageService.remove("selectViewId"); localStorageService.set("selectViewId", id); var obj = { viewCategoryId:id, page:$scope.page, rows:$scope.rows }; mallService.getMallList(obj).then(function(data){ if (data.status == "OK"){ $scope.itemList = data.result; if(!$scope.$$phase){ $scope.$apply(); } } },function(err){ }); }; $scope.getItemDetail = function (params) { // var params = {goodsId:goodsId}; $rootScope.itemDetail = null; mallDetailService.getMallDetail(params).then(function(data){ console.log(data); if (data.status == "OK"){ $rootScope.itemDetail = data.result; $state.go("itemDetail",params); } },function(err){ }); }; });
import firebase from '../firebase'; import { fetchMessages } from './chatroom_actions'; import { fetchChannels } from './channel_actions'; import DeviceInfo from 'react-native-device-info'; // import FCM, { FCMEvent, NotificationType, WillPresentNotificationResult, RemoteNotificationResult } from 'react-native-fcm'; import { Platform } from 'react-native'; export const setUserName = (name) => ({ type: 'SET_USER_NAME', name }); export const setUserAvatar = (avatar) => ({ type: 'SET_USER_AVATAR', avatar: avatar }); export const login = () => { return function (dispatch, getState) { dispatch(startAuthorizing()); firebase.auth() .signInAnonymously() .then(() => { const { name, avatar } = getState().user; firebase.database() .ref(`users/${DeviceInfo.getUniqueID()}`) .set({ name, avatar }); startChatting(dispatch); }); } } export const checkUserExists = () => { return function (dispatch) { dispatch(startAuthorizing()); firebase.auth() .signInAnonymously() .then(() => firebase.database() .ref(`users/${DeviceInfo.getUniqueID()}`) .once('value', (snapshot) => { const val = snapshot.val(); if (val === null) { dispatch(userNoExist()); }else{ dispatch(setUserName(val.name)); dispatch(setUserAvatar(val.avatar)); startChatting(dispatch); } })) .catch(err => console.log(err)) } } const startChatting = function (dispatch) { dispatch(userAuthorized()); dispatch(fetchChannels()); dispatch(fetchMessages()); // FCM.requestPermissions(); // FCM.getFCMToken() // .then(token => { // console.log(token) // }); // FCM.subscribeToTopic('secret-chatroom'); // FCM.on(FCMEvent.Notification, async (notif) => { // console.log(notif); // if (Platform.OS === 'ios') { // switch (notif._notificationType) { // case NotificationType.Remote: // notif.finish(RemoteNotificationResult.NewData); //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed // break; // case NotificationType.NotificationResponse: // notif.finish(); // break; // case NotificationType.WillPresent: // notif.finish(WillPresentNotificationResult.All); //other types available: WillPresentNotificationResult.None // break; // } // } // }); // FCM.on(FCMEvent.RefreshToken, token => { // console.log(token); // }); } export const startAuthorizing = () => ({ type: 'USER_START_AUTHORIZING' }); export const userAuthorized = () => ({ type: 'USER_AUTHORIZED' }); export const userNoExist = () => ({ type: 'USER_NO_EXIST' });
var program = require('commander'); var fs = require('fs'); var path = require('path'); var createHash = require('crypto').createHash; program .option('-o, --out <file>', 'Output file', 'filepack.json') .option('-i, --in <folder>', 'Input folder', '.') .parse(process.argv); /* * @return {String} md5 hash of file */ function md5HashSync(fullPath) { var hash = createHash('md5'); return hash.update(fs.readFileSync(fullPath)).digest('hex'); } /* * @param {String} path folder to walk * @param {Object} obj in which to store file/folder objects * @return {Object} filepack object */ function walkFolder(dir) { var ret = {}; var list = fs.readdirSync(dir); list.forEach(function(file) { var fullPath = path.resolve(dir, file); var stat = fs.statSync(fullPath); if (stat) { if (stat.isDirectory()) { if(!ret.hasOwnProperty('dirs')) { ret.dirs = []; } var rec = walkFolder(fullPath); var dirObj = {name: file}; if(rec.files) { dirObj.files = rec.files; } if(rec.dirs) { dirObj.dirs = rec.dirs; } ret.dirs.push(dirObj); } else { if(!ret.hasOwnProperty('files')) { ret.files = []; } ret.files.push({name: file, md5: md5HashSync(fullPath)}); } } }); return ret; } var started = Date.now(); var obj = {}; obj.filepack = walkFolder(program.in); var objStr = JSON.stringify(obj, null, '\t'); fs.writeFileSync(program.out, objStr);
import React, { useState } from 'react'; import './App.css'; import Dashboard from './Componment/Dashboard' import RightCompo from "./Componment/RightCompo"; import Agenda from "./Componment/Agenda"; import SignIn from "./Componment/OutsideDash/SignIn"; import SignUp from "./Componment/OutsideDash/SignUp"; import Go from "./Componment/OutsideDash/Go"; function App() { return ( <Go/> ); } export default App;
function Table(userTableColumns, id) { that = this; this.table = document.getElementById(id); this.columns = userTableColumns; this.count = 0; this.createHeader(); } Table.prototype.addRow = function() { this.count++; var row = this.table.insertRow(1); row.id = this.count; this.addCells(row, this.count); } Table.prototype.addCells = function(row, countTrack) { for (var key in this.columns) { var cell = row.insertCell(); this.element = this.createInputElement(this.columns[key]); this.element.id = key + countTrack; cell.appendChild(this.element); if (key == "action") { var counter = countTrack; this.element.value = "Save"; this.element.onclick = function() { that.clickSaveButton(counter); return false; } } } } Table.prototype.createInputElement = function(keyValue) { var item = document.createElement("input"); item.type = keyValue; return item; } Table.prototype.createHeader = function() { var row = this.table.insertRow(0); row.id = this.count; for (var key in this.columns) { var cell = row.insertCell(); var keyTextNode = document.createTextNode(key); cell.appendChild(keyTextNode); } } Table.prototype.clickSaveButton = function(counter) { var currentRow = document.getElementById(counter); var textboxText = []; var i = 0; for (var key in this.columns) { var rowElement = document.getElementById(key + counter); var cellNode = rowElement.parentNode; if (this.columns[key] == "textbox") { textboxText[i] = rowElement.value; cellNode.replaceChild(document.createTextNode(rowElement.value), rowElement); i++; } else if(key == "action") { var edit = this.createAnchorNode("edit"); var del = this.createAnchorNode("/ del"); cellNode.replaceChild(edit, rowElement); cellNode.appendChild(del); edit.onclick = function() { that.editClick(currentRow, counter, textboxText); return false; } del.onclick = function() { that.delClick(currentRow); return false; } } } return false; } Table.prototype.editClick = function(currentRow, counter, textboxText) { while(currentRow.firstChild) { currentRow.removeChild(currentRow.firstChild); } this.addCells(currentRow, counter); var i = 0; for (var key in this.columns) { if (this.columns[key] == "textbox") { var elementVal = document.getElementById(key + counter); elementVal.value = textboxText[i]; i++; } } } Table.prototype.createAnchorNode = function(item) { var itemName = document.createElement("a"); itemName.href = "#"; itemName.appendChild(document.createTextNode(item)); return itemName; } Table.prototype.delClick = function(currentRow) { var tablebody = document.getElementsByTagName("tbody"); tablebody[0].removeChild(currentRow); } var userTableColumns = { name: "textbox", email: "textbox", action: "button" }; var userTable = new Table(userTableColumns, "dynamictable");
function setup() { //Setup Function const canvas = createCanvas(document.getElementById("gameContainer").offsetWidth, document.getElementById("gameContainer").offsetHeight); canvas.parent("gameWindow"); //Canvas creation }; var miliTarget = 200; //Mili Target for repeated down moves const dropSpeed = 200; //Speed between drops var autoDrop = true; //If autodrop is enabled const deadzone = new Array; //Creates empty variable for deadzone pieces var allowChange = true; //Boolean to allow change var allowControl = true; //Boolean to allow control var held; //Creates empty variable for held piece var ghostBlocks = new Array; //Creates empty array for ghostBlocks var isFalling = true; //Boolean to determine if piece is falling //Color Codes stored in variables const color_red = [254, 0, 0]; const color_orange = [255, 100, 0]; const color_yellow = [255, 255, 0]; const color_pink = [255, 153, 203]; const color_green = [0, 128, 0]; const color_purple = [129, 0, 127]; const color_blue = [0, 0, 255]; var tetrisWindow = { //Properties for tetris window in object width: 10 * Math.floor(document.getElementById("gameContainer").offsetHeight / 25), height: 24 * Math.floor(document.getElementById("gameContainer").offsetHeight / 25), xOffset: 15 + 5 * Math.floor(document.getElementById("gameContainer").offsetHeight / 25), yOffset: 10, blockLength : (10 * Math.floor(document.getElementById("gameContainer").offsetHeight / 25)) / 10 } //Function for returning control to user after timeout function controlTimeout(){ allowControl = true; }; function checkExistanceArray(locations){ //This function checks if locations passed in are occupied by pieces that have been written to the board for(var x = 0; x < locations.length; x++){ var destination = mainBoard.boardArray[locations[x][0]][locations[x][1]]; if(destination != null){ return true; break; } } return false; } function inArray(original, toCheck){ //Check whether a single item of the passed in toCheck array exists in the original array var sOriginal = JSON.stringify(original); var sToCheck = new Array; var includes = false; for (var x = 0; x < toCheck.length; x++){ if (sOriginal.includes(JSON.stringify(toCheck[x]))){ includes = true; break; } } return includes; }; function hold(passedPiece){ //Function to hold a piece in the game isFalling = false; ghostBlocks = []; if(held.pieceType == null){ held.pieceType = passedPiece.pieceType; inPlay = new Piece(upcoming1.pieceType); upcoming1 = new External(upcoming2.pieceType, 15, 0); upcoming2 = new External(Math.floor(Math.random() * 7) + 1, 15, 7) upcoming1.update(); upcoming2.update(); } else{ var heldTemp = held.pieceType; held.pieceType = passedPiece.pieceType; inPlay = new Piece(heldTemp); } held.update(); } function renderRect(location , color) //function to render each block with location of block passed in plus color { if (location[0] != null && location[1] != null){ fill(color[0],color[1],color[2]); rect(tetrisWindow.xOffset + location[0] * tetrisWindow.blockLength, tetrisWindow.yOffset + location[1] * tetrisWindow.blockLength, tetrisWindow.blockLength, tetrisWindow.blockLength); } }; function renderUI(){ //Function that contains render code for main UI and outlines //Main Rect: background(255,255,255); fill(197,215,189); rect(tetrisWindow.xOffset - 1, tetrisWindow.yOffset - 1, tetrisWindow.width + 2, tetrisWindow.height + 2); fill(255,255,255); //Outer Rects: rect(tetrisWindow.xOffset - (tetrisWindow.blockLength * 5) - 1, tetrisWindow.yOffset -1, tetrisWindow.blockLength * 5, tetrisWindow.blockLength * 6); rect(tetrisWindow.xOffset + tetrisWindow.width + 1, tetrisWindow.yOffset - 1, tetrisWindow.blockLength * 5, tetrisWindow.blockLength * 6); rect(tetrisWindow.xOffset + tetrisWindow.width + 1, tetrisWindow.yOffset + (tetrisWindow.blockLength * 6) - 1, tetrisWindow.blockLength * 5, tetrisWindow.blockLength * 6); } for (var x = 0; x < 24; x++){ //Creates a deadzone to prevent horizontal bound breaking deadzone.push([-1, x]); deadzone.push([10, x]); } for (var x = 0; x < 10; x++){ //Creates a deadzone to prevent vertical bound breaking deadzone.push([x, 24]); deadzone.push([x, -1]); } //---- CLASSES ----\\ class Boards{ //Main class for Board object constructor(){ this.boardArray = new Array; } } Boards.prototype.initArray = function(){ //Setups up mainboard array for(var x = 0; x < 10; x++){ var arrayToPush = new Array; for(var y = 0; y < 24; y++){ arrayToPush.push(null); } this.boardArray.push(arrayToPush); } } Boards.prototype.checkLines = function(){ //Checks lines for matches var linesMatched = new Array; for (var y = 0; y < 24 ; y++){ linesMatched.push(y); for(var x = 0; x < 10; x++){ if(mainBoard.boardArray[x][y] == null){ linesMatched.pop(); break; } } } if (linesMatched.length >= 1){ this.clearLines(linesMatched); } } Boards.prototype.clearLines = function(lines){ //Clear lines that are matched for(var y = 0; y < lines.length; y++){ for(var x = 0; x < 10; x++){ this.boardArray[x][lines[y]] = null; } for(var y2 = lines[y]; y2 >= 0; y2--){ for(var x = 0; x < 10; x++){ if(this.boardArray[x][y2] != null){ this.boardArray[x][y2 + 1] = this.boardArray[x][y2]; this.boardArray[x][y2] = null; } } } } } class External{ //Class for external pieces such as held piece and upcoming pieces constructor(pieceType, xOffset, yOffset){ this.pieceType = pieceType; this.xOffset = xOffset; this.yOffset = yOffset; this.blocks = null; this.color = null; } }; External.prototype.update = function(){ //Updates piece location to organize them on screen switch (this.pieceType){ case 1: //T-Pice this.blocks = [[-2.5,2.5],[-2.5,1.5],[-2.5,3.5],[-3.5,2.5]]; //first block should be point to rotate around this.color = color_blue; break; case 2: //left side L this.blocks = [[-2.5,1.5],[-2.5,2.5],[-2.5,3.5],[-3.5,3.5]]; this.color = color_orange; break; case 3: //Right side L this.blocks = [[-3.5,1.5],[-3.5,2.5],[-3.5,3.5],[-2.5,3.5]]; this.color = color_yellow; break; case 4: //Straight this.blocks = [[-3,1],[-3,2],[-3,3],[-3,4]]; this.color = color_red; break; case 5: //Square this.blocks = [[-3.5,2],[-3.5,3],[-2.5,2],[-2.5,3]]; this.color = color_pink; break; case 6: //Right Z this.blocks = [[-2.5,1.5],[-2.5,2.5],[-3.5,2.5],[-3.5,3.5]]; this.color = color_purple; break; case 7: //Left Z this.blocks = [[-3.5,1.5],[-3.5,2.5],[-2.5,2.5],[-2.5,3.5]]; this.color = color_green; break; } } External.prototype.draw = function(){ //Dunction to draw external blocks for(const block of this.blocks){ renderRect([block[0] + this.xOffset,block[1] + this.yOffset], this.color); } isFalling = true; } class Piece{ //Class for piece constructor(pieceType){ this.color = color_green; this.state = 1; //State of rotation this.landed = false; //Is landed, want to exhange any instances of this with land state this.landState = 1; //1: has not touched any blocks, 2: Touched blocks, in cooldown, 3: Ready to be locked in this.pieceType = pieceType; switch(pieceType){ case 1: //T-Pice this.blocks = [[2,2],[2,1],[2,3],[1,2]]; //first block should be point to rotate around this.color = color_blue; break; case 2: //left side L this.blocks = [[5,1],[5,0],[5,2],[4,2]]; this.color = color_orange; break; case 3: //Right side L this.blocks = [[5,1],[5,0],[5,2],[6,2]]; this.color = color_yellow; break; case 4: //Straight this.blocks = [[5,1],[5,0],[5,2],[5,3]]; this.color = color_red; break; case 5: //Square this.blocks = [[5,1],[5,0],[6,1],[6,0]]; this.color = color_pink; break; case 6: //Right Z this.blocks = [[5,1],[5,0],[4,1],[4,2]]; this.color = color_purple; break; case 7: //Left Z this.blocks = [[5,1],[5,0],[6,1],[6,2]]; this.color = color_green; break; } } }; Piece.prototype.draw = function(){ //Draws the given piece on the screen for (const block of this.blocks){ const location = block; fill(this.color[0],this.color[1],this.color[2]); rect(tetrisWindow.xOffset + location[0] * tetrisWindow.blockLength, tetrisWindow.yOffset + location[1] * tetrisWindow.blockLength, tetrisWindow.blockLength); } } Piece.prototype.move = function(direction) { //Moves the piece in the 4 cardinal directions isFalling = true; var index = null; var modifier = null; allowChange = true; switch(direction){ //index 0 is x axis 1 is y, modifier is how much to change by case("up"): index = 1; modifier = -1; break; case("down"): index = 1; modifier = 1; break; case("left"): index = 0; modifier = -1; break; case("right"): index = 0; modifier = 1; break; } var incomingBlocks = new Array; if (direction == "left"){ for (const block of this.blocks){ //incomingBlock = [this.blocks[x][0] - 1, this.blocks[x][1]]; incomingBlocks.push([block[0] - 1, block[1]]); } if(inArray(deadzone, incomingBlocks) || checkExistanceArray(incomingBlocks)){ allowChange = false; } } else if (direction == "right"){ for (const block of this.blocks){ //incomingBlock = [this.blocks[x][0] + 1, this.blocks[x][1]]; incomingBlocks.push([block[0] + 1, block[1]]); } if(inArray(deadzone, incomingBlocks) || checkExistanceArray(incomingBlocks)){ allowChange = false; } } else if (direction == "down"){ for (const block of this.blocks){ incomingBlocks.push([block[0], block[1] + 1]); } if(inArray(deadzone, incomingBlocks) || checkExistanceArray(incomingBlocks)){ allowChange = false; } } if (allowChange){ //Makes sure both the index and modifier exist for (const block of this.blocks){ block[index] += modifier; } } if(inPlay.trackFall() == true){ //Checks for where the piece is each time the move function is run, move method is used by both player and autoDrop inPlay.writeBlocks(); inPlay = new Piece(upcoming1.pieceType); upcoming1 = new External(upcoming2.pieceType, 15, 0); upcoming2 = new External(Math.floor(Math.random() * 7) + 1, 15, 6) upcoming1.update(); upcoming2.update(); mainBoard.checkLines(); } this.renderGhost(); } Piece.prototype.rotate = function(){ //Rotates pieces in a clockwise var modifiers = new Array; var allowRotate = true; switch (this.state){ case(1): this.state = 2 break; case(2): this.state = 3; break; case(3): this.state = 4; break; case(4): this.state = 1; break; } modifiers = rotationLogic[this.pieceType - 1][this.state - 1]; var toBeRotated = [ [this.blocks[0][0] + modifiers[0][0], this.blocks[0][1] + modifiers[0][1]], [this.blocks[0][0] + modifiers[1][0], this.blocks[0][1] + modifiers[1][1]], [this.blocks[0][0] + modifiers[2][0], this.blocks[0][1] + modifiers[2][1]] ]; if (inArray(deadzone, toBeRotated) || checkExistanceArray(toBeRotated)){ allowRotate = false; } //modify blocks if(allowRotate){ this.blocks[1] = [this.blocks[0][0] + modifiers[0][0], this.blocks[0][1] + modifiers[0][1]] //block one below origin this.blocks[2] = [this.blocks[0][0] + modifiers[1][0], this.blocks[0][1] + modifiers[1][1]] //One to the right this.blocks[3] = [this.blocks[0][0] + modifiers[2][0], this.blocks[0][1] + modifiers[2][1]] //One to the left } else{ //need a condition for what to do if rotation is blocked } this.renderGhost(); } Piece.prototype.writeBlocks = function(){ //Write blocks to previously dropped blocks array, I want to check for line clears here isFalling = false; for (const block of this.blocks){ var xDest = block[0]; var yDest = block[1]; mainBoard.boardArray[xDest][yDest] = this.color; //different colors for different locations at one point } ghostBlocks = []; } Piece.prototype.trackFall = function(){ //Tracks fall and checks for piece placement if (this.landState != null){ //may not be needed, depends on how I continue this code var bottomBlocks = new Array; for (const block of this.blocks){ bottomBlocks.push([block[0], block[1] + 1]); } if(checkExistanceArray(bottomBlocks) || inArray(deadzone, bottomBlocks)){ if(this.landState == 1){ this.landState = 2 setTimeout(function(){ inPlay.landState = 3; }, 1000); return false; } else if(this.landState == 3){ this.landState = 1; this.writeBlocks(); return true; } } else{ return false; } } } Piece.prototype.renderGhost = function(){ //renders ghost piece for the corresponding tetris piece if (isFalling){ ghostBlocks = new Array; for(const block of this.blocks){ ghostBlocks.push(block); } while(!inArray(deadzone, ghostBlocks) && !checkExistanceArray(ghostBlocks)){ for (var x = 0; x < ghostBlocks.length; x++){ ghostBlocks[x] = [ghostBlocks[x][0], ghostBlocks[x][1] + 1]; } } for(var x = 0; x < ghostBlocks.length; x++){ ghostBlocks[x] = [ghostBlocks[x][0], ghostBlocks[x][1] - 1]; } } } var inPlay = new Piece(Math.floor(Math.random() * 7) + 1); //Creates initial piece for game var held = new External(null, 0, 0); //creates a placeholder held piece var upcoming1 = new External(Math.floor(Math.random() * 7) + 1, 15, 0); //Creates first upcoming piece var upcoming2 = new External(Math.floor(Math.random() * 7) + 1, 15, 6); //Creates second upcoming piece upcoming1.update(); //preps the first upcoming piece upcoming2.update(); //preps the second upcoming piece mainBoard = new Boards(); //Creates board mainBoard.initArray(); //initializes board inPlay.renderGhost(); //Renders ghost piece function draw() { //Main looping draw function var input = false; if (millis() > miliTarget && autoDrop){ inPlay.move("down"); miliTarget = millis() + dropSpeed; } strokeWeight(2); renderUI(); stroke(inPlay.color[0],inPlay.color[1],inPlay.color[2]); if(isFalling){ for(const block of ghostBlocks){ renderRect(block, [197,215,189]); } } stroke(0,0,0); inPlay.draw() if (held.pieceType != null){ held.draw(); } upcoming1.draw(); upcoming2.draw(); for(var x = 0; x < 10; x++){ for(var y = 0; y < 24; y++){ if(mainBoard.boardArray[x][y] != null){ renderRect([x, y], mainBoard.boardArray[x][y]); } } } if (allowControl == true){ if (keyIsDown(37)){ inPlay.move('left'); input = true; } else if (keyIsDown(39)){ inPlay.move('right'); input = true; } else if (keyIsDown(40)){ inPlay.move('down'); input = true; } if (input){ setTimeout(controlTimeout ,100); allowControl = false; } } }; function keyPressed(){ //Function to detect key presses switch(keyCode){ case(32): isFalling = false; inPlay.landState = 3; while (inPlay.landState == 3){ inPlay.move('down'); } break; case 67: isFalling = false; hold(inPlay); break; case 38: inPlay.rotate(); break; case 80: autoDrop = false; break; } }
var express = require('express'); var router = express.Router(); var request = require('request'); var querystring = require('querystring'); var credentials = require('../credentials'); var client_id = credentials.id; var client_secret = credentials.secret; var spotify_username = credentials.user; var redirect_uri = 'http://localhost:3000/callback'; /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express'}); }); var findPlaylist = function(playlists, cb) { playlists = JSON.parse(playlists); var found = false; var discover_url; for (i in playlists.items) { var item = playlists.items[i]; if (item.name == "Discover Weekly") { found = true; discover_url = item.external_urls.spotify break; } } if (found) return cb(discover_url); else console.log("not found"); // TODO : needs to fetch more using the offset param if not found }; var parseTracks = function(discover_tracks, cb) { var tracks = []; discover_tracks = JSON.parse(discover_tracks); for (i in discover_tracks.items) { var track = discover_tracks.items[i].track; var _track = {}; _track.name = track.name; _track.url = track.external_urls.spotify; _track.album = track.album.name; _track.artists = track.artists[0].name; // TODO : foreach required here //console.log("t: " + _track); tracks.push(_track); } //console.log("does this call: ", tracks); return cb(tracks); } var fetchTracks = function(playlist_url, auth_token, cb) { var url_parts = playlist_url.split("/"); request({ url: "https://api.spotify.com/v1/users/spotifydiscover/playlists/" + url_parts[6] + "/tracks", method : 'GET', headers : { "Accept": "application/json", "Authorization" :" Bearer " + auth_token } }, function(err,response,body) { if (!err && response.statusCode == 200) { //console.log("body: " + body); parseTracks(body, function(discover_tracks) { //console.log("Tracks: "+ discover_tracks); return(cb(discover_tracks)); }); } else { console.log("error fetch tracks: " + err); } }); } router.get('/playlists', function(req, res, next) { //probably should have exception checking here but ¯\_(ツ)_/¯ request({ url : "https://api.spotify.com/v1/users/" + spotify_username + "/playlists", method : 'GET', headers : { "Accept": "application/json", "Authorization" :" Bearer " + req.query.access_token } }, function(err, response, body) { if (!err && response.statusCode == 200) { var playlists = body; findPlaylist(playlists, function(playlist_url) { console.log(playlist_url); fetchTracks(playlist_url, req.query.access_token, function(r) { console.log(r); res.render('index', {tokens: true, auth_token: req.query.access_token, tracks: r}); }); }); } else { console.log("cb1 error" + err); } }); }); var generateRandomString = function(length) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; var stateKey = 'spotify_auth_state'; router.get('/login', function(req, res) { var state = generateRandomString(16); res.cookie('spotify_auth_state', state); var scope = 'playlist-read-private playlist-read-collaborative'; res.redirect('https://accounts.spotify.com/authorize?' + querystring.stringify({ response_type: 'code', client_id: client_id, scope: scope, redirect_uri: redirect_uri, state: state })); }); router.get('/callback', function(req, res) { // your application requests refresh and access tokens // after checking the state parameter var code = req.query.code || null; var state = req.query.state || null; var storedState = req.cookies ? req.cookies[stateKey] : null; if (state === null || state !== storedState) { res.redirect('/#' + querystring.stringify({ error: 'state_mismatch' })); } else { res.clearCookie(stateKey); var authOptions = { url: 'https://accounts.spotify.com/api/token', form: { code: code, redirect_uri: redirect_uri, grant_type: 'authorization_code' }, headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, json: true }; request.post(authOptions, function(error, response, body) { if (!error && response.statusCode === 200) { var access_token = body.access_token, refresh_token = body.refresh_token; // we can also pass the token to the browser to make requests from there res.redirect('/playlists?' + querystring.stringify({ access_token: access_token, refresh_token: refresh_token })); } else { res.redirect('/#' + querystring.stringify({ error: 'invalid_token' })); } }); } }); module.exports = router;
import Vue from 'vue' import Vuex from 'vuex' import 'whatwg-fetch' Vue.use(Vuex) export const state = () => ({ authUser: null, csrfToken: null, article: null, register: [] }) export const mutations = { SET_CSRF_TOKEN(state, csrfToken) { state.csrfToken = csrfToken }, setArticle(state, data) { state.article = data }, setRegister(state, data) { state.register = data }, SET_USER(state, user) { state.authUser = user } } export const actions = { nuxtServerInit({ commit }, { req }) { if (req.session && req.session.authUser) { commit('SET_USER', req.session.authUser) } if (req.cookies) { commit('SET_CSRF_TOKEN', req.csrfToken()) } }, register({ commit }, { name, email, password, permission, _csrf }) { return fetch('/api/register', { credentials: 'same-origin', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + _csrf, 'X-CSRF-TOKEN': _csrf }, body: JSON.stringify({ name, email, password, permission, _csrf }) }) .then((res) => { if (res.status === 401) { throw new Error('既にメールアドレスが登録されています') } else { return res.json() } }) .then((register) => { commit('setRegister', register) }) }, login({ commit }, { usermail, password, _csrf }) { return fetch('/api/login', { credentials: 'same-origin', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + _csrf, 'X-CSRF-TOKEN': _csrf }, body: JSON.stringify({ usermail, password, _csrf }) }) .then((res) => { if (res.status === 401) { throw new Error('ログイン失敗') } else { return res.json() } }) .then((authUser) => { commit('SET_USER', authUser) }) }, logout({ commit }, { _csrf }) { return fetch('/api/logout', { credentials: 'same-origin', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + _csrf, 'X-CSRF-TOKEN': _csrf } }) .then(() => { commit('SET_USER', null) }) } }
import {BACKEND_URL} from 'src/config' export default reqBody => fetch(`${BACKEND_URL}/get-page-data`, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', }, body: JSON.stringify(reqBody), }).then(response => { if ( ! response.ok) throw new Error(`Response is not OK (status code is ${response.status})`) return response.json() })
import React, {useContext} from 'react' import styled from "styled-components" import { GithubContext } from '../../Context/UserContext' import {GoRepo, GoGist} from "react-icons/go" import {FiUsers, FiUserPlus} from "react-icons/fi" const UserRFFG = () => { const {githubUser} = useContext(GithubContext); const {public_repos, followers, following, public_gists} = githubUser; const items = [ { id: 1, label: "Repos", value: public_repos, color: "cardRed", icon: <GoRepo className="singleIcon"></GoRepo>, }, { id: 2, label: "Followers", value: followers, color: "cardCream", icon: <FiUsers className="singleIcon"></FiUsers>, }, { id: 3, label: "Following", value: following, color: "cardPale", icon: <FiUserPlus className="singleIcon"></FiUserPlus>, }, { id: 4, label: "Gists", value: public_gists, color: "cardCyan", icon: <GoGist className="singleIcon"></GoGist>, }, ] return ( <section className="rffg-section"> <Wrapper> {items.map((item)=>{ return ( <Item key={item.id} {...item}></Item> ) })} </Wrapper> </section> ) } // ITEM Component: const Item = ({label, value, color, icon}) => { return ( <article className={`rffg-card ${color}`}> <div className="rffg-text-container"> <div> <h2>{value}</h2> <p>{label}</p> </div> <span> {icon} </span> </div> </article> ); }; // Styled Components const Wrapper = styled.div` width: 90vw; margin: 0 auto; display: flex; flex-direction: column; justify-content: space-between; align-items: center; /* Card */ .rffg-card{ width: 100%; height: 5rem; display: grid; place-items: center; font-family: var(--FontMontserrat); margin-bottom: 0.35rem; border-radius: 0.7rem; cursor: pointer; transition: var(--TransFast); } .rffg-card:hover{ transform:scale(1.025); box-shadow: 0px 0px 9px var(--ShadowSmooth); } .rffg-text-container{ width: 85%; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; } h2{ font-size: 1.5rem; letter-spacing: 1.2px; } p{ font-size: 0.8rem; font-weight: 300; } span{ font-size: 2rem; margin-top: 0.5rem; } /* Colors */ .cardRed{ background-color: var(--PrimaryRed); color: var(--BgWhite); } .cardCream{ background-color: var(--PrimaryCream); color: var(--Dark); } .cardPale{ background-color: var(--PrimaryPale); color: var(--Dark); } .cardCyan{ background-color: var(--PrimaryCyan); color: var(--BgWhite); } `; export default UserRFFG;
import Background from './Background'; export default class WaterdhavianNoble extends Background { constructor() { super('waterdhavianNoble'); } }
var express = require('express'); var exSession = require('express-session'); var bodyParser = require('body-parser'); var app = express(); var login = require('./controllers/login'); var admin = require('./controllers/admin'); var employee = require('./controllers/employee'); const cookieParser = require('cookie-parser'); var session = require('express-session'); app.set('view engine', 'ejs'); app.use(cookieParser()); app.use(bodyParser.urlencoded({extended: false})); app.use(exSession({secret: 'my secret value', saveUninitialized: true, resave: false})); app.use('/login',login); app.use('/admin',admin); app.use('/employee',employee); app.listen(25565, function(){ console.log('express http server started at...25565'); }); app.get('/', function(req, res){ res.redirect('/login'); });
import React, { Component } from 'react'; import Eos from 'eosjs'; // https://github.com/EOSIO/eosjs // material-ui dependencies import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import TextField from '@material-ui/core/TextField'; import Paper from '@material-ui/core/Paper'; import Button from '@material-ui/core/Button'; import Grid from '@material-ui/core/Grid'; import MyMap from '../components/MyMap'; import * as _ from 'lodash'; // NEVER store private keys in any source code in your real life development // This is for demo purposes only! const accounts = [ {"name":"useraaaaaaaa", "privateKey":"5K7mtrinTFrVTduSxizUc5hjXJEtTjVTsqSHeBHes1Viep86FP5", "publicKey":"EOS6kYgMTCh1iqpq9XGNQbEi8Q6k5GujefN9DSs55dcjVyFAq7B6b"}, {"name":"useraaaaaaab", "privateKey":"5KLqT1UFxVnKRWkjvhFur4sECrPhciuUqsYRihc1p9rxhXQMZBg", "publicKey":"EOS78RuuHNgtmDv9jwAzhxZ9LmC6F295snyQ9eUDQ5YtVHJ1udE6p"}, {"name":"useraaaaaaac", "privateKey":"5K2jun7wohStgiCDSDYjk3eteRH1KaxUQsZTEmTGPH4GS9vVFb7", "publicKey":"EOS5yd9aufDv7MqMquGcQdD6Bfmv6umqSuh9ru3kheDBqbi6vtJ58"}, {"name":"useraaaaaaad", "privateKey":"5KNm1BgaopP9n5NqJDo9rbr49zJFWJTMJheLoLM5b7gjdhqAwCx", "publicKey":"EOS8LoJJUU3dhiFyJ5HmsMiAuNLGc6HMkxF4Etx6pxLRG7FU89x6X"}, {"name":"useraaaaaaae", "privateKey":"5KE2UNPCZX5QepKcLpLXVCLdAw7dBfJFJnuCHhXUf61hPRMtUZg", "publicKey":"EOS7XPiPuL3jbgpfS3FFmjtXK62Th9n2WZdvJb6XLygAghfx1W7Nb"}, {"name":"useraaaaaaaf", "privateKey":"5KaqYiQzKsXXXxVvrG8Q3ECZdQAj2hNcvCgGEubRvvq7CU3LySK", "publicKey":"EOS5btzHW33f9zbhkwjJTYsoyRzXUNstx1Da9X2nTzk8BQztxoP3H"}, {"name":"useraaaaaaag", "privateKey":"5KFyaxQW8L6uXFB6wSgC44EsAbzC7ideyhhQ68tiYfdKQp69xKo", "publicKey":"EOS8Du668rSVDE3KkmhwKkmAyxdBd73B51FKE7SjkKe5YERBULMrw"} ]; // set up styling classes using material-ui "withStyles" const styles = theme => ({ card: { margin: 20, }, paper: { ...theme.mixins.gutters(), paddingTop: theme.spacing.unit * 2, paddingBottom: theme.spacing.unit * 2, }, formButton: { marginTop: theme.spacing.unit, width: "100%", }, pre: { background: "#ccc", padding: 10, marginBottom: 0. }, }); const ENDPOINT = 'http://172.16.96.83:8888'; // Vendor component class Vendor extends Component { constructor(props) { super(props); this.state = { treeTable: [], // to store the table rows from smart contract loading: false, }; this.seed = this.seed.bind(this); this.handleFormEvent = this.handleFormEvent.bind(this); } // gets table data from the blockchain // and saves it into the component state: "treeTable" async search(query = {}) { this.setState({ loading: true }); const result = await Eos({httpEndpoint: ENDPOINT}) .getTableRows({ "json": true, "code": "treechainacc", // contract who owns the table "scope": "treechainacc", // scope of the table "table": "treestruct", // name of the table as specified by the contract abi "limit": 100, }); const rows = _.filter(result.rows, query); this.setState({ treeTable: rows, loading: false }); } async seed() { const trees = require('../fixtures/trees.json'); return await Promise.all( _.map(trees, tree => { return this.insertRow(tree.name, tree.private_key, tree.dna, tree.message); }) ); } async insertRow(account, privateKey, dna, message) { // define actionName and action according to event type const actionName = "insert"; const actionData = { _user: account, _dna: dna, _message: message, }; // eosjs function call: connect to the blockchain const eos = Eos({ httpEndpoint: ENDPOINT, keyProvider: privateKey }); return await eos.transaction({ actions: [{ account: "treechainacc", name: actionName, authorization: [{ actor: account, permission: 'active', }], data: actionData, }], }); } // generic function to handle form events (e.g. "submit" / "reset") // push transactions to the blockchain by using eosjs async handleFormEvent(event) { // stop default behaviour event.preventDefault(); // collect form data let account = event.target.account.value; let privateKey = event.target.privateKey.value; let dna = event.target.dna.value; let message = event.target.message.value; const result = await this.insertRow(account, privateKey, dna, message); console.log(result); this.getTable(); } getTable() { this.search(); } componentDidMount() { this.getTable(); } render() { const { treeTable } = this.state; const { classes } = this.props; // generate each tree as a card const generateCard = (key, timestamp, id, user, dna, message) => ( <Card className={classes.card} key={key}> <CardContent> <Typography variant="headline" component="h2"> {user} </Typography> <Typography component="pre"> {id} </Typography> <Typography style={{fontSize:12}} color="textSecondary" gutterBottom> {new Date(timestamp*1000).toString()} </Typography> <Typography component="pre"> {dna} </Typography> <Typography component="pre"> {message} </Typography> </CardContent> </Card> ); let treeCards = treeTable.map((row, i) => generateCard(i, row.timestamp, row.prim_key, row.user, row.dna, row.message)); return ( <div style={{height: '100%'}}> <AppBar position="static" color="default"> <Toolbar> <Typography variant="title" color="inherit"> Tree Chain </Typography> </Toolbar> </AppBar> {treeCards} <Paper className={classes.paper}> <Button variant="contained" color="primary" className={classes.formButton} onClick={this.seed} type="button"> Seed data </Button> <form onSubmit={this.handleFormEvent}> <TextField name="account" autoComplete="off" label="Account" margin="normal" fullWidth /> <TextField name="privateKey" autoComplete="off" label="Private key" margin="normal" fullWidth /> <TextField name="dna" autoComplete="off" label="DNA" margin="normal" fullWidth /> <TextField name="message" autoComplete="off" label="Message (Optional)" margin="normal" multiline rows="10" fullWidth /> <Button variant="contained" color="primary" className={classes.formButton} type="submit"> Add tree </Button> </form> </Paper> <pre className={classes.pre}> Below is a list of pre-created accounts information for add/update tree: <br/><br/> accounts = { JSON.stringify(accounts, null, 2) } </pre> </div> ); } } export default withStyles(styles)(Vendor);
const http = require('http'); const fs = require('fs'); let server = http.createServer(function(request,response){ let {url} = request; fs.readFile('www'+url,(err,data) => { if(err){ response.write('404'); }else{ response.write(data); } response.end(); }); }); server.listen(8020);
import { css } from 'lit-element'; export default css` :host { height: 100%; } .navigation { display: inline-flex; font-size: 0; height: 100%; min-height: 48px; position: relative; z-index: 9999; } .navigation__icon-btn-wrap { display: inline-flex; flex-direction: column; flex-grow: 1; align-items: center; justify-content: center; width: 40px; position: relative; z-index: 2; } .navigation__icon-btn { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; cursor: pointer; } .navigation__icon-btn:hover .svg-color { fill: #5F5F64; } .navigation__icon-btn-wrap_state_active .navigation__icon-btn:hover { cursor: default; } .navigation__icon-btn-wrap_state_active .svg-color { fill: #5F5F64; } .navigation__menu-overlay { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1; } .navigation__menu { position: absolute; top: 100%; right: 0; z-index: 2; font-size: 18px; box-shadow: 0px 2px 14px #0000001A; } .navigation__icon-btn-wrap_state_active::before { content: ''; position: absolute; top: 100%; margin-top: -3px; left: 0; right: 0; height: 3px; background: #828289; } `;
import React, { useState, useEffect, useContext } from "react"; import Collection from "./Collection"; import CreateCollection from "./CreateCollection"; import { Layout, Row, Col } from "antd"; import image from "../res/Doubs.png"; import HeaderTitle from "./HeaderTitle"; import { UserContext } from "../contexts/UserContext"; import { TokenContext } from "../contexts/TokenContext"; const { Header, Content } = Layout; const HomePage = ({ logout }) => { const [token, setToken] = useContext(TokenContext); const [collections, setCollections] = useState([]); const { username } = useContext(UserContext); const [usernameValue, setUsernameValue] = username; const [grid, setGrid] = useState([]); const [adding, setAdding] = useState(false); useEffect(() => { const getData = async () => { try { let response = await fetch( "https://366q1oq2q5.execute-api.eu-south-1.amazonaws.com/dev/api/collections", { method: "GET", headers: { Authorization: token }, } ); let fetchedData = await response.json(); setCollections(fetchedData); } catch (error) { console.log(error); } }; getData(); }, [adding]); useEffect(() => { setGrid(createGrid(collections)); }, [collections]); const createGrid = (array) => { let rows = []; let counter = 1; rows[counter] = []; array.forEach((element, index) => { if (index % 4 === 0 && index !== 0) { counter++; rows[counter] = []; rows[counter].push(element); } else { rows[counter].push(element); } }); rows.shift(); return rows; }; const eliminate = async (id) => { setCollections(collections.filter((collection) => collection._id !== id)); try { await fetch( "https://366q1oq2q5.execute-api.eu-south-1.amazonaws.com/dev/api/collections/" + id, { method: "DELETE", headers: { Authorization: token, }, } ); } catch (error) { console.log(error); } }; const createNew = async (name) => { try { await fetch( "https://366q1oq2q5.execute-api.eu-south-1.amazonaws.com/dev/api/collections/", { method: "POST", headers: { Authorization: token }, body: JSON.stringify({ name }), } ); setAdding(!adding); } catch (error) { console.log(error); } }; const save = async (id, name) => { try { await fetch( "https://366q1oq2q5.execute-api.eu-south-1.amazonaws.com/dev/api/collections/" + id, { method: "PATCH", headers: { Authorization: token, }, body: JSON.stringify({ name: name }), } ); } catch (error) { console.log(error); } }; return ( <Layout> <Header style={styles.header}> <HeaderTitle title="Home" username={usernameValue} isTodo={false} logout={logout} /> </Header> <Content style={styles.content}> {grid.map((elements, index) => { return ( <Row key={index} gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }} style={styles.row} > {elements.map((element, index) => { return ( <Col key={index} span={6}> <Collection id={element._id} name={element.name} number={element.count} eliminate={eliminate} username={usernameValue} save={save} logout={logout} ></Collection> </Col> ); })} </Row> ); })} <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }} style={styles.row}> <Col span={6}> <CreateCollection createNew={createNew} /> </Col> </Row> </Content> </Layout> ); }; const styles = { header: { backgroundColor: "white", minHeight: "8vh", textAlign: "center", }, content: { height: "90vh", backgroundImage: "url(" + image + ")", backgroundPosition: "center", backgroundSize: "cover", backgroundColor: "rgb(240, 242, 245)", }, title: { marginTop: "16px", }, row: { padding: "32px 80px 0px 80px", }, }; export default HomePage;
import React, {useContext} from "react"; import {useHistory} from "react-router-dom" import { useStateContext, authContext} from "../../utils/GlobalState"; import { Navbar, Nav } from "react-bootstrap"; import "./style.css"; import API from "../../utils/api"; const Index = () => { const [state, dispatch] = useStateContext(); const history = useHistory(); const {authData, setAuth}= useContext(authContext); const loguserout =()=>{ console.log("button click"); API.logout().then(()=>{ setAuth({...authData, isAuthenticated: false, user: null}); history.push("/"); }); console.log("[INFO] Shoud have routed the user to the login screen \ Navbar line 18"); } return ( <nav class="mynav navbar navbar-expand-lg navbar-dark"> <img class="logo" src="/assets/bubbles.svg"></img> <a class="navbar-brand" id="appName" href="#"> Bubbles </a> {window.location.pathname !== "/login" && window.location.pathname !== "/" ? ( <> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#"> <button type="button" class="btn btn-dark btn-circle btn-sm" onClick={() => dispatch({ type: "open-news" })} > News </button> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <button type="button" class="btn btn-dark btn-circle btn-sm" onClick={() => dispatch({ type: "open-time" })} > Time </button> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <button type="button" class="btn btn-dark btn-circle btn-sm " onClick={() => dispatch({ type: "open-pay" })} > Pay </button> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <button type="button" class="btn btn-dark btn-circle btn-sm" onClick={ !state.openDirectory ? () => dispatch({ type: "open-directory" }) : null } > Directory </button> </a> </li> <li class="nav-item"> <a class="nav-link" href="/" onClick= {() => alert("You Logged Out")}> <button type="button" class="button is-link" class="btn btn-dark btn-circle btn-sm" onClick={()=>{ loguserout(); }}> Logout </button> </a> </li> </ul> </> ) : ( <></> )} </nav> ); }; export default Index;
(function() { 'use strict'; angular .module('Data') .service('MenuDataService', MenuDataService); MenuDataService.$inject = ['$http']; function MenuDataService($http) { var baseUrl = 'https://davids-restaurant.herokuapp.com/'; var service = this; service.getAllCategories = function() { return httpGet('categories.json') .then(function(response) { return response.data; }); }; service.getCategory = function(categoryId) { return service.getAllCategories().then(function(categories) { for (var i = 0; i < categories.length; i ++) { if (categories[i].short_name === categoryId) { return categories[i]; } } }); }; service.getItemsForCategory = function(categoryShortName) { return httpGet('menu_items.json', {category: categoryShortName}) .then(function(response) { return response.data.menu_items; }); }; function httpGet(url, params) { return $http({ method: 'GET', url: baseUrl + url + '?' + paramsToQueryString(params) }); } function paramsToQueryString(params) { if (params == undefined) { params = {}; } var result = []; for (var k in params) { result.push(encodeURIComponent(k) + '=' + encodeURIComponent(params[k])); } return result.join('&'); } } })();
exports.up = function (knex) { return knex.schema .createTable("owners", (tbl) => { tbl.increments("owner_id"); tbl.string("owner_username", 128).notNullable().unique(); tbl.string("store_name", 128).notNullable(); tbl.string("owner_password", 128).notNullable(); tbl.string("store_category", 128).notNullable(); }) .createTable("items", (tbl) => { tbl.increments("item_id"); tbl .integer("owner_id") .unsigned() .notNullable() .references("owner_id") .inTable("owners") .onDelete("RESTRICT"); tbl.string("item_name", 128).notNullable(); tbl.integer("item_price").notNullable(); tbl.string("item_description", 500).notNullable(); }) .createTable("users", (tbl) => { tbl.increments("user_id"); tbl.string("user_username", 128).notNullable().unique(); tbl.string("user_password", 128).notNullable(); }); }; exports.down = function (knex) { return knex.schema .dropTableIfExists("owners") .dropTableIfExists("items") .dropTableIfExists("users"); };
/** * Created by Administrator on 2017/9/8 0008. */ const async = require('async'); const AuthorityRoleService = require('./../service/authorityRoleService'); const redisUtil = require('./../utils/redisUtil'); const redis = require('redis'); const redisCon = require('./../config/config_dev.json').redis_url; const client = redis.createClient(redisCon.port, redisCon.host); //获取所有用户组(角色)权限,存储到redis中 const getRoleAuthority = function(callback){ async.auto({ //获取所有用户组权限 getRoleAuthorityList:function(cb){ AuthorityRoleService.findAuthorityRoleByRoleId({},{},function(error,data){ if(error){ return cb(error); } cb(null,data); }) }, //处理数据 handleData:["getRoleAuthorityList",function(result,cb){ let roleAuthorityList = result.getRoleAuthorityList; let roleData = {}; let roleList = []; for(let i=0;i<roleAuthorityList.length;i++){ //如果没有role_1 对象则创建一个 let dbName = 'role_'+roleAuthorityList[i].RoleId; if(!roleData[dbName]){ roleData[dbName] = {}; } roleData[dbName][roleAuthorityList[i].authority.url] = roleAuthorityList[i].authority.name; } for(let item in roleData){ roleData[item]['dbName'] = item; roleList.push(roleData[item]); } cb(null,roleList); }], //添加到redis addInRedis:["handleData",function(result,cb){ let roleList = result.handleData; async.eachSeries(roleList,function(role,cb){ let param = { db:'15', dbName:role.dbName }; delete role.dbName; param.dataValue = role; client.select(param.db, function(error){ if(error) { console.log(error); } else { client.hmset(param.dbName, param.dataValue, function(error, result){ if(error) { cb(error); } else { cb(null,result); } }); } }); },function(error){ // 关闭链接 client.quit(); if(error){ return cb(error); } cb(); }) }] },function(error,results){ if(error){ return callback(error); } callback(null,results); }) }; module.exports = { getRoleAuthority: getRoleAuthority };
const router = require('koa-router')(); const Admin = require(config.__DOPath + 'Admin'); router.prefix('/initData'); router.get('/', async (ctx,next) => { ctx.body = "插入数据"; }); router.get('/addAdmin', async (ctx) => { //向数据库插入一条admin数据 let temp = new Admin({ "ano": 0, "name": "admin", "password": md5(md5("123456").substr(4, 7) + md5("123456")), "power": [-1], "phone": "18826252375", }); ctx.body =await new Promise(function (resolve, reject) { temp.save(function (err) { if (err) { return resolve("数据插入失败"); } return resolve("数据插入成功"); }); }); //查找admin管理信息 // ctx.response.body = await new Promise(function (resolve, reject) { // // return Admin.find({}, function (err, result) { // // if (err) { // ctx.response.status = 404; // return resolve(404); // } else { // return resolve(result); // } // // }); //删除admin管理员 // Admin.remove({ano: "0"}, function (err, result) { // // if (err) { // ctx.response.status = 404; // return resolve(404); // } // // console.log(result.result.ok); // // return resolve("管理员删除成功!"); // // }); // }); }); module.exports = router;
/** * Created by zmievskaya on 05.10.16. */ $(function() { $('.rating').removeClass('col-md-offset-5').addClass('col-md-offset-7'); $('button.manage').parent().siblings('.rating').removeClass('col-md-offset-5').addClass('col-md-offset-4'); $('.vote-buttons').siblings('.rating').removeClass('col-md-offset-4').addClass('col-md-offset-5'); $('.status').on('click', function() { $('.rating').removeClass('col-md-offset-8').addClass('col-md-offset-5'); }); });
/*模板引擎*/ /*mydemo-art>npm init -y package.json /*mydemo-art>npm install art-template --save * */ let template=require("art-template"); /*template(模板路径,数据对象);*/ let html=template(__dirname+"/mytpl.art",{ user:{ name:'小白' } }); console.info(html); let h=template(__dirname+"/score.art",{ chinese:'120', math:'140', english:'100', summary:'360' }); console.info(h); /*循环取值的模板*/ //let tpl='<ul>{{each list as value}}<li>{{value}}</li>{{/each}}</ul>'; let tpl='<ul>{{each list}}<li>{{$index}}----{{$value}}</li>{{/each}}</ul>'; let aa=template.compile(tpl); let ret=aa({ list:['red','yellow','green','blue'] }); console.info(ret);
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by an Apache-style license that can be // found in the LICENSE file. (function(global){ "use strict"; var csp = global.csp = {}; // // Utility methods // Object.defineProperty(Array.prototype, "_has", { value: function(value) { return this.indexOf(value) != -1; }, writable: true, configurable: true, enumerable: false, }); Object.defineProperty(String.prototype, "_has", { value: function(value) { return this.indexOf(value) != -1; }, writable: true, configurable: true, enumerable: false, }); var toCamelCase = (function() { var _tcc = Object.create(null); return function(str) { var cr = _tcc[str]; if (cr) { return cr; } var first = true; var ccv = str.split(/[-_]/).map(function(v, i) { if (!v) { return; } if (v && !first) { return v.substr(0, 1).toUpperCase() + v.substr(1); } first = false; return v; }).join(""); // Cache it. _tcc[str] = ccv; return ccv; }; })(); var own = function(obj, cb, context) { Object.getOwnPropertyNames(obj).forEach(cb, context||global); return obj; }; var extend = function(obj, props) { own(props, function(x) { var pd = Object.getOwnPropertyDescriptor(props, x); if ( (typeof pd["get"] == "function") || (typeof pd["set"] == "function") ) { Object.defineProperty(obj, x, pd); } else if (typeof pd["value"] == "function" ||x.charAt(0) === "_") { pd.writable = true; pd.configurable = true; pd.enumerable = false; Object.defineProperty(obj, x, pd); } else { obj[x] = props[x]; } }); return obj; }; var inherit = function(props) { var ctor = null; var parent = null if (props["extends"]) { parent = props["extends"]; delete props["extends"]; } if (props["initialize"]) { ctor = props["initialize"]; delete props["initialize"]; } var realCtor = ctor || function() { }; var rp = realCtor.prototype = Object.create( ((parent) ? parent.prototype : Object.prototype) ); extend(rp, props); return realCtor; }; // // CriSP-y // var Url = csp.Url = inherit({ initialize: function(url) { // Initialize the object shape. this.source = url || ""; this.scheme = ""; this.host = ""; this.port = ""; this.query = ""; this.file = ""; this.hash = ""; this.path = ""; this.hasWildcardHost = false; this.hasWildcardPort = false; /* this.relative = ""; this.params = {}; this.segments = []; */ if (url) { this._parseUrl(url); } }, toString: function() { /* console.log(this.scheme); console.log(this.path); */ var url = ""; if (this.scheme) { url += this.scheme; } if (this.host || this.path) { if (this.scheme) { url += "://"; } if (this.hasWildcardHost) { url += "*"; } url += this.host; if (this.hasWildcardPort) { url += ":*"; } else if (this.port) { url += ":" + this.port; } if (this.file || this.query || this.path) { if (this.path) { url += this.path; } } else { url += "/"; } if (this.hash) { url += "#" + this.hash; } if (this.query) { url += "?" + this.query; } } return url; }, // FIXME(slightlyoff): TESTS!!! _parseUrl: function(url) { // Parsing constants var SCHEME_SEP = "://"; var PORT_TOKEN = ":"; var SLASH = "/"; if (url._has(SCHEME_SEP)){ this.scheme = url.substring(0, url.indexOf(SCHEME_SEP)); } var remainder = ""; var hostPart = url; if (url._has(SCHEME_SEP)) { // Lop the scheme off hostPart = url.substring(url.indexOf(SCHEME_SEP) + SCHEME_SEP.length); } // FIXME: should probably validate host based on production in EBNF var idx = -1; var idxen = [ hostPart.indexOf(SLASH), hostPart.indexOf(PORT_TOKEN) ].filter(function(i) { return i != -1; }); if (idxen.length) { idx = Math.min.apply(null, idxen); } if (idx == -1) { // If we don't have a "/" or a ":", the whole thing is the host this.host = hostPart; return; } this.host = hostPart.substring(0, idx); remainder = hostPart.substring(idx+1); if (this.host) { // Now look for a port and path if (hostPart.indexOf(PORT_TOKEN) == idx) { // We've got a port. Save it and continue. var si = remainder.indexOf(SLASH); if (si != -1) { this.port = remainder.substring(0, remainder.indexOf(SLASH)); remainder = remainder.substring(remainder.indexOf(SLASH)+1); } else { this.port = remainder; return; } } if (remainder) { // FIXME(slightlyoff): do we need to prepend "/"? // this.path = remainder; var pathParts = remainder.split("?", 2); if (pathParts[1]) { this.query = pathParts[1]; } this.path = "/" + pathParts[0]; var fileParts = this.path.split("/"); this.file = fileParts[fileParts.length - 1] || ""; } } else { this.path = "/"; } }, set host(host) { // Is the host wildcarded? If so, strip the astrisk; it makes comparison // simpler later on, as we can do a simple suffix test. var ASTERISK = "*"; var PERIOD = "."; if (host.indexOf(ASTERISK) == 0 && host.indexOf(PERIOD) == 1) { this.hasWildcardHost = true; this._host = host.substring(1); } else { this.hasWildcardHost = false; this._host = host; } }, get host() { return this._host; }, set port(port) { // Is the port wildcarded? If so, strip it; it makes comparison // simpler later on, as we can just check the bool. var ASTERISK = "*"; if (port == ASTERISK) { this.hasWildcardPort = true; this._port = true; } else { this.hasWildcardPort = false; this._port = port; } }, get port() { return this._port; }, get effectivePort() { // If port is the empty string, return the default port for the URL's scheme if (this.port == "") { // FIXME: Are we sure that the scheme matches the document's scheme? switch (this.scheme) { case "https": return 443; case "http": return 80; default: return ""; }; } return this.port; } }); // Parsing is giving by spec as: // source-list = *WSP [ source-expression *( 1*WSP source-expression ) *WSP ] // / *WSP "'none'" *WSP // source-expression = scheme-source / host-source / keyword-source // scheme-source = scheme ":" // host-source = [ scheme "://" ] host [ port ] [ path ] // keyword-source = "'self'" / "'unsafe-inline'" / "'unsafe-eval'" // scheme = <scheme production from RFC 3986, section 3.1> // host = "*" / [ "*." ] 1*host-char *( "." 1*host-char ) // host-char = ALPHA / DIGIT / "-" // path = <path production from RFC 3986, section 3.3> // port = ":" ( 1*DIGIT / "*" ) var SourceExpression = csp.SourceExpression = inherit({ extends: Url, initialize: function(expressionStr) { Url.call(this); this._parseExpression(expressionStr); }, _keywordSources: [ "'self'", "'unsafe-inline'", "'unsafe-eval'" ], _parseExpression: function(expr) { // See if it's one of our reserved tokens if (expr == "'none'") { return; } if (this._keywordSources._has(expr)) { this.keywordSource = expr; } else { // Parse it as a URL pattern this._parseUrl(expr); } }, portIsDefaultForScheme: function() { if (!this.port) return true; var scheme = this.scheme || "http"; switch(scheme) { case "http": return this.port == "80"; case "https": return this.port == "443"; default: return true; } } }); var ciMatch = function() { // Case-insensitive match all arguments var match = true; var varArgs = Array.prototype.slice.call(arguments, 0); var first = varArgs.shift().toUpperCase(); varArgs.every(function(a) { if (a.toUpperCase() != first) { match = false; return false; } return true; }); return match; }; var ciSuffix = function(string, suffix) { // Is 'suffix' a case-insensitive suffix of 'string'? var idx = string.toUpperCase().lastIndexOf(suffix.toUpperCase()); return !( idx == -1 || idx + suffix.length != string.length) }; // A URL matches a source list, if, and only if, the URL matches at least one // source expression in the set of source expressions obtained by parsing the // source list. Notice that no URLs match an empty set of source expressions, // such as the set obtained by parsing the source list 'none'. var matchSourceExpression = csp.matchSourceExpression = function(documentUrl, source, url) { // 3.2.2.2 Matching // // To check whether a URL matches a source expression, the user agent must use // an algorithm equivalent to the following: // // If the source expression a consists of a single U+002A ASTERISK character // (*), then return does match. if (source == "*") { return true; } // Empty set, no match for anything. if (source == "'none'") { return false; } var doc = new SourceExpression(documentUrl); var se = new SourceExpression(source); var url = new SourceExpression(url); // If the source expression matches the grammar for scheme-source: if (se.scheme == se.source) { // If the URL's scheme is a case-insensitive match for the source // expression's scheme, return does match. // Otherwise, return does not match. return ciMatch(se.scheme, url.scheme); } // If the source expression matches the grammar for host-source: if (se.host) { // If the URL does not contain a host, then return does not match. if (!url.host) return false; // Let uri-scheme, uri-host, and uri-port be the scheme, host, and port of // the URL, respectively. If the URL does not have a port, then let uri- // port be the default port for uri-scheme. Let uri-path be the path of // the URL after decoding percent-encoded characters. If the URL does not // have a path, then let uri-path be the U+002F SOLIDUS character (/). // If the source expression has a scheme that is not a case insensitive // match for uri-scheme, then return does not match. if (se.scheme) { if (!ciMatch(se.scheme, url.scheme)) return false; } else { // If the source expression does not have a scheme and if uri-scheme is // not a case insensitive match for the scheme of the protected resource's // URL, then return does not match. if (!ciMatch(url.scheme, doc.scheme)) return false; } // If the first character of the source expression's host is an U+002A // ASTERISK character (*) and the remaining characters, including the // leading U+002E FULL STOP character (.), are not a case insensitive // match for the rightmost characters of uri-host, then return does not // match. if (se.hasWildcardHost && !ciSuffix(url.host, se.host)) return false; // If uri-host is not a case insensitive match for the source expression's // host, then return does not match. if (!se.hasWildcardHost && !ciMatch(se.host, url.host)) return false; // If the source expression does not contain a port and uri-port is not // the default port for uri-scheme, then return does not match. if (!se.port && !url.portIsDefaultForScheme()) return false; // If the source expression does contain a port, then return does not // match if port does not contain a U+002A ASTERISK character (*), and // port does not represent the same number as uri-port. if (se.port && !se.hasWildcardPort && (se.effectivePort != url.effectivePort)) { return false; } // If the source expression contains a non-empty path, then: if (se.path) { // Let decoded-path be the result of decoding path's percent-encoded // characters. var decodedPath = decodeURIComponent(se.path); // If the final character of decoded-path is the U+002F SOLIDUS // character (/), and decoded-path is not a prefix of uri-path, then // return does not match. if (decodedPath.charAt(decodedPath.length-1) == "/") { if (url.path.indexOf(decodedPath) != 0) { return false; } // If the final character of decoded-path is not the the U+002F // SOLIDUS character (/), and decoded-path is not an exact match for // uri-path then return does not match. } else { if (url.path != decodedPath) { return false; } } } // Otherwise, return does match. return true; } // If the source expression is a case insensitive match for 'self' (including // the quotation marks), then return does match if the URL has the same // scheme, host, and port as the protected resource's URL (using the default // port for the appropriate scheme if either or both URLs are missing ports). if (se.keywordSource == "'self'") { return ( (url.scheme == doc.scheme) && (url.host == doc.host) && (url.port == doc.port) ); } // Otherwise, return does not match. return false; }; var matchSourceExpressionList = function(base, list, url) { for (var y = 0; y < list.length; y++) { if (matchSourceExpression(base, list[y], url)) { return true; } } return false; }; // Models each policy directive. Instances are used in SecurityPolicy. var PolicyDirective = csp.PolicyDirective = inherit({ initialize: function(policyName) { // Copy constructor if (policyName instanceof PolicyDirective) { this.name = policyName.name; this.set = policyName.set; this.sourceList = policyName.sourceList; // Normal init } else { this.name = policyName; this.set = false; this.sourceList = []; } }, addSource: function(origin) { if (!origin) return; this.set = true; if (!this._has(origin)) { this.sourceList.push(origin); } }, _has: function() { return this.sourceList._has.apply(this.sourceList, arguments); }, toString: function() { return this.name + ((this.sourceList.length) ? (" " + this.sourceList.join(" ")) : ""); }, }); // Class to model a policy // // From the 1.1 spec we have an (as-yet unimplemneted) scripting interface: // // interface SecurityPolicy { // readonly attribute DOMString[] reportURIs; // bool allowsEval(); // bool allowsInlineScript(); // bool allowsInlineStyle(); // bool allowsConnectionTo(DOMString url); // bool allowsFontFrom(DOMString url); // bool allowsFormAction(DOMString url); // bool allowsFrameFrom(DOMString url); // bool allowsImageFrom(DOMString url); // bool allowsMediaFrom(DOMString url); // bool allowsObjectFrom(DOMString url); // bool allowsPluginType(DOMString type); // bool allowsScriptFrom(DOMString url); // bool allowsStyleFrom(DOMString url); // bool isActive(); // }; var SecurityPolicy = csp.SecurityPolicy = inherit({ initialize: function(policyStringOrPolicy, baseUrl) { this._clear(); this.baseUrl = baseUrl; if (policyStringOrPolicy) { if (typeof policyStringOrPolicy == "string") { this.policy = policyStringOrPolicy; } else { // We act as a copy constructor should we be passed an SP // Duck typing! if (!baseUrl && policyStringOrPolicy.baseUrl) { this.baseUrl = policyStringOrPolicy.baseUrl; } if (policyStringOrPolicy.policy) { this.policy = policyStringOrPolicy.policy; } } } }, _clear: function() { // Initialize the following properties: // defaultSrc // scriptSrc // objectSrc // styleSrc // imgSrc // mediaSrc // frameSrc // fontSrc // connectSrc // formAction // sandbox // scriptNonce // pluginTypes // reportUri SecurityPolicy.directives.forEach(function(directive) { this[toCamelCase(directive)] = new PolicyDirective(directive); }, this); }, get policy() { return this.toString(); }, set policy(p) { this._parsePolicy(p+""); }, _parsePolicy: function(policy) { var clauses = policy.split(";") clauses.forEach(function(clause) { var terms = clause.trim().split(/[\s\t]+/); if (!terms.length) return; var directive = toCamelCase(terms.shift()); var prop = this[directive]; if (prop instanceof PolicyDirective) { prop.set = true; prop.sourceList = terms; } }, this); }, toString: function() { var r = []; SecurityPolicy.directives.forEach(function(d) { var prop = this[toCamelCase(d)]; if (prop && prop.set) { r.push(prop.toString()); } }, this); return r.join("; "); }, _allowsFromSet: function(type, set) { for (var x = 0; x < set.length; x++) { if (set[x].set) { return (set[x]._has(type)); } } return true; }, _allowsUrlFromSet: function(url, set) { if (!this.baseUrl) throw new Error("No baseUrl set!"); for (var x = 0; x < set.length; x++) { if (set[x].set) { return matchSourceExpressionList(this.baseUrl, set[x].sourceList, url); } } return true; }, get allowsEval() { return this._allowsFromSet("'unsafe-eval'", [this.scriptSrc, this.defaultSrc]); }, get allowsInlineScript() { return this._allowsFromSet("'unsafe-inline'", [this.scriptSrc, this.defaultSrc]); }, get allowsInlineStyle() { return this._allowsFromSet("'unsafe-inline'", [this.styleSrc, this.defaultSrc]); }, allowsConnectionTo: function(url) { return this._allowsUrlFromSet(url, [this.connectSrc, this.defaultSrc]); }, allowsFontFrom: function(url) { return this._allowsUrlFromSet(url, [this.fontSrc, this.defaultSrc]); }, allowsFormAction: function(url) { return this._allowsUrlFromSet(url, [this.formAction, this.defaultSrc]); }, allowsFrameFrom: function(url) { return this._allowsUrlFromSet(url, [this.frameSrc, this.defaultSrc]); }, allowsImageFrom: function(url) { return this._allowsUrlFromSet(url, [this.imgSrc, this.defaultSrc]); }, allowsMediaFrom: function(url) { return this._allowsUrlFromSet(url, [this.mediaSrc, this.defaultSrc]); }, allowsObjectFrom: function(url) { return this._allowsUrlFromSet(url, [this.objectSrc, this.defaultSrc]); }, allowsPluginType: function(type) { // FIXME(slightlyoff) }, allowsScriptFrom: function(url) { return this._allowsUrlFromSet(url, [this.scriptSrc, this.defaultSrc]); }, allowsStyleFrom: function(url) { return this._allowsUrlFromSet(url, [this.styleSrc, this.defaultSrc]); }, // FIXME(slightlyoff): this is really a DOM concern about the state of the // document (i.e., "is there any CSP policy currently applied?"). It doesn't // belong here in the API. get isActive() { return false; }, }); // Merging SecurityPolicy instances *weakens* the overall policy. For the most // restrictive subset, see SecurityPolicy.intersection(...) SecurityPolicy.union = function(/*...varArgs*/) { var bp = new SecurityPolicy(); var varArgs = Array.prototype.slice.call(arguments, 0).map(function(a) { return new SecurityPolicy(a); }); varArgs.forEach(function(arg) { SecurityPolicy.directives.forEach(function(d) { var propName = toCamelCase(d); var prop = arg[propName]; // We only bother doing this dance to weaken a policy that's been set on // the baseline policy, else we already are open by default, so there's // very little be done. // FIXME(slightlyoff): should we be somewhat more restrictive, adopting // set policies if there isn't one, but loosening them if they both are? if (prop && prop.set && bp[propName].set) { prop.sourceList.forEach(function(origin) { bp[propName].addSource(origin); }); } }); }); return bp; }; // The intersection method returns a policy object that enforces the // restrictions of all of the passed policies. That is to say, if one policy // loosens a restriction to allow some domain but the other doesn't, it won't be // allowed in the resulting SecurityPolicy object. SecurityPolicy.intersection = function(/*...varArgs*/) { var varArgs = Array.prototype.slice.call(arguments, 0).map(function(a) { return new SecurityPolicy(a); }); var baseline = varArgs.shift(); // We baseline our union on the first policy and subtract from there. var bp = new SecurityPolicy(baseline); if (!varArgs.length || !baseline) { return bp; } varArgs.forEach(function(arg) { SecurityPolicy.directives.forEach(function(d) { var propName = toCamelCase(d); var bProp = bp[propName]; var prop = arg[propName]; // CSP is open by default, closed as soon as a value is set (opening back // up from there), so if our baseline isn't set but the new one is, then // we want to adopt the new one wholesale, even if it's "*" if (!bProp.set && prop.set) { bp[propName] = prop; return; } // Else we only care if both are set as it means there are policies to // resolve if(!bProp.set || !prop.set) { return; } // We want to be the strictest. This isn't necessarialy the shorter list // (as a single "*" is looser and a "" == "'none'"). We do this by strict // subsetting, ignoring 'none' as it's implied by the current spec anyway. // See: // http://lists.w3.org/Archives/Public/public-webappsec/2013Jan/0006.html var inBoth = []; bProp.sourceList.forEach(function(v) { if (prop._has(v) && v != "'none'") { inBoth.push(v); } }); bp[propName].sourceList = inBoth; bp[propName].set = true; }); }); return bp; }; // Merge is a hybrid of union and intersection. Unlike union, we start with the // most restrictive subset, but we add all the rules that weaken the clause // *from every policy*. SecurityPolicy.merge = function(/*...varArgs*/) { var bp = new SecurityPolicy(); var varArgs = Array.prototype.slice.call(arguments, 0).map(function(a) { return new SecurityPolicy(a); }); // For every passed policy, we ensure that bp takes the union of values for // each directive, which is to say that we strengthen any policy that might // remain entirely open under union(), but loosen it as far as every policy in // the arguments might want varArgs.forEach(function(arg) { SecurityPolicy.directives.forEach(function(d) { var n = toCamelCase(d); var bProp = bp[n]; arg[n].sourceList.forEach(bProp.addSource.bind(bProp)); // Capture null lists. bProp.set = bProp.set || arg[n].set; }); }); return bp; }; SecurityPolicy.headerList = [ "X-WebKit-CSP", "X-Content-Security-Policy", "Content-Security-Policy", // If a site sends us a "Report-Only" directive, we enforced it. "X-WebKit-CSP-Report-Only", "Content-Security-Policy-Report-Only", "X-Content-Security-Policy-Report-Only" ]; SecurityPolicy.directiveReservedValues = [ "'none'", "'self'", "'unsafe-inline'", "'unsafe-eval'" ]; SecurityPolicy.directives = [ "default-src", "script-src", "object-src", "style-src", "img-src", "media-src", "frame-src", "font-src", "connect-src", "form-action", "sandbox", "script-nonce", "plugin-types", "report-uri" ]; })(this);
collideWith(obj) { if (this.x + this.w > obj.x && this.x < obj.x + obj.w && this.y + this.h > obj.y && this.y < obj.y + obj.h ){ console.log('collides with ' + obj); return true; } } class Wall extends Sprite{ constructor(x, y, w, h, color){ super(x, y, w, h, color); this.x = x; this.y = y; this.w = w; this.h = h; this.color = color; } create(x, y, w, h, color) { return new Wall(x, y, w, h, color); } get type(){ return "wall"; } }
import './index.less'; import React from 'react'; import {Table, Modal, Tree,Icon,Button,Input} from 'antd'; import ResetInfo from './alert/index' const {confirm} = Modal; const { TreeNode } = Tree; const req = { "code": 0, "msg": "", "count": 3, "data": [{ "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:37", "isDelete": 0, "roleId": 1, "roleName": "超级管理员", "comments": "超级管理员" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 2, "roleName": "管理员", "comments": "系统管理员" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }, { "createBy": 1, "createTime": "2018/12/13 11:11:44", "updateBy": 1, "updateTime": "2018/12/13 15:50:35", "isDelete": 0, "roleId": 3, "roleName": "普通用户", "comments": "系统普通用户" }] }; export default class role extends React.Component { state = { expandedKeys: ['0-0-0', '0-0-1'], autoExpandParent: true, checkedKeys: ['0-0-0'], selectedKeys: [], data: req.data.map(item => Object.assign(item, {key: item.roleId})), columns: [{ title: '角色名', dataIndex: 'roleName', sorter(a, b) { return a.roleId - b.roleId } }, { title: '备注', dataIndex: 'comments', sorter(a, b) { return a.comments.length - b.comments.length } }, { title: '创建时间', dataIndex: 'createTime', sorter(a, b) { return new Date(a.createTime) - new Date(b.createTime) } }, { title: '操作', dataIndex: '', key: 'x', render: (text, record, index) => ( <div className={'action'}> <span onClick={() => this.reset(text, record)}>修改</span><span onClick={() => this.delete(text, record, index)} className={'delect'}>删除</span><span onClick={() => this.permission(text, record)}>权限管理</span> </div> ) }], treeData :[ { title: '0-0', key: '0-0', children: [ { title: '0-0-0', key: '0-0-0', children: [ { title: '0-0-0-0', key: '0-0-0-0' }, { title: '0-0-0-1', key: '0-0-0-1' }, { title: '0-0-0-2', key: '0-0-0-2' }, ], }, { title: '0-0-1', key: '0-0-1', children: [ { title: '0-0-1-0', key: '0-0-1-0' }, { title: '0-0-1-1', key: '0-0-1-1' }, { title: '0-0-1-2', key: '0-0-1-2' }, ], }, { title: '0-0-2', key: '0-0-2', }, ], }, { title: '0-1', key: '0-1', children: [ { title: '0-1-0-0', key: '0-1-0-0' }, { title: '0-1-0-1', key: '0-1-0-1' }, { title: '0-1-0-2', key: '0-1-0-2' }, ], }, { title: '0-2', key: '0-2', }, ], visible:false, reset_visible:false, form:{} } onExpand = expandedKeys => { this.setState({ expandedKeys, autoExpandParent: false, }); }; onCheck = checkedKeys => { console.log('onCheck', checkedKeys); this.setState({ checkedKeys }); }; onSelect = (selectedKeys, info) => { this.setState({ selectedKeys }); }; renderTreeNodes = data => data.map(item => { if (item.children) { return ( <TreeNode title={item.title} switcherIcon={<Icon type="appstore" />} key={item.key} dataRef={item}> {this.renderTreeNodes(item.children)} </TreeNode> ); } return <TreeNode {...item} />; }); sort1 = (pager, unnow, size) => { console.log(pager.unnow,size) } //修改 reset(text) { if(text){ this.setState({ form:{ roleName:text.roleName, comments:text.comments, roleId:text.roleId }, reset_visible:!this.state.reset_visible }) }else this.setState({ reset_visible:!this.state.reset_visible }) } //权限 permission(text) { this.setState({ visible:true }) } //权限确定,向后台发送 handleOk(){ } //删除 delete(text, full, index) { const _this = this; confirm({ title:'确定删除吗?', onOk() { _this.state.data.splice(index, 1) _this.setState({ data: [..._this.state.data] }) }, onCancel() { console.log('Cancel'); } }) } render() { return ( <div className={'content'}> <div className={'search'}> <span>搜索:</span> <Input value={''} placeholder={'请输入关键词'} style={{width:'auto',margin:'0 15px'}}/> <Button icon="search">搜索</Button> </div> <Table bordered={true} dataSource={this.state.data} onChange={this.sort1} columns={this.state.columns} ></Table> <Modal visible={this.state.visible} title="权限管理" onOk={this.handleOk} onCancel={()=>{this.setState({visible:false})}} > <Tree checkable onExpand={this.onExpand} expandedKeys={this.state.expandedKeys} autoExpandParent={this.state.autoExpandParent} onCheck={this.onCheck} checkedKeys={this.state.checkedKeys} onSelect={this.onSelect} selectedKeys={this.state.selectedKeys} switcherIcon={<Icon type="appstore" />} > {this.renderTreeNodes(this.state.treeData)} </Tree> </Modal> { !this.state.reset_visible?null:( <ResetInfo visible={this.state.reset_visible} handleCanle={this.reset.bind(this)} form={this.state.form} ></ResetInfo> ) } </div> ); } }
(function () { angular .module('app') .config(config); // .filter('percentage', ['$filter', function ($filter) { // return function (input, decimals) { // return $filter('number')(input * 100, decimals) + '%'; // }; // }]) function config($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/login"); $stateProvider .state('login',{ url: '/login', templateUrl: 'app/partials/login.html', controller: 'authCtrl' }) .state('signup',{ url: '/signup', templateUrl: 'app/partials/signup.html', controller: 'authCtrl' }) .state('nav', { abstract: true, url: '/nav', templateUrl: 'app/partials/nav.html', controller: 'navCtrl' }) .state('home', { parent: 'nav', url: '/home', templateUrl: 'app/partials/home.html', controller: 'homeCtrl' }) .state('newissue', { parent: 'nav', url: '/newissue', templateUrl: 'app/partials/newIssue.html', controller: 'newIssueCtrl' }) .state('manage', { parent: 'nav', url: '/manage', templateUrl: 'app/partials/manage.html', controller: 'manageCtrl' }) .state('upload', { parent: 'nav', url: '/upload', templateUrl: 'app/partials/upload.html', controller: 'uploadCtrl' }) .state('logout', { url: '/logout', controller: 'logoutCtrl' }) } })(); // .state('newissue', { // url: '/newissue', // templateUrl: 'app/partials/newissue.html', // controller: 'newissueCtrl' // }) // .state('passwordreset', { // url: '/passwordreset', // templateUrl: 'app/partials/passwordreset.html', // controller: 'passwordresetCtrl' // }) // .state('contact', { // url: "/contact", // templateUrl: "app/partials/contact.html" // }) // .state('change', { // url: '/change', // templateUrl: 'app/partials/change.html', // controller: 'changeCtrl' // }) // .state('myissues', { // url: '/myissues', // templateUrl: 'app/partials/myissues.html', // controller: 'myissuesCtrl' // }) // .state('editIssue', { // url: '/editIssue?issueId', // templateUrl: 'app/partials/editIssueMaster.html', // controller: 'editIssueMasterCtrl' // }) // .state('editIssue.edit', { // url: '/edit', // templateUrl: 'app/partials/editIssueModal-edit.html', // controller: 'editIssueModal-editCtrl', // parent: 'editIssue' // }) // .state('editIssue.discussion', { // url: '/discussion', // templateUrl: 'app/partials/editIssueModal-discussion.html', // controller: 'editIssueModal-discussionCtrl', // parent: 'editIssue', // }) // .state('editIssue.resolve', { // url: '/resolve', // templateUrl: 'app/partials/editIssueModal-resolve.html', // controller: 'editIssueModal-resolveCtrl', // parent: 'editIssue' // })
'use strict'; const app = require('./server/api'); const config = require('./config'); const rConcole = require('./server/utils/logger'); const http = require('http'); const sequelize = require('./server/utils/sequelize'); let info = `info, web server is available at http://%s:%s, ${config.server.host}, ${config.server.port}`; // let server = app.listen(config.server.port, // config.server.host, // () => console.log(info)); sequelize.sync() .then(() => { app.listen(config.server.port, config.server.host, () => console.log(info)); }) .catch((err) => { throw Error(err); }); module.exports = app;
const express = require("express"); const router = express.Router(); const EmployeeModel = require("../../models/Employee.model"); const TransactionModel = require("../../models/Transaction.model"); router.post("/", async (req, res) => { try { const { employeeId, day } = req.body; //Validation if (!day) return res.json({ status: false, message: "يجب تحديد اليوم الذي تريد احصائياته", }); //Check if employee exist if (employeeId && !(await EmployeeModel.findOne({ _id: employeeId }))) return res.json({ status: false, message: "الموظف الذي اخترته غير مسجل من قبل", }); //Get all transactions for the submitted day const transactions = await TransactionModel.find({ ...(employeeId && { "employee._id": employeeId }), day, }); if (transactions.length == 0) return res.json({ status: false, message: "لا يوجد أي عمليات لهذا اليوم", }); const employees = await EmployeeModel.find({}); return res.json({ status: true, message: "تم استرجاع البيانات بنجاح", data: { transactions, employees }, }); } catch (e) { console.log(`Error in /transactions/get, error: ${e.message}`, e); res.json({ status: false, message: e.message, }); } }); module.exports = router;
import React, { useContext } from "react"; import { TouchableOpacity } from "react-native"; import { FontAwesome5 as FA5Icon } from "@expo/vector-icons/"; import { ColorContext } from "../../functions/providers/ColorContext"; import styles from "../../styles/signInStyles"; import generalStyles from "../../styles/generalStyles" export default function Button(props) { const { onPress, size, icon } = props; const { color } = useContext(ColorContext); return ( <TouchableOpacity onPress={onPress} style={[styles.button, generalStyles.shadow, { backgroundColor: color.highlight, shadowColor: color.shadow }]}> <FA5Icon name={icon} color={color.primary} size={size} /> </TouchableOpacity> ); }