text
stringlengths
7
3.69M
import React from 'react' import { Card } from 'react-bootstrap' import { Link } from 'react-router-dom' import './Home.css' const Home = (props) => { return ( <div className='main-card'> <Card style={{ width: '40rem'}}> <Card.Body> <Card.Title className='title'>Important Information</Card.Title> <Card.Subtitle className="mb-2 text-muted" style={{'padding-bottom': '10px'}}> Note* This is a test application so please use the Ropsten Test Network option in MetaMask. </Card.Subtitle> <Card.Text> In order for you to send transactions and get data, this test application requires you to have an account number and <b>private key</b> through MetaMask. Please use the following links to either get set up or continue. Go to <Card.Link href={`https://faucet.ropsten.be/`}> https://faucet.ropsten.be/ </Card.Link> to deposit test ether. </Card.Text> <div className='acct-links'> <Link to='/create'>I have my information</Link> <Card.Link href="https://metamask.io/">Go to MetaMask</Card.Link> </div> </Card.Body> </Card> </div> ) } export default Home
/*! * 基于手机端的下拉刷新+上拉加载组件 * author:xiangzongliang * time:20180810 * version:V1.0.0 * github:https://github.com/xiangzongliang/iantoo-old */ import "../less/dragRefresh.less" import elem from './lib/elem.js' ;(function (win,undefined) { var iantoo = win.iantoo || {}, _dom; var D = { //初始化 init: function (opction) { this.data.content = opction.content || 'body' this.data.loadingBox = opction.loadingBox || '#dragRefreshLoading' this.data.downDragText = opction.downDragText || '页面刷新中...' this.data.upDragText = opction.upDragText || '数据加载中...' this.data.downTextColor = opction.downTextColor || '#9c9c9c' this.data.upTextColor = opction.upTextColor || '#9c9c9c' this.data.downRefresh = opction.downRefresh || function(){} this.data.upRefresh = opction.upRefresh || function(){} this.data.closeDown = opction.closeDown || function(){} this.data.closeUp = opction.closeUp || function(){} this.render() }, data:{ content:'', //内容显示的主题区域 loadingBox:'', //loading的盒子 downDragText:'', //下拉刷新的文字 upDragText:'', //上拉加载的文字 downTextColor:'', //下拉刷新的文字颜色 upTextColor:'', //上拉加载的文字颜色 downRefresh:'', //下拉刷新的回调方法 upRefresh:'', //上拉加载的回调方法 closeDown:'', //关闭了下拉刷新回调 closeUp:'', //关闭了上拉加载回调 isDown:false, //是否触发了下拉刷新 isUp:false, //是否触发了上拉加载 isIdenDown:true, //用于判断没有触发下拉刷新的时候下拉的跳屏现象 isIdenUp:true, //同上 }, dom:{ iantooDragRefresh:'', //最外层的下拉刷新框 iantooTopLoading:'', //顶部的loading盒子 dragContent:'', //用户自定义内容区域 loadingBox:'', //加载的盒子 iantooBottomLoading:'', //底部loading 盒子 topImg:'', //顶部的loading图片 bottomImg:'', //底部的loading图片 topSpan:'', //顶部的文字 bottomSpan:'', //底部的文字 }, //渲染 render(){ this.dom.iantooDragRefresh = document.querySelector('#iantooDragRefresh') this.dom.dragContent = document.querySelector(this.data.content) this.dom.loadingBox = document.querySelector(this.data.loadingBox) this.dom.iantooTopLoading = elem.dom('div',{id:'iantooTopLoading'}) this.dom.iantooBottomLoading = elem.dom('div',{id:'iantooBottomLoading'}) this.dom.topImg = elem.dom('i') this.dom.topSpan = elem.dom('span') this.dom.bottomImg = elem.dom('i') this.dom.bottomSpan = elem.dom('span') //设置文字和样式 this.dom.topSpan.innerText = this.data.downDragText this.dom.bottomSpan.innerText = this.data.upDragText this.dom.topSpan.style.color = this.data.downTextColor this.dom.bottomSpan.style.color = this.data.upTextColor this.dom.iantooTopLoading.appendChild(this.dom.topImg) this.dom.iantooTopLoading.appendChild(this.dom.topSpan) this.dom.iantooBottomLoading.appendChild(this.dom.bottomImg) this.dom.iantooBottomLoading.appendChild(this.dom.bottomSpan) // this.dom.iantooDragRefresh.appendChild(this.dom.iantooBottomLoading) // this.dom.iantooDragRefresh.insertBefore(this.dom.iantooTopLoading,this.dom.dragContent) this.dom.loadingBox.appendChild(this.dom.iantooTopLoading) this.dom.loadingBox.appendChild(this.dom.iantooBottomLoading) this.event() }, event(){ let C_obj = { dargDom:null, //惯性滑动的DOM区域 startX:0, //开始偏移的X startY:0, //开始偏移的Y clientX:0, clientY:0, translateX:0, //保存的X偏移 translateY:0, //保存的Y偏移 contentH:0, //内容区域的高度 contentScrollHeight:0, boxH:0, //盒子的高度 animate(y){ } } this.dom.dragContent.addEventListener('touchstart',(event)=>{ event.stopPropagation(); //停止事件传播 C_obj.clientX = event.changedTouches[0].clientX; C_obj.clientY = event.changedTouches[0].clientY; //每次点击的时候重新去获取内容区域的高度,避免异步数据回来新增了长度 C_obj.contentH = this.dom.dragContent.clientHeight; C_obj.boxH = window.screen.availHeight || window.screen.height; C_obj.contentScrollHeight = this.dom.dragContent.scrollHeight; this.dom.dragContent.style.WebkitTransition = this.dom.dragContent.style.transition = ''; C_obj.startX = C_obj.translateX; C_obj.startY = C_obj.translateY; //处理跳屏现象 this.data.isIdenDown = this.data.isDown === true ? true : false this.data.isIdenUp = this.data.isUp === true ? true : false //初始化loading模块的样式 if(this.data.isDown !== true){ this.dom.iantooTopLoading.setAttribute('style',`top:-60px;transition: all 0s ease-out`) } if(this.data.isUp !== true){ this.dom.iantooBottomLoading.setAttribute('style',`bottom:-60px;transition: all 0s ease-out`) } },false) this.dom.dragContent.addEventListener('touchmove',(event)=>{ event.stopPropagation(); //停止事件传播 //此处是定制化的写法,建议使用第二句 let scrollTop = document.querySelector('div').scrollTop || document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; // let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; C_obj.translateX = event.changedTouches[0].clientX - C_obj.clientX + C_obj.startX; C_obj.translateY = event.changedTouches[0].clientY - C_obj.clientY + C_obj.startY; if(C_obj.translateY > 0 ){ //拖动系数. 拉力的感觉 C_obj.translateY *= 0.4 ; }else if( C_obj.translateY < -(C_obj.contentScrollHeight - this.dom.dragContent.clientHeight)){ C_obj.translateY = (event.changedTouches[0].clientY - C_obj.clientY) * 0.4 + C_obj.startY; } //如果已经处于没有被下拉刷新状态 if(this.data.isDown === false){ if(C_obj.translateY <= 60){ this.dom.iantooTopLoading.style.top = C_obj.translateY - 60 +'px' this.dom.topSpan.innerText = '继续下拉刷新页面' this.dom.topImg.style.display = 'none' }else{ this.data.isDown = true this.dom.iantooTopLoading.style.top = '0px' //修改提示文字与图标样式 this.dom.topSpan.innerText = this.data.downDragText this.dom.topImg.style.display = 'inline-block' //触发了下拉刷新的回调 this.data.downRefresh() } //如果已经处于没有被上拉加载的状态 } if(this.data.isUp === false){ //页面必须有滚动的时候才能触发上拉加载 if(C_obj.contentH >= C_obj.boxH){ //如果已经拉到底部了 if(scrollTop >= (C_obj.contentH - C_obj.boxH)){ this.dom.bottomSpan.innerText = '继续上拉加载更多' this.dom.bottomImg.style.display = 'none' //设置底部loading的高度的同时也设置滚动条的位置, this.dom.iantooBottomLoading.style.bottom = -60 - C_obj.translateY +'px' if(C_obj.translateY < -60){ //触发了上拉加载 this.data.isUp = true this.dom.iantooBottomLoading.style.bottom = '0px' //重新设置底部加载文字和图标样式 this.dom.bottomSpan.innerText = this.data.upDragText this.dom.bottomImg.style.display = 'inline-block' //触发了上拉加载的回调 this.data.upRefresh() } } } } if(this.data.isDown === true && this.data.isIdenDown === true){ this.animate(60 + C_obj.translateY); }else if(this.data.isUp === true && this.data.isIdenUp === true){ this.animate(-60 + C_obj.translateY); }else{ this.animate(C_obj.translateY); } },false) this.dom.dragContent.addEventListener('touchend',(event)=>{ event.stopPropagation(); //停止事件传播 C_obj.translateY = 0; this.dom.dragContent.style.WebkitTransition = this.dom.dragContent.style.transition = 'transform 500ms cubic-bezier(0.1, 0.57, 0.1, 1)'; //如果没有触发了下拉刷新 if(this.data.isDown === true){ D.animate(60); }else if(this.data.isUp === true){ D.animate(-60); }else{ this.dom.iantooTopLoading.setAttribute('style',`top:-60px;transition: all 0.2s ease-out`) this.dom.iantooBottomLoading.setAttribute('style',`bottom:-60px;transition: all 0.2s ease-out`) D.animate(0); } },false) }, animate(y){ D.dom.dragContent.style.WebkitTransform = D.dom.dragContent.style.transform = 'translateY('+y+'px)'; } }, E = { closeDown(opction){ if(opction == true){ D.dom.topSpan.innerText = '刷新成功' }else{ D.dom.topSpan.innerText = '刷新失败' } D.dom.iantooTopLoading.setAttribute('style',`top:-60px;transition: all 0.3s ease-out`) D.animate(0) D.data.isDown = false //触发关闭下拉刷新 D.data.closeDown() }, closeUp(opction){ if(opction == true){ D.dom.bottomSpan.innerText = '加载成功' }else{ D.dom.bottomSpan.innerText = '加载失败' } D.dom.iantooBottomLoading.setAttribute('style',`bottom:-60px;transition: all 0.3s ease-out`) D.animate(0) D.data.isUp = false //触发上拉加载的回调 D.data.closeUp() }, updata(opction){ D.data.downDragText = opction.downDragText || D.data.downDragText D.data.upDragText = opction.upDragText || D.data.upDragText D.data.downTextColor = opction.downTextColor || D.data.downTextColor D.data.upTextColor = opction.upTextColor || D.data.upTextColor D.dom.topSpan.innerText = D.data.downDragText D.dom.topSpan.style.color = D.data.downTextColor D.dom.bottomSpan.innerText = D.data.upDragText D.dom.bottomSpan.style.color = D.data.upTextColor } } //------------------------------------------------// iantoo.dragRefresh = (opction) => { return new D.init(opction) } iantoo.dragRefresh.__proto__ = E D.init.prototype = D win.iantoo = iantoo })(window)
let sensitivity = { coarse: 0, fine: 0 }; let sensitivityElem = document.getElementById('current-sensitivity'); let mode = 'coarse'; /* document.getElementById('plus').addEventListener('click', () => { sensitivity[mode]++ sensitivity[mode] = Math.min(9, sensitivity[mode]); sensitivityElem.textContent = sensitivity[mode]; }); document.getElementById('minus').addEventListener('click', () => { sensitivity[mode]--; sensitivity[mode] = Math.max(-9, sensitivity[mode]); sensitivityElem.textContent = sensitivity[mode]; }); */ const start = document.getElementById('start'); const stop = document.getElementById('stop'); start.addEventListener('click', () => { start.style.display = 'none'; stop.style.display = 'block'; }); stop.addEventListener('click', () => { stop.style.display = 'none'; start.style.display = 'block'; }); const fineElem = document.getElementById('mode-fine'); const coarseElem = document.getElementById('mode-coarse'); fineElem.addEventListener('click', () => { if (mode === 'fine') { return; } mode = 'fine'; coarseElem.classList.remove('blue'); coarseElem.classList.add('disabled'); fineElem.classList.add('blue'); fineElem.classList.remove('disabled'); document.getElementById('sensitivity-label').textContent = sensitivity[mode]; document.getElementById('sensitivity-range').value = sensitivity[mode]; }); coarseElem.addEventListener('click', () => { if (mode === 'coarse') { return; } mode = 'coarse'; fineElem.classList.remove('blue'); fineElem.classList.add('disabled'); coarseElem.classList.add('blue'); coarseElem.classList.remove('disabled'); document.getElementById('sensitivity-label').textContent = sensitivity[mode]; document.getElementById('sensitivity-range').value = sensitivity[mode]; }); document.getElementById('sensitivity-range').addEventListener('input', (event) => { sensitivity[mode] = event.target.value; document.getElementById('sensitivity-label').textContent = event.target.value; }); document.getElementById('smoothing-range').addEventListener('input', (event) => { document.getElementById('smoothing-label').textContent = event.target.value; });
const forOwn = require('lodash.forown'); const snakeCase = require('lodash.snakecase'); const camelCase = require('lodash.camelcase'); const isPlainObject = require('lodash.isplainobject'); const isArray = require('lodash.isarray'); /** * @description walk tree * @param {Object | Array} obj * @param {Function} cb - callback * @returns {Object | Array} */ function walk(obj, cb) { const x = isArray(obj) ? [] : {}; forOwn(obj, (v, k) => { if (isPlainObject(v) || isArray(v) || typeof (v) === typeof ({}) && v != null && !(v instanceof Date)) { v = walk(v, cb); } x[cb(k)] = v; }); return x; } const toCamel = (obj) => { const newObj = walk(obj, k => camelCase(k)); return newObj; }; const toSnake = (obj) => { const newObj = walk(obj, (k) => { return snakeCase(k); }); return newObj; }; module.exports = { toCamel, toSnake, };
const JSONPath = require('./json-path') const convertors = require('./convertors') const getUniqueFields = fields => { const result = [] fields.forEach(field => { if (result.indexOf(field.name) < 0) { result.push(field.name) } }) return result } const getTable = (data, fields) => { const table = [] data.forEach(data_row => { let row = [] fields.forEach(field => { const value = JSONPath.getValue(data_row, field.path || field.name) row.push(field.convert ? convertors[field.convert](value) : value) }) table.push(row) }) return table } const getTableHeader = fields => fields.map(field => field.path || field.name) module.exports = { getUniqueFields, getTableHeader, getTable }
const enzyme = require("enzyme"); const Adapter = require('enzyme-adapter-react-16'); // Adding jquery to global namespace // global.$ = global.jQuery = $; enzyme.configure({ adapter: new Adapter() });
import React from "react"; import { View, StyleSheet, Dimensions, Image, TouchableOpacity } from "react-native"; import LinearGradient from "react-native-linear-gradient"; import Header from "../components/Header"; const Catalog = (props) => { const { main, page, linearGradient, tabImage, row, col, tabBtn, tabMain, active } = styles; return ( <LinearGradient start={{ x: 0, y: 0.3 }} end={{ x: 2, y: 0.3 }} colors={["#d13139", "#560004", "#560004"]} style={linearGradient} > <View style={main}> <Header title={props.heading} iconImageLeft={!props.rootCatalog ? require('./../assets/img/keyboardArrowLeftMaterial.png') : undefined } onPress={()=>!props.rootCatalog ? props.catalogGoBack() : {} } /> {props.rootCatalog && <View style = {[tabMain, row ]}> <TouchableOpacity style = {[ col, tabBtn, props.rootCategory === 16 && active ]} onPress={()=>props.toggleRootCategory()} > <Image style = { tabImage } resizeMode="contain" source={require("./../assets/img/reliaMark.png")} /> </TouchableOpacity> <TouchableOpacity style = {[ col, tabBtn, props.rootCategory !== 16 && active ]} onPress={props.toggleRootCategory} > <Image style = { tabImage } resizeMode="contain" source={require("./../assets/img/trabsPower.png")} /> </TouchableOpacity> </View> } <View style={page}> {props.list} </View> </View> </LinearGradient> ); }; const styles = StyleSheet.create({ linearGradient: { flex: 1 }, main: { flex: 1 }, page: { paddingBottom: 50, backgroundColor: "#fff", height:"100%", }, tabScrollInner: { flexDirection: "row", paddingHorizontal: 10 }, tabScroll: { paddingVertical: 5, width: Dimensions.get("window").width, height: 270 }, list: { flexDirection: "row", flexWrap: "wrap" }, ScrollHeading: { paddingHorizontal: 18, paddingVertical: 15 }, ScrollHeadingText: { fontSize: 16, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }, footerStyle: { backgroundColor: "#fff" }, row: { flexDirection: 'row', justifyContent: 'space-between', }, col: { width: '50%', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 16, }, tabMain:{ backgroundColor: "#fff" }, tabBtn:{ height: 51.6, borderWidth: 1, borderBottomWidth: 2, borderColor: "rgb(241, 241, 241)", backgroundColor: "#fff" }, active:{ borderBottomColor: "rgb(209, 49, 57)", }, }); export default Catalog;
import React from "react"; class NavBar extends React.Component { constructor() { super(); this.state = {}; } render() { return <nav></nav>; } } export default NavBar;
import mongoose from 'mongoose'; import bcrypt from 'bcrypt'; import { UserSchema } from '../schemas/UserSchema' let UserModel = mongoose.model('users', UserSchema); const saveUser = (newUser, cb) => { const saltRounds = 10; bcrypt.hash(newUser.password, saltRounds, (err, hash) => { newUser.password = hash; let now = new Date(); newUser.createdOn = now; newUser.lastModifiedOn = now; newUser.lastLoginOn = now; let user = new UserModel(newUser); user.save((err, data) => { if (err) return cb(err); cb(null, data); }); }); } const updateLastLoginOn = (id, cb) => { let now = new Date(); UserModel.findOneAndUpdate({ _id: id }, { lastLoginOn: now }, { new: true }).exec((err, user) => { if (err) { cb(false); } else if (!user) { cb(false); } else { cb(true); } }) } const verifyPassword = (password, hash, cb) => { bcrypt.compare(password, hash, (err, res) => { cb(res); }); } const changePassword = (id, password, cb) => { const saltRounds = 10; bcrypt.hash(password, saltRounds, (err, hash) => { let now = new Date(); UserModel.findOneAndUpdate({ _id: id }, { password: hash, lastModifiedOn: now }, { new: true }).exec((err, user) => { if (err) { cb(false); } else if (!user) { cb(false); } else { cb(true); } }); }) } const removeUser = (id, cb) => { UserModel.findOneAndRemove({ _id: id }).exec((err, user) => { if (err) { cb(false); } else if (!user) { cb(false); } else { cb(true); } }); }; const isUsernameAvailable = (username, cb) => { UserModel.findOne({ username }).exec((err, user) => { if (!user) { cb(true); } else { cb(false); } }) } export { UserModel, saveUser, verifyPassword, changePassword, removeUser, isUsernameAvailable, updateLastLoginOn };
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var questionSchema = new Schema({ title: {type: String, unique: true, required: true}, description: {type: String}, tags: [{type: String}], answer: {type: Schema.Types.ObjectId, ref:'Answer'}, author: {type: Schema.Types.ObjectId, ref:'User'}, slug: {type: String}, }) module.exports = mongoose.model('Question', questionSchema);
class Scene1 extends Phaser.Scene { constructor() { super("bootGame"); } preload() { this.load.image("background", "assets/images/background3.png"); this.load.spritesheet("playerShip", "assets/spritesheets/ship3.png", { frameWidth: 32, frameHeight: 32 }); this.load.spritesheet("spaceChicken", "assets/spritesheets/chick.png", { frameWidth: 16, frameHeight: 18 }); this.load.spritesheet("explosion", "assets/spritesheets/explosion.png", { frameWidth: 16, frameHeight: 16 }); this.load.image("alien", "assets/images/space-baddie.png") this.load.image("asteroid1", "assets/images/asteroid1.png") this.load.image("asteroid2", "assets/images/asteroid2.png") this.load.image("asteroid3", "assets/images/asteroid3.png") } create() { this.background = this.add.tileSprite(0, 0, config.width, config.height, "background"); this.background.setOrigin(0, 0); this.playerShip = this.physics.add.sprite(-70, 300, "playerShip").setScale(2); this.playerShip.angle += -90; this.anims.create({ key: "playerShip_anim", frames: this.anims.generateFrameNumbers("playerShip"), frameRate: 20, repeat: -1 }); this.playerShip.play("playerShip_anim"); for (let i = 0; i < 500; i++) { setTimeout(() => { this.playerShip.x += 1 }, 100 + (3.5 * i)) } var shipShakeForward = true; this.shipShake = setInterval(() => { if (shipShakeForward) { this.playerShip.x += 2 if (this.playerShip.x > 500 + 5) { shipShakeForward = !shipShakeForward } } else { this.playerShip.x -= 2 if (this.playerShip.x < 500 - 5) { shipShakeForward = !shipShakeForward } } }, 50) setTimeout(() => { this.chickenText = this.add.text(510, 260, "AHHHH") this.spaceChicken = this.physics.add.sprite(510, 300, "spaceChicken").setScale(-2); this.spaceChicken.angle -= 0; this.anims.create({ key: "spaceChicken_anim", frames: this.anims.generateFrameNumbers("spaceChicken"), frameRate: 10, repeat: -1 }); this.spaceChicken.play("spaceChicken_anim") for (let i = 0; i < 550; i++) { setTimeout(() => { this.spaceChicken.x += 1, this.chickenText.x += 1 }, 100 + (5 * i)) } }, 2000) setTimeout(() => { var style = { font: "bold 32px Arial", width: "1000", align: "center" }; setTimeout(() => { this.introText1 = this.add.text(78.5, 200, ["You Ejected Space Chicken out of the ship by accident!"], style) }, 100) setTimeout(() => { this.introText2 = this.add.text(145.5, 350, ["Press Space to begin Space Chicken's rescue!", "But Watch Out For the Space Aliens!"], style) gameSettings.isIntroDone = true; }, 1600) setTimeout(() => { this.shipText = this.add.text(540, 255, ["Oops"]) }, 3000) setTimeout(() => { this.shipText = this.add.text(540, 325, ["Sorry"]) }, 5000) }, 3500) this.cursorKeys = this.input.keyboard.createCursorKeys(); } update() { if (gameSettings.isIntroDone) { if (this.cursorKeys.space.isDown) { this.startGame() } } if (this.spaceChicken) { this.spaceChicken.angle += 1.5; } this.background.tilePositionX += 0.5; } startGame() { clearInterval(this.shipShake) this.scene.start("playGame"); } }
var fs = require('fs'); var http = require('http'); var file = fs.readFileSync('languages.json', 'utf8'); var content = JSON.parse(file); var arr = []; var coords = []; var url = 'http://api.tiles.mapbox.com/v4/geocode/mapbox.places-permanent/' // create array of unique country names for (var i = 0; i < content.length; i++) { var countries = content[i].properties.country; for (var j = 0; j < countries.length; j++) { if (arr.indexOf(countries[j]) == -1) { arr.push(countries[j]); } } } // replace whitespace with plus signs and add to url for (var i = 0; i < arr.length; i++) { url += (arr[i].replace(/\ /g, '+') + ';'); } url += '.json?access_token=pk.eyJ1IjoiYXVyb3Jhbm91IiwiYSI6IlJZTGp0dWMifQ.SS0yA6UMyjX7lUyMG02iBw' // node http get request for country name and center coordinates http.get(url, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { var response = JSON.parse(body) for (var i = 0; i < response.length; i++) { if (response[i]['features'][0]) { coords.push( {country: response[i]['features'][0]['text'], coordinates: response[i]['features'][0]['center']} ); } } addCoordinates(coords); fs.writeFileSync("languages.json", JSON.stringify(content)); }); }).on('error', function(error) { console.log(error); }); function addCoordinates(coords) { for (var i = 0; i < coords.length; i++) { for (var j = 0; j < content.length; j++) { if (content[j].properties.country == coords[i].country) { content[j].properties.coordinates = coords[i].coordinates; } } } }
import {StyledButton} from "./Button.style"; import LoadingIndicator from "../loadingIndicator/LoadingIndicator"; import PropTypes from "prop-types"; export default function Button({disabled, loading, ...props}) { disabled = loading ? true : props.disabled; return ( <StyledButton disabled={disabled} {...props}> {loading == true && <LoadingIndicator />} {props.children} </StyledButton> ); } Button.propTypes = { loading: PropTypes.bool, }; Button.defaultProps = { variant: "contained", loading: false, };
console.error("There is something wrong!"); console.error("THIS IS AN ERROR MESSAGE!!!");
'use strict' const tap = require('tap') const Api = require('../../api') const TypeHelp = require('../../types/help') const parent = require('path').basename(__filename, '.js') const helper = require('../helper').get(parent) const assertNoErrors = helper.assertNoErrors.bind(helper) const assertTypeDetails = helper.assertTypeDetails.bind(helper) tap.test('help > defaults', async t => { const api = Api.get().help() const typeObjects = api.initContext(true).types t.same(typeObjects[parent][0].aliases, ['help']) t.equal(typeObjects[parent][0].datatype, 'boolean') t.equal(typeObjects[parent][0].helpFlags, '--help') t.equal(typeObjects[parent][0].helpDesc, 'Show help') t.equal(typeObjects[parent][0].helpHints, '[commands: help] [boolean]') t.equal(typeObjects[parent][0].helpGroup, 'Options:') t.equal(typeObjects[parent][0].isHidden, false) const result = await api.parse('--help') t.equal(result.code, 0) t.equal(result.output, [ `Usage: ${parent} [options]`, '', 'Options:', ' --help Show help [commands: help] [boolean]' ].join('\n')) t.equal(result.errors.length, 0) t.equal(result.argv.help, true) assertTypeDetails(t, result, 1, ['help'], 'boolean', true, 'flag', [0], ['--help']) }) tap.test('help > custom flags, desc, group, hints', t => { let typeObjects = Api.get().help('-H, --get-help', { desc: 'Display the help text and exit', group: 'Global Options:', hints: '' }).initContext(true).types t.same(typeObjects[parent][0].aliases, ['H', 'get-help']) t.equal(typeObjects[parent][0].datatype, 'boolean') t.equal(typeObjects[parent][0].helpFlags, '-H, --get-help') t.equal(typeObjects[parent][0].helpDesc, 'Display the help text and exit') t.equal(typeObjects[parent][0].helpHints, '') t.equal(typeObjects[parent][0].helpGroup, 'Global Options:') t.equal(typeObjects[parent][0].isHidden, false) typeObjects = Api.get().custom( TypeHelp.get() .description('Hi there') .alias('H') .hints('[try it]') .group('Opts:') .hidden(true) ).initContext(true).types t.same(typeObjects[parent][0].aliases, ['H']) t.equal(typeObjects[parent][0].datatype, 'boolean') t.equal(typeObjects[parent][0].helpFlags, '-H') t.equal(typeObjects[parent][0].helpDesc, 'Hi there') t.equal(typeObjects[parent][0].helpHints, '[try it]') t.equal(typeObjects[parent][0].helpGroup, 'Opts:') t.equal(typeObjects[parent][0].isHidden, true) t.end() }) tap.test('help > default implicit command', async t => { const api = Api.get().help() let result = await api.parse('help') t.equal(result.code, 0) t.equal(result.output, [ `Usage: ${parent} [options]`, '', 'Options:', ' --help Show help [commands: help] [boolean]' ].join('\n')) t.equal(result.errors.length, 0) t.equal(result.argv.help, true) assertTypeDetails(t, result, 1, ['help'], 'boolean', true, 'positional', [0], ['help']) result = await api.parse('not help') assertNoErrors(t, result) t.equal(result.argv.help, false) t.same(result.argv._, ['not', 'help']) assertTypeDetails(t, result, 0, ['_'], 'array:string', ['not', 'help'], 'positional', [0, 1], ['not', 'help']) assertTypeDetails(t, result, 1, ['help'], 'boolean', false, 'default', [], []) }) tap.test('help > custom implicit command via flags', async t => { const api = Api.get().help('-H | --get-help') let result = await api.parse('get-help') t.equal(result.code, 0) t.equal(result.output, [ `Usage: ${parent} [options]`, '', 'Options:', ' -H | --get-help Show help [commands: get-help] [boolean]' ].join('\n')) t.equal(result.errors.length, 0) t.equal(result.argv.H, true) t.equal(result.argv['get-help'], true) assertTypeDetails(t, result, 1, ['H', 'get-help'], 'boolean', true, 'positional', [0], ['get-help']) result = await api.parse('H') assertNoErrors(t, result) t.equal(result.argv.H, false) t.equal(result.argv['get-help'], false) t.same(result.argv._, ['H']) assertTypeDetails(t, result, 0, ['_'], 'array:string', ['H'], 'positional', [0], ['H']) assertTypeDetails(t, result, 1, ['H', 'get-help'], 'boolean', false, 'default', [], []) }) tap.test('help > disable implicit command', async t => { const result = await Api.get().help({ implicitCommand: false }).parse('help') assertNoErrors(t, result) t.equal(result.argv.help, false) t.same(result.argv._, ['help']) assertTypeDetails(t, result, 0, ['_'], 'array:string', ['help'], 'positional', [0], ['help']) assertTypeDetails(t, result, 1, ['help'], 'boolean', false, 'default', [], []) })
/** * Created by jia on 2019/3/21. */
// Initial array of rappers var topics = ["J. Cole", "Kendrick Lamar", "Lil Yachty", "Post Malone", "Chance the Rapper", "Kanye", "Future", "Lil Uzi Vert", "21 Savage", "Big Sean", "Young Thug", "Travis Scott", "Migos", "Gucci Mane", "Desiigner"]; // displayRapperGifs function re-renders the HTML to display the appropriate content function displayRapperGifs() { var rapper = $(this).attr("data-name"); var giphyURL = "https://api.giphy.com/v1/gifs/search?q=" + rapper + "&limit=10&rating=pg-13&api_key=dc6zaTOxFJmzC"; //"http://www.omdbapi.com/?t=" + rapper + "&y=&plot=short&apikey=40e9cece"; // Creates AJAX call for the specific rapper button being clicked $.ajax({ url: giphyURL, method: "GET" }).done(function(response) { $("#gifs-view").empty(); $("#gifs-view").prepend("<h4> Click on the image to play the Gif </h4>"); //console.log(response.data[0].rating); for (var j = 0; j < response.data.length; j++) { // Creating a div to hold the gif var gifDiv = $("<div class='gifClass'>"); // Retrieving the URL for the image var imgURL = response.data[j].images.fixed_height_still.url; var movieURL = response.data[j].images.fixed_height.url; // console.log(imgURL); // Creating an element to hold the image var image = $("<img>") .attr("src", imgURL) .attr("data-video", movieURL) .attr("data-still", imgURL) .attr("data-state", "off") .addClass("gifImage"); // Appending the image gifDiv.append(image); // Storing the rating data var rating = response.data[j].rating; // Creating an element to have the rating displayed var gifRating = $("<p>").text("Rating: " + rating); // Displaying the rating gifDiv.append(gifRating); // Putting the entire gif above the previous gifs $("#gifs-view").append(gifDiv); } }); } // Function for displaying rapper data function renderButtons() { // Deletes the rappers prior to adding new rappers // (this is necessary otherwise you will have repeat buttons) $("#buttons-view").empty(); // Loops through the array of rappers for (var i = 0; i < topics.length; i++) { // Then dynamicaly generates buttons for each rapper in the array // This code $("<button>") is all jQuery needs to create the beginning and end tag. (<button></button>) var a = $("<button>"); // Adds a class of rapper to our button a.addClass("rapper btn btn-primary"); // Added a data-attribute a.attr("data-name", topics[i]); a.attr("type", "button"); // Provided the initial button text a.text(topics[i]); // Added the button to the buttons-view div $("#buttons-view").append(a); } } // This function handles events where the add rapper button is clicked $("#add-gif").on("click", function(event) { event.preventDefault(); // This line of code will grab the input from the textbox var rapper = $("#gif-input").val().trim(); // The rapper from the textbox is then added to our array topics.push(rapper); // Calling renderButtons which handles the processing of our rapper array renderButtons(); $("#gif-input").val(""); }); // Adding click event listeners to all elements with a class of "rapper" $(document).on("click", ".rapper", displayRapperGifs); // Calling the renderButtons function to display the intial buttons renderButtons(); $("#gifs-view").on("click", ".gifImage", function(){ var state = $(this).attr("data-state"); if (state == "off") { var takeOut = $(this).attr("data-video"); $(this).attr('src', takeOut); state = $(this).attr("data-state", "on"); } else { var putIn = $(this).attr("data-still"); $(this).attr('src', putIn); state = $(this).attr("data-state", "off"); } });
// JavaScript source code var target_name = "" , target_gender = "" , target_hd_img = "" , target_company_id = -1 , target_company_name = "" , target_pt_id = [] , target_pt_name = [] , temp_code = ""; var isOwner = false; if (user_id == target_id && user_authority == target_authority && user_authority == "Teacher") { isOwner = true; } //form区 + 大区 layui.use(['form', 'jquery', 'layer'], function () { var form = layui.form , $ = layui.jquery , layer = layui.layer; //获取信息 $.ajax({ type: "POST", url: GetCompanyTeacherInfoURL, async: true, data: JSON.stringify({ "reqId": "", "reqParam": target_id }), dataType: "json", success: function (res) { console.log(res); target_name = res.resData.name , target_gender = res.resData.sex , target_company_id = res.resData.company , target_company_name = res.resData.companyName , target_hd_img = res.resData.head ? res.resData.head : ""; document.getElementById("target_hd_img").src = (target_hd_img == "" ? "../../img/defaultHead.jpg" : GetHeadImgURL + target_hd_img); document.getElementById("target_hd_img").style.border = "1px solid #6e7474"; document.getElementById("username").innerText = target_name; document.getElementById("gender").innerHTML = (target_gender == "男") ? '<i class="layui-icon layui-icon-male" style="height:100px; color: #1E9FFF; font-size:40px; margin-left: 20px;"></i>' : '<i class="layui-icon layui-icon-female" style="height:100px; color: #fd5087; font-size:40px; margin-left: 20px;"></i>' //获取公司名称 $.ajax({ type: "POST", url: GetCompanyNameURL, async: true, data: JSON.stringify({ "reqId": "", "reqParam": target_company_id }), dataType: "json", success: function (res) { console.log(res); target_company_name = res.resData.name; document.getElementById("company_name").innerText = target_company_name; }, error: function (res) { console.log("error"); console.log(res); } }); //获取负责的实训ID $.ajax({ type: "POST", url: GetPTInChargeURL, async: true, data: JSON.stringify({ "reqId": "", "reqParam": target_id }), dataType: "json", success: function (res) { console.log(res); for (var i = 0; i < res.resData.length; i++) { target_pt_id.push(res.resData[i].id); target_pt_name.push(res.resData[i].name); } temp_code = addItemInCharge(0, temp_code) }, error: function (res) { console.log("error"); console.log(res); } }); //添加负责项目栏 function addItemInCharge(index, temp) { $.ajax({ type: "POST", url: GetItemInChargeURL, async: true, data: JSON.stringify({ "reqId": "", "reqParam": { "id": target_id, "practice": target_pt_id[index], "canModify": true } }), dataType: "json", success: function (res) { console.log(res); for (var i = 0; i < res.resData.length; i++) { temp += ` <li> <div class="layui-row" style="height:100px; font-size:24px; margin-right: 20px;"> <div class="layui-col-md8"> <div class="grid-demo grid-demo-bg1"> <div style="height:auto; margin: 20px 0 20px 20px;"> <i class="layui-icon layui-icon-form" style="font-size:26px;color: #1E9FFF;"></i> <span style="font-size: 26px; color= #000">` + res.resData[i].name + `</span> </div> </div> </div> <div class="layui-col-md2"> <div class="grid-demo" style="height:auto; margin: 20px 0 20px 20px;"> <input type='button' class="layui-btn layui-btn-normal" onclick='check_diary(this)' id="check_diary_` + target_pt_id[index] + `_` + res.resData[i].id + `" id="team_process_` + target_pt_id[index] + `_` + res.resData[i].id + `" style="font-size:20px;" value="评阅周志"/> </div> </div> <div class="layui-col-md2"> <div class="grid-demo" style="height:auto; margin: 20px 0 20px 20px;"> <input type='button' class="layui-btn layui-btn-normal" onclick='score_team(this)' id="score_team_` + target_pt_id[index] + `_` + res.resData[i].id + `" id="score_team_` + target_pt_id[index] + `_` + res.resData[i].idi + `" style="font-size:20px;" value="团队详情"/> </div> </div> </div> </li>`; } index += 1; if (index >= target_pt_id.length) { document.getElementById("pt_item_in_charge_now").innerHTML += temp; return false; } temp = addItemInCharge(index, temp); return temp; }, error: function (res) { console.log("error"); console.log(res); } }); } }, error: function (res) { console.log("获取用户基本W信息失败"); } }); }); function check_diary(obj) { var strs = obj.id.split("_"); var extra_url = "&target_item_id=" + strs[3] + "&target_pt_id=" + strs[2]; window.open(CompanyTeacherCheckDiaryURL + basic_extra_url + extra_url) } function score_team(obj) { console.log(obj.id) var strs = obj.id.split("_"); var extra_url = "&target_item_id=" + strs[3] + "&target_pt_id=" + strs[2]; window.open(CompanyTeacherScoreURL + basic_extra_url + extra_url) }
import React from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; const StyledDisplay = styled.div` height: 2rem; font-size: 1.5rem; text-align: right; margin: 1.5rem 0; padding: 2rem 0.5rem; border-radius: 5px; max-width: 22rem; overflow-x: auto; overflow-y: hidden; &.dark { background-color: hsl(224, 36%, 15%); } &.light { background-color: hsl(0, 0%, 93%); } &.modern { background-color: hsl(268, 71%, 12%); } `; function Display() { const calculator = useSelector((state) => state.calculator); const theme = useSelector((state) => state.theme); return ( <StyledDisplay className={theme.theme}>{calculator.string}</StyledDisplay> ); } export default Display;
import React, { Component } from 'react' import {Link} from 'react-router-dom' import Search from './Search' class Header extends Component { render(){ return ( <div> <div className='nav'> <Link className='logo' to='/' > React Demo App </Link> <Search filter={this.props.filter} filterSearch={this.props.filterSearch} /> </div> </div> ) } } export default Header
#!/usr/bin/env node var argumentString = '' var args = process.argv.splice(process.execArgv.length + 2) for (var i = 0; i < args.length; i++) { if (i === args.length - 1) argumentString += args[i] else argumentString += args[i] + ' ' } if (argumentString.length < 1) { console.log('RconApp::Error: Please specify an RCON command') process.exit() } console.log('RconApp::Relaying RCON command: ' + argumentString) var serverHostname = 'localhost' var serverPort = process.env.RUST_RCON_PORT var serverPassword = process.env.RUST_RCON_PASSWORD var messageSent = false var WebSocket = require('ws') var ws = new WebSocket('ws://' + serverHostname + ':' + serverPort + '/' + serverPassword) ws.on('open', function open () { setTimeout(function () { messageSent = true ws.send(createPacket(argumentString)) setTimeout(function () { ws.close(1000) setTimeout(function () { console.log('RconApp::Command relayed') process.exit() }) }, 1000) }, 250) }) ws.on('message', function (data, flags) { if (!messageSent) return try { var json = JSON.parse(data) if (json !== undefined) { if (json.Message !== undefined && json.Message.length > 0) { console.log('RconApp::Received message:', json.Message) } } else console.log('RconApp::Error: Invalid JSON received') } catch (e) { if (e) console.log('RconApp::Error:', e) } }) ws.on('error', function (e) { console.log('RconApp::Error:', e) process.exit() }) function createPacket (command) { var packet = { Identifier: -1, Message: command, Name: 'WebRcon' } return JSON.stringify(packet) }
/* * @Author: xr * @Date: 2021-03-20 12:05:07 * @LastEditors: xr * @LastEditTime: 2021-04-18 16:43:31 * @version: v1.0.0 * @Descripttion: 功能说明 * @FilePath: \ui\src\main.js */ import { createApp } from 'vue' import App from './App.vue' import './assets/css.styl' //一些扩展 import './extends/index' const app = createApp(App); //vuex import store from './store' app.use(store); //路由 import router from './router' app.use(router); //一些自定义指令 import directive from './directive/index' directive(app); // import VMdEditor from '@kangc/v-md-editor'; // import '@kangc/v-md-editor/lib/style/base-editor.css'; // import githubTheme from '@kangc/v-md-editor/lib/theme/github.js'; // import '@kangc/v-md-editor/lib/theme/style/github.css'; // VMdEditor.use(githubTheme); // app.use(VMdEditor); import ElementPlus from 'element-plus'; import 'element-plus/lib/theme-chalk/index.css'; import { createI18n } from 'vue-i18n' import enLocale from 'element-plus/lib/locale/lang/en' import zhLocale from 'element-plus/lib/locale/lang/zh-cn' import langs from './lang/index' langs[enLocale.name].el = enLocale.el; langs[zhLocale.name].el = zhLocale.el; const i18n = createI18n({ locale: zhLocale.name, fallbackLocale: enLocale.name, messages: langs, }); app.use(ElementPlus, { i18n: i18n.global.t }) app.use(i18n); //自动注册的全局组件 import gloalComponents from './components/gloal'; app.use(gloalComponents); import gloalLayoutComponents from './components/layout/gloal'; app.use(gloalLayoutComponents); //menu菜单相关的全局组件 import menuComponents from './components/menu/index'; app.use(menuComponents); app.mount('#app')
import React, { Component } from 'react' import enzyme, { shallow } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import renderer from 'react-test-renderer' import AlarmType from './AlarmType' import { Text, View, Image, TouchableOpacity } from 'react-native' enzyme.configure({ adapter: new Adapter()}) let wrapper beforeEach(() => { wrapper = shallow(<AlarmType status={true}/>) }) describe('<AlarmType/>', () => { it('should render <AlarmType/>', () => { expect(wrapper).toBeDefined() }) }) describe('<AlarmType/> child is rendered', () => { it('should render <TouchableOpacity/>' , () => { expect(wrapper.find(<TouchableOpacity/>)).toBeDefined() expect(wrapper.find('TouchableOpacity').length).toBe(1) }) it('Should render <View/>', () => { expect(wrapper.find(<View/>)).toBeDefined() expect(wrapper.find('View').length).toBe(3) }) it('Should render <Image/>', () => { expect(wrapper.find(<Image/>)).toBeDefined() expect(wrapper.find('Image').length).toBe(2) }) }) describe('<Image/> renders the correct image', () => { it('should render the proper image if status is true', () => { let wraptrue = shallow(<AlarmType status={true}/>) expect(wraptrue.find(<Image source={require('../components/assets/puerta.png')}/>)).toBeDefined() expect(wraptrue.find(<Image source={require('../components/assets/greyarrow.png')}/>)).toBeDefined() }) it('should render the proper image if status is false', () => { let wrapfalse = shallow(<AlarmType status={false}/>) expect(wrapfalse.find(<Image source={ require('../components/assets/access.png')} />)).toBeDefined() expect(wrapfalse.find(<Image source={ require('../components/assets/desbloqueado.png')} />)).toBeDefined() }) }) describe('snapshot testing', () => { it('snapshot', () => { const tree = renderer.create(<AlarmType/>) expect(tree).toMatchSnapshot() }) })
const lista1 = [ 100, 200, 300, 500, ]; function calcularMedia(lista){ // let sumaLista = 0; // for(let valorLista1 of lista){ // sumaLista = sumaLista + valorLista1; // } const sumaLista = lista.reduce( function (nuevoElemento, valorAcumulado = 0) { return valorAcumulado + nuevoElemento; } ); const promedioLista = (sumaLista / lista.length); return promedioLista; }
/* A class to handle customize error messages for different error status code except status code 500 */ class CustomError extends Error { constructor(statusCode, message) { super(message); this.statusCode = statusCode; } } module.exports = CustomError
// jquery.mpAjax.js (multi-part Ajax response support) // v0.3.2 (c) Kyle Simpson // MIT License ;(function($){ var UNDEF = "undefined", // for better compression JSFUNC = "function", AJAXSCS = "ajaxSuccess", CONTTYPE = "content-type", PLAINTXT = "plain/text", JSOBJ = "object", JSEVTS = "events", JSTRUE = true, JSFALSE = false, old_$ajax = $.ajax, old_$ajaxSuccess = $.fn["ajaxSuccess"]; delimiter_stub = "!!!!!!=_NextPart_", delimiter_regexp = delimiter_stub+"[0-9.]+", // change these if you want a different delimiter format s2 = null; // an array of objects that have the AJAXSCS handler bound to them $.fn.extend({ unbind: function(type,fn) { if (type === AJAXSCS && s2 !== null && s2.length > 0) { var elem = this.get(0); s2 = $(s2).filter(function(){return this!==elem;}).get(); } return this.each(function(){ $.event.remove( this, type, fn ); }); }, ajaxSuccess: function(f) { if (s2 === null) s2 = []; s2.push(this.get(0)); if (typeof f !== JSFUNC) { var handlers = f; f = function(){}; f.mp_handlers = handlers; } return old_$ajaxSuccess.call(this,f); } }); function parseEngine() { var processed_data = null, multipart = JSFALSE, publicAPI = null, _data = null; function faster_trim(str) { // from: http://blog.stevenlevithan.com/archives/faster-trim-javascript var str = str.replace(/^\s\s*/, ''), ws = /\s/, i = str.length; while (ws.test(str.charAt(--i))); return str.slice(0, i + 1); } function parse_part(part) { var part_obj = {}; part = faster_trim(part); var temp_part = part.replace(/\n|\r/gm,"\t"); var each_headers_pattern = /^(((content-type)|(content-length))\s*?:\s*?(\S+))/igm; var all_headers_pattern = /^(((content-type)|(content-length))\s*?:\s*?([^\t]+)\t+)+/ig; var headers = temp_part.match(all_headers_pattern); if (headers && headers.length > 0) { var allheaders = headers[0]; headers = part.match(each_headers_pattern); for (var i=0; i<headers.length; i++) { if (allheaders.indexOf(headers[i]) !== -1) { var header_parts = headers[i].split(":"); var key = faster_trim(header_parts[0]), val = faster_trim(header_parts[1]); part_obj[key.toLowerCase()] = val; } } each_headers_pattern.lastIndex = 0; part = part.replace(each_headers_pattern,""); } else { part_obj[CONTTYPE] = PLAINTXT; } part = part.replace(/^\s\s*/,""); part_obj.data = part; return part_obj; } publicAPI = { multipart:function(){return multipart;}, processData:function(data,successFn) { if (_data !== data) { processed_data = []; _data = data; multipart = JSFALSE; var delims = null, temp_data, delim_pattern = new RegExp(delimiter_regexp+"\s*?$","igm"); // check if data is a string, if it's non-empty (trim'd), and if it has the right delimiter pattern if ((typeof data === "string") && (temp_data = faster_trim(data)) && (delims = temp_data.match(delim_pattern))) { multipart = JSTRUE; delim_pattern.lastIndex = 0; var parts = temp_data.split(delim_pattern); parts = $(parts).filter(function(){return this!=""&&this.replace(/[\n\r]/ig,"")!="";}).get(); if (parts.length > delims.length) delims.unshift(delimiter_stub+Math.random()); // less delims than parts, add implicit delim at beginning else if (delims.length > parts.length) parts.push(""); // less parts than delims, add empty implicit part at end for (var i=0; i<parts.length; i++) { var part = parse_part(parts[i]); part.delimiter = faster_trim(delims[i]); processed_data.push(part); } } else { // format non-multi-part data for consistent 'success' handler processing if (typeof successFn === JSFUNC) processed_data = data; else if ($.isArray(successFn)) processed_data.push(data); else if (typeof successFn === JSOBJ) { processed_data.push({"content-type":PLAINTXT,delimiter:"",data:data}); } } } return processed_data; } }; return publicAPI; } $.extend({ ajax:function(s) { var s1 = s.success || null; if (s1 !== null || (s2 !== null && s2.length > 0)) { var engine = new parseEngine(), success_trigger = function(data,args,sFunc,replaceData) { args = $.makeArray(args), // copy/dup the array to prevent unintended modifications _this = this; replaceData = !(!replaceData); if (replaceData) args.unshift(data); // add "data" argument back to beginning of "success" handler call else args.push(data); // append "data" argument onto end of "ajaxSuccess" handler call sFunc.apply(_this,args); }, data_map_and_trigger = function() { var args = $.makeArray(arguments), _this = this, processed_data = args[0], replaceData = args[1], successFn = args[2]; args.shift(); // remove "processed_data" argument args.shift(); // remove "replaceData" argument args.shift(); // remove "successFn" argument if (replaceData) args.shift(); // remove "data" argument from "success" handler call, we'll add it back later try { if (typeof successFn === JSFUNC) { success_trigger.call(_this,processed_data,args,successFn,replaceData); } else if ($.isArray(successFn)) { for (var i=0; i<successFn.length; i++) { if (typeof successFn[i] === JSFUNC && typeof processed_data[i] !== UNDEF) { success_trigger.call(_this,processed_data[i],args,successFn[i],replaceData); } } } else if (typeof successFn === JSOBJ) { for (var i=0; i<processed_data.length; i++) { var ct = processed_data[i][CONTTYPE], dataToPass = null; if (typeof successFn[ct] === JSFUNC) { if (engine.multipart()) dataToPass = processed_data[i]; // response was multipart, assume handler is expecting a processed_data object else dataToPass = processed_data[i].data; // response was not multi-part, assume handler expects a data string success_trigger.call(_this,dataToPass,args,successFn[ct],replaceData); } } } } catch (err) { } }; if (s1 !== null) { if (typeof s.success.__mpAjax === UNDEF) { s.success = function() { var args = $.makeArray(arguments), _this = this; try { var processed_data = engine.processData(args[0],s1); args.unshift(s1); args.unshift(JSTRUE); // *replace* the data argument in the "success" call signature args.unshift(processed_data); data_map_and_trigger.apply(_this,args); } catch (err) { } }; s.success.__mpAjax = JSTRUE; } } if (s2 !== null && s2.length > 0) { // s2 is an array of objects that have the ajaxSuccess handler bound to them $(s2).each(function(){ // loop through stored object/handler refs which were bound to "ajaxSuccess" var evts = $(this).data(JSEVTS); if (typeof evts !== UNDEF && evts !== null && typeof evts[AJAXSCS] === JSOBJ) { // is object/handler ref still bound to "ajaxSuccess"? for (var i in evts[AJAXSCS]) { if (evts[AJAXSCS][i] !== Object.prototype[i]) { var s2_func = evts[AJAXSCS][i]; if (typeof s2_func.__mpAjax === UNDEF) { // prevent wrapping the handler more than once evts[AJAXSCS][i] = function(){ var args = $.makeArray(arguments), _this = this; try { var processed_data = engine.processData(args[1].responseText,s2_func); if (typeof s2_func.mp_handlers !== UNDEF) args.unshift(s2_func.mp_handlers); else args.unshift(s2_func); args.unshift(JSFALSE); // *append* the data argument to the "ajaxSuccess" call signature args.unshift(processed_data); data_map_and_trigger.apply(_this,args); } catch (err) { } }; evts[AJAXSCS][i].__mpAjax = JSTRUE; // mark this success handler as wrapped by mpAjax evts[AJAXSCS][i].guid = s2_func.guid; evts[AJAXSCS][i].type = s2_func.type; $(this).data(JSEVTS,evts); } } } } }); } } return old_$ajax.call(this,s); } }); })(jQuery);
var MyTeamModel = require('../mongoDB/team-member-model') var express = require('express'); var router = express.Router(); var async = require('async'); var fs = require('fs-extra'); var customPaths = require('./paths'); var groupModel = require('../mongoDB/group-model') var GalleryModel = require('../mongoDB/gallery_schema'); var PictureModel = require('../mongoDB/picture-schema'); var TableRowModel = require('../mongoDB/table-row-schema'); router.post('/add-member', function(req, res, next){ /*############################################################## CREATE NEW USER ###############################################################*/ var body = JSON.parse(req.body.data); var user_folder_name = body.name +'_'+Date.now(); body['folder_name'] = user_folder_name; async.parallel([function(call){ /*********************** ADD USER TO DATABASE ***************** */ new MyTeamModel(body).save(function(err,data){ if(err){res.json(err);return;} call(null,data); }); },function(call){ /*********************** ADD USER FOLDER TO FYLE SYSTEM ***************** */ var route = customPaths.public_folder+'/'+user_folder_name fs.mkdir(route,function(err,data){ if(err){ call(err); return;} call(null, user_folder_name); }); }],function(err,call){ if(err){ res.json(err); return;} res.json(call); }); }).get('/get-members', function(req, res, next){ /*############################################################## FINDS ALL USERS ###############################################################*/ MyTeamModel.find(function(err,data){ if(err){res.json(err);return;} res.json(data); }); }).get('/:user_id', function(req, res, next){ /*############################################################## FINDS SPECIFIC USER ###############################################################*/ var user_id = req.params.user_id; MyTeamModel.findOne({_id:user_id},function(err,data){ if(err){res.json(err);return;} res.json(data); }); }).put('/update-member',function(req,res,end){ /*############################################################## UPDATE USER INFO ###############################################################*/ var body = JSON.parse(req.body.data); MyTeamModel.update({_id:body._id},{ name: body.name, forname: body.forname, age: body.age, profesion: body.profesion, hobby: body.hobby, phone:body.phone, email: body.email}, function(err,data){ if(err){res.json(err);return;} res.json(data); }); }).put('/update-status',function(req,res,end){ /*############################################################## UPDATE USER STATUS ###############################################################*/ var body = JSON.parse(req.body.data); MyTeamModel.update({_id:body._id},{ status: body.status, message: body.message, date: body.date, days_left: body.days_left, updated: Date.now() }, function(err,data){ if(err){res.json(err);return;} res.json(data); }); }).post('/add-pictures/:user_id',function(req,res,end){ /*############################################################## ADD PICTURES TO USER ###############################################################*/ var user_id = req.params.user_id; var body = JSON.parse(req.body.data); MyTeamModel.update({_id:user_id},{ $push: { images: { $each: body } } }, function(err,data){ if(err){res.json(err);return;} res.json(data); }); }).put('/remove-pictures/:user_id',function(req,res,end){ /*############################################################## DELETES PICTURES FROM USER ###############################################################*/ var user_id = req.params.user_id; var body = JSON.parse(req.body.data); var pictures_id = []; for(var picture of body) pictures_id.push(picture._id) console.log(pictures_id) MyTeamModel.update({_id:user_id},{ $pull: { images:{_id:{$in:pictures_id}}} }, function(err,data){ if(err){res.json(err);return;} res.json(data); }); }).put('/delete-member',function(req,res,end){ /*############################################################## DELETES USER ###############################################################*/ var member_ids = JSON.parse(req.body.data); var log_file = []; (function iterator(i){ if(i >= member_ids.length){ res.json(log_file); return; } async.waterfall([ function(call){ /*********************** FINDS USER IN DATABES AND DELETE THAT USER ***************** */ MyTeamModel.findOneAndRemove({_id:member_ids[i]},function(err,user){ if(err){call(err);return;} call(null,user) }) },function(user,call){ var folderPath = customPaths.public_folder+'/'+user.folder_name; fs.stat(folderPath, (err,stat) => { if(stat){ fs.remove(folderPath,function(err){ if(err){log_file.push(err);call(err);return;} log_file.push({status:'deleted',path:folderPath}); call(null,user); }); }else{ res.status(500).send('no path with name - '+folderPath); return; } }); },function(user,call){ /*********************** DELETES USER GALLERYS FROM DATABASE ***************** */ GalleryModel.remove({user_id:user._id},function(err,data){ if(err){call(err);return;} log_file.push(data); call(null,user) }); },function(user,call){ /*********************** DELETES USER GALLERYS PICTURES FROM DATABASE ***************** */ PictureModel.remove({user_id:user._id},function(err,data){ if(err){call(err);return;} log_file.push(data); call(null,user) }); },function(user,call){ /*********************** DELETES USER GROUPS FROM DATABASE ***************** */ groupModel.remove({user_id:user._id},function(err,data){ if(err){call(err);return;} log_file.push(data); call(null,user) }); },function(user,call){ /*********************** DELETES USER TABLE ROWS FROM DATABASE ***************** */ TableRowModel.remove({user_id:user._id},function(err,data){ if(err){call(err);return;} log_file.push(data); call(null,user) }); }],function(err,call){ if(err){res.json(err);return;} iterator(i+1); }); })(0); }); module.exports = router;
(function () { 'use strict'; angular .module('app.catalProdFmly') .controller('CatalProdFmlyController', CatalProdFmlyController); CatalProdFmlyController.$inject = ['logger', '$stateParams', '$location', 'CatalProdFmly', 'TableSettings', 'CatalProdFmlyForm']; /* @ngInject */ function CatalProdFmlyController(logger, $stateParams, $location, CatalProdFmly, TableSettings, CatalProdFmlyForm) { var vm = this; vm.tableParams = TableSettings.getParams(CatalProdFmly); vm.catalProdFmly = {}; vm.setFormFields = function(disabled) { vm.formFields = CatalProdFmlyForm.getFormFields(disabled); }; vm.create = function() { vm.catalProdFmly.famPath = '/'+vm.catalProdFmly.identif+'/'+vm.catalProdFmly.parentIdentif+'/' // Create new CatalProdFmly object var catalProdFmly = new CatalProdFmly(vm.catalProdFmly); // Redirect after save catalProdFmly.$save(function(response) { logger.success('CatalProdFmly created'); $location.path('catal-prod-fmly/' + response.id); }, function(errorResponse) { vm.error = errorResponse.data.summary; }); }; // Remove existing CatalProdFmly vm.remove = function(catalProdFmly) { if (catalProdFmly) { catalProdFmly = CatalProdFmly.get({catalProdFmlyId:catalProdFmly.id}, function() { catalProdFmly.$remove(function() { logger.success('CatalProdFmly deleted'); vm.tableParams.reload(); }); }); } else { vm.catalProdFmly.$remove(function() { logger.success('CatalProdFmly deleted'); $location.path('/catal-prod-fmly'); }); } }; // Update existing CatalProdFmly vm.update = function() { var catalProdFmly = vm.catalProdFmly; catalProdFmly.$update(function() { logger.success('CatalProdFmly updated'); $location.path('catal-prod-fmly/' + catalProdFmly.id); }, function(errorResponse) { vm.error = errorResponse.data.summary; }); }; vm.toViewCatalProdFmly = function() { vm.catalProdFmly = CatalProdFmly.get({catalProdFmlyId: $stateParams.catalProdFmlyId}); CatalProdFmlyForm.catalProdFmlyId = $stateParams.catalProdFmlyId; vm.setFormFields(true); }; vm.toEditCatalProdFmly = function() { vm.catalProdFmly = CatalProdFmly.get({catalProdFmlyId: $stateParams.catalProdFmlyId}); vm.setFormFields(false); }; activate(); function activate() { //logger.info('Activated CatalProdFmly View'); } } })();
const Jogo = require("../models/index"); const mongoose = require("../database/connection"); const valid = (id,res) => { if(!mongoose.Types.ObjectId.isValid(id)){ // return 'Id inválido'; res.status(400).json({erro:"Id inválido"}) } } const listarTodos = async (req,res) => { const jogos = await Jogo.find(); res.json(jogos) } const listarPorId = async (req,res) => { const id = req.params.id; if (!mongoose.Types.ObjectId.isValid(id)) { res.status(422).send({ error: "Id inválido" }); return; } const find = await Jogo.findById(id); if(!find){ res.status(400).json({erro:"Filme Não Encontrado"}) } res.status(200).json(find); }; const novoJogo = async (req,res) => { const jogo = req.body; if (!jogo || !jogo.nome || !jogo.img) { res.status(400).send({ error: "Jogo inválido!" }); return; } const novojogo = await new Jogo(jogo).save(); res.status(201).json(novojogo); } const atualizarJogo = async(req,res) => { const id = req.params.id; if (!mongoose.Types.ObjectId.isValid(id)) { res.status(422).send({ error: "Id inválido" }); return; } const jogo = await Jogo.findById(id); if (!jogo) { res.status(404).send({ erro: "Jogo não encontrado!" }); return; } const novogame = req.body; if (!jogo || !jogo.nome || !jogo.img) { res.status(400).send({ error: "Filme inválido!" }); return; } await Jogo.findOneAndUpdate({ _id: id }, novogame); const JogoAtualizado = await Jogo.findById(id); res.send(JogoAtualizado); }; const excluirJogo = async (req,res) => { const id = req.params.id; if (!mongoose.Types.ObjectId.isValid(id)) { res.status(422).send({ error: "Id inválido" }); return; } const jogo = await Jogo.findById(id); if (!jogo) { res.status(404).send({ error: "Jogo não encontrado!" }); return; } await Jogo.findByIdAndDelete(id); res.send({message: 'jogo excluído com sucesso!'}) }; module.exports = {listarTodos, novoJogo,listarPorId,atualizarJogo,excluirJogo}
import React, { Component } from "react"; import { connect } from "react-redux"; import { selectSong } from "../actions"; class SongList extends Component { render() { return ( <> <div> SongList </div> {this.props.songs.map((song) => { return ( <> <div key={song.title}> {song.title} </div> <button onClick={()=> this.props.selectSong(song)}> Select </button> <br /> <br /> </> ); })} </> ); } } const mapStateToProps = (state) => { return { songs: state.songs }; }; export default connect(mapStateToProps, { selectSong })(SongList);
import React from 'react' import {connect} from 'react-redux' import {compose} from 'redux' import Item from '../item' import {withFavoritesMethod} from '../hoc' import './list.less' class List extends React.Component{ render(){ const {items, viewType, onItemSelected} = this.props if(viewType !== 'list') { return null } return( <div className="panels-wrapper"> <div className="container p-0"> <div className="panels-filter"> <div className="panels-filter__element" style={{width: '120px'}} > <div className="panels-filter__name no-filter"> Артикул </div> </div> <div className="panels-filter__element" style={{width: '160px'}} > <div className="panels-filter__name">ЖК</div> </div> <div className="panels-filter__element" style={{width: '70px'}} > <div className="panels-filter__name no-filter"> Корпус </div> </div> <div className="panels-filter__element" style={{width: '70px'}} > <div className="panels-filter__name no-filter"> Этаж </div> </div> <div className="panels-filter__element" style={{width: '70px'}} > <div className="panels-filter__name">Комнат</div> </div> <div className="panels-filter__element" style={{width: '80px'}} > <div className="panels-filter__name">Площадь</div> </div> <div className="panels-filter__element" style={{width: '100px'}} > <div className="panels-filter__name">м2</div> </div> <div className="panels-filter__element" style={{width: '100px'}} > <div className="panels-filter__name">Стоимость</div> </div> <div className="panels-filter__element" style={{width: '100px'}} > <div className="panels-filter__name no-filter"> Избранное </div> </div> </div> {items.map(item => { return <Item key={item.id} item={item} onItemSelected={onItemSelected} {...this.props}/> }) } </div> </div> ) } } const mapStateToProps = ({itemList: {items, viewType}}) => { return { items, viewType } } export default compose( withFavoritesMethod, connect(mapStateToProps) )(List)
import { cons } from 'hexlet-pairs'; import startGame from '../game'; import { generateRandomNumber, generateNumberBetween } from '../utils'; const description = 'What number is missing in this progression?'; const progressionLength = 10; const delimiter = '..'; const game = () => { const startNumber = generateRandomNumber(); const step = generateNumberBetween(2, 6); const removeIndex = generateNumberBetween(0, progressionLength); const array = [startNumber]; for (let i = 1; i < progressionLength; i += 1) { array[i] = array[i - 1] + step; } const expected = array[removeIndex]; array[removeIndex] = delimiter; return cons(String(expected), array.join(' ')); }; export default () => { startGame(description, game); };
function solve(x1, y1, x2, y2) { calculateDistance(x1, y1, 0, 0); calculateDistance(x2, y2, 0, 0); calculateDistance(x1, y1, x2, y2); function calculateDistance(x_1, y_1, x_2, y_2) { let distance = Math.sqrt(Math.pow((x_2 - x_1), 2) + Math.pow(y_2 - y_1, 2)); if (Number.isInteger(distance)) { console.log(`{${x_1}, ${y_1}} to {${x_2}, ${y_2}} is valid`); } else { console.log(`{${x_1}, ${y_1}} to {${x_2}, ${y_2}} is invalid`); } } }
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import IconButton from 'material-ui/IconButton'; import Close from 'material-ui/svg-icons/navigation/close'; const propTypes = { dish: PropTypes.object.isRequired, restaurant: PropTypes.object.isRequired, closeModal: PropTypes.func.isRequired, }; class DishPage extends React.PureComponent { render() { const { dish, restaurant } = this.props; return ( <Card style={{ minHeight: 1000 }}> <IconButton style={{ position: 'absolute', right: 30, top: 30 }} onTouchTap={this.props.closeModal}> <Close /> </IconButton> <CardHeader title={restaurant.name} subtitle={restaurant.location} avatar="https://media.timeout.com/images/100666581/image.jpg" /> <CardMedia mediaStyle={{ height: 500, overflow: 'hidden' }} > <img src="https://s3-media4.fl.yelpcdn.com/bphoto/kYZOjS_Vd8R88qTYYU3aYQ/l.jpg" height={500} alt="the dish" /> </CardMedia> <CardTitle title={dish.name} subtitle={dish.description} /> <CardText> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> ); } } DishPage.propTypes = propTypes; export default DishPage;
import React from "react"; import "./App.css"; import { Route, Link, Switch } from "react-router-dom"; import Display from "./Display"; import Form from "./Form"; function App() { const url = "https://mern-app-329.herokuapp.com"; // set State to hold list of birds const [birds, setBirds] = React.useState([]); //empty bird for the create form const emptyBird = { name: "", img: "", description: "", }; const [selectedBird, setSelectedBird] = React.useState(emptyBird); //get / call list of all birds const getBirds = () => { fetch(url + "/birds/") .then((response) => response.json()) .then((data) => { setBirds(data); }); }; //useEffect to get data upon page load React.useEffect(() => { getBirds(); }, [selectedBird]); //handleCreate for when form is submitted const handleCreate = (newBird) => { fetch(url + "/birds/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newBird), }).then(() => getBirds()); }; //handleUpdate for when the edit form is submitted const handleUpdate = (bird) => { fetch(url + "/birds/" + bird._id, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(bird), }).then(() => getBirds()); }; const selectBird = (bird) => { setSelectedBird(bird); }; //deleteBird const deleteBird = (bird) => { fetch(url + "/birds/" + bird._id, { method: "DELETE", }).then(() => { getBirds(); }); }; //function to specify which bird we updated return ( <div className="App"> <h1>Birdex</h1> <hr /> <Link to="/create"> <button>Add bird</button> </Link> <main> <Switch> <Route exact path="/" render={(rp) => ( <Display {...rp} birds={birds} selectBird={selectBird} deleteBird={deleteBird} /> )} /> <Route exact path="/create" render={(rp) => ( <Form {...rp} label="create" bird={emptyBird} handleSubmit={handleCreate} /> )} /> <Route exact path="/edit" render={(rp) => ( <Form {...rp} label="update" bird={selectedBird} handleSubmit={handleUpdate} /> )} /> </Switch> </main> </div> ); } export default App;
import React from 'react'; import './App.css'; import Home from './pages/Home' // import About from './pages/About' // import Contacts from './pages/Contacts' // import CustomMade from './pages/CustomMade' // import WhatsNew from './pages/WhatsNew' // import Catalog from './pages/Catalog' // import Collection from './pages/Collection' import InDevelopment from './pages/InDevelopment' import Error from './pages/Error' import Navbar from "./Components/Navbar"; import {Route, Switch} from 'react-router-dom' function App() { return ( <div> <Navbar /> <Switch> <Route exact path="/" component={Home}/> {/*<Route exact path="/about" component={About}/>*/} {/*<Route exact path="/catalog" component={Catalog}/>*/} {/*<Route exact path="/catalog/:slug" component={Collection}/>*/} {/*<Route exact path="/custom" component={CustomMade}/>*/} {/*<Route exact path="/news" component={WhatsNew}/>*/} {/*<Route exact path="/contacts" component={Contacts}/>*/} <Route exact path="/dev" component={InDevelopment}/> <Route component={Error}/> </Switch> </div> ); } export default App;
import React from 'react' import ReactDOM from 'react-dom' import TabMenu from './tabMenus' export default class Tab extends React.Component{ handleTabClick(i){ this.props.tabActive(i); } render(){ return( <TabMenu onTabClick={this.handleTabClick.bind(this)} index={this.props.index}> <div id="tabset1" label="1st Panel"> <div className="c-card__header"><h2>1st Panel</h2></div> <ul className="c-menu"> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> </ul> </div> <div id="tabset2" label="2nd Panel"> <div className="c-card__header"><h2>2nd Panel</h2></div> <ul className="c-menu"> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> </ul> </div> <div id="tabset3" label="3rd Panel"> <div className="c-card__header"><h2>3rd Panel</h2></div> <ul className="c-menu"> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> <li className="c-menu__item"><a href="http://example.com" target="_blank">example.com</a></li> </ul> </div> </TabMenu> ); } }
import React, { Component } from 'react'; import {Redirect,Link} from "react-router-dom"; export class Attachements extends Component { constructor(props) { super(props); this.state = { selectedFile: null } } state={ Passporterror:"", Marksheeterror:"", Rationcarderror:"", Aadharcarderror:"", Voteriderror:"", Drivinglicenceerror:"", Passportsizephotoerror:"", Divorcecopyerror:"", MarriageCertificateerror:"", Spousedeathcertificateerror:"", Singlestatuscertificateerror:"", Bridepassporterror:"", BrideMarksheeterror:"", BrideRationcarderror:"", BrideAaharcarderror:"", BrideVoteriderror:"", BrideDrivinglicenceerror:"", BridePassportsizephotoerror:"", BrideDivorcecopyerror:"", BrideMarriageCertificateerror:"", BrideSpousedeathcertificateerror:"", BrideSinglestatuscertificateerror:"", Invitationerror:"", Marriagereceipterror:"", Marriagereciptdocerror:"" } continue=e=>{ e.preventDefault(); this.props.nextStep(); }; back = e => { e.preventDefault(); this.props.prevStep(); }; closeform() { document.getElementById('errormsg1').style.display = 'none'; } closeform1() { document.getElementById('errormsg2').style.display = 'none'; } closeform2() { document.getElementById('errormsg3').style.display = 'none'; } submit = e =>{ e.preventDefault(); const {value:{Dateofmarriage,Name,Nationality,ResidentialStatus,Religion,Caste,DOB,Employername,Designation, maritalstatus,Mobileno,whatsappnumber,emailaddress,Passportno,Street,Village,District,State,Country,Pincode, Taluk,Fathername,FatherAge,FatherOccupation,Fatherreligion,groomfatherlivingstatus,fatherschooseaddress,Street1, Village1,Taluk1,District1,State1,Country1,Pincode1,MotherName,Motherreligion,groommotherlivingstatus,MotherAge,MotherOccupation,motherchooseaddress, Street2,Village2,Taluk2,District2,State2,Country2,Pincode2,bridename,BrideNationality,brideresidential,bridereligion,bridecaste,BrideDateofbirth,brideemployername, bridedesignation,bridemaritalstatus,bridemobilenumber,bridewhatsapp,brideemail,Street3,Village3,Taluk3,District3, State3,Country3,Pincode3,bridepassport,bridefather,bridefatherreligion,bridefatherlivingstatus,bridefatherage,bridefatheroccupation, bridebridefatherchooseaddress,Street4,Village4,Taluk4,District4,State4,Country4,Pincode4,bridemother,bridemotherage,bridemotherreligion,bridemotheroccupation,bridemotherlivingstatuss, bridemotherchooseaddress,Street5,Village5,Taluk5,District5,State5,Country5,Pincode5,placeofmarriage,marriageplacename,Street6,Village6,Taluk6,District6,State6,Country6,Pincode6, marriagedate,whosolemnimarriage,Street7,Village7,Taluk7,District7,State7,Country7,Pincode7, bridemotherpresent, bridefatherpresent,groommother,groomfather, relationship,witnessname,fatherhusbandname,Street8,Village8,Taluk8,District8,State8,Country8,Pincode8,idcard,idcardno, Passport,Marksheet,Rationcard,Aadharcard,Voterid,Drivinglicence,Passportsizephoto,Divorcecopy, MarriageCertificate,Spousedeathcertificate,Singlestatuscertificate,Bridepassport,BrideMarksheet, BrideRationcard,BrideAaharcard,BrideVoterid,BrideDrivinglicence,BridePassportsizephoto, BrideDivorcecopy,BrideMarriageertificate,BrideSpousedeadcertificate,BrideSinglestatuscertificate, Invitation,Marriagereceipt}}=this.props; let url="http://ec2-18-221-198-250.us-east-2.compute.amazonaws.com:9001/weddingform"; let access_token=localStorage.getItem('token'); const formData = new FormData(); formData.append('Dateofmarriage', Dateofmarriage); formData.append('Name', Name); formData.append('Nationality',Nationality); formData.append('ResidentialStatus',ResidentialStatus); formData.append('Religion',Religion); formData.append('Caste',Caste); formData.append('Dateofbirth',DOB); formData.append('Employername',Employername); formData.append('Designation',Designation); formData.append('MaritalStatusBeforeMarriage', maritalstatus); formData.append('Mobileno',Mobileno); formData.append('whatsappnumber',whatsappnumber); formData.append('Email',emailaddress); formData.append('ResiAddress.Street',Street); formData.append('ResiAddress.village',Village); formData.append('ResiAddress.Taluk',Taluk); formData.append('ResiAddress.District',District); formData.append('ResiAddress.State',State); formData.append('ResiAddress.Country',Country); formData.append('ResiAddress.Pincode',Pincode); formData.append('Passportno',Passportno); formData.append('Fathername',Fathername); formData.append('Fatherreligion',Fatherreligion); formData.append('Livingstatus','1'); formData.append('FLivingStatus',groomfatherlivingstatus); if(groomfatherlivingstatus==="1") { formData.append('FatherAge',FatherAge); } else{ formData.append('FatherAge',0); } formData.append('FatherOccupation',FatherOccupation); if(fatherschooseaddress==="1") { formData.append('Fatheraddress.Street',Street); formData.append('Fatheraddress.village',Village); formData.append('Fatheraddress.Taluk',Taluk); formData.append('Fatheraddress.District',District); formData.append('Fatheraddress.State',State); formData.append('Fatheraddress.Country',Country); formData.append('Fatheraddress.Pincode',Pincode); } else { formData.append('Fatheraddress.Street',Street1); formData.append('Fatheraddress.village',Village1); formData.append('Fatheraddress.Taluk',Taluk1); formData.append('Fatheraddress.District',District1); formData.append('Fatheraddress.State',State1); formData.append('Fatheraddress.Country',Country1); formData.append('Fatheraddress.Pincode',Pincode1); } formData.append('MotherName',MotherName); formData.append('Motherreligion',Motherreligion); formData.append('MLivingStatus',groommotherlivingstatus); if(groommotherlivingstatus==="1") { formData.append('MotherAge',MotherAge); } else { formData.append('MotherAge',0); } formData.append('MotherOccupation',MotherOccupation); if(motherchooseaddress==="1"&&fatherschooseaddress==="1") { formData.append('Motheraddress.Street',Street); formData.append('Motheraddress.village',Village); formData.append('Motheraddress.Taluk',Taluk); formData.append('Motheraddress.District',District); formData.append('Motheraddress.State',State); formData.append('Motheraddress.Country',Country); formData.append('Motheraddress.Pincode',Pincode); } else if(motherchooseaddress==="2") { formData.append('Motheraddress.Street',Street1); formData.append('Motheraddress.village',Village1); formData.append('Motheraddress.Taluk',Taluk1); formData.append('Motheraddress.District',District1); formData.append('Motheraddress.State',State1); formData.append('Motheraddress.Country',Country1); formData.append('Motheraddress.Pincode',Pincode1); } else{ formData.append('Motheraddress.Street',Street2); formData.append('Motheraddress.village',Village2); formData.append('Motheraddress.Taluk',Taluk2); formData.append('Motheraddress.District',District2); formData.append('Motheraddress.State',State2); formData.append('Motheraddress.Country',Country2); formData.append('Motheraddress.Pincode',Pincode2); } formData.append('BrideName',bridename); formData.append('BrideNationality',BrideNationality); formData.append('BrideResidentialStatus',brideresidential); formData.append('BrideReligion',bridereligion); formData.append('BrideCaste',bridecaste); formData.append('BrideDateofbirth',BrideDateofbirth); formData.append('BrideEmployername',brideemployername); formData.append('BrideDesignation',bridedesignation); formData.append('BrideMaritalStatusBeforeMarriage',bridemaritalstatus); formData.append('BrideMobileno',bridemobilenumber); formData.append('Bridewhatsappnumber',bridewhatsapp); formData.append('BrideEmail',brideemail); formData.append('BrideResiAddress.Street',Street3); formData.append('BrideResiAddress.village',Village3); formData.append('BrideResiAddress.Taluk3',Taluk3); formData.append('BrideResiAddress.District',District3); formData.append('BrideResiAddress.State',State3); formData.append('BrideResiAddress.Country',Country3); formData.append('BrideResiAddress.Pincode',Pincode3); formData.append('BridePassportno',bridepassport); formData.append('BrideFathername',bridefather); formData.append('BrideFatherreligion',bridefatherreligion); formData.append('BrideLivingStatus','1'); formData.append('BrideFLivingStatus',bridefatherlivingstatus); if(bridefatherlivingstatus==="1"){ formData.append('BrideFatherAge',bridefatherage); } else{ formData.append('BrideFatherAge',0); } formData.append('BrideFatherOccupation',bridefatheroccupation); if(bridebridefatherchooseaddress==="1") { formData.append('BrideFatheraddress.Street',Street3); formData.append('BrideFatheraddress.village',Village3); formData.append('BrideFatheraddress.Taluk',Taluk3); formData.append('BrideFatheraddress.District4',District3); formData.append('BrideFatheraddress.State',State3); formData.append('BrideFatheraddress.Country',Country3); formData.append('BrideFatheraddress.Pincode',Pincode3); } else{ formData.append('BrideFatheraddress.Street',Street4); formData.append('BrideFatheraddress.village',Village4); formData.append('BrideFatheraddress.Taluk',Taluk4); formData.append('BrideFatheraddress.District4',District4); formData.append('BrideFatheraddress.State',State4); formData.append('BrideFatheraddress.Country',Country4); formData.append('BrideFatheraddress.Pincode',Pincode4); } formData.append('BrideMotherName',bridemother); formData.append('BrideMotherreligion',bridemotherreligion); formData.append('BrideMLivingStatus',bridemotherlivingstatuss); if(bridemotherlivingstatuss==="1"){ formData.append('BrideMotherAge',bridemotherage); } else{ formData.append('BrideMotherAge',0); } formData.append('BrideMotherOccupation',bridemotheroccupation); if(bridemotherchooseaddress==="1"&&bridebridefatherchooseaddress==="1") { formData.append('BrideMotheraddress.Street',Street3); formData.append('BrideMotheraddress.village',Village3); formData.append('BrideMotheraddress.Taluk',Taluk3); formData.append('BrideMotheraddress.District',District3); formData.append('BrideMotheraddress.State',State3); formData.append('BrideMotheraddress.Country',Country3); formData.append('BrideMotheraddress.Pincode',Pincode3); } else if(bridemotherchooseaddress==="2") { formData.append('BrideMotheraddress.Street',Street4); formData.append('BrideMotheraddress.village',Village4); formData.append('BrideMotheraddress.Taluk',Taluk4); formData.append('BrideMotheraddress.District',District4); formData.append('BrideMotheraddress.State',State4); formData.append('BrideMotheraddress.Country',Country4); formData.append('BrideMotheraddress.Pincode',Pincode4); } else{ formData.append('BrideMotheraddress.Street',Street5); formData.append('BrideMotheraddress.village',Village5); formData.append('BrideMotheraddress.Taluk',Taluk5); formData.append('BrideMotheraddress.District',District5); formData.append('BrideMotheraddress.State',State5); formData.append('BrideMotheraddress.Country',Country5); formData.append('BrideMotheraddress.Pincode',Pincode5); } formData.append('placeofmarriage.Name',marriageplacename); formData.append('placeofmarriage. Street', Street6); formData.append('placeofmarriage.village',Village6); formData.append('placeofmarriage.Taluk',Taluk6); formData.append('placeofmarriage.District',District6); formData.append('placeofmarriage.State',State6); formData.append('placeofmarriage.Country',Country6); formData.append('placeofmarriage.Pincode',Pincode6); formData.append('MarriageDate',marriagedate); formData.append('MarriageNotes','test'); formData.append('whosolemnizedmarriage',whosolemnimarriage); formData.append('Addressofsolemnized.Street',Street7); formData.append('Addressofsolemnized.village',Village7); formData.append('Addressofsolemnized.Taluk',Taluk7); formData.append('Addressofsolemnized.District',District7); formData.append('Addressofsolemnized.State',State7); formData.append('Addressofsolemnized.Country',Country7); formData.append('Addressofsolemnized.Pincode',Pincode7); formData.append('Bridemother',bridemotherpresent); formData.append('BrideFather',bridefatherpresent); formData.append('BrideFatherGroom',groommother); formData.append('BridemotherGroom',groomfather); formData.append('Witness','1'); formData.append('Witnessname',witnessname); formData.append('Witnessrelation',relationship); formData.append('Witnessaddress.Street',Street8); formData.append('Witnessaddress.village',Village8); formData.append('Witnessaddress.Taluk',Taluk8); formData.append('Witnessaddress.District',District8); formData.append('Witnessaddress.State',State8); formData.append('Witnessaddress.Country',Country8); formData.append('Witnessaddress.Pincode',Pincode8); formData.append('Identitynumber',idcardno); formData.append('Passport',this.state.Passport); formData.append('Marksheet',this.state.Marksheet); formData.append('Rationcard',this.state.Rationcard); formData.append('Aadharcard',this.state.Aadharcard); formData.append('Voterid',this.state.Voterid); formData.append('DrivingLicence',this.state.Drivinglicence); formData.append('PassportSizePhotograph',this.state.Passportsizephoto); formData.append('DivorceCopy',this.state.Divorcecopy); formData.append('FirstMarriageCertificate',this.state.MarriageCertificate); formData.append('SpouseDeathCertificate',this.state.Spousedeathcertificate); formData.append('SingleStatusCertificate',this.state.Singlestatuscertificate); formData.append('BridePassport',this.state.BridePassport); formData.append('BrideMarksheet',this.state.BrideMarksheet); formData.append('BrideRationCard',this.state.BrideRationcard); formData.append('BrideAadharcard',this.state.BrideAadharcard); formData.append('BrideVoterid',this.state.BrideVoterid); formData.append('BrideDrivingLicence',this.state.BrideDrivinglicence); formData.append('BridePassportSizePhotograph',this.state.BridePassportsizephoto); formData.append('BrideDivorceCopy',this.state.BrideDivorcecopy); formData.append('BrideFirstMarriageCertificate',this.state.BrideMarriageCertificate); formData.append('BrideSpouseDeathCertificate',this.state.BrideSpousedeadcertificate); formData.append('BrideSingleStatusCertificate',this.state.BrideSinglestatuscertificate); formData.append('Invitation',this.state.Invitation); formData.append('MarriageReceipt',this.state.Marriagereceipt); formData.append('Moreattach','test'); formData.append('Declaration','1'); formData.append('Otherservices','1'); formData.append('Subservices','1'); console.log(formData); fetch(url,{ method:'POST', headers: { 'x-access-token':access_token }, body:formData }).then((result)=> { result.json().then((resp)=> { console.warn("resp",resp) if (result.status===200) { } else if(result.status===401) { this.props.history.push('/Login') return result; } else if(result.status===400) { document.getElementById('errormsg1').style.display = 'block'; return result; } else if(result.status===500) { document.getElementById('errormsg1').style.display = 'block'; return result; } else if(result.status===503) { document.getElementById('errormsg1').style.display = 'block'; return result; } else{ } }) }) }; validateForm=()=>{ let isValid = true; var today = new Date(), date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); const {value:{Passport,Marksheet,Rationcard,Aadharcard,Voterid,Drivinglicence,Passportsizephoto,Divorcecopy, MarriageCertificate,Spousedeathcertificate,Singlestatuscertificate,Bridepassport,BrideRationcard,BrideMarksheet, BrideAaharcard,BrideVoterid,BrideDrivinglicence,BridePassportsizephoto,BrideDivorcecopy,BrideMarriageCertificate,BrideSpousedeathcertificate,BrideSinglestatuscertificate,Invitation,Marriagereceipt,Marriagereciptdoc}}=this.props; let Passporterror = ""; let Marksheeterror = ""; let Rationcarderror=""; let Aadharcarderror=""; let Voteriderror=""; let Drivinglicenceerror=""; let Passportsizephotoerror=""; let Divorcecopyerror=""; let MarriageCertificateerror=""; let Spousedeathcertificateerror=""; let Singlestatuscertificateerror=""; let Bridepassporterror=""; let BrideMarksheeterror=""; let BrideRationcarderror=""; let BrideAaharcarderror=""; let BrideVoteriderror=""; let BrideDrivinglicenceerror=""; let BridePassportsizephotoerror=""; let BrideDivorcecopyerror=""; let BrideMarriageCertificateerror=""; let BrideSpousedeathcertificateerror=""; let BrideSinglestatuscertificateerror=""; let Invitationerror =""; let Marriagereceipterror=""; let Marriagereciptdocerror=""; if(Passport===""||Passport===undefined) { Passporterror="Please upload passport"; isValid=false; } else{ if(!Passport.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { Passporterror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(Marksheet===""||Marksheet===undefined) { Marksheeterror="Please upload marksheet"; isValid=false; } else{ if(!Marksheeterror.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { Marksheeterror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(Rationcard===""||Rationcard===undefined) { Rationcarderror="Please upload rationcard"; isValid=false; } else{ if(!Rationcard.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { Rationcarderror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(Aadharcard===""||Aadharcard===undefined) { Aadharcarderror="Please upload aadharcard"; isValid=false; } else{ if(!Aadharcard.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { Aadharcarderror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(Voterid===""||Voterid===undefined) { Voteriderror="Please upload voterid"; isValid=false; } else{ if(!Voterid.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { Voteriderror="Please upload only .doc|.docx|.pdf document"; isValid=false; } } if(Passportsizephoto===""||Passportsizephoto===undefined) { Voteriderror="Please upload passport size photo"; isValid=false; } else{ if(!Passportsizephoto.match(/([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif|.jpeg)$/)) { Passportsizephotoerror="Please upload only .png|.jpg|.gif|.jpeg document"; isValid=false; } } if(Bridepassport===""||Bridepassport===undefined) { Bridepassporterror="Please upload passport"; isValid=false; } else{ if(!Bridepassport.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$/)) { Bridepassporterror="Please upload only .doc|.docx|.pdf document"; isValid=false; } } if(BrideRationcard===""||BrideRationcard===undefined) { BrideRationcarderror="Please upload rationcard"; isValid=false; } else{ if(!BrideRationcard.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { BrideRationcarderror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(BrideAaharcard===""||BrideAaharcard===undefined) { BrideAaharcarderror="Please upload aaharcard"; isValid=false; } else{ if(!BrideAaharcard.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { BrideAaharcarderror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(BrideMarksheet===""||BrideMarksheet===undefined) { BrideMarksheeterror="Please upload marksheet"; isValid=false; } else{ if(!BrideMarksheet.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { BrideMarksheeterror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(BrideVoterid===""||BrideVoterid===undefined) { BrideVoteriderror="Please upload voterid"; isValid=false; } else{ if(!BrideVoterid.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { BrideVoteriderror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(BridePassportsizephoto===""||BridePassportsizephoto===undefined) { BridePassportsizephotoerror="Please upload voterid"; isValid=false; } else{ if(!BridePassportsizephoto.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$/)) { BridePassportsizephotoerror="Please upload only .doc|.docx|.pdf document"; isValid=false; } } if(Invitation===""||Invitation===undefined) { Invitationerror="Please upload Invitation"; isValid=false; } else{ if(!Invitation.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf|.png|.jpg|.gif|.jpeg)$/)) { Invitationerror="Please upload only .doc|.docx|.pdf|.png|.jpg|.gif|.jpeg document"; isValid=false; } } if(Marriagereceipt===""||Marriagereceipt===undefined||Marriagereceipt===0) { Marriagereceipterror="Please select marriage receipt"; isValid=false; } if(Marriagereciptdoc===""||Marriagereciptdoc===undefined) { Marriagereciptdocerror="Please upload marriage receipt"; isValid=false; } else{ if(!Marriagereciptdoc.match(/([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$/)) { Marriagereciptdocerror="Please upload only .doc|.docx|.pdf document"; isValid=false; } } this.setState({Passporterror,Marksheeterror,Rationcarderror,Aadharcarderror,Voteriderror,Drivinglicenceerror,Passportsizephotoerror,Divorcecopyerror, MarriageCertificateerror,Spousedeathcertificateerror,Singlestatuscertificateerror,Bridepassporterror,BrideRationcarderror,BrideAaharcarderror,BrideMarksheeterror,BrideVoteriderror, BrideDrivinglicenceerror,BridePassportsizephotoerror,BrideDivorcecopyerror,BrideMarriageCertificateerror,BrideSpousedeathcertificateerror, BrideSinglestatuscertificateerror,Invitationerror,Marriagereceipterror,Marriagereciptdocerror}) return isValid; } closeform=e=> { window.localStorage.clear(); this.setState({referrer: '/sign-in'}); } render() { const {referrer} = this.state; if (referrer) return <Redirect to={referrer} />; var fname=localStorage.getItem('firstname'); var lname=localStorage.getItem('lastname'); const {value,inputChange}=this.props; const {value:{Passport,Marksheet,Rationcard,Aadharcard,Voterid,Drivinglicence,Passportsizephoto,Divorcecopy, MarriageCertificate,Spousedeathcertificate,Singlestatuscertificate,Bridepassport,BrideMarksheet, BrideRationcard,BrideAaharcard,BrideVoterid,BrideDrivinglicence,BridePassportsizephoto, BrideDivorcecopy,BrideMarriageertificate,BrideSpousedeadcertificate,BrideSinglestatuscertificate, Invitation,Marriagereceipt,Marriagereciptdoc}}=this.props; return( <div > <div class="header_design w-100"> <div class="row float-right m-3" style={{marginRight:"20px"}}> <b style={{marginTop: "7px"}}><label >Welcome {fname }</label></b> &nbsp; &nbsp;<button style={{marginTop: "-7px"}} className="btn btn-primary" onClick={() => this.closeform()} style={{marginToptop: "-7px"}}>logout</button></div> <div class="text-black"> <div class="text-black"> <div class="border-image p-4"></div> </div> </div> </div> <div class="body_UX"> <div class="body_color_code m-4"> <div className="img_logo"></div> <br></br> <br></br><br></br> <div class="box m-4"> <div className="form-container "> <br></br> <h1>Attachements</h1> <div class="row"> <div class="col-md-12"> <div className="form-group"> <label>BRIDE GROOM:</label> </div></div> <div class="col-md-3"> <div class="form-group"> <label>Passport<span style={{color:"red"}}> *</span></label> <input type="file" name="Passport" onChange={(e) => this.setState({ Passport: e.target.files[0] })}/> <p style={{color:"red"}}>{this.state.Passporterror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>10th Marksheet/ 12th Marksheet<span style={{color:"red"}}> *</span> </label> <input type="file" name="Marksheet" onChange={(e) => this.setState({ Marksheet: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.Marksheeterror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Ration Card<span style={{color:"red"}}> *</span></label> <input type="file" name="Rationcard" onChange={(e) => this.setState({ Rationcard: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.Rationcarderror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Aadhar Card<span style={{color:"red"}}> *</span></label> <input type="file" name="Aadharcard" onChange={(e) => this.setState({ Aadharcard: e.target.files[0] })}/> <p style={{color:"red"}}>{this.state.Aadharcarderror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Voter ID<span style={{color:"red"}}> *</span> </label> <input type="file" name="Voterid" onChange={(e) => this.setState({ Voterid: e.target.files[0] })}></input> <p style={{color:"red"}}>{this.state.Voteriderror}</p> </div> </div> <div class="col-md-3"> <label>Driving Licence</label> <input type="file" name="Drivinglicence" onChange={(e) => this.setState({ Drivinglicence: e.target.files[0] })}></input> <p style={{color:"red"}}>{this.state.Drivinglicenceerror}</p> </div> <div class="col-md-3"> <div class="form-group"> <label>Passport Size Photography<span style={{color:"red"}}> *</span></label> <input type="file" name="Passportsizephoto" onChange={(e) => this.setState({ Passportsizephoto: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.Passportsizephotoerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if divorce) Divorce Copy</label> <input type="file" name="Divorcecopy" onChange={(e) => this.setState({ Divorcecopy: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.Divorcecopyerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(in divorce) 1st Marriage Certificate</label> <input type="file" name="MarriageCertificate" onChange={(e) => this.setState({ MarriageCertificate: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.MarriageCertificateerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if widower) Spouse Death Certificate</label> <input type="file" name="Spousedeathcertificate" onChange={(e) => this.setState({ Spousedeathcertificate: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.Spousedeathcertificateerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if other than Resident) Single Status</label> <input type="file" name="Singlestatuscertificate" onChange={(e) => this.setState({ Singlestatuscertificate: e.target.files[0] })}/> <p style={{color:"red"}}>{this.state.Singlestatuscertificateerror}</p> </div> </div> </div> <br></br> <div class="row"> <div class="col-md-12"> <div className="form-group"> <label>BRIDE :</label> </div></div> <div class="col-md-3"> <div class="form-group"> <label>Passport<span style={{color:"red"}}> *</span></label> <input type="file" name="BridePassport" onChange={(e) => this.setState({ BridePassport: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.Bridepassporterror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>10th Marksheet/ 12th Marksheet<span style={{color:"red"}}> *</span> </label> <input type="file" name="BrideMarksheet" onChange={(e) => this.setState({ BrideMarksheet: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BrideMarksheeterror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Ration Card<span style={{color:"red"}}> *</span></label> <input type="file" name="BrideRationcard" onChange={(e) => this.setState({ BrideRationcard: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BrideRationcarderror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Aadhar Card<span style={{color:"red"}}> *</span></label> <input type="file" name="BrideAadharcard" onChange={(e) => this.setState({ BrideAadharcard: e.target.files[0] })}/> <p style={{color:"red"}}>{this.state.BrideAaharcarderror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Voter ID<span style={{color:"red"}}> *</span> </label> <input type="file" name="BrideVoterid" onChange={(e) => this.setState({ BrideVoterid: e.target.files[0] })}></input> <p style={{color:"red"}}>{this.state.BrideVoteriderror}</p> </div> </div> <div class="col-md-3"> <label>Driving Licence</label> <input type="file" name=" BrideDrivinglicence" onChange={(e) => this.setState({ BrideDrivinglicence: e.target.files[0] })}></input> <p style={{color:"red"}}>{this.state.BrideDrivinglicenceerror}</p> </div> <div class="col-md-3"> <div class="form-group"> <label>Passport Size Photography</label> <input type="file" id="fileInput" name="BridePassportsizephoto" onChange={(e) => this.setState({ BridePassportsizephoto: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BridePassportsizephotoerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if divorce) Divorce Copy</label> <input type="file" name="BrideDivorcecopy" onChange={(e) => this.setState({ BrideDivorcecopy: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BrideDivorcecopyerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if divorce) 1st Marriage Certificate</label> <input type="file" name="BrideMarriageCertificate" onChange={(e) => this.setState({ BrideMarriageCertificate: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BrideMarriageCertificateerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if widower) Spouse Death Certificate</label> <input type="file" name="BrideSpousedeathcertificate" onChange={(e) => this.setState({ BrideSpousedeadcertificate: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BrideSpousedeathcertificateerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>(if other than Resident) Single Status </label> <input type="file" name="BrideSinglestatuscertificate" onChange={(e) => this.setState({ BrideSinglestatuscertificate: e.target.files[0] })} /> <p style={{color:"red"}}>{this.state.BrideSinglestatuscertificateerror}</p> </div> </div> </div> <br></br> <div class="row"> <div class="col-md-12"> <div className="form-group"> <label>MARRIAGE PROOF:</label> </div></div> <div class="col-md-3"> <div class="form-group"> <label>Invitation<span style={{color:"red"}}> *</span></label> <input type="file" name="Invitation" onChange={(e) => this.setState({ Invitation: e.target.files[0] })}/> <p style={{color:"red"}}>{this.state.Invitationerror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <label>Marriage Receipt<span style={{color:"red"}}> *</span></label> <select id="Marriagereceipt" className="input" name="Marriagereceipt" onChange={this.onChangeHandler}> <option value="0">-Select Value-</option> <option value="1">Hall Receipt</option> <option value="2">Temple Receipt</option> <option value="3">Chutch Certificate</option> <option value="4">Jamath Document</option> <option value="5"> Chief Khaji Certificate</option> </select> <p style={{color:"red"}}>{this.state.Marriagereceipterror}</p> </div> </div> <div class="col-md-3"> <div class="form-group"> <input type="file" name="Marriagereciptdoc" onChange={(e) => this.setState({ Marriagereceipt: e.target.files[0] })}/> <p style={{color:"red"}}>{this.state.Marriagereciptdocerror}</p> </div> </div> </div> </div> </div> <div className="row"> <div className="col-md-6"> <button className="pev m-4" onClick={this.back}>Back</button> </div> <div className="col-md-6"> <div className="text-right"> <button className="next m-4" onClick={this.submit}>Submit</button> </div> </div> </div> <div className="row"> <div className="col-md-4"></div> <div className="col-md-4"> <div id="errormsg2" style={{display:"none"}}> <div class="alert" > <span class="closebtn" onClick={this.closeform1}>&times;</span> The request was not completed due to an internal error on the server side </div></div> <div id="errormsg3" style={{display:"none"}}> <div class="alert" > <span class="closebtn" onClick={this.closeform2}>&times;</span> The server was unavailable </div> </div> <div className="col-md-4"></div> </div> <div id="errormsg1" style={{display:"none"}}> <div class="alert" > <span class="closebtn" onClick={this.closeform}>&times;</span> The request was invalid </div></div> </div><br></br><br></br> <br></br><br></br> <br></br> </div> </div> </div> ); } } export default Attachements
import Index from "@/layout/Client/Index.vue"; import Home from "@/pages/Client/home/Home.vue"; import DashboardLayout from "@/layout/dashboard/DashboardLayout.vue"; import Dashboard from "@/pages/admin/Dashboard/Dashboard.vue"; import Goods from "@/pages/admin/Goods/List.vue"; import RestaurantDetail from "@/pages/Client/Restaurant/Index.vue"; import Customer from "@/pages/admin/Customer/List.vue"; import Merchant from "@/pages/admin/Merchant/List.vue"; import Restaurant from "@/pages/admin/Restaurant/List.vue"; import Location from "@/pages/admin/Location/List.vue"; import Order from "@/pages/admin/Order/List.vue"; import LoginPage from "@/pages/client/Login/Form.vue"; import RegisterPage from "@/pages/client/Register/Form.vue"; import LoginDashboard from "@/pages/admin/Login/Form.vue"; import OrderRestaurant from "@/pages/Merchant/Order/List.vue"; import FoodRestaurant from "@/pages/Merchant/Goods/List.vue"; import LoginMerchant from "@/pages/Merchant/Login/Form.vue"; import MerchantDashboardLayout from "@/layout/Merchant/DashboardLayout.vue"; import DashboardMerchant from "@/pages/merchant/Dashboard/Dashboard.vue"; import NotFound from "@/pages/System/NotFoundPage.vue"; import ReportRevenue from "@/pages/admin/Report/List.vue"; import DiscountCode from "@/pages/admin/Discount/List.vue"; import ReportOfMerchant from "@/pages/Merchant/Report/List.vue"; import DiscountCodeOfRestaurant from "@/pages/Merchant/Discount/List.vue"; import RestaurantCombo from "@/pages/Admin/ComboFood/List.vue"; import LadingBill from "@/pages/Admin/LadingBill/List.vue"; const appName = " | Nghiện ăn"; const routes = [{ path: "/", component: Index, redirect: "home", children: [{ path: "home", name: "Trang chủ", component: Home, meta: { title: 'Trang chủ' + appName } }, { path: "detail-restaurant", name: "Chi tiết món", component: RestaurantDetail, meta: { title: 'Quán ăn' + appName } }, { path: "register", name: "Đăng kí", component: RegisterPage, meta: { title: 'Đăng kí' + appName } }, { path: "/login", name: "Đăng nhập", component: LoginPage, meta: { title: 'Đăng nhập' + appName } } ] }, { path: "/admin", component: DashboardLayout, redirect: "admin/dashboard", meta: { auth: true }, children: [{ path: "dashboard", title: "Tổng quan", component: Dashboard, meta: { auth: true, title: 'Tổng quan' + appName } }, { path: "food", title: "Món ăn", component: Goods, meta: { auth: true, title: 'Món ăn' + appName }, }, { path: "customer", title: "Khách hàng", component: Customer, meta: { auth: true, title: 'Khách hàng' + appName }, }, { path: "merchant", title: "Đối tác", component: Merchant, meta: { auth: true, title: 'Đối tác' + appName }, }, { path: "restaurant", title: "Quán ăn", component: Restaurant, meta: { auth: true, title: 'Quán ăn' + appName }, }, { path: "location", title: "Địa điểm", component: Location, meta: { auth: true, title: 'Địa điểm' + appName }, }, { path: "order", title: "Đơn hàng", component: Order, meta: { auth: true, title: 'Đơn hàng' + appName }, }, { path: "report-revenue", title: "Báo cáo doanh thu", component: ReportRevenue, meta: { auth: true, title: 'Báo cáo doanh thu' + appName }, }, , { path: "discount-code", title: "Mã giảm giá", component: DiscountCode, meta: { auth: true, title: 'Mã giảm giá' + appName }, } , { path: "restaurant-combo", title: "Combo đồ ăn", component: RestaurantCombo, meta: { auth: true, title: 'Combo đồ ăn' + appName }, }, { path: "lading-bill", title: "Vận đơn", component: LadingBill, meta: { auth: true, title: 'Vận đơn' + appName }, } ] }, { path: "/admin/login", name: "Đăng nhập quản lý", component: LoginDashboard, meta: { auth: false, title: "Đăng nhập", }, }, { path: "/merchant/login", name: "Đăng nhập đối tác", component: LoginMerchant, meta: { authMerchant: false, title: "Đăng nhập" + appName, }, }, { path: "/merchant", component: MerchantDashboardLayout, redirect: "merchant/order", meta: { auth: true, }, children: [{ path: "order", title: "Đơn hàng", component: OrderRestaurant, meta: { authMerchant: true, title: "Đơn hàng" + appName, } }, { path: "food", title: "Món ăn", component: FoodRestaurant, meta: { authMerchant: true, title: "Món ăn" + appName, } }, { path: "dashboard", title: "Tổng quan", component: DashboardMerchant, meta: { authMerchant: true, title: "Tổng quan" + appName, } } , { path: "report-revenue", title: "Báo cáo doanh thu", component: ReportOfMerchant, meta: { authMerchant: true, title: "Báo cáo doanh thu" + appName, } } , { path: "discount-code", title: "Ưu đãi", component: DiscountCodeOfRestaurant, meta: { authMerchant: true, title: "Ưu đãi" + appName, } } ] }, { path: "*", component: NotFound }, ] export default routes;
const testConcerts = require('../test_concerts'); exports.seed = function(knex) { return knex('concerts').insert(testConcerts); };
const SEARCH_URL = 'http://localhost:3000/search/'; const MOVIE_URL = 'http://localhost:3000/movie/'; const app = new Vue({ el: '#app', data: { search_term: '', movies: [], movieResults: [], showTable: false }, methods: { searchMovies(search_term) { this.movieResults = []; this.search_term = search_term const url = `${SEARCH_URL}${search_term}` fetch(url) .then(response => response.json()) .then(json => { this.movies = json this.showTable = true this.search_term = '' }) }, getMovie(imdbID) { const url = `${MOVIE_URL}${imdbID}` fetch(url) .then(response => response.json()) .then(json => { console.log(json); this.movieResults.push(json) this.showTable = false }) } } });
import create from '../src'; describe('edge cases', () => { test('bad keys', () => { expect(0 in {"0": undefined}).toBe(true); expect("0" in {0: undefined}).toBe(true) expect(undefined in {[undefined]: undefined}).toBe(true) }); test('undefined child', () => { const subject = create({a: undefined}); expect(subject.a).toBeUndefined() }); });
import React from 'react'; function SearchBar(props) { return ( <div className="searchBar"> <h3>Search</h3> <input type="text" placeholder="Search for an item" id="searchBox" onChange={props.onChange}/> <div> <input type="checkbox" id="inStock" name="inStock" onChange={props.onSelect}/> <label htmlFor="inStock">Only show products on stock</label> </div> </div> ); } export default SearchBar;
// @ts-check import ReactDOM from 'react-dom'; import React from 'react'; import ListGroup from './ListGroup.jsx'; const dom = ( <ListGroup> <p>one</p> <p>two</p> </ListGroup> ); ReactDOM.render( dom, document.getElementById('container'), );
import produce from 'immer'; import { CHANGE_DATE, GET_DATES_BY_PERSON_ID } from '@/containers/DateSelector/constants'; import { REQUEST_STATUS } from '@/utils/constants'; export const INITIAL_STATE = CONSTANTS => ({ [CONSTANTS.REDUCER_KEY.RESULTS]: [], [CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE]: [], [CONSTANTS.REDUCER_KEY.STATUS]: { [CONSTANTS.REDUCER_KEY.RESULTS]: REQUEST_STATUS.LOADING, [CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE]: REQUEST_STATUS.LOADING } }); /* eslint-disable default-case, no-param-reassign */ export const defaultProduce = (CONSTANTS, initialState) => (state = initialState, action) => produce(state, draft => { switch (action.type) { case CONSTANTS.ACTIONS.LOAD_SUCCESS: draft[CONSTANTS.REDUCER_KEY.RESULTS] = action.payload; draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS] = REQUEST_STATUS.LOADED; break; case CONSTANTS.ACTIONS.DATE_RANGE_LOAD_SUCCESS: draft[CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE] = action.payload; draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE] = REQUEST_STATUS.LOADED; break; case CONSTANTS.ACTIONS.LOAD_ERROR: draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS] = REQUEST_STATUS.ERROR; break; case CONSTANTS.ACTIONS.DATE_RANGE_LOAD_ERROR: draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE] = REQUEST_STATUS.ERROR; break; case GET_DATES_BY_PERSON_ID: draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS] = REQUEST_STATUS.LOADING; draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE] = REQUEST_STATUS.LOADING; break; case CHANGE_DATE: draft[CONSTANTS.REDUCER_KEY.STATUS][CONSTANTS.REDUCER_KEY.RESULTS_BY_RANGE] = REQUEST_STATUS.LOADING; break; } });
import React from 'react'; const Hobby = () => ( <React.Fragment> <h2>Hobby</h2> <ul> <li>ポケモンGO</li> <li>MARVEL映画</li> <li>モンスターエナジー</li> <li>タピオカ</li> <li>コーヒー</li> <li>ラーメン</li> </ul> </React.Fragment> ); export default Hobby;
/* * All routes for Widgets are defined here * Since this file is loaded in server.js into api/widgets, * these routes are mounted onto /widgets * See: https://expressjs.com/en/guide/using-middleware.html#middleware.router */ const express = require('express'); const router = express.Router(); module.exports = (db) => { router.get("/", (req, res) => { let query = `SELECT * FROM menu_items`; console.log(query); db.query(query) .then(data => { const menu = data.rows; res.json({ menu }); }) .catch(err => { res .status(500) .json({ error: err.message }); }); }); router.get("/:id", (req, res) => { let query = `SELECT * FROM menu_items WHERE menu_items.id = $1;`; db.query(query, [req.params.id]) .then((data) => { const menu = data.rows; res.json({ menu }); }) .catch((err) => { console.log(err.message); res .status(500) .json({ error: err.message }); }) }); router.get("/name/:name", (req, res) => { let query = `SELECT menu_items.id FROM menu_items WHERE menu_items.name LIKE '%${req.params.name}%';`; db.query(query) .then((data) => { const menu_item = data.rows; res.json({ menu_item }); }) .catch((err) => { console.log(err.message,); res .status(500) .json({ error: err.message }); }) }); router.post("/", (req, res) => { // let obj = { // burger: 2, // fries: 3, // pop: 4 // } // CHANGE THE USER ID TO COOKIES (REQ.SESSION?) let query = ` INSERT INTO menu_items (name, price, thumbnail_picture_url, description, category) VALUES ($1, $2, $3, $4, $5);` console.log(query); db.query(query, [req.body.name, req.body.price, req.body.thumbnailPictureUrl, req.body.description, req.body.category]) .then(data => { const addToMenu = data.rows; res.json({ addToMenu }); }) .catch(err => { res .status(500) .json({ error: err.message }); }); }); router.put("/", (req, res) => { console.log(req.body); let query = `UPDATE menu_items SET `; let options = []; if (req.body.name) { options.push(req.body.name); query += `name = '$${options.length}' `; } if (req.body.price) { options.push(req.body.price); query += `, price = $${options.length} `; } if (req.body.thumbnailPictureUrl) { options.push(req.body.thumbnailPictureUrl); query += `, thumnailPictureURL = '$${options.length}', `; } if (req.body.description) { options.push(req.body.description); query += `, description = '$${options.length}' `; } if (req.body.category) { options.push(req.body.category); query += `, category = '$${options.length}' `; } options.push(req.body.menuItemId); query += `WHERE menu_items.id = $${options.length};`; console.log(query); db.query(query, options) .then(data => { const menu_items = data.rows; res.json({ menu_items }); }) .catch(err => { res .status(500) .json({ error: err.message }); }); }); router.delete("/", (req, res) => { let query = `DELETE FROM menu_items WHERE menu_items.id = $1;`; db.query(query, [req.body.menuItemId]) .then(data => { const menu_items = data.rows; res.json({ menu_items }); }) .catch(err => { res .status(500) .json({ error: err.message }); }); }); return router; };
import React from 'react' import marked from 'marked'; export default class Comment extends React.Component{ rawMarkup() { let rawMarkupHtml = marked(this.props.children.toString(), {sanitize: true}); return { __html: rawMarkupHtml }; } render() { return ( <div className="c-card"> <div className="c-card__header"> <h3>{this.props.author}</h3> </div> <div className="c-card__content"> <p dangerouslySetInnerHTML={this.rawMarkup()} /> </div> </div> ); } };
import {LocalStorage} from "quasar"; export default function () { return { user: { token: LocalStorage.getItem('token') } } }
const express = require("express"); const cors = require("cors"); const { ExpressPeerServer } = require("peer"); const app = express(); const server = app.listen(process.env.PORT); let host = null; let connections = []; const peerServer = ExpressPeerServer(server); peerServer.on("connection", ({ id }) => { if (!host) { host = id; } connections = [id, ...connections]; }); peerServer.on("disconnect", ({ id }) => { connections = connections.filter((id) => connections.indexOf(id) !== 1); if (host === id) { host = connections[0]; } }); app.use(cors()); app.use("/", peerServer); app.get("/peerjs/host", (req, res) => { res.status(200).send({ host, connections }); });
// requestAnimFrame shim window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, frameOffset) { window.setTimeout(callback, frameOffset); }; })(); // helper functions function el(id) { return document.getElementById(id); } // user variables var width, height, ctx; // global variables TODO: namespace! var shimCanvasDefaultSize = 500; var shimRealtime, shimAnimate, shimError, shimCanvas; // onload handler function shimOnload() { // canvas shim init shimRealtime = el("control-realtime").checked; shimAnimate = el("control-animate").checked; shimError = false; shimCanvas = el("canvas"); shimCanvas.width = shimCanvas.height = shimCanvasDefaultSize; // user controls event handlers el("control-realtime").addEventListener("change", function() { shimRealtime = el("control-realtime").checked; //el("control-run").disabled = shimRealtime; if (shimRealtime) fnCompile(); }, false); el("control-animate").addEventListener("change", function() { shimAnimate = el("control-animate").checked; if (shimAnimate) fnShimAnimate(); }, false); el("control-run").addEventListener("click", function() { fnCompile(); }, false); el("control-demos").addEventListener("change", function() { var demofile = el("control-demos").value; if (demofile) { // Request content of the example .js file var oXHR = new XMLHttpRequest(); oXHR.open("GET", el("control-demos").value, true); oXHR.onreadystatechange = function (e) { if (oXHR.readyState === 4) { // Status 200 OK or local dev code is 0 if (oXHR.status === 200 || oXHR.status === 0) { el("code").value = oXHR.responseText; if (shimRealtime) fnCompile(); } } }; oXHR.send(null); } }, false); // init user variables width = shimCanvas.width; height = shimCanvas.height; ctx = shimCanvas.getContext('2d'); // handler for realtime script compile el("code").addEventListener('keyup', function(e) { // ignore keycodes for cursors etc. if ((e.keyCode < 16 || e.keyCode > 40) && shimRealtime) fnCompile(); }, false); // init liquid layout shimResizeHandler(); // kick off initial compile and animation if checked fnCompile(); if (shimAnimate) fnShimAnimate(); } // resize handler function shimResizeHandler() { var code = el("code"); var w = (window.innerWidth - shimCanvasDefaultSize - 32); // minimum width of the code entry area if (w > 320) code.style.width = w + "px"; // approx height of the info section code.style.height = (window.innerHeight - 190) + "px"; } window.addEventListener('resize', shimResizeHandler, false); window.addEventListener('load', shimOnload, false); // user code function and compiler var shimCode = null; function fnCompile() { try { // test code for evaluation success - update the function that is used by the animation // new lines are added to deal with potential comments on final line of input string eval("shimCode = function() {\n" + el("code").value + "\n};"); // clear any error info that might have previously been displayed if (shimError) { el("errors").style.display = "none"; shimError = false; } if (!shimAnimate) fnShimAnimate(); } catch (e) { // syntax error or similar el("errors").innerHTML = e.message; el("errors").style.display = "block"; shimError = true; } } // animation function function fnShimAnimate() { ctx.save(); try { if (shimCode) shimCode.call(this); } catch (e) { // runtime error or similar el("errors").innerHTML = e.message; el("errors").style.display = "block"; shimError = true; } ctx.restore(); if (shimAnimate) requestAnimFrame(fnShimAnimate); }
function getDurationString(sd, ed) { const startString = `${new Date( sd.year, sd.month - 1, sd.date ).toLocaleString("default", { month: "long" })} ${sd.year}`; let endString = `${new Date(ed.year, ed.month - 1, ed.date).toLocaleString( "default", { month: "long" } )} ${ed.year}`; const currYear = new Date().getFullYear(); const currMonth = new Date().getMonth(); const currDate = new Date().getDate(); if (currYear === ed.year && currMonth === ed.month && currDate === ed.date) { endString = "Present"; } return `${startString} - ${endString}`; } function getDurationLength(sd, ed) { const durationInMonths = Math.round( (new Date(ed.year, ed.month - 1, ed.date) - new Date(sd.year, sd.month - 1, sd.date)) / 2629746000 ); const years = Math.floor(durationInMonths / 12); const months = durationInMonths % 12; return { years, months }; } export { getDurationString, getDurationLength };
function saveImage(size) { var document_name = app.activeDocument.name.replace(/\.[^\.]+$/, ''); var extension = decodeURI(app.activeDocument.name).replace(/^.*\./,''); // if(extension.toLowerCase() != 'psd') return; var path = app.activeDocument.path; var short_name = app.activeDocument.name.split(".")[0]; var saveFile = File(path + "/" + short_name + "_" + size ); if(saveFile.exists) saveFile.remove(); savePNG(saveFile); } function savePNG(saveFile){ pngSaveOptions = new PNGSaveOptions(); activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE); } function main() { var docRef = app.activeDocument var goodState = docRef.activeHistoryState; app.preferences.rulerUnits = Units.PIXELS; var icon_sizes = [2048,1024,512,256,152,144,128,120,114,96,76,72,57,48,36]; for(var i=0; i < icon_sizes.length; i++) { var resize = app.activeDocument.resizeImage(icon_sizes[i],icon_sizes[i]); saveImage(icon_sizes[i]); //undo after each one or we get multiplicity-style copy-of-a-copy-of-a-copy docRef.activeHistoryState = goodState; } alert("Process complete"); } main();
/**** Process the form with jQuery Form Malsup Plugin *****/ $( '#button-reset-form' ).click(function(){ $('select option:first-child').attr("selected", "selected"); $('[id^="answer"]').html(''); $('#test-response').html(''); }); $('#testForm').ajaxForm(function() { $('html,body').animate({ scrollTop: $("#test-response").offset().top + 50}, 'slow'); $('#test-response').html('<b>Wait an instant while we validate the information. <i class="fa fa-spinner fa-spin fa-2x"></i></b>'); validation(); }); function validation(){ var contador = 14; var message = ""; /** GROUP 1 **/ /** Option 1 => 1 **/ if( $('#question1', '#testForm').val() != 1){ contador = contador-1; $('#answer1').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer1').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 2 => 2 **/ if( $('#question2', '#testForm').val() != 2){ contador = contador-1; $('#answer2').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer2').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 3 => 3 **/ if( $('#question3', '#testForm').val() != 3){ contador = contador-1; $('#answer3').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer3').html("<i class='fa fa-check' style='color:green;'></i>"); } /** GROUP 2 **/ /** Option 4 => 1**/ if( $('#question4', '#testForm').val() != 1){ contador = contador-1; $('#answer4').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer4').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 5 => 2**/ if( $('#question5', '#testForm').val() != 2){ contador = contador-1; $('#answer5').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer5').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 6 => 3**/ if( $('#question6', '#testForm').val() != 3){ contador = contador-1; $('#answer6').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer6').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 7 => 4**/ if( $('#question7', '#testForm').val() != 4){ contador = contador-1; $('#answer7').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer7').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 8 => 5**/ if( $('#question8', '#testForm').val() != 5){ contador = contador-1; $('#answer8').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer8').html("<i class='fa fa-check' style='color:green;'></i>"); } /**** GROUP 3 ****/ /** Option 9 => 1 **/ if( $('#question9', '#testForm').val() != 1){ contador = contador-1; $('#answer9').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer9').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 10 => 2 **/ if( $('#question10', '#testForm').val() != 2){ contador = contador-1; $('#answer10').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer10').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 11 => 3 **/ if( $('#question11', '#testForm').val() != 3){ contador = contador-1; $('#answer11').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer11').html("<i class='fa fa-check' style='color:green;'></i>"); } /*** GROUP 4 ***/ /** Option 12 => 1**/ if( $('#question12', '#testForm').val() != 1){ contador = contador-1; $('#answer12').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer12').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 13 => 2**/ if( $('#question13', '#testForm').val() != 2){ contador = contador-1; $('#answer13').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer13').html("<i class='fa fa-check' style='color:green;'></i>"); } /** Option 14 => 3**/ if( $('#question14', '#testForm').val() != 3){ contador = contador-1; $('#answer14').html("<i class='fa fa-close' style='color:red;'></i>"); }else{ $('#answer14').html("<i class='fa fa-check' style='color:green;'></i>"); } /*** Switch for responses ***/ if(contador == 14){ message = '<b>Congratulations! <i class="fa fa-smile-o fa-2x"></i></b>'; } else if (contador >= 9 && contador < 14){ message = '<b>Well done! <i class="fa fa-thumbs-o-up fa-2x"></i></b>'; }else if(contador >= 1 && contador < 9){ message = '<b>You need more practice <i class="fa fa-frown-o fa-2x"></i></b>'; }else{ message = '<b>Keep trying <i class="fa fa-thumbs-o-down fa-2x"></i></b>'; } /*** Print response on well ***/ setTimeout(function(){ $('#test-response').html('<div class="alert alert-success" role="alert"><p>You have answered correctly '+contador+' out of 14 questions<br>'+message+'</div>'); }, 4000); }
const {EventEmitter} = require('events'); let e = new EventEmitter(); async function sleep(ms) { return new Promise(resolve => { setTimeout(()=>{ resolve() }, ms) }) } let i = 0; (async ()=> { while (true) { e.once(Date.now().toString(), ()=>{ }); i++; await sleep(2); console.log(i); } })();
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ import componentTemplate from './userStatus.html'; class VerifyEmailController { static get $$ngIsClass() { return true; } static get $inject() { return []; } constructor() {} } export default { controller: VerifyEmailController, template: componentTemplate, bindings: { user: '<?' } };
QUnit.test( "Let:", function( assert ) { var name = "test old"; { let name ="test new"; assert.ok( name == "test new"); } assert.equal( name, "test old"); }); QUnit.test( "Let: podem", function( assert ) { var test; assert.ok(test == undefined); assert.ok(name == undefined); var name = "test old"; assert.throws( function () { { name = 3; let name ="test new"; } }, ReferenceError, 'You can not get var before let'); }); QUnit.test( "Let: get var out of scope", function( assert ) { assert.throws( function () { { let name ="test new"; assert.ok(name == "test new") } name == "test new" }, ReferenceError, 'You can not get var before let'); { var name2 ="test new"; } name2 = "test old"; assert.equal(name2, "test old") }); QUnit.test( "Let: for with var", function( assert ) { assert.ok( a == undefined); for (var a=0; a < 10;a++){ assert.ok( a < 10); } }); QUnit.test( "Let: for with let", function( assert ) { assert.throws( function () { a == undefined for (let a=0; a < 10;a++){ assert.ok(a < 10); } }, ReferenceError, 'You can not get var before let'); }); QUnit.test( "Let: for and closure", function( assert ) { funcs = []; for (let a = 0; a < 10; a++){ funcs.push(function () { return a }) } assert.equal( funcs[0](), 0); assert.equal( funcs[3](), 3); assert.equal( funcs[9](), 9); }); QUnit.test( "Let: var and for and closure", function( assert ) { var funcs = []; for (var a = 0; a < 10; a++){ funcs.push(function () { return a }) } assert.equal( a, 10); assert.equal( funcs[0](), 10); assert.equal( funcs[3](), 10); });
arr = [1, 4, 20, 3, 10, 5]; k = 23; function sumSubArrayToK(arr, k) { let sum = 0; let endIndex = null; let preSum = { 0: 1 }; for (let i = 0; i < nums.length; i++) { sum += nums[i]; if (preSum[sum - k]) { endIndex = i; break; } // increment preSum[sum] by 1 if we dont default to zero then it's going to be undefined + 1 preSum[sum] = (preSum[sum] || 0) + 1; } if (endIndex === null) { return endIndex; } sum = 0; let startIndex = null; for (let i = endIndex; i >= 0; i--) { sum += nums[i]; if (sums === k) { startIndex = i; break; } } return [startIndex, endIndex]; }
import Merge from 'merge'; import { EventEmitter } from 'events'; import ServerAPI from '../serverAPIs/serverAPI.js'; import Dispatcher from 'assets/dispatcher.js'; /* example data */ let serverDataList = new Array(); let dataList = new Array(); /* Definitions */ const DATAMEMBERS = 5; function DataObj () { this['ID'] = ''; this['name'] = ''; } /* example event listener id */ const EXAMPLE_EVENT_ID = 'exampleFlux_server'; /* store emitter */ const ExampleStore = Merge(EventEmitter.prototype, { exampleFlux_server_getData : function() { return dataList; }, exampleFlux_server_emitChange : function () { this.emit(EXAMPLE_EVENT_ID); }, exampleFlux_server_addChangeListener : function (callback) { this.on(EXAMPLE_EVENT_ID, callback); }, exampleFlux_server_removeChangeListener : function (callback) { this.removeListener(EXAMPLE_EVENT_ID, callback); } }); /* regist event to dispatcher */ Dispatcher.register((event) => { let obj; switch (event.actionType) { case 'fluxServer_fetch': // if data is empty, init data if (0 == serverDataList.length) { serverDataList = ServerAPI.initData(); } else { serverDataList = ServerAPI.getData(); } dataList = serverDataList; ExampleStore.exampleFlux_server_emitChange(); break; case 'fluxServer_add': obj = new DataObj(); obj['name'] = event['userName']; if (DATAMEMBERS <= dataList.length) { alert('User is full.'); break; } dataList = ServerAPI.addData(obj); ExampleStore.exampleFlux_server_emitChange(); break; case 'fluxServer_remove': obj = new DataObj(); obj['ID'] = event['userID']; dataList = ServerAPI.deleteData(obj); ExampleStore.exampleFlux_server_emitChange(); break; } }); export default ExampleStore;
import checkPermission from './permission' const permissionMixin = { methods: { checkPermission: checkPermission } } export default permissionMixin
let i = 0; while (i <= 10) { string = ""; switch (i) { case 10: string = "10," + string; case 9: string = "9," + string; case 8: string = "8," + string; case 7: string = "7," + string; case 6: string = "6," + string; case 5: string = "5," + string; case 4: string = "4," + string; case 3: string = "3," + string; case 2: string = "2," + string; case 1: string = "1," + string; } string = string.substring(0,string.length-1); string = string + "."; if (string != ".") { console.log(string); } i++; }
import React, { Component } from 'react' import './senior-form.scss' export default class SeniorForm extends Component{ constructor(props){ super(props); this.state = { name: '', zipcode: '', addLearn: '', addTeach: '', addRequirement: '', needToKnow: '', lease: '', hours: '', learnTopics: [], teachTopics: [] } this.handleInputChange = this.handleInputChange.bind(this) this.createAccount = this.createAccount.bind(this) this.addLearn = this.addLearn.bind(this) } handleInputChange(e) { const target = e.target const value = target.type === 'checkbox' ? target.checked : target.value const name = target.name this.setState({ [name]: value }) } addLearn(e) { e.preventDefault() let updatedLearnTopics = [...this.state.learnTopics, this.state.addLearn ] this.setState({ learnTopics: updatedLearnTopics, addLearn: '' }) } createAccount(e){ e.preventDefault() this.setState({ user: Object.assign({}, this.state) }) } render() { let { name, zipcode, addLearn, addTeach, addRequirement, needToKnow, lease, hours, learnTopics } = this.state let inputLearn = learnTopics.length >= 1 ? learnTopics.map((learn, index) => <p key={index}>{learn}</p>) : '' return ( <form className='senior-form'> <h2>Create Your Account</h2> <label> NAME </label> <input placeholder='Cynthia Aguilar' type='text' name='name' value={name} onChange={this.handleInputChange}/> <br/> <label>ZIPCODE</label> <input placeholder='80202' value={zipcode} type='number' name='zipcode' onChange={this.handleInputChange}/> <br/> <button onClick={this.renderNext}>SUBMIT</button> <br/> <br/> <hr /> <label>I would like to learn about:</label> <br/> <input type='checkbox' name='learnSci' onChange={this.handleInputChange}/>Science <br/> <input type='checkbox' name='learnArt' onChange={this.handleInputChange}/>Art <br/> <input type='checkbox' name='learnTech' onChange={this.handleInputChange}/> Technology <br/> <input type='checkbox' name='learnSports' onChange={this.handleInputChange}/> Sports <br/> <section>{inputLearn}</section> <input placeholder='pop culture' name='addLearn' value={addLearn} onChange={this.handleInputChange}/> <button name='learnTopics' onClick={this.addLearn} className='add-like-submit'> + </button> <br/> <button onClick={this.renderNext}>SUBMIT</button> <hr /> <br/> <label>I would like to teach about:</label> <br/> <input type='checkbox' name='teachSci' onChange={this.handleInputChange}/>Science <br/> <input type='checkbox' name='teachArt' onChange={this.handleInputChange}/>Art <br/> <input type='checkbox' name='teachTech' onChange={this.handleInputChange}/> Technology <br/> <input type='checkbox' name='teachSports' onChange={this.handleInputChange}/> Sports <br/> <input placeholder='music theory' name='addTeach' value={addTeach} onChange={this.handleInputChange}/> <button name ='teachTopics' onClick={this.addItem} className='add-teach-submit'> + </button> <hr /> <input type='submit' onClick={this.createAccount} value="Create Account"/> </form> ) } }
// Have to tell application to listen for these modules. var express = require('express'), app = express(), mongoose = require('mongoose'), //Require the model for the microblog bodyParser = require('body-parser'), _ = require("underscore"); mongoose.connect('mongodb://localhost/microblog') // tell app to use bodyParser middleware app.use(bodyParser.urlencoded({extended: true})); // serve js and css files from public folder app.use(express.static(__dirname + '/public')); var Microblog = require('./models/microblogModel') // //pre-seeded blog data // var posts = [ // { // id: 1, // blog: 'July 4th: I spent an amazing time watching fireworks on a rooftop in downtown Oakland with queer activist friends.', // comment: "Those sparklers made the night shine! - Francois",}, // { // id: 2, // blog: 'July 3rd: I soaked in the sun, water, laughter and delicious treats along the Russian River!', // comment: 'Best summer. ever. epic. - Maria'}, // { // id: 3, // blog: 'July 2nd: Spent the night watching OINTB and discussing how it trivializes the prison industrial complex and the experiences of women within that system of oppression. Tastee still makes me laugh', // comment: 'On point as usual - Anna' // } //ROUTES app.get('/', function (req, res) { res.sendFile(__dirname + '/public/views/index.html'); }); //Show blog archive data Microblog.find(function (err, microblog) { console.log(microblog); }) //get ALL posts app.get('/api/microblogs', function (req, res) { Microblog.find(function (err, microblogs) { res.json(microblogs) }) }) //get ONE post by ID app.get('/api/microblogs/:id', function (req, res) { //set the value of the ID var targetId = req.params.id; //find ONE post by ID Microblog.findOne({_id: targetId}, function (err, foundMicroblog) { res.json(foundMicroblog); }); }); //POST blogs to server app.post('/api/microblogs', function (req, res) { var newMicroblog = new Microblog({ blog: req.body.blog, comment: req.body.comment }); newMicroblog.save(function (err, savedMicroblog) { res.json(savedMicroblog); }); }); // // //modify object in the server app.put('/api/microblogs/:id', function (req, res) { //set the value of the id var targetId = req.params.id; //find post in db by id Microblog.findOne({_id: targetId}, function (err, savedMicroblog) { savedMicroblog.blog = req.body.blog; savedMicroblog.comment = req.body.comment; //save updated post in db savedMicroblog.save(function (err, savedMicroblog) { res.json(savedMicroblog); }); }); }); //DELETE blog post from archive app.delete('/api/microblogs/:id', function (req, res) { //set the value of the id var targetId = req.params.id; // find phrase in db by id and remove Microblog.findOneAndRemove({_id: targetId}, function (err, deletedMicroblog) { res.json(deletedMicroblog); }); }); // //set id to new post to add blog archive array // if (posts.length > 0) { // newBlogItem.id = posts[posts.length - 1].id + 1; // } else { // newBlogItem.id = 0; // } // //add new post to blog archive array // posts.push(newBlogItem); // //send new post as JSon response // res.json(newBlogItem); // }); // //modify specific array object // app.put('/api/posts/:id', function(req, res) { // var targetId = parseInt(req.params.id); // //find item in blog archive array that matches the id // var targetPost = _.findWhere(posts, {id:targetId}); // //update the blog // targetPost.blog = req.body.blog; // // update the blog comments // targetPost.comment = req.body.comment; // //send back edited object // res.json(targetPost); // }); // //delete blog post from archive // app.delete('/api/posts/:id', function(req, res) { // //set the value of the id to be deleted // var targetId = parseInt(req.params.id); // //find item in blog archive array matches the id // var deletePost = _.findWhere(posts, {id:targetId}); // //get the index of the blog item to be deleted // var index = posts.indexOf(deletePost); // //remove the item at that index, only remove 1 item // posts.splice(index, 1); // //send back deleted object // res.json(deletePost); // }); app.listen(3000, function (){ console.log('server started at localhost: 3000'); })
class Label extends Widget { constructor(centerPos, text, textSize, scaleMult=1, size=new p5.Vector(0, 0)) { var topLeftPos = p5.Vector.sub(centerPos, p5.Vector.div(size, 2)); super(topLeftPos, size, text, textSize, scaleMult); } draw(translation=new p5.Vector(0, 0)) { push(); scale(this.scaleMult); translate(translation); this.setupTextSize(); this.setupTextColor(); this.setupTextOutline(); text(this.text, this.topLeftPos.x + this.size.x / 2, this.topLeftPos.y + this.size.y / 2); pop(); } }
{ modalLabelImport: 'Paste all your code here below and click import', modalLabelExport: 'Copy the code and use it wherever you want', codeViewerTheme: 'material', categoryLabel: 'Basic', importPlaceholder: '<table class="table"><tr><td class="cell">Paste all your code here below and click import</td></tr></table>', cellStyle: { 'font-size': '12px', 'font-weight': 300, 'vertical-align': 'top', color: 'rgb(111, 119, 125)', margin: 0, padding: 0, } }
import React from 'react'; import s from '../styles/navBar.style'; import { withRouter } from "react-router-dom"; // font icons import FontIcon from 'material-ui/FontIcon'; import {blueGrey50, deepPurple800, blue500} from 'material-ui/styles/colors'; // buttons import IconButton from 'material-ui/IconButton'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; const iconStyles = { }; class NavBar extends React.Component { constructor(props) { super(props); this.state = { homePath: '/home', usagePath: '/usage', communityPath: '/community', profilePath: '/profile', default: '/', open: false } this.handleOpen = this.handleOpen.bind(this); } handleOpen(event, path) { if (!this.props.loginStatus) { this.setState({open: true}); } else { this.props.history.push(path); } } handleClose = () => { this.setState({open: false}); }; handleLogin = () => { this.props.history.push('/home'); this.setState({open: false}); } render() { const actions = [ <FlatButton label="Cancel" primary={true} onClick={this.handleClose} />, <FlatButton label="Confirm" primary={true} onClick={this.handleLogin} />, ]; return ( <div> <div> <Dialog title="Are you sure?" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} contentStyle={s.dialog} > Login without an account. </Dialog> </div> <div style={s.navBar}> <IconButton style={s.button} tooltip='Home' tooltipPosition='top-center' touch={true} onClick={(e) => this.handleOpen(e, this.state.homePath)} > <FontIcon className="material-icons" style={iconStyles} color={blueGrey50}>home</FontIcon> </IconButton> <IconButton style={s.button} tooltip='Usage' tooltipPosition='top-center' touch={true} onClick={(e) => this.handleOpen(e, this.state.usagePath)} > <FontIcon className="material-icons" style={iconStyles} color={blueGrey50}>trending_up</FontIcon> </IconButton> <IconButton style={s.button} tooltip='Community' tooltipPosition='top-center' touch={true} onClick={(e) => this.handleOpen(e, this.state.communityPath)} > <FontIcon className="material-icons" style={iconStyles} color={blueGrey50}>group</FontIcon> </IconButton> <IconButton style={s.button} tooltip='Profile' tooltipPosition='top-center' touch={true} onClick={(e) => this.handleOpen(e, this.state.profilePath)} > <FontIcon className="material-icons" style={iconStyles} color={blueGrey50}>person_pin</FontIcon> </IconButton> </div> </div> ); } } export default withRouter(NavBar);
var _viewer = this; jQuery("#ou-topPic").remove(); jQuery(".header").remove(); jQuery("#SY_GAVE_AUTH_AGENT-winTabs").children().first().remove(); jQuery("#SY_GAVE_AUTH_AGENT-save").children().first().text("授权"); var souUser = _viewer.getItem("SOURCE_USER_NAME"); var deptName = _viewer.getItem("DEPT_NAME"); var curUser = _viewer.getItem("CURRENT_USER_NAME"); var begDate = _viewer.getItem("BEG_DATE"); var begHour = _viewer.getItem("BEG_HOUR"); var endDate = _viewer.getItem("END_DATE"); var endHour = _viewer.getItem("END_HOUR"); initHourData(); // 获取当前用户的权限字段信息 var roleCode=System.getVar("@ROLE_CODES@"); var adminRoleCode = System.getVar("@C_SY_ADMIN_ROLE_CODE@"); if (adminRoleCode == null || adminRoleCode == "") { adminRoleCode = "RADMIN"; } if(roleCode.indexOf(adminRoleCode)<0){ // 非系统管理员,弹出提示 jQuery("#SY_GAVE_AUTH_AGENT-save").unbind("click").bind("click", function() { alert("非系统管理员,没有权限代授权"); }); } else { // 添加授权按钮监听 jQuery("#SY_GAVE_AUTH_AGENT-save").unbind("click").bind("click", function() { var souUserValue = souUser.getValue(); var deptNameValue = deptName.getValue(); var curUserValue = curUser.getValue(); var begDateValue = begDate.getValue(); var begHourValue = begHour.getValue(); var endDateValue = endDate.getValue(); var endHourValue = endHour.getValue(); if (souUserValue == null || souUserValue == "") { alert("获取授权人为空,请检查授权人框的输入!"); return; } if (deptNameValue == null || deptNameValue == "") { alert("获取机构为空,请检查机构框的输入!"); return; } if (curUserValue == null || curUserValue == "") { alert("获取受权人为空,请检查受权人框的输入!"); return; } if ((begDateValue == null || begDateValue == "") || (begHourValue == null || begHourValue.length < 2)) { alert("获取开始时间有误,请检查开始时间框的输入!"); return; } if ((endDateValue == null || endDateValue == "") || (endHourValue == null || endHourValue.length < 2)) { alert("获取结束时间有误,请检查开始时间框的输入!"); return; } var nowDateParam = getNowFormatDate(); var nowDateTime = nowDateParam.CUR_DATE + " " + nowDateParam.CUR_HOUR; var begDateTime = begDateValue + " " + begHourValue.substring(0,2); var endDateTime = endDateValue + " " + endHourValue.substring(0,2); if (begDateTime < nowDateTime) { alert("开始时间输入有误,请输入当前时间或者之后的时间!"); return; } if (endDateTime <= begDateTime) { alert("结束时间输入有误,结束时间要在开始时间之后!"); return; } var souUserId = JSON.parse(souUser.getValue()).value; var deptCode = JSON.parse(deptName.getValue()).value; var curUserId = JSON.parse(curUser.getValue()).value; var param = { SOURCE_USER_ID : souUserId, DEPT_CODE : deptCode, CURRENT_USER_ID : curUserId, BEG_DATE : begDateTime, END_DATE : endDateTime } var result = FireFly.doAct("SY_GAVE_AUTH_AGENT", "gaveDeptAuth", param, true); if (result['_MSG_'].indexOf('ERROR') >= 0) { var resultStr = result['_MSG_'].split(","); if (resultStr.length > 1) { alert(resultStr[1]); } else { alert("授权失败!"); } return; } _viewer.refresh(); alert("授权成功!"); }); } function getNowFormatDate() { var date = new Date(); var seperator = "-"; var month = date.getMonth() + 1; var strDate = date.getDate(); var day = date.getDay(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = date.getFullYear() + seperator + month + seperator + strDate; var currentHour = date.getHours(); if (currentHour >= 0 && currentHour <= 9) { currentHour = "0" + currentHour; } var param = { CUR_DATE : currentdate, CUR_HOUR : currentHour } return param; } function initHourData(){ var hour = getNowFormatDate().CUR_HOUR; begHour.setValue(hour + ":00"); endHour.setValue(hour + ":00"); }
const URL = "http://localhost:3000/a_cappella_groups" const acgList = new ACappellaList () fetch(URL) .then (res => res.json()) .then (groups => acgList.createList(groups)) .then (() => acgList.renderList())
// var mongoose = require('mongoose'); // // Create a blueprint for the monsters // var wordSchema = mongoose.Schema({ // name: String, // }); // // Export the created model connection to our schema // module.exports = mongoose.model('word', wordSchema);
var covid,covidImage,mask,maskImage,warrior,warriorImage; var gamestate = PLAY; var PLAY = 1; var END = 0; function preload() { covidImage = loadImage("covid.png"); maskImage = loadImage("mask.png"); warriorImage = loadImage("covid warrior.png") } function setup() { createCanvas(400,400); if(gamestate === PLAY){ covid = createSprite(200,0,200,200); covid.addImage("covid",covidImage); covid.velocityY = 3; covid.scale = 0.3; warrior = createSprite(200,350,200,200); warrior.addImage("warrior",warriorImage); warrior.scale = 0.3; mask = createSprite(300,0,200,200); mask.addImage("mask",maskImage); mask.scale = 0.3; } } function draw() { background(48,48,48); if(gamestate === PLAY){ warrior.x = mouseX; warrior.y = mouseY; if(warrior.isTouching(covid)){ covid.y = 0; text("gameover",200,200); covid.velocityY = 0; gamestate = END; } } drawSprites(); }
import React from 'react'; import { Route } from 'react-router'; import TitleContainer from 'app/react/containers/title'; const routes = ( <div> <Route path="*" component={TitleContainer} /> </div> ); export default routes;
module.exports = { title: 'JavaScript入門1', subtitle: '変数5', language: 'javascript', defaultValue: `function hello() { // キーワードletを使って変数value1に文字列"Hello let!"をしまってみよう // 変数value1の中身を出力してみよう // 変数value1に文字列"Hello let2!"を再代入してみよう // 変数value1の中身を出力してみよう } hello() `, answer: `function hello() { // キーワードletを使って変数value1に文字列"Hello let!"をしまってみよう let value1 = "Hello let!" // 変数value1の中身を出力してみよう console.log(value1) // 変数value1に文字列"Hello let2!"を再代入してみよう value1 = "Hello let2!" // 変数value1の中身を出力してみよう console.log(value1) } hello() `, correctOutput: 'Hello let!Hello let2!', nextLessonId: null }
import React, { Component } from 'react' import { connect } from 'react-redux' import { push } from 'react-router-redux' import { createStructuredSelector } from 'reselect' import { closeTrezorWindow } from 'Utilities/wallet' import toastr from 'Utilities/toastrWrapper' import log from 'Utilities/log' import { getAllSwapsArray, doesCurrentSwundleRequireSigning, isCurrentSwundleReadyToSign, isCurrentSwundleReadyToSend, } from 'Selectors' import { signSwapTxs, sendSwapTxs } from 'Actions/swap' import { resetSwaps } from 'Actions/swap' import { toggleOrderModal } from 'Actions/orderModal' import SwapSubmitModalView from './view' class SwapSubmitModal extends Component { constructor (props) { super(props) this.state = { startedSigning: false, startedSending: false, } this.handleCancel = this.handleCancel.bind(this) this.handleSignTxs = this.handleSignTxs.bind(this) this.handleSendTxs = this.handleSendTxs.bind(this) } handleCancel () { const { toggle, resetSwaps } = this.props this.setState({ startedSigning: false }) closeTrezorWindow() toggle() resetSwaps() } handleSignTxs () { const { swaps, signSwapTxs } = this.props this.setState({ startedSigning: true }) signSwapTxs(swaps) .catch((e) => { toastr.error(e.message || e) log.error(e) closeTrezorWindow() }) } handleSendTxs () { const { swaps, sendSwapTxs, toggle, routerPush } = this.props this.setState({ startedSending: true }) sendSwapTxs(swaps) .then((updatedSwaps) => { if (updatedSwaps.every((swap) => swap.tx.sent)) { toggle() routerPush('/dashboard') } }) .catch((e) => { toastr.error(e.message || e) log.error(e) }) } render () { const { requiresSigning, readyToSign, readyToSend } = this.props const { startedSigning, startedSending } = this.state const showSubmit = !requiresSigning || startedSigning // True if continue button triggers tx sending, false for signing const continueDisabled = showSubmit ? (!readyToSend || startedSending) : (!readyToSign || startedSigning) const continueLoading = showSubmit ? startedSending : startedSigning const continueHandler = showSubmit ? this.handleSendTxs : this.handleSignTxs const continueText = showSubmit ? 'Submit all' : 'Begin signing' const headerText = showSubmit ? 'Confirm and Submit' : 'Review and Sign' return ( <SwapSubmitModalView headerText={headerText} continueDisabled={continueDisabled} continueLoading={continueLoading} continueText={continueText} handleContinue={continueHandler} handleCancel={this.handleCancel} {...this.props} /> ) } } const mapStateToProps = createStructuredSelector({ swaps: getAllSwapsArray, requiresSigning: doesCurrentSwundleRequireSigning, readyToSign: isCurrentSwundleReadyToSign, readyToSend: isCurrentSwundleReadyToSend, isOpen: ({ orderModal: { show } }) => show }) const mapDispatchToProps = { resetSwaps, toggle: toggleOrderModal, signSwapTxs, sendSwapTxs, routerPush: push, } export default connect(mapStateToProps, mapDispatchToProps)(SwapSubmitModal)
/** Requires */ const cluster = require('cluster'); const numCPUs = require('os').cpus().length; const threads = process.env.NODE_ENV === 'development' ? 1 : numCPUs - 1; const context = require('./init/context'); const server = require('./init/server'); /** Cluster */ if (cluster.isMaster) { for (let i = 0; i < threads; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker exited: ${worker.id} \nCode: ${code} \nSignal: ${signal}`); // Forks a new process if app crashes if (code !== 0) { cluster.fork(); } }); cluster.on('online', (worker) => { console.log(`Worker online: ${worker.id}`); }); cluster.on('listening', (worker, address) => { console.log(`Worker: ${worker.id}, in listening to address: ${address}`); }); } else if (cluster.isWorker) { // Main logic // Init (async () => { try { // Context const appCtx = await context.init(); console.log('Context initiated successfully'); // Server server.init(appCtx); // process.exit(1); } catch (err) { console.log('@main->err', err); } })(); // Handles uncaught exception process.on('uncaughtException', (err) => { console.log(`Uncaught exception in a thread : ${JSON.stringify(err)}`); throw err; }); // Process exits process.on('exit', () => { console.log('Thread exits'); }); }
import styled from 'styled-components'; import { Flex } from '@rebass/grid'; import { colors } from '../../style/theme'; const Outer = styled.header` position: fixed; left: 0; top: 0; right: 0; height: 80px; z-index: 200; background-color: white; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1); .logo { height: 80px; .brand { font-size: 24px; font-weight: 700; span { color: ${colors.primary}; } } } .action { font-size: 36px; outline: none; line-height: 0; padding: 0; cursor: pointer; transition: 0.2s; &, &:active, &:visited, &:focus { color: ${colors.font}; } &:hover { color: ${colors.primary}; } & + .action { margin-left: 15px; } } `; const Info = styled(Flex)` .libs { margin: 20px -5px 0; width: calc(100% + 15px); .lib { text-decoration: none; text-align: center; display: flex; justify-content: center; align-items: center; width: calc(33.33% - 15px); height: 50px; background-color: ${colors.primary}; border-radius: 3px; margin: 7.5px; transition: 0.25s; &, &:active, &:hover, &:visited { color: white; } &:hover { background-color: ${colors.primary_darken}; } } } `; export { Outer, Info };
const express = require('express') const app = express() var con = require('./model/mysql_connector.js') app.set('views','./views'); app.set('view engine', 'pug'); app.get('/', function (req, res){ console.log("Home page accessed") res.render('home', {guestname: ''}) }) app.get('/login', function (req, res){ console.log("User at /login") res.render('login') }) //list of available subjects app.get('/quizlist', function (req, res){ console.log("Quiz List page accessed") res.render('quizlist') }) app.get('/quiz', function (req, res){ console.log("Quiz page accessed") res.render('quiz') }) app.get('/math', function (req, res){ console.log("Math page accessed") res.render('math') }) //list of cool hobbies such as gardening cam, security cam app.get('/hobbies', function (req, res){ console.log("Hobbies page accessed") }) app.get('/garden', function (req, res){ console.log("Garden page accessed") res.render('garden') }) app.listen(3000, () => console.log ('Hello world app listening on port 3000!'))
module.exports = class asyncFuncs { resolveAfter2Seconds() { return new Promise(resolve => { //setTimeout not required, only used here to simulate a time consuming process. //resolve(your function / data) is required. setTimeout(() => { resolve({ output1: 'Hello', output2: 'World'}); }, 2000); }); } async asyncCall() { console.log('calling'); const result = await this.resolveAfter2Seconds(); console.log(`${result.output1} ${result.output2}`); // expected output: "resolved" } }
import React from 'react'; import ToggleShow from "./toogleShow"; class Contact extends React.Component { constructor(props) { super(props); this.state={ greeting:'Good Evening, Sorry to we missed you sir', contactPerson:'React JS', arr:[1,2,3] } } render() { console.log(this); return ( <div> <ToggleShow greeting={this.state.greeting} contactPerson={this.state.contactPerson} /> <h1>Contact</h1> </div> ) } } export default Contact;
import { doesRoleUseSemanticallyInteractiveTag } from '../utils/roleUtils'; describe('Roles', () => { describe('doesRoleUseSemanticallyInteractiveTag', () => { it('returns true for interactive tags', () => { expect(doesRoleUseSemanticallyInteractiveTag('link')).toEqual(true); expect( doesRoleUseSemanticallyInteractiveTag('multiselectlistbox') ).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('checkbox')).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('radio')).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('searchbox')).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('slider')).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('spinbutton')).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('multilinetextbox')).toEqual( true ); expect(doesRoleUseSemanticallyInteractiveTag('button')).toEqual(true); expect(doesRoleUseSemanticallyInteractiveTag('switch')).toEqual(true); }); it('returns false for non-interactive tags', () => { expect(doesRoleUseSemanticallyInteractiveTag('article')).toEqual(false); expect(doesRoleUseSemanticallyInteractiveTag('img')).toEqual(false); expect(doesRoleUseSemanticallyInteractiveTag('span')).toEqual(false); expect(doesRoleUseSemanticallyInteractiveTag('table')).toEqual(false); }); }); });
// 定义名为 todo-item 的新组件 Vue.component('todo-item', { template: '<li>这是个待办项</li>' })
import * as actions from '../actions/types'; const initialState = { report: [], loading: false } const reportReducer = (state = initialState, action) => { switch(action.type) { case actions.GET_REPORT: return { ...state, report: action.payload, loading: false } case actions.REPORT_LOADING: return { ...state, loading: true } default: return state } } export default reportReducer;
/** * jTinder initialization */ var likedComments = ["Good pick!", "OMG!", "Yay!", "Liked!", "<3"]; var dislikedComments = ["Whattt?", "Seriously?", "Ouch..", "Regret now?"]; $("#tinderslide").jTinder({ // dislike callback onDislike: function (item) { // set the status text var text = _.sample(dislikedComments, 1); $('#status').html(text); }, // like callback onLike: function (item) { // set the status text var text = _.sample(likedComments, 1); $('#status').html(text); }, animationRevertSpeed: 200, animationSpeed: 400, threshold: 1, likeSelector: '.like', dislikeSelector: '.dislike' }); /** * Set button action to trigger jTinder like & dislike. */ $('.actions .like, .actions .dislike').click(function(e){ e.preventDefault(); $("#tinderslide").jTinder($(this).attr('class')); });
let button = document.getElementById('btn-mostrar'); button.addEventListener('click', mostrarMais) function mostrarMais(){ document.querySelector('.mais-noticias').style.display = "block" }
import Home from './Home'; import EndRegistration from './EndRegistration'; import Settings from './Settings'; import Timetable from './Timetable'; import NotFound from './NotFound'; export { Home, EndRegistration, Settings, Timetable, NotFound };
import React, { useEffect, useState } from 'react'; import Axios from 'axios'; import { Col, Image, Typography, Rate, Divider } from 'antd'; import ReviewGrid from './ReviewGrid'; import DetailWaitlist from './DetailWaitlist'; import Commons from '../../img/Commons.jpg'; import TwoThreeOOne from '../../img/2301.jpg'; import EBI from '../../img/EBI.jpg'; import Kissam from '../../img/Kissam.jpg'; import Rand from '../../img/Rand.jpg'; import Zeppos from '../../img/Zeppos.jpg'; import './ReviewDetail.css'; const { Title } = Typography function ReviewDetail(props) { const [Reviews, setReviews] = useState([]); const diningName = props.location.name; const rating = props.location.rating; useEffect(() => { let body = { location: diningName } Axios.post('/api/Reviews/getReview', body) .then(response => { setReviews(response.data); }) }, []) return ( <div className='app'> <div className='review_container'> <Col lg={24} md={24} xs={24} style={{ height: '200px', display: 'flex' }}> {diningName === 'Commons' && <Image style={{ width: '230px', height: '230px', marginTop: '10px', marginLeft: '35px' }} src={Commons} alt='' /> } {diningName === '2301' && <Image style={{ width: '230px', height: '230px', marginTop: '10px', marginLeft: '35px' }} src={TwoThreeOOne} alt='' /> } {diningName === 'EBI' && <Image style={{ width: '230px', height: '230px', marginTop: '10px', marginLeft: '35px' }} src={EBI} alt='' /> } {diningName === 'Kissam' && <Image style={{ width: '230px', height: '230px', marginTop: '10px', marginLeft: '35px' }} src={Kissam} alt='' /> } {diningName === 'Rand' && <Image style={{ width: '230px', height: '230px', marginTop: '10px', marginLeft: '35px' }} src={Rand} alt='' /> } {diningName === 'Zeppos' && <Image style={{ width: '230px', height: '230px', marginTop: '10px', marginLeft: '35px' }} src={Zeppos} alt='' /> } <div className='dining_info_review'> <Title level={1} style={{ marginTop: '30px' }}>{props.location.name}</Title> <div className='rating_and_waitlist_review'> <div> <Title level={3}> Current Rating : {rating.toFixed(2)}</Title> <Rate disabled allowHalf defaultValue={0} value={Math.round(rating / 2.0)} /> </div> <br /> <DetailWaitlist name={props.location.name}/> </div> </div> </Col> <br /> <div className='reviews'> {Reviews && Reviews.map((Review, index) => { return( <React.Fragment key={index}> <Divider style={{margin : '0 0'}}/> <ReviewGrid Rating={Review.rating} Comment={Review.comment}/> </React.Fragment> ) })} </div> </div> </div> ) } export default ReviewDetail
'use strict' var chalk = require('chalk') var constants = require('../constants') var User = require('../user') var Points = require('./points') var _ = require('lodash') var log = global.log var translate = global.translate function Price () { if (global.configuration.get().systems.points === true && global.configuration.get().systems.price === true) { global.parser.register(this, '!price set', this.set, constants.OWNER_ONLY) global.parser.register(this, '!price list', this.list, constants.OWNER_ONLY) global.parser.register(this, '!price unset', this.unset, constants.OWNER_ONLY) global.parser.register(this, '!price', this.help, constants.OWNER_ONLY) global.parser.registerParser(this, 'price', this.checkPrice, constants.VIEWERS) } log.info('Price system ' + translate('core.loaded') + ' ' + (global.configuration.get().systems.price === true && global.configuration.get().systems.points === true ? chalk.green('enabled') : chalk.red('disabled'))) } Price.prototype.help = function (self, sender) { global.commons.sendMessage(translate('core.usage') + ': !price set <cmd> <price> | !price unset <cmd> | !price list', sender) } Price.prototype.set = function (self, sender, text) { try { var parsed = text.match(/^(\w+) ([0-9]+)$/) global.botDB.update({_id: 'price_' + parsed[1]}, {$set: {command: parsed[1], price: parsed[2]}}, {upsert: true}) global.commons.sendMessage(translate('price.success.set') .replace('(command)', parsed[1]) .replace('(amount)', parsed[2]) .replace('(pointsName)', Points.getPointsName(parsed[2])), sender) } catch (e) { global.commons.sendMessage(translate('price.failed.parse'), sender) } } Price.prototype.unset = function (self, sender, text) { try { var parsed = text.match(/^(\w+)$/) global.botDB.remove({_id: 'price_' + parsed[1], command: parsed[1]}, {}, function (err, numRemoved) { if (err) log.error(err) var message = (numRemoved === 0 ? translate('price.failed.remove') : translate('price.success.remove')) global.commons.sendMessage(message.replace('(command)', parsed[1]), sender) }) } catch (e) { global.commons.sendMessage(translate('price.failed.parse'), sender) } } Price.prototype.list = function (self, sender, text) { var parsed = text.match(/^(\w+)$/) if (_.isNull(parsed)) { global.botDB.find({$where: function () { return this._id.startsWith('price') }}, function (err, docs) { if (err) { log.error(err) } var commands = [] docs.forEach(function (e, i, ar) { commands.push(e.command) }) var output = (docs.length === 0 ? translate('price.failed.list') : translate('price.success.list') + ': ' + commands.join(', ')) global.commons.sendMessage(output, sender) }) } else { global.commons.sendMessage(translate('price.failed.parse', sender)) } } Price.prototype.checkPrice = function (self, id, sender, text) { try { var parsed = text.match(/^!(\w+)/) global.botDB.findOne({_id: 'price_' + parsed[1]}, function (err, item) { if (err) log.error(err) if (!_.isNull(item)) { var user = new User(sender.username) user.isLoaded().then(function () { var availablePts = parseInt(user.get('points'), 10) var removePts = parseInt(item.price, 10) var command = item.command if (availablePts < removePts) { global.updateQueue(id, false) global.commons.sendMessage(translate('price.failed.notEnough') .replace('(amount)', removePts) .replace('(command)', command) .replace('(pointsName)', Points.getPointsName(removePts)), sender) } else { user.set('points', availablePts - removePts) global.updateQueue(id, true) } }) } else { global.updateQueue(id, true) } }) } catch (err) { global.updateQueue(id, true) // it's not a command -> no price } } module.exports = new Price()
const inquirer = require("inquirer"); const fs = require("fs"); const { engineerPrompts, internPrompts, managerPrompts } = require("./prompt/prompts"); const Engineer = require("./classes/Engineer.js"); const Intern = require("./classes/Intern.js"); const Manager = require("./classes/Manager.js"); const teamArray = [] init(); function writeToFile(fileName, data) { console.log(data); // basic layout of html // iterate through the teamArray // create html for each employee // add it to the html // write it to the file let html = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My custom Bulma website</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css"> </head> <body> `; // add the employees // for loop () // html += html += ` </body> </html> `; //fs.writeFile(fileName, generateHTML(data), () => { }); }; function init() { managerPrompts().then(function (manager) { const newManager = new Manager(manager.employeeId, manager.employeeName, manager.employeeEmail, manager.officeNum) teamArray.push(newManager) employeeInfo(); }) }; function employeeInfo() { inquirer.prompt({ type: "list", name: "type", message: "What employee are we adding?", choices: ["Engineer", "Intern", "I'm Done"], }) .then(function (employee) { switch (employee.type) { case "Engineer": return engineerPrompts().then(function (engineer) { console.log(engineer) // employeeInfo(); let newEngineer = new Engineer(engineer.id, engineer.name, engineer.email, engineer.github) teamArray.push(newEngineer) console.log(newEngineer) employeeInfo(); }); case "Intern": return internPrompts().then(function (intern) { let newIntern = new Intern(intern.employeeName, intern.employeeId, intern.employeeEmail, intern.school) teamArray.push(newIntern) employeeInfo(); }); case "Im Done": writeToFile(); default: } }) }
const path = require('path'); const os = require('os'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const WebpackBar = require('webpackbar'); // 获取文件路径,相对于根目录 const getFileUrl = url => path.resolve(__dirname, `../${url}`); // 是否是生产 const isProduction = process.env.NODE_ENV === 'production'; // 入口配置 const getEntry = () => { const initEntry = { hot: 'react-hot-loader/patch', app: getFileUrl('/src/index.js'), }; if (isProduction) { Reflect.deleteProperty(initEntry, 'hot'); } return initEntry; }; // 开发环境server配置 const getDevServer = () => { if (isProduction) { return {}; } return { static: false, compress: true, static: './dist', port: 8080, hot: true, client: { logging: 'error', }, proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: { '^/api': '' }, }, }, }; }; // 插件配置 const getPlugins = () => { const normalPlugins = [ new HtmlWebpackPlugin({ title: '页面默认标题', env: process.env.NODE_ENV, description: '页面描述', filename: 'index.html', template: getFileUrl('/src/index.html'), minify: false, }), new WebpackBar(), ]; if (isProduction) { normalPlugins.push(new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash].css', chunkFilename: '[id].css' })); } return normalPlugins; }; const config = { entry: getEntry(), output: { path: getFileUrl('/dist'), filename: 'js/[name].[contenthash].js', clean: true, }, module: { rules: [ { test: /\.ts|tsx|js$/, exclude: [/(node_modules)/], use: [ { loader: 'thread-loader', options: { workers: os.cpus(), }, }, { loader: 'babel-loader', options: { cacheDirectory: true, }, }, ], }, { test: /\.css|less/, use: [ isProduction ? MiniCssExtractPlugin.loader : 'style-loader', { loader: 'css-loader', options: { importLoaders: 2, modules: { localIdentName: '[name]__[local]--[hash:base64:5]', }, }, }, 'postcss-loader', 'less-loader', ], }, { test: /\.(jpg|png|jpe?g|gif|svg)(\?.*)?$/i, use: [ { loader: 'url-loader', options: { outputPath: 'images', // 输出目录 limit: 3 * 1024, }, }, ], }, { test: /\.(eot|woff2?|ttf|svg)$/, use: [ { loader: 'url-loader', options: { name: '[name]-[hash:5].min.[ext]', limit: 5000, outputPath: 'fonts', }, }, ], }, ], }, optimization: { usedExports: true, minimize: true, minimizer: [ new TerserPlugin({ parallel: true, terserOptions: { format: { comments: false, }, }, extractComments: false, }), ], splitChunks: { cacheGroups: { commons: { name: 'commons', chunks: 'initial', minChunks: 2, reuseExistingChunk: true, priority: -20, }, vendors: { test: /[\\/]node_modules[\\/]/, name: 'vendors', priority: -10, chunks: 'all', }, }, }, }, stats: isProduction ? 'normal' : 'errors-only', resolve: { alias: { '@@': getFileUrl('/src'), }, extensions: ['.tsx', '.ts', '.js'], }, // externals: { // react: 'react', // 'react-dom': 'react-dom', // }, devtool: isProduction ? 'hidden-source-map' : 'eval-source-map', devServer: getDevServer(), plugins: getPlugins(), // module: { // noParse: /jquery|lodash/, // }, }; module.exports = config;
"use strict"; function InviteInit() { require(['settings', 'translator'], function (settings, translator) { var uninvitedGroup, invitedGroup, invitedUsers, Invite = { }; translator.translate("[[invite:uninvite]]", function (translation) { Invite.strUninvite = translation; }); translator.translate("[[invite:resend]]", function (translation) { Invite.strResend = translation; }); function saveInvites() { // Use the DOM to determine the new invite list. var invitedUsers = [ ]; $('.user-email').each(function(){ console.log($(this).html()); invitedUsers.push($(this).html()); }); // Save the invite list and invite groups to the db. settings.save('newuser-invitation', $('.newuser-invitation-settings'), function () { socket.emit('plugins.invitation.setInvitedUsers', {users: invitedUsers}, function () { }); }); } // For saving the invite groups. $('#save').on('click', function (e) { e.preventDefault(); console.log("aaaa"); saveInvites(); }); // Load the invite list. socket.emit('admin.settings.get', { hash: 'newuser-invitation' }, function(err, values) { if (err) { console.log('Unable to load settings'); } else { $('#users-container').empty(); if (values.invitedUsers) { values.invitedUsers = JSON.parse(values.invitedUsers); for (var x = 0; x < values.invitedUsers.length; x++) { addInvite(values.invitedUsers[x]); } } //invitedGroup = values.invitedGroup; //uninvitedGroup = values.uninvitedGroup; } // Load the invite groups. settings.load('newuser-invitation', $('.newuser-invitation-settings')); }); // Add the invited user to the invited users table. function addInvite(email) { var html = $('<tr />').attr('class', 'users-invite'); html.append($('<td />').append($('<span />').attr('class', 'user-email').html(email))); html.append($('<td />').attr('class','text-right') .append($('<button />').attr('class', 'user-uninvite btn btn-warning').html(Invite.strUninvite)) .append($('<button />').attr('class', 'user-reinvite btn btn-success').html(Invite.strResend))); $('#users-container').append(html); } $('#new-user-invite-send').on('click', function() { var email = $('#new-user-invite-user').val(), emails = [], matches, exists; matches = email.match(/[^,"\n\r]*@[^,"\n\r]+\.[^,"\n\r]+/g); $.each(matches, function(i, el){ el = el.replace(/ /g, ''); if($.inArray(el, emails) === -1) emails.push(el); }); emails.forEach(function (email) { $('.user-email').each(function(){ if ($(this).html().trim() === email) { exists = true; } }); if (exists) { app.alert({ type: 'warning', alert_id: 'newuser-invitation-failed-' + email.replace(/[@\.]/g, '_'), title: "User " + email + ' was already invited.', timeout: 5000 }); }else{ socket.emit('plugins.invitation.check', {email:email}, function (err) { if (!err) { addInvite(email); saveInvites(); app.alert({ type: 'success', alert_id: 'newuser-invitation-success-' + email.replace(/[@\.]/g, '_'), title: 'Sent invitation to ' + email, timeout: 5000 }); }else{ app.alert({ type: 'danger', alert_id: 'newuser-invitation-failed-' + email.replace(/[@\.]/g, '_'), title: "Invitation to " + email + " failed.", message: err.message, timeout: 8000 }); } }); } }); }); function reinvite(email) { socket.emit('plugins.invitation.send', {email:email}, function (err) { if (!err) { app.alert({ type: 'success', alert_id: 'newuser-invitation-success-' + email.replace(/[@\.]/g, '_'), title: 'Re-sent invitation to ' + email, timeout: 5000 }); }else{ app.alert({ type: 'danger', alert_id: 'newuser-invitation-failed-' + email.replace(/[@\.]/g, '_'), title: "Re-invite to " + email + " failed.", message: err.message, timeout: 8000 }); } }); } $('#users-container').on('click', '.user-uninvite', function () { $(this).closest('tr').remove(); saveInvites(); }); $('#users-container').on('click', '.user-reinvite', function () { reinvite($(this).closest('tr').find('.user-email').html().trim()); }); $('#bulk-uninvite').on('click', function() { bootbox.confirm("Are you sure? This will uninvite all invited users that have not yet accepted their invitation. This action is not reversible.", function (result) { if (result) { $('.user-email').each(function(){ $(this).closest('tr').remove(); }); saveInvites(); } }); }); $('#bulk-reinvite').on('click', function() { bootbox.confirm("Are you sure? This will reinvite all invited users that have not yet accepted their invitation.", function (result) { if (result) { $('.user-email').each(function(){ reinvite($(this).html().trim()); }); } }); }); }); } define('admin/plugins/newuser-invitation', function () { console.log("Loading NewUserInvitation..."); var Invite = { }; Invite.init = InviteInit; return Invite; });
module.exports = ({ message, client }) => { message.channel.send( `🏓 Latency is ${Date.now() - message.createdTimestamp} ms. API Latency is ${Math.round( client.ws.ping )} ms` ); };
define(['main'], function(ngApp) { 'use strict'; ngApp.provider.controller('ctrlPage', ['$scope', function($scope) {}]); });
// // // /* becode/javascript // * // * /02-maths/02-calculator-two/script.js - 2.2: calculatrice (2) // * // * coded by leny@BeCode // * started at 26/10/2018 // */ // // NOTE: don't focus on the existing code structure for now. // // You will have time to focus on it later. let a = 0; let b = 0; document.getElementById("addition").onclick = calculate; document.getElementById("substraction").onclick = calculate; document.getElementById("multiplication").onclick = calculate; document.getElementById("division").onclick = calculate; function calculate(a,b) { a = new Number(document.getElementById("op-one").value); b = new Number(document.getElementById("op-two").value); switch (calculate) { case 'addition': alert(calculate(a + b)); break; case 'substraction': alert(calculate(a - b)); break; case 'multiplication': alert(calculate(a * b)); break; case 'division': alert(calculate(a / b)); break; default: alert('please enter a valid number'); break; } } /* becode/javascript * * /02-maths/02-calculator-two/script.js - 2.2: calculatrice (2) * * coded by leny@BeCode * started at 26/10/2018 */ // NOTE: don't focus on the existing code structure for now. // You will have time to focus on it later.
import React from "react"; import styled from "styled-components"; import Icon from "./icon"; const Button = styled.div.attrs({ role: "button" })` top: 0; right: 0; padding: 0; opacity: 0.5; cursor: pointer; position: absolute; margin: ${props => props.theme.modal.margin}rem; color: ${props => props.theme.modal.closeButtonColor}; `; class CloseButton extends React.Component { render() { const { ...rest } = this.props; return ( <Button {...rest}> <Icon name="close" size="1" /> </Button> ); } } export default CloseButton;
"use strict"; //api key const apiKey = "MfwQqFxPzYw2yEtJ1DLGoJkJ0HrFXgHFaFuckoqO"; const searchURL = "https://developer.nps.gov/api/v1/parks?parkCode=acad&api_key=INSERT-API-KEY-HERE"; $(function() { $("#submit").on("click", event => { event.preventDefault(); let userLimit = $("#resultAmounts").val(); let userInput = $("#userRequest").val(); console.log(userInput); let URL = `https://developer.nps.gov/api/v1/parks?limit=${userLimit}&stateCode=${userInput}&api_key=MfwQqFxPzYw2yEtJ1DLGoJkJ0HrFXgHFaFuckoqO` console.log(URL) fetch(URL) .then(response => response.json()) .then(responseJson => { $("#response").empty() for (let i = 0; i < responseJson.data.length; i++) { let parkName = responseJson.data[i].name let description = responseJson.data[i].description let parkUrl = responseJson.data[i].url $("#response").append(` <p>${parkName}</p> <p>${description}</p> <p> <a href="${parkUrl}">${parkUrl}</a> </p> `) console.log(responseJson.data[i].states) } console.log(responseJson) }) }) })
const AWS = require('aws-sdk'); const DYNAMO_DB_PORT = process.env.DYNAMO_DB_PORT || '5001' const endpoint = `http://localhost:${DYNAMO_DB_PORT}` const dynamoDb = new AWS.DynamoDB({ apiVersion: '2012-08-10', endpoint, region: 'us-west-2', accessKeyId: '1232', secretAccessKey: '12344', sessionToken: '1234' }); const params = { AttributeDefinitions: [ { AttributeName: 'Slug', AttributeType: 'S', } ], KeySchema: [ { AttributeName: 'Slug', KeyType: 'HASH', } ], ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5, }, TableName: 'ShortUrl', }; dynamoDb.createTable(params).promise() .then(() => { console.log('Table Created: ShortUrl') }) .catch(() => { console.log('Table Creation Failed') })
const chokidar = require('chokidar'); function watch(dir, onChange) { const watcher = chokidar.watch(dir, { ignoreInitial: true, ignorePermissionErrors: true, }); watcher.on('change', onChange) .on('add', onChange) .on('unlink', onChange); } module.exports.watch = watch;
$('#Register_frm').on('submit', function (stop) { stop.preventDefault(); $fname = $('#fname').val(); $lname = $('#lname').val(); $email = $('#email').val(); $phone = $('#phone').val(); $pass = $('#password').val(); $cpass = $('#cpassword').val(); let userData = { firstname: $fname, lastname: $lname, email: $email, phone: $phone, password: $pass }; // if ($pass === $cpass) { // let datasend = { // firstname: $fname, // lastname: $lname, // email: $email, // phone: $phone, // password: $pass // } // console.log(datasend); // } else { // let notmatch = $('#notmatch'); // notmatch.html("password missmatch"); // } $.ajax({ type: 'post', url: 'http://localhost/api_demo/api/register.php', data: userData, dataType: 'json', success:function(response){ if (response.status == 'success') { alert(response.message); window.location.href = 'http://localhost/api_demo/api/skir-tech/pages/login.html' } else{ console.log(response.message); } }, error: function (xhr, status, msg) { console.log(msg); } }); }); //** login part **// $('#form1').on('submit', function (x) { x.preventDefault(); $userName = $('#username').val(); $pass = $('#password').val(); let info = { user_id: $userName, password:$pass, }; $.ajax({ type: 'post', url: 'http://localhost/api_demo/api/login.php', data: info, dataType: 'json', success: function (response) { if (response.status == 'success') { let mytoken = response.user.access_token; // Here ajax request was made inside this form to store the token // // $.ajax({ // type: 'post', // url: 'http://localhost/api_demo/session.php', // data: { // action: 'set_session', token: mytoken // }, // dataType: 'json', // success: function (response) { // console.log(response) // window.location.href = "http://localhost/api_demo/api/skir-tech/pages/home.html" // } // }); store_token(mytoken); } else { alert(response.message); } }, error: function(xhr, status, msg){ console.log(msg); } }); }); // Here is the external function created to store token // function store_token(tokenId) { let login_status = false; /*sir i dont understand the funtionality of this line of code*/ $.ajax({ type: 'post', url: 'http://localhost/api_demo/session.php', data: { action: 'set_session', token: tokenId}, dataType: 'json', success: function (response) { if (response.status == 'success') { window.location.href = 'http://localhost/api_demo/api/skir-tech/pages/home.html' } else { alert('Unexpected Error'); } }, error: function(xhr, status, msg){ console.log(msg); }, }); }; // // function to taget // $(document).ready(function () { // $.get('postpages/', function (response) { // $('#work_page').html(response); // }) // }) // $('#post_data a').on('click', function () { // $eachpage = $(this).attr('id') + '.html'; // $.get('postpages/' + $eachpage, function (response) { // $('#work_page').html(response); // console.log(response) // }); // }); ///* ajax request to retrieve token back from session*/// $.ajax({ type: 'post', url: 'http://localhost/api_demo/session.php', data: {action: 'get_session'}, dataType: 'json', async: false, /* whats the function fo this line */ success: function (response) { if (response.status == 'success') { let token = response.access_token; // save the token with an input element $('#mytoken').val(token); } else { location.href = 'http://localhost/api_demo/login.html'; } }, error: function(xhr, status, msg){ console.log(msg); }, }); $('#formadd').on('submit', function (e) { e.preventDefault(); $title = $('#title').val(); $body = $('#textarea').val(); $token = $('#mytoken').val(); let postdata = { action: 'save_post', title: $title, body: $body, token: $token }; $.ajax({ type: 'post', url: 'http://localhost/api_demo/api/manage_post.php', data: postdata, dataType: 'json', success: function (response) { if(response.status == 'success'){ alert(response.message); }else{ alert(response.message); } // console.log(response); } }) $.ajax({ type: 'post', url: 'http://localhost/api_demo/api/manage_post.php', data: { action: 'fetch_posts'}, dataType: 'json', success: function (response) { console.log(response) } }) });
import React from 'react'; import Routes from '../routes'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; const App = props => { const isAuthenticated = !!props.userData; const routes = Routes(isAuthenticated); return ( <> {routes} </> ); }; const mapStateToProps = state => ({ userData: state.auth.userData, }); export default withRouter(connect(mapStateToProps)(App));
import React from 'react'; import NavigationBar from '../components/NavigiationBar/NavigationBar'; import ResultList from '../components/ResultList/ResultList'; import axios from 'axios'; class Results extends React.Component { constructor(props) { super(props) this.state = { searchValue: props.location.state.searchValue, language: props.location.state.language, level: props.location.state.level, resultDocs: [], error: false } this.getResultDocs(); } getResultDocs = () => { // source: https://github.com/axios/axios // IMPORTANT: install this on chrome: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related axios.get(`http://localhost:8080/find&query=${this.state.searchValue}`) .then((response) => { // handle success this.setState({resultDocs: response.data}) }) .catch((error) =>{ // handle error this.setState({error: true}) }) .then(() =>{ // always executed }); } render() { return ( <div> <NavigationBar results values={[this.state.searchValue, this.state.language, this.state.level]} /> <ResultList error={this.state.error} resultDocs={this.state.resultDocs}/> </div> ); } } export default Results;
function(doc, meta) { if (/^BEER/.test(meta.id)) { emit(meta.id, null); } if (doc.type && doc.type == "beer") { //emit(doc.id,null); emit(doc.name, doc.id) } }