text
stringlengths
7
3.69M
import React, { Component } from 'react' import { Alert, Image, Linking, Platform, Text, View } from 'react-native' import PropTypes from 'prop-types' import get from 'lodash.get' import { AntDesign } from '@expo/vector-icons' import MetricLabel from '../MetricLabel' import Section from './Section' import styles from './style' function openMap(location) { if (location) { let mapUrl = Platform.OS === 'ios' ? 'http://maps.apple.com/?q=' : 'https://www.google.com/maps/place/' return Linking.openURL(mapUrl + location.split(' ').join('+')) } return Alert.alert('No Location') } export default class UserProfile extends Component { navigate(route, param) { this.props.navigation.navigate(route, { ...param, }) } render() { const { user } = this.props const followers = get(user, 'followers.totalCount') const following = get(user, 'following.totalCount') const repositories = get(user, 'repositories.totalCount') const stars = get(user, 'starredRepositories.totalCount') const infoList = [ { leftIcon: null, renderLabel: () => { return ( <View style={{ flexDirection: 'row' }}> <AntDesign name="team" size={26} style={styles.icon} /> <View> <Text>Company</Text> <Text style={[styles.smallText, styles.lightText]}> {user.company} </Text> </View> </View> ) }, }, { leftIcon: null, renderLabel: () => { return ( <View style={{ flexDirection: 'row' }}> <AntDesign name="find" size={26} style={styles.icon} /> <View> <Text>Location</Text> <Text style={[styles.smallText, styles.lightText]}> {user.location} </Text> </View> </View> ) }, onPress: () => { openMap(user.location) }, }, { leftIcon: null, renderLabel: () => { return ( <View style={{ flexDirection: 'row' }}> <AntDesign name="mail" size={26} style={styles.icon} /> <View> <Text>Email</Text> <Text style={[styles.smallText, styles.lightText]}> {user.email} </Text> </View> </View> ) }, onPress: () => { Linking.openURL(`mailto:${user.email}`) }, }, { leftIcon: null, renderLabel: () => { return ( <View style={{ flexDirection: 'row' }}> <AntDesign name="laptop" size={26} style={styles.icon} /> <View> <Text>Website</Text> <Text style={[styles.smallText, styles.lightText]}> {user.websiteUrl} </Text> </View> </View> ) }, onPress: () => { Linking.openURL(user.websiteUrl) }, }, ] // let orgList = [] if (!user) { return <Text>Error 🖖🏼</Text> } return ( <View style={styles.container}> <View style={styles.imageWrapper}> <Image style={styles.image} source={{ uri: user.avatarUrl }} /> <View style={styles.textContainer}> <View style={styles.textWrapper}> <Text style={[styles.bold]}>{user.name}</Text> <Text style={[styles.smallText, styles.handle]}> @{user.login} </Text> <Text style={[styles.bio]}>{user.bio}</Text> <View style={styles.bottomLinks}> <MetricLabel metric={repositories} label="Repositories" onPress={() => { this.navigate('Repositories', { repositories, login: user.login, }) }} /> <MetricLabel metric={stars} label="Stars" onPress={() => { this.navigate('Stars', { stars, login: user.login }) }} /> <MetricLabel metric={followers} label="Followers" onPress={() => { this.navigate('Followers', { followers, login: user.login }) }} /> <MetricLabel metric={following} label="Following" onPress={() => { this.navigate('Following', { following, login: user.login }) }} /> </View> </View> <Section title="Info" listItems={infoList} /> </View> </View> </View> ) } } UserProfile.propTypes = { user: PropTypes.object, navigation: PropTypes.object, }
#!/usr/bin/env node const getStdin = require('get-stdin'); const MessageFormat = require("messageformat"); (async () => { const input = (await getStdin()).trim(); let rawCatalog; try { rawCatalog = JSON.parse(input); } catch (e) { console.error(`Parsing the JSON failed: ${e.message}`); console.error(e); console.error(""); console.error("Input was:"); console.error(input); process.exit(1); } try { const messageFormat = new MessageFormat("de"); const catalogue = messageFormat.compile(rawCatalog, "de"); // the only way to get our desired output format is if a dot is in the `global` name. // So we use a object with a property. console.log(`(function(){ var r = {a: {}}; ${catalogue.toString("r.a")}; return r.a; })()`); process.exit(0); } catch (e) { console.error(`Compiling the catalogue failed: ${e.message}`); console.error(e); console.error(""); process.exit(1); } })();
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import VueRouter from 'vue-router' import routes from './router' import $ from 'webpack-zepto' import store from './vuex/user.js' import filters from './filters.js' import Alert from './lib/alert.js' Vue.use(VueRouter) Vue.use(Alert) $.ajaxSettings.crossDomain = true Object.keys(filters).forEach(k => Vue.filter(k, filters[k])); // Vue.config.productionTip = false const router = new VueRouter({ mode: 'history', routes }) /*这里控制了路由必须经过meta登录成功,才可以进入个别的页面*/ router.beforeEach((to, from, next) => { $('html, body, #page').removeClass('scroll-hide'); if (to.matched.some(record => record.meta.requiresAuth)) { if (store.state.userInfo.userId) { next(); } else { next({ path: '/login', query: {redirect: to.fullPath} }) } } else { next()//确保这里一定要调用next } }) /* eslint-disable no-new */ new Vue({ router, store }).$mount('#app')
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var HomepageDataSchema = new Schema({ aboutUsText: { type: String, default: '', trim: true }, aboutUsImage: { type: String, default: '', trim: true }, subscribeText: { type: String, default: '', trim: true }, subscribeImage: { type: String, default: '', trim: true }, individualProdText: { type: String, default: '', trim: true }, individualProdImage: { type: String, default: '', trim: true } }); mongoose.model('HomepageData', HomepageDataSchema);
/* * @lc app=leetcode.cn id=350 lang=javascript * * [350] 两个数组的交集 II * * https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/description/ * * algorithms * Easy (53.15%) * Likes: 425 * Dislikes: 0 * Total Accepted: 160K * Total Submissions: 298.8K * Testcase Example: '[1,2,2,1]\n[2,2]' * * 给定两个数组,编写一个函数来计算它们的交集。 * * * * 示例 1: * * 输入:nums1 = [1,2,2,1], nums2 = [2,2] * 输出:[2,2] * * * 示例 2: * * 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] * 输出:[4,9] * * * * 说明: * * * 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。 * 我们可以不考虑输出结果的顺序。 * * * 进阶: * * * 如果给定的数组已经排好序呢?你将如何优化你的算法? * 如果 nums1 的大小比 nums2 小很多,哪种方法更优? * 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办? * * */ // @lc code=start /** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersect = function(nums1, nums2) { let map = new Map(); for (let i = 0; i < nums1.length; i++) { map.set(nums1[i], map.has(nums1[i]) ? map.get(nums1[i]) + 1 : 1); } let res = []; for (let i = 0; i < nums2.length; i++) { if (map.has(nums2[i]) && map.get(nums2[i]) > 0) { map.set(nums2[i], map.get(nums2[i]) - 1); res.push(nums2[i]) } } return res; }; // @lc code=end
function noticeSave() { // 유효성 검사 // 파일 용량 체크 var fileName = document.getElementById('fileName_a').value; if (fileName != "") { var pathFileName = fileName.lastIndexOf(".") + 1; // 확장자 제외한 경로+파일명 var extension = (fileName.substr(pathFileName)).toLowerCase(); // 확장자명 // 파일명.확장자 if (extension == "exe" || extension == "jar" || extension == "zip") { alert(extension + " 형식 파일은 업로드 안됩니다."); return; } // 첨부 용량 체크 var file = document.getElementById('fileName_a'); if (file.value != "") { // 사이즈체크 var maxSize = 20 * 1024 * 1024; // 20MB // 브라우저 확인 var browser = navigator.appName; // 익스플로러일 경우 if (browser == "Microsoft Internet Explorer") { var oas = new ActiveXObject("Scripting.FileSystemObject"); fileSize = oas.getFile(file.value).size; } else { // 익스플로러가 아닐경우 fileSize = file.files[0].size; } if (fileSize > maxSize) { alert("첨부파일 사이즈는 20MB 이내로 등록 가능합니다. "); return; } } } }
/** * Created by cl-macmini-63 on 1/21/17. */ 'use strict'; const responseFormatter = require('Utils/responseformatter.js'); const masterServiceSchema = require('schema/mongo/masterserviceschema'); const gigServiceSchema = require('schema/mongo/gigsschema'); const serviceLocationMapper=require('schema/mongo/serviceLocationMapper') const SPprofileSchema=require('schema/mongo/SPprofile') const log = require('Utils/logger.js'); const logger = log.getLogger(); var async=require('async') var config=require('../config'); var AWS = config.amazon.s3 let commonFunction=require('Utils/commonfunction.js'); let mongoose=require('mongoose') module.exports = {}; var checkServiceByName = function(serviceName, callback){ masterServiceSchema.MasterService.findOne({'service_name':serviceName}, function (err, service) { console.log('Service returned', service); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { console.log("service",service); responseFormatter.formatServiceResponse((service ? service.toJSON() : null), callback); } }); }; module.exports.createMasterServices = function(payload , callback){ console.log("in model createMasterServices : payload ",payload); let dataToSave=payload let masterServiceRecord = new masterServiceSchema.MasterService(dataToSave); masterServiceRecord.service_id = masterServiceRecord._id; masterServiceRecord.service_name = payload.service_name; console.log('masterServiceRecord :: ',masterServiceRecord); let savedData=null async.series([ function(cb){ checkServiceByName(payload.service_name,function(response) { console.log('response :: ', response); if (response.status == 'error') { responseFormatter.formatServiceResponse({}, cb, "Error Occured.", 'error', 400); return; } //if service already exists if (response.data) { responseFormatter.formatServiceResponse({}, cb, "Service already registered with this name.", 'error', 409); return; } else { cb() } }); }, function(cb){ let x={} if (payload.hasOwnProperty("service_icon") && payload.service_icon) { x = payload.service_icon.filename; let tempPath = payload.service_icon.path; if(typeof payload.service_icon !== 'undefined' && payload.service_icon.length){ x = payload.service_icon[1].filename; tempPath = payload.service_icon[1].path; } let extension = x.split('.').pop(); let fileName=masterServiceRecord._id+"."+extension console.log("tempPath",fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { //let x = fileName; //let fileNameFirst = fileName.substr(0, x.lastIndexOf('.')); //let extension = x.split('.').pop(); masterServiceRecord.service_icon = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + masterServiceRecord._id + "_thumb." + extension }; console.log("file upload success"); console.log("teamPhoto", masterServiceRecord.service_icon); cb(null) } }); } else { cb(null); } }, function(cb){ masterServiceRecord.save(function(err,masterServiceRecord){ if (err){ responseFormatter.formatServiceResponse(err, cb); } else { savedData=masterServiceRecord console.log("in success :masterServiceRecord created successfully"); responseFormatter.formatServiceResponse(masterServiceRecord, cb, 'master service created successfully','success',200); } }); } ],function(err,data){ if(err){ callback(err) } else{ data=savedData callback(null,data) } }) }; module.exports.getMasterServices = function(callback){ console.log(['in master service.js getMasterServices() start :']) //masterServiceSchema.MasterService.find({},{},{sort:{service_name:1}}, function (err, masterservices) { // if (err){ // logger.error("Find failed", err); // responseFormatter.formatServiceResponse(err, callback); // } // else { // if(masterservices && masterservices.length){ // console.log(['in master service.js getMasterServices() end :',masterservices]) // responseFormatter.formatServiceResponse(masterservices, callback ,'','success',200); // } // else{ // console.log(['in master service.js getMasterServices() end :',masterservices]) // responseFormatter.formatServiceResponse({}, callback, "No masterservices Found." , "error",404); // } // } //}); masterServiceSchema.MasterService.aggregate([ { "$project": { service_id:1, "service_name": 1, "service_icon":1, "is_active":1, "description":1, "insensitive": { "$toLower": "$service_name" } }}, { "$sort": { "insensitive": 1 } } ]).exec(function(err,data){ if(err){ callback(err) } else{ console.log("in getMasterServices aggregation>>>>>",data) callback(data) } }) }; module.exports.updateMasterService = function(payload , callback){ let dataToUpdate=payload let updatedData=null async.series([ function(cb){ masterServiceSchema.MasterService.find({service_id:payload.service_id},function(err,data){ if(err){ cb(err) } else{ if(data && data.length ==0){ responseFormatter.formatServiceResponse({}, cb , 'No Such Gig Registered ', 'err',400); } else{ cb(null) } } }) }, function (cb) { let x={} if (payload.hasOwnProperty("service_icon") && payload.service_icon) { x = payload.service_icon.filename; let tempPath = payload.service_icon.path; if(typeof payload.service_icon !== 'undefined' && payload.service_icon.length){ x = payload.service_icon[1].filename; tempPath = payload.service_icon[1].path; } let extension = x.split('.').pop(); const rand=commonFunction.generateRandomString() let fileName=payload.service_id+rand+"."+extension console.log("tempPath",fileName) console.log("tempPath",fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { dataToUpdate.service_icon = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + payload.service_id+rand + "_thumb." + extension }; console.log("file upload success"); console.log("teamPhoto"); cb(null) } }); } else { cb(null); } }, function(cb){ masterServiceSchema.MasterService.findOneAndUpdate({service_id:payload.service_id},dataToUpdate,{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback); } else{ console.log("data__",data) updatedData=data cb(null) } }) }, function(cb){ gigServiceSchema.Gigs.find({service_id:payload.service_id},{},{lean:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback); } else{ if(data &&data.length ==0){ cb(null) } else{ gigServiceSchema.Gigs.update({service_id:payload.service_id},{service_name : payload.service_name},{multi:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback); } else{ console.log("data while updating service name in gigs collection ::: ",data); cb(null); } }) } } }) }, function(cb){ const id=mongoose.Types.ObjectId(payload.service_id) serviceLocationMapper.Mapper.find({service:id},{},{lean:true},function(err,data){ if(err){ cb(err) } else{ if(data && data.length==0){ cb(null) } else{ serviceLocationMapper.Mapper.update({service:id},{service_name : payload.service_name},{multi:true},function(err,data){ if(err){ cb(err) } else{ console.log("data while updating service name in mapper collection ::: ",data); cb(null); } }) } } }) }, function(cb){ SPprofileSchema.SPProfile.find({'service_and_gigs_info.service_id':payload.service_id}, {}, {lean:true}, function(err,data) { if(err){ cb(err) } else{ if(data &&data.length==0){ cb(null) } else{ SPprofileSchema.SPProfile.update({'service_and_gigs_info.service_id':payload.service_id}, {$set: {"service_and_gigs_info.$.service_name": payload.service_name}}, {new:true,multi:true}, function(err,data){ if(err){ cb(err) } else{ console.log("data while updating service name in sp profile schema collection ::: ",data); cb(null); } }) } } }) } ],function(err,data){ if(err){ callback(err) } else{ data=updatedData callback(null,data) } }) }; module.exports.activateMasterService = function(payload , callback){ masterServiceSchema.MasterService.update({ service_id: payload.service_id }, payload ,function (err, result) { console.log('activateMasterService result :: ',result); if(err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); }else{ if(result.nModified != 0){ responseFormatter.formatServiceResponse({}, callback ,'Service updated successfully','success',200); }else{ responseFormatter.formatServiceResponse({}, callback ,'Service not found','error',404); } } }); }; //Chandan
module.exports = { //table createTable(type,origin){ let re switch (type) { case 'simple': re = judgeErr(origin) break; default: re = origin break; } return re }, listTable(type,origin){ let re switch (type) { case 'simple': re = origin.table_names break; default: re = origin break; } return re }, deleteTable(type, origin) { let re switch (type) { case 'simple': re = judgeErr(origin) break; default: re = origin break; } return re }, //searchIndex createIndex(type, origin) { let re switch (type) { case 'simple': re = judgeErr(origin) break; default: re = origin break; } return re }, deleteIndex(type, origin) { let re switch (type) { case 'simple': re = judgeErr(origin) break; default: re = origin break; } return re }, listIndex(type,origin){ let re switch (type) { case 'simple': re = [] for(let key in origin.indices){ let item = origin.indices[key] re.push(item.index_name) } break; default: re = origin break; } return re }, //curd c(type,origin){ let re switch (type) { case 'simple': let rows = [] let row for (let key in origin.row.primaryKey) { row = {} let item = origin.row.primaryKey[key] // re.push(shiftType(item.value)) row[item.name] = shiftType(item.value) } if (row) { re = { err:0, err_msg:'添加成功', rows:[row] } } else { re = { err: origin.code || 1, err_msg: '添加失败', err_msg_origin: origin.message, rows: [] } } break; default: re = origin break; } return re }, u(type,origin){ let re switch (type) { case 'simple': let rows = [] // console.log(60,origin); if (origin.code > 0) { rows = [] break } for (let key_tb in origin.tables){ let item_tb = origin.tables[key_tb] let row = {} for (let key in item_tb.primaryKey) { let item = item_tb.primaryKey[key] row[item.name] = shiftType(item.value) } rows.push(row) } if (rows.length > 0) { re = { err:0, err_msg:'更新成功!', rows } }else{ re = { rows, err: origin.code || 1, err_msg: '更新失败!', err_msg_origin: origin.message, } } break; default: re = origin break; } return re }, r(type,origin){ let re = {} let rows = [] if (origin.nextToken) { origin.nextToken = origin.nextToken.toString("base64", origin.nextToken.offset, origin.nextToken.limit) } switch (type) { case 'simple': for(let key in origin.rows){ let row = {} let item = origin.rows[key] for(let key_p in item.primaryKey){ let item_p = item.primaryKey[key_p] row[item_p.name]=shiftType(item_p.value) } for(let key_r in item.attributes){ let item_r = item.attributes[key_r] row[item_r.columnName]=shiftType(item_r.columnValue) } rows.push(row) // console.log(100,rows); } re = { next: origin.nextToken, rows:rows, err: origin.code || 0, err_msg: origin.message || 'success', } if (origin.totalCounts) { re.count = parseInt(origin.totalCounts) } break; default: re = origin break; } return re }, inc(type, origin) { let re switch (type) { case 'simple': // console.log(179,JSON.stringify(origin)); // console.log(179, JSON.stringify(origin.row)); for(let key_or in origin){ re = [] let item_or = origin[key_or] // console.log(182,JSON.stringify(item)); // if (item_or.row.primaryKey.length >1) { // res = [] // for (let key in item_or.row.primaryKey) { // let item = item_or.row.primaryKey[key] // res.push(shiftType(item.value)) // } // } else { res = shiftType(item_or.row.primaryKey[0].value) // } re.push(res) } break; default: re = origin break; } return re }, } function shiftType(val) { let re switch (typeof(val)) { case 'object': re = val.toNumber() break; default: re = val break; } return re } function judgeErr(origin) { let re = {} if (origin.RequestId) { re = { err: 0, err_msg: 'success', } } else { re = { err: origin.code || 1, err_msg: origin.message || 'faile', } } return re }
var arr = [-5, 10, -3, 12, -9, 5, 90, 0, 1]; let arrP=[]; let sumN=0; function countPositivesSumNegatives(arr) { for(let ind in arr){ if(arr[ind]>=0){ arrP.push(arr[ind]); } else{ sumN=sumN+arr[ind]; } } arr.unshift(sumN); arr.unshift(arrP.length) return arr; } console.log(countPositivesSumNegatives(arr));
import React, { Component } from 'react'; import Fade from './Fade'; import logo from '../images/initials_logo.png'; import './App.css'; class App extends Component { constructor() { super() this.setScrollEvent = this.setScrollEvent.bind(this) this.getSectionPosition = this.getSectionPosition.bind(this) this.checkScrollToElem = this.checkScrollToElem.bind(this) this.state = { sectionOnescrolledTo: null, sectionTwoScrolledTo: null, sectionThreeScrolledTo: null, sectionFourScrolledTo: null } } componentWillMount() { this.setScrollEvent() } componentDidMount() { // console.log(document.getElementById('section-1').offsetLeft) const elems = [ document.getElementById('section-1'), document.getElementById('section-2'), document.getElementById('section-3'), document.getElementById('section-4') ] this.setState(this.getSectionPosition(elems)) } setScrollEvent() { window.addEventListener('scroll', (e) => { // this.setState({ scrollPos: window.scrollY }) // console.log(window.scrollY) this.checkScrollToElem(window.scrollY) }) } getSectionPosition(elemArray) { const result = [] elemArray.forEach((elem, index) => { let obj = elem.getBoundingClientRect(); return result.push({ left: obj.left + document.body.scrollLeft, top: obj.top + document.body.scrollTop, width: obj.width, height: obj.height }); }) return result } checkScrollToElem(pos) { // this will check if the current scrolled position (pos) is >= the section element positions on the page // console.log(pos, document.querySelector('body').clientHeight) const offset = 200 if (pos >= this.state[0].top - 500) this.setState({sectionOnescrolledTo: true}) if (pos >= this.state[1].top - 300) this.setState({sectionTwoScrolledTo: true}) if (pos >= this.state[2].top - 300) this.setState({sectionThreeScrolledTo: true}) if (pos >= (document.querySelector('body').clientHeight - window.innerHeight)) this.setState({sectionFourScrolledTo: true}) } render() { return ( <div className="App"> <section className="App-header-section"> <Fade duration={300}> <img src={logo} className="App-logo" alt="logo" /> </Fade> <Fade duration={500}> <div className="App-header"> <h1>Jeremy Levy</h1> <h4>web developer</h4> {/*<div className="arrow-down">></div>*/} </div> </Fade> </section> <section id="section-1" className={this.state.sectionOnescrolledTo ? "App-section scrolled-over" : "App-section" }> <div className="App-section-bar"></div><div><h3>About me</h3></div> <p>I'm based in <span className="highlight">SF</span>. I build with <span className="highlight">JS</span>, <span className="highlight">CSS</span> and <span className="highlight">HTML</span>. My framework of choice is <span className="highlight">ReactJS</span> and I use <span className="highlight">NodeJS</span> for server-side development. </p> </section> <section id="section-2" className={this.state.sectionTwoScrolledTo ? "App-section scrolled-over" : "App-section" }> <div className="App-section-bar"></div><div><h3>Where to find me</h3></div> <p>You can find my code on <a className="link-highlight" href='https://github.com/Jlevyd15'>GitHub</a>{'\n'} or more about me on <a className="link-highlight" href='https://www.linkedin.com/in/jeremy-levy-9a3b9058/'>Linkedin</a>.</p> </section> <section id="section-3" className={this.state.sectionThreeScrolledTo ? "App-section scrolled-over" : "App-section" }> <div className="App-section-bar"></div><div><h3>My projects</h3></div> <ul> <li><a href="https://github.com/Jlevyd15/cryptoDorado">cryptoDorado</a> - a crypto currency wallet aggregator</li> <li><a href="https://github.com/Jlevyd15/car-share-compare">car share compare</a> - a car share comparison website</li> <li><a href="https://github.com/Jlevyd15/tahoe-snow">tahoe snow</a> - an Amazon Alexa based voice app</li> </ul> </section> <section id="section-4" className={this.state.sectionFourScrolledTo ? "App-section App-section-last scrolled-over" : "App-section App-section-last" }> <div className="App-section-bar"></div><div><h3>Contact me</h3></div> <p>Feel free to <a className="link-highlight" href="mailto:jlevyd@gmail.com">email me</a></p> </section> <div className="footer-flex"><img src={logo} className="App-logo" alt="logo" /><div><div className="created-by">created by</div><div> Jeremy Levy</div></div></div> </div> ); } } export default App;
// https://codepen.io/mikethedj4/pen/snjpF $(document).ready(function() { $(".device-list li").draggable({ // use a helper-clone that is append to "body" so is not "contained" by a pane helper: function() { return $(this).clone().addClass('moveDevice').appendTo("#device-drop").css({ "zIndex": 5 }).show(); }, cursor: "move", containment: "html" }); $("#device-drop").droppable({ hoverClass: "ui-state-hover", accept: ".device-list li", drop: function(event, ui) { if (!ui.draggable.hasClass("dropped")) $(this).append($(ui.draggable).clone().removeClass("ui-draggable-handle ui-draggable add-element").removeClass("dropped").addClass('DeviceElement').append('<span class="closing"><i class="icon-close"></i></span>')); $('li.DeviceElement span').on('click', function() { $(this).parent().remove(); }); } }).sortable({ placeholder: "sort-placer", cursor: "move", helper: function (evt, ui) { return $(ui).clone().appendTo("#device-drop").show(); } }); // simulator drag $(".simulator-device-list li").draggable({ // use a helper-clone that is append to "body" so is not "contained" by a pane helper: function() { return $(this).clone().addClass('simulator-moveDevice').appendTo("#simulator-device-drop").css({ "zIndex": 5 }).show(); }, cursor: "move", containment: "html" }); $("#simulator-device-drop").droppable({ hoverClass: "ui-state-hover", accept: ".simulator-device-list li", drop: function(event, ui) { if (!ui.draggable.hasClass("dropped")) $(this).append($(ui.draggable).clone().removeClass("ui-draggable-handle ui-draggable add-element").removeClass("dropped").addClass('DeviceElement').append('<span class="closing"><i class="icon-close"></i></span>')); $('li.DeviceElement span').on('click', function() { $(this).parent().remove(); }); } }).sortable({ placeholder: "sort-placer", cursor: "move", helper: function (evt, ui) { return $(ui).clone().appendTo("#simulator-device-drop").show(); } }); // list view slide $('.simulator-list-view').hover(function() { $(this).children().children('.simulation-list-option').toggleClass('show'); }); // $('.simulator-drop-section button').click(function() { // $('.simulator-drag-section').slideToggle('slow', function() { // $('.simulator-drop-section').toggleClass('selecionado'); // }); // }); $("#btn").click(function () { // $("#Create").toggle(); $('#simulator-drag-box').slideToggle('slow', function() { $('.simulator-drop-section').toggleClass('drop-box-minimize'); }); }); // search js //jQuery(document).ready(function($){ $('.device-search-list li').each(function(){ $(this).attr('data-search-term', $(this).text().toLowerCase()); }); $('.device-search-box').on('keyup', function(){ var searchTerm = $(this).val().toLowerCase(); $('.device-search-list li').each(function(){ if ($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) { $(this).show(); } else { $(this).hide(); } }); }); //}); // subscribtion section $(function () { $("#btnAdd").bind("click", function () { var div = $("<tr />"); div.html(GetDynamicTextBox("")); $("#TextBoxContainer").append(div); }); $("body").on("click", ".remove", function () { $(this).closest("tr").remove(); }); }); function GetDynamicTextBox(value) { return '<td><input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><select name="" class="form-control"><option> Select</option><option> Male</option><option> Female</option></select></td>' + '<td><input name = "DynamicTextBox" type="radio" value = "' + value + '" /></td>' + '<td><input name = "DynamicTextBox" type="checkbox" value = "' + value + '" /></td>' + '<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>' } });
$(function(){ /** * Research.jsp = ResearchController * */ var doc = document; var width; var height; var branchChart; var collectChart; var distributionEchart; (function (){ var collect_reserach_echarts = doc.getElementById('collect-reserach-echarts'); if (collect_reserach_echarts) { //自适应设置 width = $(window).width(); height = $(window).height(); //$("#distribution-echarts").css("width",width-40); $("#collect-reserach-echarts").css("height",height-40); //$("#distribution-echarts").css("width",width-40); $("#branch-reserach-echarts").css("height",height-40); } }()); (function () { var collect_reserach_echarts = doc.getElementById('collect-reserach-echarts'); if (collect_reserach_echarts) { //加载列表 var dt =$("#research-table").DataTable({ "serverSide":true, //服务端处理 "searchDelay": 1000,//搜索延迟 "destroy": true, "order":[[0,'desc']],//默认排序方式 "lengthMenu":[100000],//每页显示数据条数菜单 "ajax":{ url:"/MyScenarios/scenarios.json", //获取数据的URL type:"get" //获取数据的方式 }, "columns":[ //返回的JSON中的对象和列的对应关系 {"data":"id","name":"id"}, {"data":"scenariosName","name":"scenarios_name"} ], "columnDefs":[ //具体列的定义 { "targets":[0,1], "visible":false } ], "initComplete": function (settings, data) { //console.log(data); if (data.data) { var result = data.data, len = result.length; $('#research-name1').empty(); $('#research-name2').empty(); $('#research-name1').off("click"); $('#research-name2').off("click"); for (var i=0;i<len;i++) { var add='<option value='+result[i].scenariosName+'>'+result[i].scenariosName+'</option>'; $('#research-name1').append(add); $('#research-name2').append(add); } } var data1 = { "name":$('#research-name1').val() }, data2 = { "name":$('#research-name2').val() } collectEcharts(data1,data2); branchEcharts(data1,data2);//data1,data2 } }); } }()); function collectEcharts(){ collectChart = echarts.init(document.getElementById('collect-reserach-echarts')); //自适应 window.onresize = collectChart.resize; collectChart.setOption({ title : { text: '收端到达集散点时间分布', x:'center', y:'top' }, tooltip : { trigger: 'axis' }, legend: { x:'center', y:'bottom', data:['1','2'] }, toolbox: { show : true, feature : { mark : {show: true}, dataView : {show: true, readOnly: false}, magicType : {show: true, type: ['line', 'bar']}, restore : {show: true}, saveAsImage : {show: true} } }, calculable : true, xAxis : [ { type : 'category', data : ['提早70','提早60','提早50','提早40','提早30','提早20','提早10','准时到'], //设置字体倾斜 axisLabel:{ interval:0, rotate:0,//倾斜度 -90 至 90 默认为0 margin:5, textStyle:{ fontWeight:"bolder", color:"#000000" } }, } ], yAxis : [ { type : 'value', splitArea : {show : true} } ], series : [ { name:'1', type:'bar', data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2], barWidth : 30,//柱图宽度 //顶部数字展示pzr itemStyle: { normal: { color:"#5b9bd5", label: { show: true,//是否展示 position: 'top', textStyle: { fontWeight:'bolder', fontSize : '12', fontFamily : '微软雅黑', } } } } }, { name:'1', type:'bar', data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2], barWidth : 30,//柱图宽度 //顶部数字展示pzr itemStyle: { normal: { color:'#ed7d31', label: { show: true,//是否展示 position: 'top', textStyle: { fontWeight:'bolder', fontSize : '12', fontFamily : '微软雅黑', } } } } //barGap:'10%' } ] }); } function branchEcharts(data1,data2){ branchChart = echarts.init(document.getElementById('branch-reserach-echarts')); //自适应 window.onresize = branchChart.resize; branchChart.setOption({ title : { text: '支线到达目的地集散点时间分布', x:'center', y:'top' }, tooltip : { trigger: 'axis' }, legend: { x:'center', y:'bottom', data:[data1.name,data2.name] }, toolbox: { show : true, feature : { mark : {show: true}, dataView : {show: true, readOnly: false}, magicType : {show: true, type: ['line', 'bar']}, restore : {show: true}, saveAsImage : {show: true} } }, calculable : true, xAxis : [ { type : 'category', data : ['提早60','提早50','提早40','提早30','提早20','提早10','准时到'], //设置字体倾斜 axisLabel:{ interval:0, rotate:0,//倾斜度 -90 至 90 默认为0 margin:5, textStyle:{ fontWeight:"bolder", color:"#000000" } }, } ], yAxis : [ { type : 'value', splitArea : {show : true} } ], series : [ { name:data1.name, type:'bar', data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6], barWidth : 30,//柱图宽度 //顶部数字展示pzr itemStyle: { normal: { color:"#5b9bd5", label: { show: true,//是否展示 position: 'top', textStyle: { fontWeight:'bolder', fontSize : '12', fontFamily : '微软雅黑', } } } }, }, { name:data2.name, type:'bar', data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6], barWidth : 30,//柱图宽度 //顶部数字展示pzr itemStyle: { normal: { color:'#ed7d31', label: { show: true,//是否展示 position: 'top', textStyle: { fontWeight:'bolder', fontSize : '12', fontFamily : '微软雅黑', } } } }, } ] }); } //点击选项 切换图表信息 (function () { var collect_reserach_echarts = doc.getElementById('collect-reserach-echarts'); if (collect_reserach_echarts) { $('#research-name1').click(function (){ }); $('#research-name2').click(function (){ }); } }()); /** *distribution.jsp == SolutionDistributionController * */ function startNum (a,b) { return a.start-b.start; } //求时间 function operationTime (data) { var result = parseInt(data), h = parseInt(result/60), m = result%60; return add0(h)+":"+add0(m); } function add0(m){return m<10?'0'+m:m }; (function () { var distribution_echarts = doc.getElementById('distribution-echarts'); if (distribution_echarts) { //自适应设置 width = $(window).width(); height = $(window).height(); $("#distribution-echarts").css("height",height-300); var _val = $('#distribution-choose').val(); $.get("/distribution/getMaxMix.json",{"type":_val}).done(function (res){ ////console.log(res); $('.echarts-error-info').hide(); var arr = []; for (var i in res) { var obj = {} var s = i.split("-"); s.push(res[i]); ////console.log(s) obj["start"] = s[0]; obj["end"] = s[1]; obj["num"] = s[2]; arr.push(obj); } arr.sort(startNum); ////console.log(arr); var xinfo = []; var seriesinfo = []; for (var j=0,len=arr.length;j<len;j++) { var time = operationTime(arr[j].start) +"-"+operationTime(arr[j].end); xinfo.push(time); var val = arr[j].num; seriesinfo.push(val); } var data = { "xinfo":xinfo, "seriesinfo":seriesinfo } distributionEcharts(data); }).fail(function () { //$('.echarts-error-info').show(); }); $('#distribution-choose').change(function () { var _val = $(this).val(); $.get("/distribution/getMaxMix.json",{"type":_val}).done(function (res){ ////console.log(res); $('.echarts-error-info').hide(); if (_val == 0 || _val== 1) { var arr = []; for (var i in res) { var obj = {} var s = i.split("-"); s.push(res[i]); ////console.log(s) obj["start"] = s[0]; obj["end"] = s[1]; obj["num"] = s[2]; arr.push(obj); } arr.sort(startNum); ////console.log(arr); var xinfo = []; var seriesinfo = []; for (var j=0,len=arr.length;j<len;j++) { var time = operationTime(arr[j].start) +"-"+operationTime(arr[j].end); xinfo.push(time); var val = arr[j].num; seriesinfo.push(val); } var data = { "xinfo":xinfo, "seriesinfo":seriesinfo } distributionEcharts(data); }else{ var xinfo = ['提早60','提早50以上','提早40以上','提早30以上','提早20以上','提早10以上','准时到']; var arr = [res.tiqian60,res.tiqian50,res.tiqian40,res.tiqian30,res.tiqian20,res.tiqian10,res.zunshi]; ////console.log(arr) var arrlen = arr.length; var seriesinfo = []; for (var x=0;x<arrlen;x++) { var sum = ""; for (var y=0;y<x+1;y++) { sum = (Number(sum) + Number(arr[y])).toFixed(2); } if(sum>100){ sum = 100; } seriesinfo.push(sum); } var slen = seriesinfo.length; seriesinfo[slen-1] = 100; var data = { "xinfo":xinfo, "seriesinfo":seriesinfo } distributionEcharts(data); } }).fail(function () { //$('.echarts-error-info').show(); }); }); } }()); function distributionEcharts(datas){ distributionEchart = echarts.init(document.getElementById('distribution-echarts')); //自适应 window.onresize = distributionEchart.resize; distributionEchart.setOption({ tooltip : { trigger: 'axis' }, toolbox: { show : true, feature : { mark : {show: true}, dataView : {show: true, readOnly: false}, magicType : {show: true, type: ['line', 'bar']}, restore : {show: true}, saveAsImage : {show: true} } }, calculable : true, xAxis : [ { type : 'category', data : datas.xinfo, //设置字体倾斜 axisLabel:{ interval:0, rotate:45,//倾斜度 -90 至 90 默认为0 margin:5, textStyle:{ fontWeight:"bolder", color:"#000000" } }, } ], yAxis : [ { type : 'value', axisLabel: { formatter: '{value} %', //显示百分比 show: true, interval: 'auto', }, splitArea : {show : true} } ], series : [ { name:'1', type:'bar', data:datas.seriesinfo, barWidth : 30,//柱图宽度 //顶部数字展示pzr itemStyle: { normal: { color:"#5b9bd5", label: { show: true,//是否展示 position: 'top', //formatter:'{b}\n{c}%', formatter:'{c}%', //显示百分比 textStyle: { fontWeight:'bolder', fontSize : '12', fontFamily : '微软雅黑', } } } } } ] }); } //导出excel表格 $('.export-btn').click(function () { var _xls = $(this).attr('data-xls'); if (_xls) { window.location.href="/distribution/exportResult"; } $(".modal-header span").trigger('click'); }); });
/** * Responsible for friends information * * @ngdoc service * @name ffFriendService * @requires $http */ function ffFriendService($http, $rootScope) { return { list: list } /** * Retrieve the list of friends. * * @ngdoc method * @name ffFriendService#list * @param {function} fnSuccess Executes when successfully retrieves * the list of friends receiving the result. * @param {function} fnError Executes when fail to retrieve * the list of friends receiving the error data object from the backend. */ function list(fnSuccess, fnError){ return $http.get('/facebook/' + $rootScope.userInfo.id + '/friends') .success(function(data, status, headers) { if (fnSuccess){ fnSuccess(data); } }) .error(function(data, status, headers) { if (fnError){ fnError(data); } console.log('ffNewsService failed to get activities'); }); } } module.exports = { service: ['$http','$rootScope', ffFriendService], name: 'ffFriendService' }
import React from "react"; import "./style.scss"; export default function Input({ placeholderStr, type, id, value, onChange }) { return ( <input placeholder={placeholderStr} type={type} id={id} value={value} onChange={onChange} required /> ); }
describe('navigation >', () => { it('opens settings configure plug', () => { cy.deleteSettings(); cy.visit('/'); cy.get('{configure-settings-plug}').should('be.visible'); }); it('opens root page on invalid route', () => { cy.visit('/non/existing/route'); cy.url().should('not.equal', /\/non\/existing\/route\/$/); }); it('opens settings page', () => { cy.visit('/settings'); cy.url().should('match', /\/settings$/); cy.get('{settings-page}').should('be.visible'); }); it('opens build details page', () => { cy.visit('/build/123'); cy.url().should('match', /\/build\/123$/); cy.get('{build-details-page}').should('be.visible'); }); });
var webserver = require('./lib/webserver'), datasift = require('./lib/datasift'), publisher = require('./lib/publisher'), brands = require('./lib/brand_data_loader'); brands.load(function() { datasift.start(); webserver.start(); publisher.start(); });
$('document').ready(function(){ // Variables const listaProductos = $('#lista-productos'); //Cargar los productos en el DOM renderizarProductos(); function renderizarProductos(){ productosDatos.map((item) => { listaProductos.append( `<div class="producto"> <img class="producto__imagen" src=${item.imagen} alt=${item.descripImagen}/> <div class="producto__informacion"> <h4>${item.nombre}</h4> <p>Fermín ${item.categoria}</p> <label>Cantidad:</label> <input type="number" min="1" value="1" value=${item.cantidad}></input> <div class="producto__precio"> <p class="precio">$${item.precio}</p> <p class="oferta">$${item.oferta}</p> </div> <a href="#" class="producto__btnAgregarCarrito modal__open" data-id= ${item.id}>Agregar Al Carrito</a> </div>` ); }); } //Ajax const URL = 'https://jsonplaceholder.typicode.com/comments?postId=1'; $.get(URL, function(response, status) { if (status === 'success') { for (const data of response) { $('.testimonios').append(` <div class="cliente"> <div class="cliente__informacion"> <p>${data.body}</p> <h4>${data.email}</h4> </div> </div>`) } } }); //Animacion Scroll Secciones $('#navegacion__nosotros').click(function(e){ e.preventDefault(); $('html, body').animate({ scrollTop: $('#nosotros').offset().top }, 1000); }); $('#navegacion__tienda').click(function(e){ e.preventDefault(); $('html, body').animate({ scrollTop: $('#tienda').offset().top }, 1500); }); $('#navegacion__contacto').click(function(e){ e.preventDefault(); $('html, body').animate({ scrollTop: $('#contacto').offset().top }, 2000); }); });
import App from "./components/preview_components/App";
import { assert, match, stub, spy } from 'sinon'; import _ from 'lodash'; import { expect } from 'chai'; import { path as p } from '../../../lib/string-utils'; import proxyquire from 'proxyquire' describe('watchmaker', () => { let watchmaker, pieWatchConstructor, pieWatch, fileWatch, watcherStub, fileWatchConstructor, questionConfig, elements, dirs, mappings; beforeEach(() => { questionConfig = () => { return { dir: 'dir', filenames: { config: 'config.json', markup: 'index.html', resolveConfig: spy(function (dir) { return `${dir}/config.json` }), resolveSession: spy(function (dir) { return `${dir}/session.json` }) } } } }); beforeEach(() => { let watchers = require('../../../lib/watch/watchers'); class StubPieWatch extends watchers.PieWatch { constructor() { return { start: stub() } } } class StubFileWatch extends watchers.FileWatch { constructor() { return { start: stub() } } } pieWatch = new StubPieWatch() pieWatchConstructor = spy(function () { // console.log('arguments: ', arguments); return pieWatch; }); fileWatch = new StubFileWatch(); fileWatchConstructor = stub().returns(fileWatch); mappings = { controllers: [{ pie: 'stub', target: 'stub-controller' }], configure: [{ pie: 'stub', target: 'stub-configure' }] } dirs = { root: 'dir/.pie', controllers: 'dir/.pie/controllers', configure: 'dir/.pie/configure' } watchmaker = proxyquire('../../../lib/watch/watchmaker', { './watchers': { PieWatch: pieWatchConstructor, FileWatch: fileWatchConstructor } }); }); describe('init', () => { it('returns an empty array for an empty array of localDependencies', () => { let watchers = watchmaker.init(questionConfig([]), stub(), [], mappings, dirs); expect(watchers.dependencies.length).to.eql(0); }); it('returns an empty array for a null localDependencies', () => { let watchers = watchmaker.init(questionConfig(null), stub(), [], mappings, dirs); expect(watchers.dependencies.length).to.eql(0); }); describe('with 1 local dependency', () => { let watchers, dep, questionCfg; beforeEach(() => { dep = stub(); questionCfg = questionConfig(); watchers = watchmaker.init( questionCfg, stub(), [], [{ isLocal: true, input: { element: 'element', value: 'input' }, element: { moduleId: 'main' }, rootModuleId: 'root-moduleId', controller: { moduleId: 'controller' }, configure: { moduleId: 'configure-module-id' } }], dirs); }); it('returns 1 watcher', () => { expect(watchers.dependencies.length).to.eql(1); }); it('calls constructor', () => { assert.calledWith(pieWatchConstructor, { moduleId: 'main' }, 'root-moduleId', 'dir', 'input', dirs, match.object, match.object); }); it('calls start', () => { assert.called(pieWatch.start); }); it('calls file watch constructor for index.html', () => { assert.calledWith(fileWatchConstructor, p`dir/index.html`, match.func); }); it('calls resolveConfig', () => { assert.calledWith(questionCfg.filenames.resolveConfig, 'dir'); }); it('calls file watch constructor for config.json', () => { assert.calledWith(fileWatchConstructor, p`dir/config.json`, match.func); }); it('calls file watch constructor for index.html', () => { assert.calledWith(fileWatchConstructor, p`dir/index.html`, match.func); }); it('calls file watch constructor for session.json', () => { assert.calledWith(fileWatchConstructor, p`dir/session.json`, match.func); }); }); }); });
import React from 'react' import PropTypes from 'prop-types' import uuid from 'uuid/v1' import { Character } from './styled' const VerticalText = ({ text = 'Words' }) => ( <div> {text.split('').map(character => ( <Character key={uuid()}>{character}</Character> ))} </div> ) VerticalText.propTypes = { text: PropTypes.string, size: PropTypes.number, } export default VerticalText
import React from 'react'; import './css/WeekItem.css'; //This component displays the day of the week and the weather data for the given day. It also allows you to change the selectedDay (which will cause a re-render of DayList/DayItem), and will indicate which day is currently selected. const WeekItem = ({day,dayOfWeek, onDaySelect,selectedDay}) => { //On each render of this component it checks if day===selectedDay, initially the first day will be the selectedDay. //Function to get className depending on the comparison between day and selectedDay const getWeekItemClass = (day,selectedDay) => { return (day===selectedDay)? 'week-item item selected':'week-item item'; }; return ( <div onClick={()=>onDaySelect(day)} className={getWeekItemClass(day,selectedDay)} > <div className="content"> <div className="header"> {dayOfWeek.substring(0,3)}<br/> <i className={`wi wi-owm-day-${day[0].weather[0].id} weathericon`}/><br/> <div className="temperature"> {Math.round(day[0].main.temp)}&deg; C </div> {day[0].weather[0].description.toUpperCase()}<br/> </div> </div> </div> ); }; export default WeekItem;
const multer=require("multer"); const storage=multer.diskStorage({ destination:function (req,file,cb) { cb(null,"./public/uploads/") }, filename:function (req,file,cb) { cb(null,file.originalname) } }); const uploads=multer({ storage:storage }); uploads.createfiles=function (filename) { let storage=multer.diskStorage({ destination:function (req,file,cb) { cb(null,"./public/uploads/"+filename); }, filename:function (req,file,cb) { cb(null,file.originalname)} }); this.storage=storage; }; module.exports=uploads;
"use strict"; var _mysql = _interopRequireDefault(require("mysql")); var _util = require("util"); var _keys = require("./keys"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var db = _mysql["default"].createPool(_keys.database); db.getConnection(function (err, connection) { if (err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.error('La conexión a la base de datos fue cerrada.'); } if (err.code === 'ER_CON_COUNT_ERROR') { console.error('La base de datos tiene muchas conexión'); } if (err.code === 'ECONNREFUSED') { console.error('La conexión se negó a conectarse'); } } if (connection) { connection.release(); console.log("La base de datos está conectada"); } return; }); db.query = (0, _util.promisify)(db.query); module.exports = db;
OperacionesManager.module("Entities", function(Entities, OperacionesManager, Backbone, Marionette, $, _){ Entities.Articulo = Backbone.Model.extend(); Entities.Articulos = Backbone.Collection.extend({ model: Entities.Articulo }); var articulos; var initializeArticulos = function () { articulos = new Entities.Contratos(); }; var API = { getArticulosEntities: function() { if (articulos === undefined) { initializeArticulos(); } return articulos; }, getArticuloEntity: function(id){ if (articulos === undefined) { initializeArticulos(); } var articulo = articulos.find(function(articulo){ return articulo.get('id') == id; }); return articulo; } }; OperacionesManager.reqres.setHandler("articulos:entities", function(){ return API.getArticulosEntities(); }); OperacionesManager.reqres.setHandler("articulos:entity", function(id){ return API.getArticuloEntity(id); }); });
import Modal from "./Modal"; import { useState } from "react"; export default function ShareButton({advice}) { const [show, setShow] = useState(false); const [shareLink, setShareLink] = useState(''); const share = () => { var l = advice; var h = l.split(' ').join('+'); let link = `quote-gen-m.netlify.app/shared/${h}`; console.log(link) // construct the link. setShow(true); setShareLink(link); } return ( <div> <button className="share-btn" onClick={share}>Share this quote</button> {/* Need to set and display (on arrive a capter the current state !!) the path*/} { show && (<Modal show={show} onShowChange={setShow} shrLink={shareLink} />) } </div> ) }
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Tab } from 'react-bootstrap'; import Tabs from '../Tabs'; import OrderBook from './OrderBook'; import TradeHistory from './TradeHistory'; import Panel from '../Panel'; const OrderBookAndTradeHistory = ({ theme, height }) => ( <Panel theme={theme} style={{ height }}> <Tabs align="center" theme={theme}> <Tab eventKey={0} title="OrderBook"> <OrderBook /> </Tab> <Tab eventKey={1} title="Trades"> <TradeHistory showPairLabel height={height} /> </Tab> </Tabs> </Panel> ); OrderBookAndTradeHistory.propTypes = { theme: PropTypes.string, height: PropTypes.string, }; OrderBookAndTradeHistory.defaultProps = { theme: 'dark', height: 'inherit', }; const mapState = state => ({ theme: state.theme, }); export default connect( mapState, undefined, )(OrderBookAndTradeHistory);
var story = { "title": "Notifications", "pages": [{ "title": "Notifications", "height": 333, "width": 345, "image": "Notifications.png", "links": [], "image2x": "Notifications@2x.png" }], "highlightLinks": true, "resolutions": [2] }
import { UISelector, baseURL, color } from "../utilities"; import { list } from "./pagination"; import { createRecipe } from "../data/model"; import { myHTTP } from "../http"; import { notifyUser } from "./errors"; import { addCard, numberOfCards } from "./card"; let modalState = "static"; let object; // select elements const dismissBtn = document.querySelector(UISelector.dismissBtn); const modalTitle = document.querySelector(UISelector.modalTitle); const deleteBtn = document.querySelector(UISelector.deleteBtn); const editBtn = document.querySelector(UISelector.editBtn); const mealType = document.querySelector(UISelector.mealType); const modalImg = document.querySelector(UISelector.modalImg); // ingr el const ingredients = document.querySelector(UISelector.ingredients); const ingrContent = document.querySelector(UISelector.ingredientsContent); const ingredientsForm = document.querySelector(UISelector.editIngredients); const ingrTextarea = document.querySelector(UISelector.ingrTextarea); // prep el const preparation = document.querySelector(UISelector.preparation); const prepContent = document.querySelector(UISelector.preparationContent); const preparationForm = document.querySelector(UISelector.editPreparation); const prepTextarea = document.querySelector(UISelector.prepTextarea); // listen for delete, edit and close deleteBtn.addEventListener("click", deleteRecipe); editBtn.addEventListener("click", editRecipe); dismissBtn.addEventListener("click", (e) => { bringToStatic(); e.preventDefault(); }); // selected list item opens modal on click function initModal(results) { list.addEventListener("click", (e) => { const item = results.find((meal) => meal.strMeal === e.target.textContent); // create recipe instance object = createRecipe(item); // populate modal with recipe data fillModal(object, true); e.preventDefault(); }); } function fillModal(object, fromList = null) { // fill modal with data modalTitle.textContent = object.title; mealType.textContent = object.type; ingrContent.textContent = object.ingredients; modalImg.src = object.image; prepContent.textContent = object.preparation; // handle buttons if (fromList) { // show save, hide edit/ delete buttons document.querySelector(UISelector.saveBtn).style.display = "block"; document.querySelector(UISelector.editBtn).style.display = "none"; deleteBtn.style.display = "none"; } else { // hide save, show edit/ delete buttons document.querySelector(UISelector.saveBtn).style.display = "none"; document.querySelector(UISelector.editBtn).style.display = "block"; deleteBtn.style.display = "block"; } } // POST recipe to JSON server & create a card on save document.querySelector(UISelector.saveBtn).addEventListener("click", () => { if (numberOfCards < 20) { numberOfCards++; myHTTP(baseURL.jsonServer) .post("posts", object) .then((data) => { addCard(data); notifyUser(UISelector.notification, "Recipe saved", color.green); console.log(numberOfCards); }) .catch((err) => handleErr(err)); } else { notifyUser( UISelector.notification, "Maximum number of recipes is 20", color.red ); } }); // delete recipe function deleteRecipe() { myHTTP(baseURL.jsonServer) // delete from server .delete(`posts/${modalTitle.id}`) // remove card .then(() => { document.querySelector(`#card${modalTitle.id}`).remove(); // close modal $(UISelector.modal).modal("hide"); // return to static view modalState = "static"; bringToStatic(); // substract one card numberOfCards--; }) .catch((err) => handleErr(err)); } // edit recipe function editRecipe() { console.log(modalState); if (modalState === "static") { // change state modalState = "edit"; // hide static elements ingredients.style.display = "none"; preparation.style.display = "none"; // show form elements ingredientsForm.style.display = "block"; preparationForm.style.display = "block"; // inject text into forms ingrTextarea.value = ingrContent.textContent; prepTextarea.value = prepContent.textContent; // change btn text editBtn.textContent = "Save changes"; } else { // update recipe on the server myHTTP(baseURL.jsonServer) .put(`posts/${modalTitle.id}`, updateObject()) .then((data) => { // update static modal fillModal(data); // return to static view bringToStatic(); }) .catch((err) => handleErr(err)); } } // set modal back to static state function bringToStatic() { modalState = "static"; // hide form elements ingredientsForm.style.display = "none"; preparationForm.style.display = "none"; // show modal elements ingredients.style.display = "block"; preparation.style.display = "block"; // reset btn text editBtn.textContent = "Edit"; } // create updated object function updateObject() { return { title: modalTitle.textContent, type: mealType.textContent, ingredients: ingrTextarea.value, image: modalImg.src, preparation: prepTextarea.value, id: modalTitle.id, }; } // handle err function handleErr(err) { console.log(err); notifyUser( UISelector.notification, `Something went wrong: ${err}`, color.red ); } export { initModal, fillModal };
import React, { Component } from 'react'; import Header from './Header'; import LogReader from './LogReader'; import Hand from './Hand'; import ResetHandButton from './ResetHandButton'; import MulliganButton from './MulliganButton'; import { parseLog } from './parser'; import './style.css'; class App extends Component { fileRef = React.createRef(); state = { cards: null, logFileText: "empty", deck: null, hand: [], handSize: 7, showReset: false, showMulligan: false } getLogPath = async event => { event.preventDefault(); const path = this.fileRef.current.pathRef.current; const file = path.files[0]; try { const contents = await this.fetchResults(file); this.setState({ logFileText: contents }); const cards = parseLog(this.state.logFileText); this.setState( {cards} ); } catch (err) { console.error(err); } // testing this.generateDeck(); await this.drawCards(7); this.setState( { showReset: true, showMulligan: true }); } fetchResults = file => { const fileReader = new FileReader(); return new Promise((resolve, reject) => { fileReader.readAsText(file); fileReader.onerror = () => { fileReader.abort(); reject(new DOMException("Could not parse log")); } fileReader.onload = () => { resolve(fileReader.result); } }) } generateDeck = () => { const cardList = this.state.cards; if (!cardList) { console.error("No cards found"); return; } else { const deck = []; const keys = Object.keys(cardList); keys.forEach(card => { let count = cardList[card]; while (count > 0) { deck.push(card); count--; } }); this.setState( {deck} ); } } drawCards = async num => { const deck = this.state.deck; if (deck === null) { console.error('Cannot generate hand without deck. Please select log files first'); return; } let hand = []; const drawnSet = new Set(); while (hand.length < num) { const card = Math.floor(Math.random() * deck.length); if (!drawnSet.has(card)) { drawnSet.add(card); hand.push(deck[card]); } } hand = await Promise.all(hand.map(async id => await this.getCardInfo(id))); hand = hand.sort((a,b) => { if (a.cmc > b.cmc) return 1; if (a.cmc < b.cmc) return -1; return 0; }) this.setState( {hand}) console.log('hand: ', hand); } handleNewDraw = async () => { await this.setState( {handSize: 7} ); this.drawCards(this.state.handSize); this.setState( { showMulligan: true} ); } handleMulligan = async () => { const handSize = this.state.handSize - 1; await this.setState( {handSize} ); this.drawCards(handSize); if (handSize <= 0) this.setState( {showMulligan: false} ); } getCardInfo = async id => { const url = `https://api.scryfall.com/cards/mtgo/${id}`; try { const response = await fetch(url, { method: "GET", format: "image", redirect: "follow" }); const json = await response.json(); return { name: json.name, img: json.image_uris.small, cmc: json.cmc } } catch(e) { console.error(e); } } render() { return ( <div className="wrapper"> <Header /> <LogReader ref={this.fileRef} getLogPath={this.getLogPath} /> <Hand hand={this.state.hand} /> <div className="buttons"> {this.state.showReset ? <ResetHandButton handleNewDraw={this.handleNewDraw} /> : null} {this.state.showMulligan ? <MulliganButton handleMulligan={this.handleMulligan} /> : null} </div> </div> ); } } export default App;
if (process.env.NODE_ENV !== 'production') { require('dotenv').config(); } const Koa = require('koa'); const serve = require('koa-static'); const path = require('path'); const publicRouter = require('./publicRouter'); const db = require('./db'); const { PORT } = require('./constants'); const koa = new Koa(); koa.use(publicRouter.routes()); koa.use(serve(path.join(__dirname, 'dist/'))); const dbinit = () => db.sequelize.sync({ force: false }).then(() => console.log('*** DB synced ***')); dbinit(); const app = koa.listen(process.env.PORT || PORT, () => console.log(`Listening on port ${process.env.PORT || PORT}`)); module.exports = { app, dbinit, };
import React, {Component} from 'react'; class Quotes extends Component { render() { return ( <section id="quotes" className="parallax pt100 pb90" data-overlay-dark="8"> <div className="background-image"> <img src="wunderkind/img/backgrounds/bg-4.jpg" alt="#" /> </div> <div className="container"> <div className="row"> <div className="col-md-12"> <div className="quote-slider navigation-thin container white text-center" data-autoplay="true" data-speed="2000"> <div> <h2> <i className="vossen-quote color"/> A Perfect Design is <strong>Passion, Dedication,</strong><br/>and a lots of Coffee <i className="vossen-quote color"/> </h2> <p className="label label-primary">Wunderkind Team</p> </div> <div> <h2> <i className="vossen-quote color"/> The Difference between ordinary and extraordinary<br/>is <strong>just that little extra</strong> <i className="vossen-quote color"/> </h2> <p className="label label-primary">Albert Einstein</p> </div> <div> <h2> <i className="vossen-quote color"/> <strong>The Desire to Create</strong> is One of the Deepest Yearnings of the Human Soul <i className="vossen-quote color"/> </h2> <p className="label label-primary">Dieter F. Uchtdorf</p> </div> </div> </div> </div> </div> </section> ); } } export default Quotes;
const assert = require('assert'); function f(x) { var x; function dummy() { return x; } x = 100; return x; } assert(f(0) === 100);
import ListLead from "presentation-layer/lead/ListLead"; import AddLead from "presentation-layer/lead/AddLead"; import ListProspect from "presentation-layer/prospect/ListProspect"; import Home from "presentation-layer/home"; import { ROUTER_PATH_LIST } from "./constants"; const routes = [ { path: ROUTER_PATH_LIST.default, component: Home, }, { path: ROUTER_PATH_LIST.leads, component: ListLead, }, { path: ROUTER_PATH_LIST.addLead, component: AddLead, }, { path: ROUTER_PATH_LIST.prospects, component: ListProspect, }, ]; export default routes;
'use strict' const express = require ("express") const fs = require("fs") const https = require ("https") var http = require('http'); const path = require ("path") const app = express() const directoryToServer = "client" var bodyParser = require('body-parser'); var config=require('./config/database'); var User = require('./models/user'); var mongoose = require('mongoose'); var passport = require('passport'); var jwt = require('jwt-simple'); var cookieSession = require('cookie-session'); var cookes = require("cookies"); var cookieParser = require("cookie-parser"); var session = require("express-session"); var morgan = require("morgan"); var helmet = require('helmet'); app.use(helmet()); app.use(cookieParser()); app.use(session({secret: "anystringoftext", saveUninitialized:true, resave:true })); app.use("/checkCookie", function(req, res){ res.send("Cookie has been assigned"); console.log(req.cookies); console.log("============"); console.log(req.session) }); // bundle our routes var register = express.Router(); app.use('/api', register); var memberarea = express.Router(); app.use('/memberarea', memberarea); //configure the express app to parse JSON-formatted body var urlencodedParser = bodyParser.urlencoded({ extended: true }); app.use(bodyParser.json()); app.use(passport.initialize()); require('./config/passport')(passport); memberarea.use(bodyParser.json()); memberarea.use(passport.initialize()); app.use(require('body-parser').json()) //app.use(bodyParser.urlencoded({ extended: false })); const httpsOptions ={ cert: fs.readFileSync(path.join(__dirname, "ssl", "server.crt")), key: fs.readFileSync(path.join(__dirname, "ssl", "server.key")) } https.createServer(httpsOptions, app) .listen(config.port, function(){ console.log(`Serving https connection`)}) // Put a friendly message on the terminal console.log("Server running at "+ config.port+" by host: "+ config.host); //create routing object var contact = require('./api/fixtures/index'); //Add routes for football api memberarea.get('/fixtures',contact.index); memberarea.get('/fixtures/:id',contact.findFixture); memberarea.post('/fixtures',contact.create); memberarea.put('/fixtures/:id',contact.update); memberarea.delete('/fixtures/:id',contact.delete); mongoose.connect(config.database); // create a new user register.post('/signup',urlencodedParser, function(req, res) { if (!req.body.name || !req.body.password || !req.body.email) { res.json({success: false, msg: 'Please fill all fields to register.'}); } else { var newUser = new User({ name: req.body.name, password: req.body.password, email: req.body.email }); // save the user newUser.save(function(err) { if (err) { return res.status(400).send({success: false, msg: 'User already exists'}); } res.json({success: true, msg: 'Successful created new user.'}); }); } }); register.post('/authenticate',urlencodedParser, function(req, res) { User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { // check if password matches user.comparePassword(req.body.password, function (err, isMatch) { if (isMatch && !err) { // if user is found and password is right create a token var token = jwt.encode(user, config.secret); // return the information including token as JSON res.json({success: true, token: 'JWT ' + token}); } else { return res.status(403).send({success: false, msg: 'Authentication failed. Wrong password.'}); } }); } }); }); //Tried creating a secure route, requiring the user to enter a token to perform get all fixtures,post,update & delete memberarea.use(passport.authenticate('jwt', { session: false}), function(req, res) { var token = getToken(req.headers); console.log('the token: ' + token); if (token) { var decoded = jwt.decode(token, config.secret); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'}); } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); var getToken = function (headers) { if (headers && headers.authorization) { var parted = headers.authorization.split(' '); if (parted.length === 2) { return parted[1]; } else { return null; } } else { return null; } };
/* * Requires: * psiturk.js * utils.js */ // Initalize psiturk object var psiTurk = new PsiTurk(uniqueId, adServerLoc, mode); var mycondition = condition; // these two variables are passed by the psiturk server process var mycounterbalance = counterbalance; // they tell you which condition you have been assigned to // they are not used in the stroop code but may be useful to you // All pages to be loaded var pages = [ "instructions/instruct-1.html", "instructions/instruct-2.html", "instructions/instruct-3.html", "instructions/instruct-ready.html", "stage.html", "postquestionnaire.html", "debriefing.html" ]; //call this inside of preload psiTurk.preloadPages(pages); var instructionPages = [ // add as a list as many pages as you like "instructions/instruct-1.html", "instructions/instruct-2.html", "instructions/instruct-3.html", "instructions/instruct-ready.html" ]; //THIS IS FOR AN ALTERNATE INSTRUCTION PAGE METHOD - NOT CURRENTLY WORKING... /* $(window).load( function(){ psiTurk.doInstructions( instructionPages, // a list of pages you want to display in sequence // what you want to do when you are done with instructions ); }); */ //You can change the upper and lower limit of the win percentage here var lowerBound = 0.2; var upperBound = 0.8; var winPercentageLeft; var winPercentageRight; var randomNumber; //for stepping through the instructions at the beginning var page = 0; var introImgBW; var introImgColor; var nextTrial = false; var newRound = true; var textNum = 0; var textPos; var selector; //Image arrays var images = []; var BWimages = []; //Set the selection keys var lettersSmall = [114, 116, 121, 117, 102, 103, 104, 106]; var lettersBig = [82, 84, 89, 85, 70, 71, 72, 74, 75]; var rightIndex; var leftIndex; var rightLetterSmall; var rightLetterBig; var leftLetterSmall; var leftLetterBig; //For randomizing the left and right of the BW/Color images var leftPos = 0+25; var rightPos = 512 +12; var colorPos; var BWPos; //For randomizing image order var colorImageSelect; var BWImageSelect; var colorShuffle = []; var BWShuffle = []; var imageCounter = 1; //For timing var imageOn; var elapsedT; var StartPauseTimer; var PauseTimer; //Recorded data variables var trialTotal = 0; var wins = 0; var losses = 0; var money = 0; var round = 0; var trial = 0; var win = false; var selected; var leftSequentialSelect = 0; var rightSequentialSelect = 0; //USING THIS TO EXPLICITLY STATE THE NUMBER OF IMAGES (instead of .length) var imageNumber = 20; var i; function preload() { //LOAD COLOR IMAGES for (i = 0; i< imageNumber; i++ ){ images[i] = loadImage( "static/images/color" + i + ".jpg" ); } //LOAD BW IMAGES for (i = 0; i< imageNumber; i++ ){ BWimages[i] = loadImage( "static/images/bw_color" + i + ".jpg" ); } } ///////////////////////////////////////////////// //////SETUP///// ///////////////////////////////////////////////// function setup() { //set screen size createCanvas(1024, 520); //Two demo images introImgBW = loadImage("static/images/intro_bw.jpg"); introImgColor = loadImage("static/images/intro_color.jpg"); //initialize round round = 0; //Initialize Array (for selecting images) for (var i = 0; i < imageNumber; i++) { colorShuffle[i] = i; BWShuffle[i] = i; } //underscore has a shuffle method colorShuffle.shuffle(); BWShuffle.shuffle(); } function draw() { //Background color and stroke color background(255); stroke(0); //Each draw cycle sets a different random value between 0 and 1 //This is used to decide whether the selection wins or loses //The randomNumber is compared to the selected bandit's winPercentage randomNumber = random(0,1); //INSTRUCTIONS: Describe the experiment here if (page==0){ instructions(); if(mouseIsPressed){ page+=1; } } //PRACTICE if (page>=1 && page<=3){ p5image(introImgColor, width/2+12, 60); p5image(introImgBW, 0+25, 60); } if (page==1) { page1(); if (key == 'g' || key == 'G') { page+=1; } } if (page == 2) { page2(); if (key == 'h' || key == 'H') { page+=1; } } if (page ==3) { page3(); if (key == 'b' || key == 'B') { page+=1; } } //PAGE WITH NEW ROUND TITLE if (page==4){ printRoundTitle(); if (mouseIsPressed){ page+=1; key='a'; //SELECTION letters are set here (reset with each new round) setLetters(); } } if (page == 5){ ////////////////// //THE EXPERIMENT// ////////////////// if(newRound){ updateRound(); newRound = false; imageSelect(); //START TIMER imageOn = millis(); } if(!newRound){ p5image(images[colorImageSelect], colorPos, 60); p5image(BWimages[BWImageSelect], BWPos, 60); if(!nextTrial) { printRound(); //FOR LEFT SELECTION if (selector == 1) { selector = 0; //TIMING CALCULATION elapsedT = millis() - imageOn; StartPauseTimer = millis(); leftSelect(); } //FOR RIGHT SELECTION if (selector == 2) { selector = 0; //TIMING CALCULATION elapsedT = millis() - imageOn; StartPauseTimer = millis(); rightSelect(); } text("Select an Image", width/2-65, 38); text(String.fromCharCode(leftLetterBig), width/4, 38); text(String.fromCharCode(rightLetterBig), 3*width/4, 38); } printEarnings(); //ONCE A SELECTION IS MADE... if(nextTrial) { printRound(); printOutcome(); //TIMING for pause PauseTimer = millis()-StartPauseTimer; //PAUSE 1500ms, then show cross if(PauseTimer>1500){ background(255); strokeWeight(3); line(width/2-15, height/2, width/2+15, height/2); line(width/2, height/2-15, width/2, height/2+15); } //PAUSE 500ms with cross on screen then go to NEXT TRIAL if(PauseTimer > 2000){ nextTrial = false; //RECORD DATA HERE record_responses(elapsedT, colorPos, BWPos, colorImageSelect, BWImageSelect, trialTotal, round, winPercentageLeft, winPercentageRight, trial, selected, win, wins, losses, money, leftSequentialSelect, rightSequentialSelect); //RESET TIMER imageOn = millis(); PauseTimer = 0; //NEW ROUND TEST: After a set number of trials (or consecutive selections of one bandit) move on to the next round... if (trial == 20 || leftSequentialSelect >= 7 || rightSequentialSelect >= 7){ newRound = true; page-=1; leftSequentialSelect =0; rightSequentialSelect = 0; setLetters(); //this may be redundant? Also called on 'page 4' } if (trialTotal >= 30){ //Then save the data psiTurk.saveData(); //Then compute the bonus [this is NOT working yet] psiTurk.computeBonus('compute_bonus'); //Then finish - which loads the debriefing page finish(); } } } } } } ///////////////////////////////////////////////// //////// RECORD DATA FUNCTION//////////////////// ///////////////////////////////////////////////// function record_responses(elapsedT, colorPos, BWPos, colorImageSelect, BWImageSelect, trialTotal, round, winPercentageLeft, winPercentageRight, trial, selected, win, wins, losses, money, leftSequentialSelect, rightSequentialSelect) { psiTurk.recordTrialData({ "Round": round, "Left_Win Percentage": winPercentageLeft, "Right_Wind Percentage": winPercentageRight, "Color Image": colorImageSelect, "BW Image": BWImageSelect, "Color Position": colorPos, "BW Position": BWPos, "Trial": trial, "Selected Image": selected, "Time Elapsed": elapsedT, "Win?": win, "Win Total": wins, "Loss Total": losses, "Earnings": money, "Left Sequential": leftSequentialSelect, "Right Sequential": rightSequentialSelect, "Total Trials": trialTotal }); //use the window alert below if you want to test what is being written to any given value //window.alert("Trial #" + trial + " Amount: " + money); }; var finish = function() { currentview = new endExperiment(); }; ///////////////////////////////////////////////// ////////END: SEND TO DEBRIEF///////////////////// ///////////////////////////////////////////////// var endExperiment = function() { prompt_resubmit = function() { replaceBody(error_message); $("#resubmit").click(resubmit); }; resubmit = function() { replaceBody("<h1>Trying to resubmit...</h1>"); reprompt = setTimeout(prompt_resubmit, 10000); psiTurk.saveData({ success: function() { clearInterval(reprompt); }, error: prompt_resubmit }); }; // Load the debriefing page psiTurk.showPage('debriefing.html'); //code for bonus?? $("#next").click(function () { record_responses(); psiTurk.saveData({ success: function(){ psiTurk.computeBonus('compute_bonus', function() { psiTurk.completeHIT(); // when finished saving compute bonus, the quit }); }, error: prompt_resubmit}); }); } function keyPressed(){ if (key == String.fromCharCode(leftLetterSmall) || key == String.fromCharCode(leftLetterBig)){ selector = 1; } else if (key == String.fromCharCode(rightLetterSmall) || key == String.fromCharCode(rightLetterBig)){ selector = 2; } return false; } function lowerBanner(){ fill(0,0,0,155); rect(width/2-150, 440, 300, 60); textSize(40); fill(200); } function setLetters(){ rightIndex = int(random(lettersSmall.length)); leftIndex = int(random(lettersSmall.length)); while (rightIndex == leftIndex){ leftIndex = int(random(lettersSmall.length)); } rightLetterSmall = lettersSmall[rightIndex]; rightLetterBig = lettersBig[rightIndex]; leftLetterSmall = lettersSmall[leftIndex]; leftLetterBig = lettersBig[leftIndex]; } Array.prototype.shuffle = function() { var input = this; for (var i = input.length-1; i >=0; i--) { var randomIndex = Math.floor(Math.random()*(i+1)); var itemAtIndex = input[randomIndex]; input[randomIndex] = input[i]; input[i] = itemAtIndex; } return input; } function imageSelect(){ if (random(0,1) < 0.5){ colorPos = rightPos; BWPos = leftPos; } else { colorPos = leftPos; BWPos = rightPos; } colorImageSelect = colorShuffle[imageCounter%colorShuffle.length]; BWImageSelect = BWShuffle[imageCounter%BWShuffle.length]; while (colorImageSelect == BWImageSelect){ imageCounter+=1; colorImageSelect = colorShuffle[imageCounter%colorShuffle.length]; BWImageSelect = BWShuffle[imageCounter%BWShuffle.length]; } imageCounter+=1; } function printOutcome(){ fill(255,255,255,100); rect(textPos, 190, 250, 100); textSize(90); fill(0); if(textNum ==1){ text("WIN", textPos+38, height/2+13); } if(textNum ==2){ text("LOSE", textPos+9, height/2+13); } } function printRound(){ textSize(24); fill(0); text("ROUND " + round, 30, 455); } function printEarnings(){ //KEEP TRACK OF EARNINGS //////////////////////// //FOR JAVA VERSION //money = (0.05*wins - 0.05*losses); //FOR JAVASCRIPT VERSION money = (0.05*wins - 0.05*losses).toFixed(2); lowerBanner(); textSize(32); text("TOTAL = $" + money, width/2-122, 440+40); } function leftSelect(){ if (randomNumber < winPercentageLeft) { //UNCOMMENT timer //elapsedT = new Date().getTime() - imageOn; win = true; wins +=1; textNum = 1; } else { win = false; losses +=1; textNum = 2; } //add datapoints to save here textPos = 138; selected = "left"; trial++; nextTrial = true; leftSequentialSelect+=1; rightSequentialSelect=0; trialTotal++; print(" Total Trials: " + trialTotal); } function rightSelect(){ if (randomNumber <winPercentageRight) { //UNCOMMENT timer //elapsedT = new Date().getTime() - imageOn; win = true; wins +=1; textNum = 1; } else { win = false; losses +=1; textNum = 2; } //add datapoints to save here textPos = width/2+138; selected = "right"; trial++; nextTrial = true; leftSequentialSelect=0; rightSequentialSelect+=1; trialTotal++; print(" trial: " + trial); print("Total Trials: " + trialTotal); } function printRoundTitle(){ background(255); fill(0,0,0,30); rect(200, 200, 624, 120); textSize(90); fill(0); text("ROUND " + (round+1), 310, height/2+13); textSize(30); fill(80); text("Click here to continue", 360, height/2+50); } function updateRound(){ if (round == 0){ if (randomNumber > 0.5){ winPercentageRight = 0.7; winPercentageLeft = 0.3; } else { winPercentageRight = 0.3; winPercentageLeft = 0.7; } round+=1; } else{ winPercentageLeft = random(lowerBound,upperBound); winPercentageLeft = (Math.ceil(winPercentageLeft*20-0.5)/20).toFixed(2); winPercentageRight = (1 - winPercentageLeft).toFixed(2); trial=0; round+=1; } print(" Round #" + round); print(" Left: "+ winPercentageLeft); print(" Right: " + winPercentageRight); } //ADD INSTRUCTIONS HERE /////////////////////// function instructions(){ textSize(30); fill(0); text("Welcome to our test experiment...", 50, 50); textSize(13); textStyle(NORMAL); textFont("Helvetica"); text("NOTE: This is not a real experiment, we are just testing out the process at this point.", 50, 80); text("Everything should work normally, but data will not be used and the trial length is shorter.", 50, 95); text("In the experiment you will select either the left or right box - each has a different image.", 50, 110); text("When you select the box you will either 'win' or 'lose'.", 50, 125); text("This will result in a bonus of either +$0.05 or - $0.05.", 50, 140); text("A tally will be kept over the course of the trial of your total bonus.", 50, 155); text("If upon completion you have a positive value you will be bonused this amount.", 50, 170); text("If you have a negative amount, this will just be calculated as a ZERO bonus.", 50, 185); text("On the next screen you will practice the process.", 50, 205); text("The actual trial will begin when you see the screen 'Round 01'.", 50, 220); fill(0,0,0,100); rect(362,250, 300,50); fill(0); textSize(24); text("Click here to continue.", 383, 284); } function page1() { fill(0); textSize(20); text("Press the 'G' key to select the left image", width/2-190, 38); lowerBanner(); text("PRACTICE", width/2-90, 440+45); } function page2() { fill(0); textSize(20); text("Press the 'H' key to select the right image", width/2-190, 38); lowerBanner(); text("PRACTICE", width/2-90, 440+45); fill(255,255,255,100); rect(138, 190, 250, 100); textSize(90); fill(0); text("LEFT", 138+28, height/2+13); } function page3 () { fill(0); textSize(20); text("Press the 'B' key to begin", width/2-115, 38); lowerBanner(); text("PRACTICE", width/2-90, 440+45); fill(255,255,255,100); rect(width/2+113, 190, 300, 100); textSize(90); fill(0); text("RIGHT", width/2+113+18, height/2+13); } //}; //var myp5 = new p5(ImageExperiment);
var searchData= [ ['inertia_20',['Inertia',['../class_lean_1_1_touch_1_1_lean_drag_translate_x.html#a08b81d88d8f79c17c48fab0c1334b398',1,'Lean.Touch.LeanDragTranslateX.Inertia()'],['../class_lean_1_1_touch_1_1_lean_drag_translate_y.html#a0924aa1bb824bcbc79a19f664d4261c7',1,'Lean.Touch.LeanDragTranslateY.Inertia()']]], ['isfrontview_21',['isFrontView',['../class_flip_camera.html#adb2903236d15991265bcacd3cf764e2b',1,'FlipCamera']]], ['isxray_22',['isXRay',['../class_scene_handler.html#a24efe58f87ec3ed014b20a29483f852a',1,'SceneHandler']]] ];
var hellopreloader = document.getElementById("hellopreloader_preload"); function fadeOutnojquery(el){el.style.opacity = 1; var interhellopreloader = setInterval(function(){el.style.opacity = el.style.opacity - 0.05; if (el.style.opacity <=0.05){ clearInterval(interhellopreloader); hellopreloader.style.display = "none";}},16);} window.onload = function() {setTimeout(function(){fadeOutnojquery(hellopreloader);},1000);}; $('.link').click(function(){ var volume = $(this); volume.toggleClass('on'); if (volume.is('.on')) $('#video').prop("volume", 1); else $('#video').prop("volume", 0); });
// switches to call right functions for context function setSketchup() { // switch to actions for Sketchup (skp:...) log.info('using Sketchup backend ...'); log.debug('browser: ' + navigator.userAgent); SKETCHUP = true; } function setTest() { // set dummy actions try { log.info('using dummy backend ...'); log.debug('browser: ' + navigator.userAgent); } catch (e) { // log might not be defined yet } SKETCHUP = false; } function applySkySettings() { // send back location and sky settings var params = modelLocation.toParamString(); if (SKETCHUP == true) { // log.debug("applySkySettings():<br/>" + params.replace(/&/g,"<br/>")); window.location = 'skp:applySkySettings@' + params; } else { log.debug("using dummy backend.applySkySettings()"); } } function onApplySkySettingsToModel() { // apply settings to Sketchup shadow_info if (SKETCHUP == true) { log.info("applying settings to Sketchup model ..."); window.location = 'skp:writeSkySettingsToShadowInfo@'; } else { log.debug("using dummy backend.writeSkySettingsToShadowInfo() ..."); modelLocation.changed = false; // TODO: // msg = modelLocation.toJSON(); // setShadowInfoFromJSON(msg); clearTZWarning(); updateSkyPage(); } } function getExportOptions() { // collect and set export option values if (SKETCHUP == true) { log.info("getting shadowInfo from SketchUp ..."); window.location = 'skp:getExportOptions@'; // setExportOptionsJSON() called by Sketchup } else { var json = test_getExportOptions(); setExportOptionsJSON( encodeJSON(json) ); } } function getSkySettings() { // get SketchUp shadow_info settings and apply to modelLocation if (SKETCHUP == true) { log.info("getting shadowInfo from SketchUp ..."); window.location = 'skp:getSkySettings@'; // setShadowInfoJSON() called by Sketchup } else { log.debug("using dummy backend.getSkySettings()"); var json = test_getSkySettings(); setShadowInfoJSON( encodeJSON(json) ); } } function loadFileCallback(text) { //dummy function to be reasigned to real callback } function loadTextFile(fname) { log.debug("loadTextFile() fname='" + fname + "'"); if (SKETCHUP == true) { window.location = 'skp:loadTextFile@' + fname; } else { log.warn("Warning: can't load file without backend! (fname='" + fname + "')"); loadFileCallback(''); } } function applyExportOptions() { var param = exportSettings.toString(); if (SKETCHUP == true) { // log.debug("applyExportOptions:<br/>" + param.replace(/&/g,"<br/>") ); window.location = 'skp:applyExportOptions@' + param; } else { log.debug("using dummy backend.applyExportOptions()"); param = param.replace(/&/g,"<br/>"); setStatusMsg("applyExportOptions:<br/>" + param); } } function applyRenderOptions() { param = radOpts.toString(); if (SKETCHUP == true) { // log.debug("applyRenderOptions:<br/>" + param.replace(/&/g,"<br/>") ); window.location = 'skp:applyRenderOptions@' + param; } else { log.debug("using dummy backend.applyRenderOptions()"); param = param.replace(/&/g,"<br/>"); setStatusMsg("applyRenderOptions:<br/>" + param); } } function decodeJSON(text) { var json = unescape(text) return json; } function decodeText(encText) { // text file is encoded via urlEncode - replace '+' var text = unescape(encText) text = text.replace(/\+/g,' '); return json; } function encodeJSON(json) { var text = escape(json); return text; } function setViewJSON(name,text) { //log.error("DEBUG: setViewJSON: '" + name + "'<br/>" + text); var viewname = decodeJSON(name); var json = decodeJSON(text); var obj = {}; try { eval("obj = " + json); viewsList.setView(viewname, obj); return true; } catch (e) { log.error("setViewJSON: error in eval() '" + e.name + "'"); log.error("json= " + json.replace(/,/g,',<br/>')); return false; } } function setViewsListJSON(text) { // eval JSON views string from SketchUp var json = decodeJSON(text); //log.debug("setViewsListJSON=<br/>" + json.replace(/,/g,',<br/>')); var newViews = new Array(); try { eval("newViews = " + json); //log.debug("eval(): newViews.length=" + newViews.length); } catch (e) { log.error("setViewsListJSON: error in eval() '" + e.name + "'"); log.error("json= " + json.replace(/,/g,',<br/>')); } viewsList.setViewsList(newViews); updateViewsSummary(); } function getViewsList() { if (SKETCHUP == true) { log.info("getting views from SketchUp ..."); window.location = 'skp:setViewsList@'; // setViewsListJSON() called by Sketchup } else { log.debug("using dummy backend.getViewsList()"); var msg = test_getViewsListTest(); setViewsListJSON( encodeJSON(msg) ); } } function applyViewSettings(viewname) { //log.debug('applyViewSettings(' + viewname + ')'); try { var view = viewsList[viewname]; } catch(e) { log.error(e) return } //log.debug('applyViewSettings(view=' + view + ')'); var text = view.toRubyString(); var param = encodeURI(text); if (SKETCHUP == true) { window.location = 'skp:applyViewSettings@' + param; } else { log.debug("using dummy backend.applyViewSettings()"); updateViewDetailsList(); } } function removeViewOverride(viewname, override) { //log.debug("removeViewOverride('" + viewname + "','" + override + "')"); var param = encodeURI(viewname) + "&" + encodeURI(override); if (SKETCHUP == true) { window.location = 'skp:removeViewOverride@' + param; } else { log.debug("using dummy backend.removeViewOverride()"); try { var view = viewsList[viewname]; var json = view.toJSON(); setViewJSON(viewname, json); } catch (err) { log.error("removeViewOverride: '" + e.name + "'"); } } } function skpRemoveMaterialAlias(skmname, skmgroup) { var text = skmname + "&" + skmgroup; var param = encodeURI(text); if (SKETCHUP == true) { window.location = 'skp:removeMaterialAlias@' + param; } else { log.debug("using dummy backend.skpSetMaterialAlias()"); } } function skpSetMaterialAlias(skmname, radname, mtype) { var text = skmname + "&" + radname + "&" + mtype; var param = encodeURI(text); if (SKETCHUP == true) { window.location = 'skp:setMaterialAlias@' + param; } else { log.debug("using dummy backend.skpSetMaterialAlias()"); } } function setMaterialsListJSON(text, type) { try { var json = decodeJSON(text); //log.error("TEST: setMaterialsListJSON=<br/>json.length=" + json.length); var newMats = new Array(); try { eval("newMats = " + json); //log.debug("materials found: " + newMats.length); } catch (e) { log.error("setMaterialsListJSON: error in eval() '" + e.name + "'"); log.error("json= " + json.replace(/,/g,',<br/>')); } if (type == 'skm') { skmMaterialsList.update(newMats); buildMaterialListByType('skm') } else if (type == 'layer') { layerMaterialsList.update(newMats); buildMaterialListByType('layer') } else if (type == 'rad') { radMaterialsList.update(newMats); setGroupSelection() buildMaterialListRad() } else { log.warn("unknown material list type '" + type + "'"); } } catch (err) { log.error("setMaterialsListJSON:'" + err.message + "'"); } }
// set express and express-router const express = require('express') const router = express.Router() // import restaurant model const Restaurant = require('../../models/restaurant') // set show restaurant detail router.get('/:restaurantId/detail', (req, res) => { const id = req.params.restaurantId return Restaurant.findById(id) .lean() .then(restaurant => res.render('show', { restaurant })) .catch(error => console.log(error)) }) // set new restaurant route router.get('/new', (req, res) => { res.render('new') }) // set create new restaurant router.post('/', (req, res) => { const name = req.body.name const name_en = req.body.name_en const category = req.body.category const image = req.body.image const location = req.body.location const phone = req.body.phone const google_map = req.body.google_map const rating = req.body.rating const description = req.body.description return Restaurant.create({ name, name_en, category, image, location, phone, google_map, rating, description }) .then(() => res.redirect('/')) .catch(error => console.log(error)) }) // set edit restaurant route router.get('/:restaurantId/edit', (req, res) => { const id = req.params.restaurantId return Restaurant.findById(id) .lean() .then(restaurant => res.render('edit', { restaurant })) .catch(error => console.log(error)) }) // set edit restaurant router.put('/:restaurantId', (req, res) => { const id = req.params.restaurantId const name = req.body.name const name_en = req.body.name_en const category = req.body.category const image = req.body.image const location = req.body.location const phone = req.body.phone const google_map = req.body.google_map const rating = req.body.rating const description = req.body.description return Restaurant.findById(id) .then(restaurant => { restaurant.name = name restaurant.name_en = name_en restaurant.category = category restaurant.image = image restaurant.location = location restaurant.phone = phone restaurant.google_map = google_map restaurant.rating = rating restaurant.description = description return restaurant.save() }) .then(() => res.redirect('/')) .catch(error => console.log(error)) }) // set delete restaurant router.delete('/:restaurantId', (req, res) => { const id = req.params.restaurantId return Restaurant.findById(id) .then(restaurant => restaurant.remove()) .then(() => res.redirect('/')) .catch(error => console.log(error)) }) // export router module.exports = router
function EntityCollection(glHost, model, vertexShader, fragmentShader) { this.glHost = glHost; this.model = model; this.vertexShader = vertexShader; this.fragmentShader = fragmentShader; this.entities = []; } EntityCollection.prototype.CreateEntity = function(uniforms, attributes) { let entity = new Entity(this.glHost, this.model, uniforms, attributes); entity.SetupProgram(this.vertexShader, this.fragmentShader); this.entities.push(entity); } EntityCollection.prototype.CopyUniformValues = function(entityIndex, uniformSet) { this.entities[entityIndex].UpdateUniforms(uniformSet) this.entities[entityIndex].EnableProgram(); this.entities[entityIndex].CopyUniformValues(); } EntityCollection.prototype.Draw = function() { this.entities.forEach((entity) => { entity.EnableProgram(); entity.Draw(); }); }
var request = require('request'); var express = require('express'); var app = express(); var bodyParser = require('body-parser') var port = process.env.PORT || 8082 var router = express.Router(); router.use(function(req,res,next){ next(); }) var seatToHold = '6A' var holdSeat = function(){ request.put('http://localhost:8081/api/seats/', {form:{'isOnHold': true, 'number': seatToHold}}, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) } }) } holdSeat();
/** * Created by My-PC on 9/13/2016. */ // Load required packages var oauth2orize = require('oauth2orize'); var passport = require('passport'); var crypto = require('crypto'); var guid = require('../utils/guid'); var server = oauth2orize.createServer(); var db = require('../models'); server.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) { console.log('abcd'); db.User.findOne({ where: { email: username } }).then(function (user) { console.log('login success'); if (!user) return done(null, false) if (password === user.password) { var token = guid.uid(256); var refreshToken = guid.uid(256); var tokenHash = crypto.createHash('sha1').update(token).digest('hex'); var refreshTokenHash = crypto.createHash('sha1').update(refreshToken).digest('hex'); var expirationDate = new Date(new Date().getTime() + (3600 * 1000)); db.AccessToken.create({ token: tokenHash, expirationDate: expirationDate, clientId: client.clientId, userId: username }).then(function () { db.RefreshToken.create({ token: refreshTokenHash, clientId: client.clientId, userId: username }).then(function () { done(null, token, refreshToken, {expires_in: expirationDate}) }, function (err) { return done(err) }); }, function (err) { return done(err) }); } else { console.log('Cannot find user'); return done(null, false) } }, function (err) { return done(err); }); })) server.exchange(oauth2orize.exchange.refreshToken(function (client, refreshToken, scope, done) { var refreshTokenHash = crypto.createHash('sha1').update(refreshToken).digest('hex'); db.RefreshToken.findOne( { where: {refreshToken: refreshTokenHash} }).then(function (token) { if (!token) return done(null, false) if (client.clientId !== token.clientId) return done(null, false) var newAccessToken = guid.uid(256) var accessTokenHash = crypto.createHash('sha1').update(newAccessToken).digest('hex'); var expirationDate = new Date(new Date().getTime() + (3600 * 1000)) db.AccessToken.update({ token: accessTokenHash, scope: scope, expirationDate: expirationDate }, { where: { userId: token.userId } }).then(function () { done(null, newAccessToken, refreshToken, {expires_in: expirationDate}); }, function (err) { return done(err); }) }, function (err) { return done(err); }); })) exports.decision = [ server.decision() ] exports.token = [ passport.authenticate(['clientBasic', 'clientPassword'], {session: false}), server.token(), server.errorHandler() ]
/** * 福利商城商品详情页 */ import React, { Component, PureComponent } from 'react'; import { StyleSheet, Dimensions, View, Text, TouchableOpacity, ImageBackground, Image, StatusBar, Platform, } from 'react-native'; import { connect } from 'rn-dva'; import config from '../../config/config'; import CommonStyles from '../../common/Styles'; import Header from '../../components/Header'; import * as requestApi from '../../config/requestApi'; import FlatListView from '../../components/FlatListView'; import WebViewCpt from '../../components/WebViewCpt'; import ShareTemplate from '../../components/ShareTemplate'; import ShowBigPicModal from '../../components/ShowBigPicModal'; import * as nativeApi from "../../config/nativeApi"; import { NavigationComponent } from '../../common/NavigationComponent'; const { width, height } = Dimensions.get('window'); const weibo = require('../../images/share/weibo.png') const weixin = require('../../images/share/weixin.png') const qqicon = require('../../images/share/qqicon.png') const friendsquan = require('../../images/share/friendsquan.png') const copylian = require('../../images/share/copylian.png') const friends = require('../../images/share/friends.png') class WMGoodsDetailScreen extends NavigationComponent { static navigationOptions = { header: null, } constructor(props) { super(props); this.state = { goodsData: {}, canGoBack: false, modalVisible: false, modalLists: [ { id: 1, title: '分享', icon: require('../../images/mall/share.png'), routeName: '' }, { id: 2, title: '意见反馈', icon: require('../../images/mall/fankui.png'), routeName: 'Feedback' }, // { // id: 3, // title: '往期揭晓', // icon: require('../../images/mall/pre_prize_icon.png'), // routeName: 'PastWinners' // } ], uri:'welfFareGoodsDetails', shareModal: false, shareUrl: '', // 分享链接 shareParams: null, showBingPicVisible: false, bigIndex: 0, // 大图索引 bigList: [], // 查看大图所有图片 goodsId:(global.nativeProps && global.nativeProps.goodsId) || this.props.navigation.getParam('goodsId',''), sequenceId:(global.nativeProps && global.nativeProps.sequenceId) || this.props.navigation.getParam('sequenceId','') } } blurState = { shareModal: false, modalVisible: false, showBingPicVisible: false, } screenDidFocus = (payload)=> { super.screenDidFocus(payload) StatusBar.setBarStyle('dark-content') } screenWillBlur = (payload)=> { super.screenWillBlur(payload) StatusBar.setBarStyle('light-content') } getGoodsDetail = (router = '') => { Loading.show(); requestApi.lotteryDetail({ sequenceId: this.state.sequenceId, }).then(res => { console.log('商品详情',this.props,res) if (router === 'Feedback') { this.props.navigation.navigate('Feedback', { goodsData:res.jSequence.goods }); } if (router === 'PastWinners') { this.props.navigation.navigate('PastWinners', { goodsData:res.jSequence.goods }); } }).catch(err => { console.log(err) }) } changeState(key, value) { this.setState({ [key]: value }); } postMessage = () => { } goBack = () => { const { navigation } = this.props; const { canGoBack } = this.state; if (canGoBack) { this.webViewRef.goBack(); } else { global.nativeProps?nativeApi.popToNative(): navigation.goBack(); } } //进入结算界面: jsOpenIndianaShopOrder(e) { let str = e.replace('jsOpenIndianaShopOrder,','') let data = JSON.parse(str) console.log('data1111',data) let datalist = [] let totlePrice = 0 if (data.jSequence.goods.id) { datalist[0] = {} datalist[0].goodsId = data.jSequence.goods.id datalist[0].quantity = data.quantity datalist[0].price = data.jSequence.lotteryWay.eachNotePrice datalist[0].name = data.jSequence.goods.name datalist[0].url = data.jSequence.goods.mainPic datalist[0].lotteryNumber = null datalist[0].participateStake = data.jSequence.currentCustomerNum datalist[0].drawTime = data.jSequence.expectLotteryDate datalist[0].drawType = data.jSequence.lotteryWay.jDrawType datalist[0].maxStake = data.jSequence.lotteryWay.eachSequenceNumber datalist[0].sequenceId = data.jSequence.id totlePrice = data.quantity * data.jSequence.lotteryWay.eachNotePrice; this.props.navigation.navigate('IndianaShopOrder', { data: datalist, totlePrice: totlePrice }); return } Toast.show('请求中,请稍候...') } // 打开购物车 jsOpenAppShoppingCart = (e) => { this.props.navigation.navigate('IndianaShopCart'); } // 打开客服 jsOpenAppCustomerService = (e) => { // Toast.show('开发中'); nativeApi.createXKCustomerSerChat() } // 打开图片浏览 jsOpenAppImageBrowser = (param) => { let _params = param.replace('jsOpenAppImageBrowser,',''); let _data = JSON.parse(_params); let { index,list } = _data let temp = []; console.log('list',list) list.map(item => { if (item.type === 'img') { temp.push({ url: item.url, type: 'images' }) } if (item.type === 'video') { temp.push({ mainPic: item.mainPic, url: item.url, type: 'video' }) } }) console.log(temp) StatusBar.setHidden(true); this.setState({ bigIndex: index, bigList: temp, showBingPicVisible: true, }) console.log('打开图片浏览',JSON.parse(_params)); } // 打开全部评价 jsOpenAppComments = (e) => { this.props.navigation.navigate('WMAllShowOrder', { goodsId:this.state.goodsId }); } // 获取分享路径 pushSharePath = (e) => { e = e.replace('pushSharePath,', '') let param = JSON.parse(e); this.changeState('shareUrl', param.shareUrl); this.changeState('shareParams', param.param); } componentWillUnmount() { super.componentWillUnmount(); Loading.hide(); } goToAlgorithm (data) { let _data = data.replace('jsOpenAlgorithm,', ''); console.log(JSON.parse(_data)) requestApi.detailJLottery({ sequenceId: JSON.parse(_data).sequenceId }).then(res => { console.log('resres', res) let param = { thirdWinningTime: res.thirdWinningTime, thirdWinningNo: res.thirdWinningNo, thirdWinningNumber: res.thirdWinningNumber, termNumber: res.termNumber, userBuyRecord: res.currentCustomerNum || 0, // 本期参与人次 lotteryNumber: res.lotteryNumber, // 中奖编号 } this.props.navigation.navigate('WMLotteryAlgorithm',{lotteryData: param}) }).catch(err => { console.log(err) }) } goToNewDetail (data) { let _data = data.replace('jsOpenPrizeDetail,', ''); this.props.navigation.navigate('WMNewGoodsDetail',JSON.parse(_data)) } handleShowpage = () => { const { bigList,bigIndex } = this.state if (bigList.length > 0) { return !(Platform.OS === 'ios' && bigList[bigIndex].type === 'video') } return true } render() { const { navigation, userInfo,dispatch } = this.props; const { goodsData, modalVisible,uri, modalLists, shareModal, shareParams, shareUrl ,goodsId,sequenceId} = this.state; let _baseUrl = `${config.baseUrl_h5}welfFareGoodsDetails`; let referralCode = userInfo.securityCode; let _url = `${_baseUrl}?id=${sequenceId}&goodsId=${goodsId}&merchantId=${userInfo.merchantId}&securityCode=${referralCode}`; // let _url = `http://192.168.2.115:8080/#/lotteryIndex?id=${sequenceId}&goodsId=${goodsId}&merchantId=${userInfo.merchantId}&securityCode=${referralCode}`; // 本地测试地址 let source = { uri: _url, showLoading: true, headers: { "Cache-Control": "no-cache" } } return ( <View style={styles.container}> <StatusBar barStyle={'dark-content'} /> {<WebViewCpt webViewRef={(e) => { this.webViewRef = e }} isNeedUrlParams={true} source={source} postMessage={() => { this.postMessage(); }} getMessage={(data) => { let params = data && data.split(','); console.log('params',params) if (params[0] === 'jsOpenAppShoppingCart') { this.jsOpenAppShoppingCart(params); } else if (params[0] === 'jsOpenAppCustomerService') { this.jsOpenAppCustomerService(params); } else if (params[0] === 'jsOpenAppImageBrowser') { this.jsOpenAppImageBrowser(data); } else if (params[0] === 'jsOpenAppComments') {// 打开全部晒单 this.jsOpenAppComments(params); } else if (params[0] === 'pushSharePath') { this.pushSharePath(data); } else if (params[0] === 'jsOpenIndianaShopOrder') { this.jsOpenIndianaShopOrder(data); } else if (params[0] === 'jsOpenAllParticipant') {//打开所有参与详情 navigation.navigate('WMPartakeDetail',{sequenceId}) } else if (params[0] === 'jsOpenPrizeDetail') {//跳转商品详情 this.goToNewDetail(data) } else if (params[0] === 'jsOpenRecentLottery') {// 跳转到往期揭晓 this.getGoodsDetail('PastWinners') } else if (params[0] === 'goToLotteryActivity') {// 跳到抽奖转盘 navigation.navigate('WMLotteryActivity') } else if (params[0] === 'jsOpenAlgorithm') {// 开奖算法 this.goToAlgorithm(data) } else if (params[0] === 'jsHiddenXKHUDView') { Loading.hide() } else { console.log(params); } }} />} <Header navigation={navigation} headerStyle={styles.headerStyle} leftView={ <TouchableOpacity style={styles.headerItem} activeOpacity={0.6} onPress={() => { this.goBack(); }} > <Image source={require('../../images/mall/goback_gray.png')} /> </TouchableOpacity> } rightView={ <TouchableOpacity style={styles.headerItem} activeOpacity={0.6} onPress={() => { this.changeState('modalVisible', true); }} > <Image source={require('../../images/mall/more_gray.png')} /> </TouchableOpacity> } /> {/* 点击更多弹窗 */} { modalVisible && <TouchableOpacity style={styles.modalOutView} activeOpacity={1} onPress={() => { this.changeState('modalVisible', false); }} > <ImageBackground style={styles.modalInnerView} resizeMode='center' source={require('../../images/mall/more_modal_bg.png')} > {/* <View style={[CommonStyles.flex_center,{height: 81,marginTop: 13}]}> */} <View style={[CommonStyles.flex_center,{height: 127 - 11,marginTop: 13}]}> { modalLists.map((item, index) => { let bottomBorder = index === modalLists.length - 1 ? null : styles.borderBottom; return ( <View key={index} style={[CommonStyles.flex_1,{paddingHorizontal: 10}]}> <TouchableOpacity key={index} style={[styles.modalInnerItem,bottomBorder]} activeOpacity={0.6} onPress={() => { this.changeState('modalVisible', false); if (item.routeName) { // 福利详情和自营详情的goodsData的商品名字不一样,这里统一,然后跳转商品反馈 if (item.routeName === 'Feedback') { this.getGoodsDetail('Feedback') return } if (item.routeName === 'PastWinners') { this.getGoodsDetail('PastWinners') } } else { console.log('shareParamsshareParams', shareParams) if (shareParams) { this.changeState('shareModal', true); } else { Toast.show('获取分享信息失败'); } } }} > <View style={[CommonStyles.flex_1,CommonStyles.flex_start]}> <Image source={item.icon} /> <Text style={styles.modalInnerItem_text}>{item.title}</Text> </View> </TouchableOpacity> </View> ) }) } </View> </ImageBackground> </TouchableOpacity> } {/* 分享 */} { shareModal && <ShareTemplate type='WM' onClose={() => { this.changeState("shareModal", false); }} shareParams={shareParams} shareUrl={shareUrl} callback={() => { Toast.show('分享成功') }} // 确认分享回调 /> } {/* 查看大图 */} <ShowBigPicModal isShowPage={this.handleShowpage()} ImageList={this.state.bigList} visible={this.state.showBingPicVisible} showImgIndex={this.state.bigIndex} onClose={() => { StatusBar.setHidden(false); this.setState({ showBingPicVisible: false, }) }} /> </View> ); } }; const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, }, headerStyle: { position: 'absolute', top: CommonStyles.headerPadding, height: 44, paddingTop: 0, backgroundColor: 'transparent', }, headerItem: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: '100%', width: 50, }, footerView: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: width, height: 50 + CommonStyles.footerPadding, paddingBottom: CommonStyles.footerPadding, }, footerItem: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 50, }, footerItem1: { flex: 1.6, backgroundColor: '#fff', }, footerItem1_imgView: { justifyContent: 'center', alignItems: 'center', height: '100%', paddingHorizontal: 10, }, footerItem2: { flex: 1, backgroundColor: '#4A90FA', }, footerItem3: { flex: 1, backgroundColor: '#EE6161', }, footerItem_text: { fontSize: 14, color: '#fff', }, modalOutView: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'transparent', // backgroundColor: 'blue' }, modalInnerView: { position: 'absolute', top: 44 + CommonStyles.headerPadding, right: 12, width: 126, height: 130, // height: 93 }, modalinnerItem_border: { borderTopWidth: 1, borderTopColor: 'rgba(255,255,255,0.2)', }, modalInnerItem: { flexDirection: "row", justifyContent: "flex-start", alignItems: "center", width: "100%", height: '100%', paddingLeft: 5, // height: 41, // paddingHorizontal: 15, // flexDirection: 'row', // justifyContent: 'flex-start', // alignItems: 'center', // width: '100%', // height: 41, // paddingLeft: 15, // paddingTop: 10 // backgroundColor:'rgba(10,10,10,.5)' }, modalInnerItem_text: { fontSize: 17, color: '#fff', marginLeft: 8, }, modalOutView2: { justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.5)', }, shareModalView: { width: width - 55, marginHorizontal: 27.5, borderRadius: 8, backgroundColor: '#fff', overflow: 'hidden', }, shareModalView_img: { width: '100%', height: 110, }, shareModalView_center: { width: '100%', // borderTopWidth: 1, // borderTopColor: '#E5E5E5', borderBottomWidth: 1, borderBottomColor: '#E5E5E5', }, shareModalView_center_top: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%', height: 80, paddingHorizontal: 10, paddingVertical: 7, }, shareModalView_center_top_left: { justifyContent: 'space-between', height: '100%', }, shareModalView_center_top_right: { width: 66, height: '100%', }, shareModalView_center_top_right_img: { width: '100%', height: '100%', }, shareModalView_center_top_left_text1: { fontSize: 12, color: '#777', }, shareModalView_center_top_left_item1: { paddingHorizontal: 20, paddingVertical: 2, borderRadius: 10, backgroundColor: '#FF545B', }, shareModalView_center_top_left_text2: { fontSize: 12, color: '#fff', }, shareModalView_center_bom: { flexDirection: 'row', flexWrap: 'wrap', paddingTop: 10, }, shareModalView_center_bom_view: { justifyContent: 'center', alignItems: 'center', width: '25%', marginBottom: 10, }, shareModalView_center_bom_img: { width: 40, height: 40, }, shareModalView_center_bom_text: { fontSize: 10, color: '#777', marginTop: 5, }, shareModalView_bom: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: '100%', height: 36, }, shareModalView_bom_text: { fontSize: 14, color: '#222', }, goodsInfoWrap: { padding: 10, }, goodsTitle: { fontSize: 14, color: '#222' }, goodsInfoPrice: { paddingHorizontal: 7, paddingVertical: 4, backgroundColor: '#FF545B', color: '#fff', fontSize: 12, borderRadius: 20, }, borderBottom: { borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255,.2)' }, }); export default connect( (state) => ({ userInfo: state.user.user, }), (dispatch) => ({ dispatch }) )(WMGoodsDetailScreen);
/***** License -------------- Copyright © 2017 Bill & Melinda Gates Foundation The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors -------------- This is the official list of the Mojaloop project contributors for this file. Names of the original copyright holders (individuals or organizations) should be listed with a '*' in the first column. People who have contributed from an organization can be listed under the organization that actually holds the copyright for their contributions (see the Gates Foundation organization for an example). Those individuals should have their names indented and be marked with a '-'. Email address can be added optionally within square brackets <email>. * Gates Foundation - Name Surname <name.surname@gatesfoundation.com> * Mowali -------------- ******/ 'use strict' const ApiErrorCodes = { MISSING_ID_VALUE: { code: 1000, message: 'ID not supplied' }, ID_NOT_UNIQUE: { code: 1001, message: 'ID is already registered' }, UNKNOWN_ERROR: { code: 1002, message: 'ID not supplied' }, // reporting errors REPORT_NOT_FOUND: { code: 6000, message: 'Report not found' }, REPORT_EMPTY: { code: 6001, message: 'Report has no content' }, REPORT_ERROR: { code: 6002, message: 'There was an error while finding Report' }, // test api errors OP_NOT_SET: { code: 7000, message: 'Scenario operation isn\'t specified' }, OPS_ERROR: { code: 7001, message: 'There was an error while processing operations' } } module.exports = { ApiErrorCodes }
/** * Created by Dominic Fitzgerald on 10/7/15. */ $(document).ready(function(){ $('select[name=study]').change(function(){ var study_id = $(this).val(); var options = []; var request_url = '/viewer/get_bnids_by_study/' + study_id + '/'; $.getJSON( request_url, function(data){ $.each(data, function(key, val) { options.push('<option value="' + key + '">' + val + '</option>'); }); $('select[name=bnids]').html(options.join('\n')); } ); }); $('select[name=bnids]').empty(); new jBox('Modal', { attach: $('.igsbviewer-modal-add-button'), ajax: { url: '/viewer/report/upload_report' }, overlay: true, closeOnClick: 'overlay', closeButton: 'box' }); var $modalEditButton = $('.igsbviewer-modal-edit-button'); $modalEditButton.click(function(){ pk = $(this).data('pk'); }); new jBox('Modal', { onOpen: function(){ this.options.ajax.url = '/viewer/report/edit_report/' + pk; }, ajax: { reload: true }, attach: $modalEditButton, overlay: true, closeOnClick: 'overlay', closeButton: 'box' }); /* Set up 'delete' modal box */ var pk = 0; var $modalDeleteButton = $('.igsbviewer-modal-delete-button'); $modalDeleteButton.click(function(){ pk = $(this).data('pk'); }); new jBox('Modal', { onOpen: function(){ this.options.ajax.url = '/viewer/report/delete_report/' + pk; }, ajax: { reload: true }, attach: $modalDeleteButton, overlay: true, closeOnClick: 'overlay', closeButton: 'box' }); /* Share button */ var $modalShareButton = $('.igsbviewer-modal-share-button'); $modalShareButton.click(function(){ pk = $(this).data('pk'); }); new jBox('Modal', { onOpen: function(){ this.options.ajax.data = function(){ var reportIds = []; $('.multiplereports').filter(':checked').each(function(){ reportIds.push('reportid=' + $(this).data('reportid')); }); if(reportIds.length < 1){ $(this).close(); return false; } return reportIds.join('&'); }(); }, ajax: { reload: true, url: '/viewer/shared/share_report/' }, attach: $('#share-reports'), overlay: true, closeOnClick: 'overlay', closeButton: 'box' }); $(".igsbviewer-view-report").click(function(){ var pk = $(this).data('pk'); var $csrf = $($(this).data('csrf')); console.log('clicked ' + pk); $("<form>").attr({ action: '/viewer/report/view_report/' + pk + '/', method: 'POST' }).append($csrf).appendTo($("body")).submit(); }); $('#information-dashboard').click(function(){ var reportIds = []; $('.multiplereports').filter(':checked').each(function(){ reportIds.push($(this).data('reportid')); }); if(reportIds.length < 1){ return false; // Do something more informative? TODO } /* Extract report IDs and add to form, submit */ var $form = $('<form>').attr({ method: 'get', action: '/viewer/info/' }); for(var i = 0; i < reportIds.length; i++){ $('<input>').attr('name', 'reportIds[]').val(reportIds[i]).appendTo($form); } $form.submit(); }); $('#download-reports').click(function(){ reportIds = []; $('.multiplereports').filter(':checked').each(function(){ reportIds.push($(this).data('reportid')); }); if(reportIds.length < 1){ return false; // Do something more informative? TODO } console.log(reportIds); $.get('/viewer/report/zip-and-download/', {reportids: reportIds}, function(data){ window.location.href = data; }); }); });
import React from 'react'; import { Layout, Row, Col, Card } from 'antd'; const { Header, Content } = Layout; export default ({ history }) => ( <Layout style={{ height: '100%' }}> <Header className="page-header"> <span className="page-header-title">Dashboard</span> </Header> <Content className="page-content"> <Row gutter={20}> <Col span={12}> </Col> </Row> </Content> </Layout> );
#!/usr/bin/env node // eslint-disable-next-line no-global-assign require = require('@std/esm')(module, { mode: 'all', }); require('@babel/register')({ ignore: [], only: [/src/], }); const program = require('commander'); const winston = require('winston'); program.version('1.0.0'); program.parse(process.argv); const logger = winston.createLogger({ level: 'info', transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.printf((info) => info.message), ), }), ], }); require('../src/cli').cli(program, logger);
// convert string to zero width chars export function toZeroWidth(str) { return str .split('') .map(char => char.charCodeAt(0).toString(2)) .join(' ') .split('') .map(char => { if (char === '0') return '\u200b'; if (char === '1') return '\u200c'; return '\u200d'; }) .join(''); } // convert string from zero width chars export function fromZeroWidth(str) { return str .split('') .map(char => { if (char === '\u200b') return '0'; if (char === '\u200c') return '1'; return ' '; }) .join('') .split(' ') .map(str => String.fromCharCode(Number.parseInt(str, 2))) .join(''); }
/** * Extension of jQuery.ajax function for queueing XML HTTP requests * * @author mariusz.bak(at)xsolve.pl * mariusz.alef.bak(at)gmail.com */ "use strict"; jQuery((function($) { return function() { var xsAjaxQueuesDemo, queues, requests; xsAjaxQueuesDemo = (function() { /********************************************************************************************** * COMMON * **********************************************************************************************/ var queueDisplays = {}; function getQueueDisplay(id) { return queueDisplays[id]; } /********************************************************************************************** * REQUEST DISPLAY * **********************************************************************************************/ function QueueDisplay(queueHandle, container) { var that = this, markup, queueSettings; queueDisplays[queueHandle.getId()] = this; this.queueHandle = queueHandle; this.queueHandle.disable(); this.queueHandle.addListener(function() { that.update(); }); this.container = $(container); markup = $( '<span class="queue-display">' + '<span class="queue-toggle">enable</span><span class="queue-slide">show</span>' + '<span class="queue-id">queue <span class="value" /></span>' + '<span class="queue-order">order <span class="value" /></span>' + '<span class="queue-priority">priority <span class="value" /></span>' + '<span class="queue-mode">mode <span class="value" /></span>' + '<span class="queue-counters">' + '<span class="queue-counter">added <span class="value" /></span>' + '<span class="queue-counter">sent <span class="value" /></span>' + '<span class="queue-counter">received <span class="value" /></span>' + '<span class="queue-counter">processed <span class="value" /></span>' + '<span class="queue-counter">canceled <span class="value" /></span>' + '<span class="queue-counter">aborted <span class="value" /></span>' + '</span>' + '<span class="queue-details">' + '<span class="queue-requests"><span class="queue-requests-header">Requests</span></span>' + '</span>' + '</span>' ); this.elements = { main: markup, toggle: $('.queue-toggle', markup), slide: $('.queue-slide', markup), id: $('.queue-id', markup), order: $('.queue-order', markup), priority: $('.queue-priority', markup), mode: $('.queue-mode', markup), requests: $('.queue-requests', markup), details: $('.queue-details', markup), counters: {} }; $.each(['added', 'sent', 'received', 'processed', 'canceled', 'aborted'], function(i, name) { that.elements.counters[name] = $('.queue-counter', markup).eq(i); }); queueSettings = this.queueHandle.getSettings(); $('.value', this.elements.id).text(this.queueHandle.getId()); $('.value', this.elements.mode).html(queueSettings.order.mode ? queueSettings.order.mode : 'request'); $('.value', this.elements.order).html(queueSettings.order ? queueSettings.order.order : 'fifo'); $('.value', this.elements.priority).html(queueSettings.order.priority ? queueSettings.order.priority : '~'); this.elements.slide.toggle(function() { that.elements.slide.html('hide'); that.elements.details.slideDown(500); }, function() { that.elements.slide.html('show'); that.elements.details.slideUp(500); }); this.elements.details.hide(); this.elements.toggle.click(function() { that.queueHandle.toggle(); if (that.queueHandle.isEnabled()) { that.elements.toggle.text('disable'); } else { that.elements.toggle.text('enable'); } }); this.update(); this.container.append(this.elements.main); } QueueDisplay.prototype.update = function() { var that = this, counters; counters = this.queueHandle.getCounters(); $.each(['added', 'sent', 'received', 'processed', 'canceled', 'aborted'], function(i, name) { $('.value', that.elements.counters[name]).html(counters[name]); }); }; /********************************************************************************************** * REQUEST DISPLAY * **********************************************************************************************/ function RequestDisplay(requestHandle) { var that = this, markup, requestSettings; this.requestHandle = requestHandle; this.queueDisplay = getQueueDisplay(requestHandle.getQueueId()); this.container = this.queueDisplay.elements.requests; markup = $( '<span class="request-display">' + '<span class="request-priority">priority <span class="value" /></span>' + '<span class="request-sleep">delay <span class="value" /></span>' + '<span class="request-callbacks">' + '<span class="request-callback">success</span>' + '<span class="request-callback">error</span>' + '<span class="request-callback">complete</span>' + '</span>' + '<span class="request-flags">' + '<span class="request-flag">sent</span>' + '<span class="request-flag">canceled</span>' + '<span class="request-flag">aborted</span>' + '</span>' + '<span class="request-buttons">' + '<span class="request-button">c</span>' + '<span class="request-button">a</span>' + '<span class="request-button">i</span>' + '</span>' + '</span>' ); this.elements = { main: markup, priority: $('.request-priority', markup), sleep: $('.request-sleep', markup), callbacks: {}, flags: {}, buttons: {} }; $.each(['success', 'error', 'complete'], function(i, name){ that.elements.callbacks[name] = $('.request-callback', markup).eq(i).css({opacity: '0.25'}); }); $.each(['sent', 'canceled', 'aborted'], function(i, name){ that.elements.flags[name] = $('.request-flag', markup).eq(i).css({opacity: '0.25'}); }); $.each(['cancel', 'abort', 'inspect'], function(i, name){ that.elements.buttons[name] = $('.request-button', markup).eq(i); }); requestSettings = this.requestHandle.getSettings(); $('.value', this.elements.priority).text(requestSettings.priority ? requestSettings.priority : '~'); $('.value', this.elements.sleep).text(requestSettings.data.sleep ? requestSettings.data.sleep : '~'); this.setPriorityColor(requestSettings.priority ? requestSettings.priority : 0); // button events this.elements.buttons.cancel.click(function() { that.requestHandle.cancel(); }); this.elements.buttons.abort.click(function() { that.requestHandle.cancel(true); }); this.elements.buttons.inspect.click(function() { var inspect = {}; $.each(['success', 'error', 'complete'], function(i, callback) { inspect[callback] = { context: requestHandle.getCallbackContext(callback), args: requestHandle.getCallbackArgs(callback) }; }); debugger; // intentional }); this.requestHandle.addListener(function(event) { switch (event) { case 'sent': case 'canceled': case 'aborted': that.setFlag(event); break; case 'success': case 'error': case 'complete': that.setCallback(event); break; } }); this.container.append(this.elements.main); } RequestDisplay.prototype.setCallback = function(name) { this.elements.callbacks[name].css({opacity: '1'}); if (name === 'complete') { this.elements.main.css({backgroundColor: '#ffffff', border: '6px solid transparent'}); } }; RequestDisplay.prototype.setPriorityColor = function(priority) { var main, other, total, rgb; main = 1; other = 1 - priority / 8; total = (main + 2 * other) / 3; main = Math.min(Math.floor(188 * main / total), 255); other = Math.floor(188 * other / total); if (priority === 0) { main = main + 20; other = other + 20; } rgb = 'rgb(' + main + ',' + main + ',' + other + ')'; this.elements.main.css({backgroundColor: rgb}); }; RequestDisplay.prototype.setFlag = function(name) { this.elements.flags[name].css({opacity: '1'}); }; /********************************************************************************************** * INTERFACE * **********************************************************************************************/ function addQueue(queueHandle) { var queueDisplay = new QueueDisplay(queueHandle, '#demo-container'); } function addRequest(requestHandle) { var requestDisplay = new RequestDisplay(requestHandle); } return { addQueue: addQueue, addRequest: addRequest }; }()); queues = [ {id: 'fifo_request'}, {id: 'lifo_request', order: 'lifo'}, {id: 'lifo_response', order: 'lifo', mode: 'response'}, {id: 'fifo_priority_request', priority: 'desc'}, {id: 'fifo_priority_response', priority: 'desc', mode: 'response'}, ]; $.each(queues, function() { xsAjaxQueuesDemo.addQueue($.ajaxQueue(this)); }); requests = [ {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'fifo_request', type: "POST", url: "error.php", data: {sleep: 4}}, {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 4}}, {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'fifo_request', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'lifo_request', type: "POST", url: "error.php", data: {sleep: 4}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 4}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'lifo_request', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 7}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'lifo_response', type: "POST", url: "error.php", data: {sleep: 5}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 5}}, {queue: 'lifo_response', type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'fifo_priority_request', priority: 3, type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'fifo_priority_request', priority: 1, type: "POST", url: "sleep.php", data: {sleep: 4}}, {queue: 'fifo_priority_request', priority: 2, type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'fifo_priority_request', priority: 4, type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'fifo_priority_request', priority: 1, type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'fifo_priority_request', priority: 2, type: "POST", url: "sleep.php", data: {sleep: 5}}, {queue: 'fifo_priority_request', priority: 1, type: "POST", url: "sleep.php", data: {sleep: 3}}, {queue: 'fifo_priority_request', priority: 3, type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'fifo_priority_response', priority: 3, type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'fifo_priority_response', priority: 1, type: "POST", url: "sleep.php", data: {sleep: 5}}, {queue: 'fifo_priority_response', priority: 2, type: "POST", url: "sleep.php", data: {sleep: 6}}, {queue: 'fifo_priority_response', priority: 4, type: "POST", url: "sleep.php", data: {sleep: 2}}, {queue: 'fifo_priority_response', priority: 1, type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'fifo_priority_response', priority: 2, type: "POST", url: "sleep.php", data: {sleep: 1}}, {queue: 'fifo_priority_response', priority: 1, type: "POST", url: "sleep.php", data: {sleep: 9}}, {queue: 'fifo_priority_response', priority: 3, type: "POST", url: "sleep.php", data: {sleep: 3}} ]; $.each(requests, function() { this.handle = true; if (this.queue !== 'fifo_priority_response') { // sending requests with $.ajax xsAjaxQueuesDemo.addRequest($.ajax(this)); } else { // sending requests with queue handle addRequest method var queueHandle = $.ajaxQueue('fifo_priority_response'); xsAjaxQueuesDemo.addRequest(queueHandle.addRequest(this)); } }); // $.ajaxQueue({id: 'intercepted_requests', priority: 'desc', mode: 'request', initializer: function() { alert(this.getId()); } }); //.disable(); // // $.ajaxFilter(function() { // return (this.queue === undefined); // }, function() { // this.queue = 'intercepted_requests'; // if (this.data || this.data.sleep || this.data.sleep > 4) { // this.priority = 0; // } // else { // this.priority = 1; // } // return this; // }, // function() { // this.addListener(function(event) { // $('body').append($('<p />').text('post ' + event + ' ' + this.getId())); // }); // }); // // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 5}, listeners: [ // function(event) { // $('body').append($('<p />').append($('<em />').text(event))); // } // ]}); // // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 6}}); // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 5}}); // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 2}}); // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 1}}); // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 1}}); // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 9}}); // $.ajax({type: "POST", url: "sleep.php", data: {sleep: 3}}); }; }(jQuery)));
import React , { Component } from 'react'; import {Text,StyleSheet} from 'react-native'; import firebase from 'firebase/app'; import 'firebase/auth'; import { Card ,CardSection ,Input,Spinner} from './common'; class LoginForm extends Component { state ={ email : '', password : '', error : '', loading : false } onButtonPress (){ const {email , password} = this.state; // setting error to null if it has already showing an error this.setState({error : '' , loading : true}) // connect to firebase ...... and asking for email and password login if exist firebase.auth().signInWithEmailAndPassword(email,password).then(this.onLoginSuccess.bind(this)) .catch(()=>{ // catch is a promise that decide that if signIn have any error then catch the error and run this funnctionn firebase.auth().createUserWithEmailAndPassword(email,password).then(this.onLoginSuccess.bind(this)) .catch(this.onLoginFail.bind(this)); }); } buttonStatus (){ if(this.state.loading){ return <Spinner />; } return( <button type="submit" style = {{ borderWidth : 0, padding : 5 , fontFamily : 'comic sans ms', fontSize : 15 , backgroundColor : '#f3f' , color : 'white', borderRadius : 3}} onClick = {this.onButtonPress.bind(this)}> Log In </button> ); } // a new function while login is successfull or failed..... onLoginSuccess() { this.setState({ email : '', password : '', loading : false, error : '' }) } onLoginFail() { this.setState({ error : 'Authentication Failed' , loading : false}) } render(){ return( <Card> <CardSection> <Input label = "Email : " value = {this.state.email} onChangeText = {email => this.setState({email})} placeholder = "myavay@gmail.com" /> </CardSection> <CardSection> <Input label = "Password : " value = {this.state.password} onChangeText = {password => this.setState({password})} secureTextEntry = {true} /> </CardSection> <Text style = {styles.warningText}> {this.state.error} </Text> <CardSection> {this.buttonStatus()} </CardSection> </Card> ); } } const styles = StyleSheet.create({ warningText : { color : 'hotpink', fontSize : 20 , alignItems : 'center' } }) export default LoginForm
/** * @file server enter * @author dongkunshan(windwithfo@yeah.net) */ import { Server } from 'hapi'; import webpack from 'webpack'; import cluster from 'cluster'; import chokidar from 'chokidar'; import nodecp from 'child_process'; import config from '../config/config'; import middleware from 'hapi-webpack-plugin'; import webConfig from '../config/webpack.dev.config'; if (cluster.isMaster) { const compiler = webpack(webConfig); const server = new Server(); server.connection({ host: config.dev.host, port: config.dev.port }); server.register({ register: middleware, options: { compiler, assets: { stats: { colors: true, chunks: false }, headers: { 'Access-Control-Allow-Origin': '*' } }, hot: {} } }); server.start((err) => { console.log(err ? err : `The server for webpack is run in ${config.dev.host} on port ${config.dev.port}`); }); let worker = cluster.fork({ 'NODE_ENV': 'development' }).on('listening', (address) => { console.log(`[master] listening: worker ${worker.id}, pid:${worker.process.pid}, ` + `Address:${address.address} :${address.port}`); }); const watchConfig = { dir: ['server'], options: {} }; chokidar.watch(watchConfig.dir, watchConfig.options).on('change', (path) => { console.log(`${path} changed`); worker.kill(); worker = cluster.fork({ 'NODE_ENV': 'development' }).on('listening', (address) => { console.log(`[master] listening: worker ${worker.id}, pid:${worker.process.pid}, ` + `Address:${address.address} :${address.port}`); }); }); } if (cluster.isWorker) { nodecp.exec('npm run lint', (err) => { if (err) { console.log(err); } else { require('./start.js'); } }); }
export default theme => ({ root: { width: '100%', height: 'calc(100vh - 64px)', pointerEvents: 'none' }, scrollbar: { width: '100vw', height: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'row', backgroundColor: '#06101f', fontSize: 20, color: '#7487a3' } })
/** * /routes/index.js * @description: Index file for the application. * All routes with "/" comes through here. */ var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); router.use('/api', require('./api')); module.exports = router;
import React from "react"; import SingleActivity from "../SingleActivity"; const ApprovedActivities = ({ approvedActivities }) => { return ( <div className="listActivities"> <h6 className="font-weight-normal py-4 border-bottom">Today 15th june</h6> <ul className="list-group list-group-flush"> {approvedActivities.length > 0 && approvedActivities.map((act) => ( <SingleActivity key={act.id} activity={act} /> ))} </ul> </div> ); }; export default ApprovedActivities;
import React, { useContext, useEffect, useState } from "react"; import { CircularProgress, LinearProgress } from "@material-ui/core"; import Counter from "./graphical-representations/counter"; import { BarGraphs, LineGraphs } from "./graphical-representations/graphs"; import { DashboardContext } from "../../contexts/DashboardContext"; function Dashboard() { const { dataLoading, fetchTopEntries, dashboardData } = useContext(DashboardContext); if (dataLoading) return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", }}> <CircularProgress/> </div> ) return ( <div className="Main-Container"> <div className="container top-section"> <Counter /> </div> <div className="container graph-section"> <div className="row"> <div className="col-sm"> <BarGraphs /> </div> <div className="col-sm"> <LineGraphs /> </div> </div> </div> </div> ); } export default Dashboard;
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import Question from '../Copy/AnswerExercice/AnswerQuestion/Question'; export default class DisplayExerciceWithAnswer extends Component { static propTypes = { exercice: PropTypes.object.isRequired, }; render() { const {exercice, copy} = this.props; return ( <> <div className="box"> <div className="columns px-1"> <div className="column is-two-thirds"> <span className="title is-5">{exercice.title}</span> </div> <div className="column is-one-third has-text-right"> <div> <div className="tags has-addons d-block"> <span className="tag is-dark">Temps est.</span> <span className="tag is-info">{moment.utc(exercice.estimatedTime * 1000).format('mm:ss')}</span> </div> </div> </div> </div> </div> <div className="content"> {exercice.questions && exercice.questions.map((question,index) => <div key={question._id} className="content"> <Question key={question._id} id={question._id} question={question} idQuestion={question._id} index={index} answer={copy.answers.filter(answer => answer.refQuestion === question._id).pop()} copy={copy} readOnly={true}/> </div>, )} </div> </> ); } }
var boardsData = `[ { "image" : "8-bit-adder.jpg", "heading" : "Number 1 8-bit-adder heading text", "emphasis" : "some emphasis"}, { "image" : "8-bit-bus-selector.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "8-bit-bus-selector2.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "4bit-demux.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "4bit-counter.jpg", "heading" : "4 bit counter text", "emphasis" : "some emphasis on 4 bit counter"}, { "image" : "ram-bank.jpg", "heading" : "ram-bank text", "emphasis" : "some emphasis ram-bank"}, { "image" : "selectable-4-reg.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "register-bank.jpg", "heading" : "register-bank heading text", "emphasis" : "some emphasis register-bank"}, { "image" : "instruction-reg1.jpg", "heading" : "instruction-reg1 heading text", "emphasis" : "some emphasis instruction-reg1"}, { "image" : "instruction-reg2.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "combi-logic1.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "combi-logic2.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "combi-logic3.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "combinational-logic.jpg", "heading" : " combinational-logic heading text", "emphasis" : "combinational-logic some emphasis"}, { "image" : "combi-logic-tester.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "instruction-reg3.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "literals.jpg", "heading" : "literals text", "emphasis" : "literals emphasis"}, { "image" : "8-bit-adder2.jpg", "heading" : "8-bit-adder heading text", "emphasis" : "some emphasis 8-bit-adder"}, { "image" : "ones-complement.jpg", "heading" : "ones-complement text", "emphasis" : "some emphasis"}, { "image" : "parity-zero-test.jpg", "heading" : "parity-zero-test text", "emphasis" : "some emphasis"}, { "image" : "ram-programmer2.jpg", "heading" : "rom-program text", "emphasis" : "some emphasis"}, { "image" : "ram-programmer1.jpg", "heading" : "rom-program text", "emphasis" : "some emphasis"}, { "image" : "rom-program.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "ring-counter.jpg", "heading" : "ring-counter text", "emphasis" : "some emphasis"}, { "image" : "8-bit-hex-display-micro-view.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "8-bit-input-micro-view.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "hex-display2.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "bar-display.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "bus-with-bar-display.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "8-bit-reg-with-display1.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "hex-display.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "decimal-display1.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "8-bit-reg-with-display.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "8-bit-reg-with-bar-display.jpg", "8-bit-reg-with-bar-display" : "8-bit-reg-with-bar-display text", "emphasis" : "some emphasis"}, { "image" : "8-bit-reg3.jpg", "heading" : "8-bit-reg3 text", "emphasis" : "some emphasis"}, { "image" : "8-bit-reg2.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "clock-programmable.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "clock.jpg", "heading" : "clock text", "emphasis" : "some emphasis"}, { "image" : "hex-input.jpg", "heading" : "hex-input text", "emphasis" : "some emphasis"}, { "image" : "hex-input3.jpg", "heading" : "hex-input3 text", "emphasis" : "some emphasis"}, { "image" : "hex-input2.jpg", "heading" : "hex-input2 text", "emphasis" : "some emphasis"}, { "image" : "hex-input6.jpg", "heading" : "hex-input6 text", "emphasis" : "some emphasis"}, { "image" : "hex-input5.jpg", "heading" : "hex-input5 text", "emphasis" : "some emphasis"}, { "image" : "hex-input4.jpg", "heading" : "hex-input4 text", "emphasis" : "some emphasis"}, { "image" : "common-bus.jpg", "heading" : "common-bus text", "emphasis" : "some emphasis"}, { "image" : "bus.jpg", "heading" : "bus text", "emphasis" : "some emphasis"}, { "image" : "memory-address-reg1.jpg", "heading" : "heading text", "emphasis" : "some emphasis"}, { "image" : "4bit-demux2.jpg", "heading" : "4bit-demux2 text", "emphasis" : "some emphasis"}, { "image" : "rom-program2.jpg", "heading" : "rom-program2 text", "emphasis" : "some emphasis"} ]`;
import firebase from '../FirebaseConection'; export const createChat = (userUid1,userUid2)=>{ return (dispatch)=>{ //estrutura do Thunkx //criando o chat let newchat = firebase.database().ref('chats').push(); newchat.child('members').child(userUid1).set({ id:userUid1 }); newchat.child('members').child(userUid2).set({ id:userUid1 }); //Associando aos envolvidos let chatId = newchat.key; //pegando nome dos usuários firebase.database().ref('users').child(userUid2).once('value').then((snapshot)=>{ firebase.database().ref('users').child(userUid1).child('chats').child(chatId).set({ id:chatId, title:snapshot.val().name, other:userUid2 }); }); firebase.database().ref('users').child(userUid1).once('value').then((snapshot)=>{ firebase.database().ref('users').child(userUid2).child('chats').child(chatId).set({ id:chatId, title:snapshot.val().name, ///alterar o getchatlist other:userUid1 }).then(()=>{ dispatch({ type:'setActiveChat', payload:{ chatId:chatId } }); }); }); /* //um retorno para o reducer dispatch({ type:'setActiveChat', payload:{ chatId:chatId } }); */ } } export const setActiveChat = (chatId)=>{ return { type:'setActiveChat', payload:{ chatId:chatId } }; } export const sendImage = (blob,progressCallback,successCallback) =>{ return (dispatch) =>{ //processo de envio para o firebase //criar um nome para a imagem let tmpKey = firebase.database().ref('chats').push().key; let fbimage = firebase.storage().ref('images').child(tmpKey); //para adicionar o progress como calback, foi adicionado um olheiro fbimage.put(blob,{contentType:'image/jpeg'}) .on('state_changed',(snapshot)=>{ //progresso progressCallback(); },(error)=>{ //erro alert(error.code); },()=>{ //sucesso //successCallback(tmpKey); - Pular essa etapa já realizando o download aqui fbimage.getDownloadURL().then((url)=>{ successCallback(url); // salvar ans mensagens a url direta da imagem }); }); //fbimage.put(blob,{contentType:'image/jpeg'}) // .then(()=>{ // // successCallback(tmpKey); // }).catch((error)=>{ // alert(error.code); // });; } } export const sendMessage = (msgType, msgContent ,autor ,activeChat )=>{ return (dispatch) =>{ let currentDate=''; let cDate = new Date(); //ele pega o mes anterior, por isso a soma currentDate = cDate.getFullYear()+'-'+(cDate.getMonth()+1)+'-'+cDate.getDate(); currentDate +=' '; currentDate += +cDate.getHours()+':'+cDate.getMinutes()+':'+cDate.getSeconds(); let msgId = firebase.database().ref('chats').child(activeChat).child('messages').push(); switch(msgType){ case 'text': msgId.set({ msgType:'text', date:currentDate, m:msgContent, uid:autor }); break; case 'image': msgId.set({ msgType:'image', date:currentDate, imgSource:msgContent, uid:autor }); break; } } } export const getChalList=(userUid , callback) =>{ return (dispatch)=>{ firebase.database().ref('users').child(userUid).child('chats').on('value',(snapshot)=>{ let chats = []; snapshot.forEach((childItem)=>{ chats.push({ key:childItem.key, other:childItem.val().other, title:childItem.val().title }); }); callback(); dispatch({ type:'setChatList', payload:{ chats :chats } }); }); }; } export const monitorChat =(activeChat)=>{ //processo de monitorar, necessário adicionar no ChatReducer um campo para salvar as conversas ativas return(dispatch)=>{ firebase.database().ref('chats').child(activeChat).child('messages').orderByChild('date').on('value',(snapshot)=>{ let arrayMsg = []; snapshot.forEach((childItem)=>{ switch(childItem.val().msgType){ case 'text': arrayMsg.push({ key:childItem.key, date:childItem.val().date, msgType:'text', m:childItem.val().m, uid:childItem.val().uid }); break; case 'image': arrayMsg.push({ key:childItem.key, date:childItem.val().date, msgType:'image', imgSource:childItem.val().imgSource, uid:childItem.val().uid }); break; } }); dispatch({ type:'setActiveChatMessage', payload:{ msgs:arrayMsg } }); }); } } export const monitorChatOff =(activeChat)=>{ return(dispatch)=>{ firebase.database().ref('chats').child(activeChat).child('messages').off('value'); //tirar o olheiro do value } } export const getContactList= (userUid,callback)=>{ return (dispatch)=>{ firebase.database().ref('users').orderByChild('name').once('value').then((snapshot)=>{ // trocado "on" por "once" para que pegue uma única vez ao inves de usar olheiro //.on('value',(snapshot)=>{ let users = []; snapshot.forEach((childItem)=>{ if(childItem.key != userUid){ users.push({ key:childItem.key, name:childItem.val().name }); } }) callback(); dispatch({ type:'setContactList', //criar no reducer payload:{ users:users } }); }).catch((erro)=>{ callback(); alert(erro); }); }; };
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { load as loadCategories } from 'redux/modules/content/categories'; import React, { Component, PropTypes } from 'react'; import { Panel } from 'react-bootstrap'; import { Link } from 'react-router'; @connect( state => ({ categories: state.categories.data }), dispatch => bindActionCreators({ loadCategories }, dispatch)) export default class Categories extends Component { static propTypes = { categories: PropTypes.array, loadCategories: PropTypes.func.isRequired } constructor(props) { super(props); this.loadIt(); } loadIt = () => { this.props.loadCategories(); } renderCategories = () => { if (this.props.categories) { return this.props.categories.map((item, nr) => { return ( <li role="presentation" key={nr}> <Link to={`/blog/${item.key}`}>{item.name} <span className="badge pull-right">{item.count || 9999}</span></Link> </li> ); }); } return ( <p>No Categories available.</p> ); } render() { return ( <Panel header="Categories"> <ul className="nav nav-pills nav-stacked"> <li><a href="/blog">All</a></li> {this.renderCategories()} </ul> </Panel> ); } }
/* BLE control of a RoboSmart Bluetooth light bulb. Thanks to Don Coleman for the structure. created 8 Feb 2017 by Tom Igoe */ var noble = require('noble'); // noble library var lampUuid = 'ff10'; // the lamp's service uuid var switchUuid = 'ff11'; // the switch characteristic uuid var brightnessUuid = 'ff12'; // the brightness characteristic uuuid var lamp; // the peripheral once you connect // The scanning function function scan(state){ if (state === 'poweredOn') { // if the radio's on, scan for lamp service noble.startScanning([lampUuid], false); console.log("Started scanning"); } else { // if the radio's off, let the user know: noble.stopScanning(); console.log("Is Bluetooth on?"); } } // the main discover function function findLamp(peripheral) { console.log('discovered ' + peripheral.advertisement.localName); peripheral.connect(); // start connection attempts lamp = peripheral; // save peripheral in a global variable peripheral.on('connect', connectToLamp); // listener for connection } // the connect function. This is local to the discover function // because it needs the peripheral to discover services: function connectToLamp() { noble.stopScanning(); console.log('Checking for characteristics on ' + lamp.advertisement.localName); // start discovering services: lamp.discoverSomeServicesAndCharacteristics([lampUuid],[switchUuid, brightnessUuid], exploreLamp); // when a peripheral disconnects, run disconnectMe: lamp.on('disconnect', disconnectMe); } // the service/characteristic exploration function: function exploreLamp(error, services,characteristics) { var lampState = 0; var brightness = 0; var difference = -1; console.log("found"); console.log('services: ' + services); console.log('characteristics: ' + characteristics); // switch on-off is the first characteristic: var switchCharacteristic = characteristics[0]; var brightnessCharacteristic = characteristics[1]; //setInterval(blink, 1000); // call blink once per second fade(); // call fade once. After that it calls itself as a callback function blink(){ var data = new Buffer(1); // .write() requires a Buffer lampState = !lampState; // invert lampState data[0] = lampState; // put lampState in the buffer // write to the characteristic, without a callback: switchCharacteristic.write(data, true); } function fade(){ var data = new Buffer(1); // .write() requires a buffer // if brightness is at either extreme: if (brightness == 0 || brightness == 255) { difference = -difference; // change gthe sign on difference } // add difference to brightness: brightness = brightness + difference; data[0] = brightness; // put brightness in the buffer console.log('Brightness: ' + brightness); // write to the characteristic, with a callback: brightnessCharacteristic.write(data, false, fade); } } // disconnect callback function: function disconnectMe() { console.log('peripheral disconnected'); process.exit(0); // exit the scrip } /* ---------------------------------------------------- The actual commands that start the program are below: */ noble.on('stateChange', scan); // when the BT radio turns on, start scanning noble.on('discover', findLamp); // when you discover peripheral, run findMe()
import React, { Component } from 'react'; import Hero from '../komponen/hero' import Header from '../komponen/navbar' import Article from '../komponen/Article' import VideoYT from '../komponen/videoiframe' // import BrandsCard from '../komponen/brandscard' import Contacts from '../komponen/contacts' import Footer from '../komponen/footer' import Products from '../komponen/Products'; class home extends Component { render() { return ( <div> <Hero/> <Header/> <Article/> <VideoYT/> <Products/> <Contacts/> <Footer/> </div> ); } } export default home;
/** * Created by Administrator on 2017/1/15. */ import bar from './app.js'; bar();
const user = require("../models/user"); class LoginControllers { root(req, res){ res.render('login'); } auth(req, res, next){ const email= req.body.email; const password = req.body.password; user.findOne({'email':`${email}`, 'password':`${password}`},(err, data)=>{ if(data){ const cookie = data._id+"/"+data.password; res.cookie('user_id', cookie, { expires: new Date(Date.now() + 72*60*60*1000) /*,httpOnly: true */ }); res.redirect('/'); }else{ res.render('login',{mess:"username or password incorrect"}) } }); } } module.exports = new LoginControllers();
var count = 1; var count_breakdown = 1; var edit_count = 1; function getCurrencySymbol(){ var currency = $("#currency").val(); if(currency==1) var currency_symbol = "&#8369;"; else if(currency==2) var currency_symbol = "&#36;"; return currency_symbol; } function changeCurrencySymbols(){ var currency_symbol = getCurrencySymbol(); $('.currency_symbol_container').html(currency_symbol); } function addField() { var currency_symbol = getCurrencySymbol(); $('.description-container').append('<div class="formfieldnewcontainer'+count+'"><div class="has-items form-group formfieldnew'+count+' text-center"><div class="col-md-1 button-holder"><button type="button" class="btn btn-danger btn-xs" onclick="removeNewField('+count+')"><span class="fa fa-times" aria-hidden="true"></span></button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-success btn-xs" onclick="addBreakdown('+count+')"><span class="fa fa-chevron-down" aria-hidden="true"></span></button></div><div class="col-md-9 text-center"><input class="form-control input-sm pull-left" type="text" name="items['+count+']" id="item'+count+'" data-validate="required"></div><div class="col-md-2"> <div class="input-group"><span class="input-group-addon currency_symbol_container">'+currency_symbol+'</span><input class="form-control input-sm pull-left" type="text" name="amounts['+count+']" id="amount'+count+'" data-validate="decimal"></div></div></div></div>'); count++; } function addBreakdown(x) { var currency_symbol = getCurrencySymbol(); $('.formfieldnewcontainer'+x).append('<div class="has-breakdown form-group formfieldnew'+x+'breakdownnew'+count_breakdown+' breakdownnew'+count_breakdown+' text-center"><div class="col-md-1 col-md-offset-1 button-holder"><button type="button" class="btn btn-danger btn-xs" onclick="removeNewBreakdown('+count_breakdown+')"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button></div><div class="col-md-8 text-center"><input class="form-control input-sm pull-left" type="text" name="breakdown['+x+'][]" id="item1" data-validate="required"></div><div class="col-sm-2"><div class="input-group" style="margin-left: 40px;"><span class="input-group-addon currency_symbol_container">'+currency_symbol+'</span><input style="width:80px;" class="form-control input-sm pull-left" type="text" name="amounts_bd['+x+'][]" id="amount1" data-validate="decimal"></div></div></div>'); count_breakdown++; } function removeNewField(x) { $('.formfieldnewcontainer'+x).remove(); count--; } function removeNewBreakdown(x) { $('.breakdownnew'+x).remove(); count_breakdown--; } // Edit page function addFieldNew() { var currency_symbol = getCurrencySymbol(); $('.description-container').append('<div class="formfieldeditcontainer'+count+'"><div class="has-items form-group formfieldnew'+count+' text-center"><div class="col-md-1 button-holder"><button type="button" class="btn btn-danger btn-xs" onclick="removeEditField('+count+')"><span class="fa fa-times" aria-hidden="true"></span></button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-success btn-xs" onclick="newEditBreakdown('+count+')"><span class="fa fa-chevron-down" aria-hidden="true"></span></button></div><div class="col-md-9 text-center"><input class="form-control input-sm pull-left" type="text" name="items['+count+']" id="item'+count+'" data-validate="required"></div><div class="col-md-2"> <div class="input-group"><span class="input-group-addon currency_symbol_container">'+currency_symbol+'</span><input class="form-control input-sm pull-left" type="text" name="amounts['+count+']" id="amount'+count+'" data-validate="decimal"></div></div></div></div>'); count++; } function newEditBreakdown(x) { var currency_symbol = getCurrencySymbol(); $('.formfieldeditcontainer'+x).append('<div class="has-breakdown form-group formfieldedit'+x+'breakdownedit formfieldedit'+x+'breakdownedit'+count_breakdown+' breakdownedit'+count_breakdown+' text-center"><div class="col-md-1 col-md-offset-1 button-holder"><button type="button" class="btn btn-danger btn-xs" onclick="removeEditBreakdown('+count_breakdown+')"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button></div><div class="col-md-8 text-center"><input class="form-control input-sm pull-left" type="text" name="breakdown['+x+'][]" id="item1" data-validate="required"></div><div class="col-sm-2"><div class="input-group" style="margin-left: 40px;"><span class="input-group-addon currency_symbol_container">'+currency_symbol+'</span><input style="width:80px;" class="form-control input-sm pull-left" type="text" name="amounts_bd['+x+'][]" id="amount1" data-validate="decimal"></div></div></div>'); count_breakdown++; } function newSavedBreakdown(x) { var currency_symbol = getCurrencySymbol(); $('.formfieldsavedcontainer'+x).append('<div class="has-breakdown form-group formfieldedit'+x+'breakdownedit formfieldedit'+x+'breakdownedit'+count_breakdown+' breakdownedit'+count_breakdown+' text-center"><div class="col-md-1 col-md-offset-1 button-holder"><button type="button" class="btn btn-danger btn-xs" onclick="removeEditBreakdown('+count_breakdown+')"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button></div><div class="col-md-8 text-center"><input class="form-control input-sm pull-left" type="text" name="new_edit_breakdown['+x+'][]" id="item1" data-validate="required"></div><div class="col-sm-2"><div class="input-group" style="margin-left: 40px;"><span class="input-group-addon currency_symbol_container">'+currency_symbol+'</span><input style="width:80px;" class="form-control input-sm pull-left" type="text" name="new_edit_amounts_bd['+x+'][]" id="amount1" data-validate="decimal"></div></div></div>'); count_breakdown++; } function removeEditField(x) { $('.formfieldeditcontainer'+x).remove(); count--; } function removeEditBreakdown(x) { $('.breakdownedit'+x).remove(); count_breakdown++; } // For deleting saved items and breakdown in edit invoice function deleteItem(x) { var bill_id = $('.bill_details_id_val'+x+'').val(); $('.deleted_items').append('<input type="hidden" name="deleted_details[]" value="'+bill_id+'"/>'); $('.formfieldsaved'+x).remove(); $('.formfieldsavedcontainer'+x+'').remove(); } function deleteBreakdown(x, y) { var breakdown_id = $('.breakdown'+x+'_id_val'+y).val(); $('.deleted_items').append('<input type="hidden" name="deleted_breakdowns[]" value="'+breakdown_id+'"/>'); $('.formfield'+x+'breakdown'+y).remove(); }
var myvids = []; var valid = []; var myvid = document.getElementById('myvideo'); var activeVideo = 0; function play(){ myvid.addEventListener('ended', addVideos); } function addVideos(e){ if(activeVideo+1 === myvids.length){ myvid.removeEventListener('ended', addVideos) } // update the video source and play myvid.src = myvids[activeVideo]; myvid.play(); // update the new active video index activeVideo = (++activeVideo); } function macerar(){ myvids.push("videos/maceracion.mp4"); valid.push(1); appendInstruction("Macerar"); } function hervir(){ myvids.push("videos/hervor.mp4"); valid.push(2); appendInstruction("Hervir"); } function enfriar(){ myvids.push("videos/enfriado.mp4"); valid.push(3); appendInstruction("Enfriar"); } function fermentar(){ myvids.push("videos/fermentacion.mp4"); valid.push(4); appendInstruction("Fermentar"); } function madurar(){ myvids.push("videos/maduracion.mp4"); valid.push(5); appendInstruction("Madurar"); } function embotellar(){ myvids.push("videos/embotellamiento.mp4"); valid.push(6); appendInstruction("Embotellar"); } function check(){ for(var i=0;i<6;++i){ if(valid[i] != i+1){ myvids.push("videos/wrong.mp4"); break; } } } function appendInstruction(text) { var node = document.createElement("LI"); var textnode = document.createTextNode(text); node.appendChild(textnode); document.getElementById("pasoAPaso").appendChild(node); } function lagerInfo(){ document.getElementById('cuadroTexto').innerHTML = "Lager es un tipo de cerveza con sabor acentuado que se sirve fría, caracterizada por fermentar en condiciones más lentas empleando levaduras especiales, conocidas como levaduras de fermentación baja, y que en las últimas partes del proceso son almacenadas en bodegas (o lagered —de allí su nombre—) durante un período en condiciones de baja temperatura con el objeto de limpiar las partículas residuales y estabilizar los sabores. Los ejemplos más populares de cerveza de tipo lager son los pale lagers o pilsners, conocidas también como largers"; } function altInfo(){ document.getElementById('cuadroTexto').innerHTML = "La Altbier (se suele abreviar a como Alt) es un tipo oscuro de cerveza de alta fermentación, proveniente de Düsseldorf y la región de Niederrhein en Alemania. El nombre Altbier, que significa literalmente cerveza vieja, se refiere al viejo estilo de la elaboración de la cerveza (levadura de alta fermentación y malta oscura). Hasta los años 50, la Alt también fue llamada Düssel (de Düsseldorf), pero puesto que no es una denominación de origen protegida, la Altbier se puede también producir fuera de la región de Düsseldorf. La Kölsch es otra de las pocas cervezas alemanas de alta fermentación que se produce exclusivamente en Colonia y que es una de las únicas cervezas del mundo que disfruta de una denominación de origen."; } function aleInfo(){ document.getElementById('cuadroTexto').innerHTML = "Ale es un nombre que abarca a todas las cervezas de fermentación alta, lo que las diferencia de las lager que son de fermentación baja. Esto quiere decir que en las ales, el proceso de fermentación ocurre en la superficie del líquido, mientras que en las cervezas lager esta ocurre cerca del fondo. En otras palabras, la levadura que cumple el proceso de fermentación flota en la superficie del líquido durante varios días antes de descender al fondo. Para esto se usa principalmente levadura del tipo Saccharomyces cerevisiae.1​ Las ales fermentan rápidamente a temperaturas entre 15 y 25 °C y se sirven, por lo general, a una temperatura de 12 °C o más."; } function scotchInfo(){ document.getElementById('cuadroTexto').innerHTML = "La Scottish ale es el nombre por el que se define la cerveza elaborada en Escocia. Históricamente, en Escocia era imposible de cultivar lúpulo que estuviese mínimamente bien; la necesidad de importar lúpulo y el clima frío de Escocia produjo una cerveza en que la malta era predominante, con la fermentación de la levadura más limpia que la cerveza Inglesa."; } function negrainfo(){ document.getElementById('cuadroTexto').innerHTML = "La cerveza negra (en alemán Schwarzbier) es un tipo de cerveza lager alemana opaca, de color muy oscuro y sabor fuerte que recuerda al chocolate o al café. Aunque tienen un sabor parecido, son más suaves y menos amargas que las stouts o porters británicas, debido al uso de levadura lager en lugar de ale y a la omisión de la cebada."; }
require('./js/all.js'); require('./sass/all.scss');
/** * Created by Alessandro Lia Fook Santos on 25/11/2016. */ var app = angular.module('myApp', []); app.controller('controller', function ($scope, $http) { $scope.taskName = ""; $scope.tasks = new Array(); $scope.listTitle = ""; $scope.taskLists = new Array(); $scope.addTaskList = function () { $scope.taskLists.push($scope.listTitle); console.log($scope.taskLists); } $scope.testPost = function(){ $http({ method:"POST", url:"/task" }).then(function (data) { console.log(JSON.stringify(data)); }); }; $scope.testGet = function(){ $http({ method:"GET", url:"/task" }).then(function (data) { console.log(JSON.stringify(data)); }); }; //base object of the system var task = function (taskName) { this.titleName = taskName; this.isDone = false; this.priority = "warning"; }; //creating start tasks and add to list to accomplish design request //first task var wakeUp = new task("Wake Up"); $scope.tasks.push(wakeUp); //second task var breakfast = new task("Breakfast"); $scope.tasks.push(breakfast); //second task var sleep = new task("Sleep"); $scope.tasks.push(sleep); // functions that manipulate the tasks $scope.addTask = function () { if (!containTaskOnTaskList($scope.taskName)) { $scope.tasks.push(new task($scope.taskName)); $scope.updateDonePercentage(); } }; function containTaskOnTaskList(taskName) { for (var index = 0; index < $scope.tasks.length; index++) { var taskTitle = $scope.tasks[index].titleName; if (taskTitle === taskName) {return true;} } return false; }; $scope.deleteTask = function (index) { var task = $scope.tasks[index]; task.isDone = false; $scope.updateConcludedList(index); $scope.tasks.splice(index, 1); $scope.updateDonePercentage(); }; $scope.removeDoneTasks = function () { var index = $scope.tasks.length; while(--index >= 0){ var task = $scope.tasks[index]; if (task.isDone === true) {$scope.deleteTask(index)} } }; //Auxiliary array that stores done tasks $scope.concludedList = new Array(); $scope.donePercentage = 0; $scope.updateConcludedList = function (index) { var task = $scope.tasks[index]; var taskIndex = $scope.concludedList.indexOf(task); if(task.isDone === true && taskIndex < 0) { $scope.concludedList.push(task); $scope.tasks[index].priority = "success"; } if(task.isDone === false && taskIndex >= 0) { $scope.concludedList.splice(taskIndex, 1); $scope.tasks[index].priority = "warning"; } $scope.updateDonePercentage(); }; $scope.updateDonePercentage = function () { $scope.donePercentage = Math.floor(($scope.concludedList.length / $scope.tasks.length) * 100); var undone = 100 - $scope.donePercentage; document.getElementById('done-bar').style.width = $scope.donePercentage+"%"; document.getElementById('undone-bar').style.width = undone+"%"; }; });
'use strict'; var gulp = require('gulp'); var gutil = require('gulp-util'); var argv = require('yargs').argv; var fs = require('fs'); module.exports = function(options) { var options = { rootPath: 'src/app/components/', src: 'src/' }; var suffixes = { controller: '.controller.js', service: '.service.js', directive: '.directive.js', filter: '.filter.js', router: '.router.js', scss: '.scss', html: '.html' }; var scssTemplate = '.__NG_NAME__-wrap {\n\n' + '}'; var htmlTemplate = '<div class="__NG_NAME__-wrap row-container" ng-init="init()">\n\n' + '</div>'; var controllerTemplate = '\'use strict\'\;\n\n' + 'angular.module(\'app\').controller(\'__NG_NAME__Ctrl\',\n' + '\tfunction($scope, __NG_NAME__Service) {\n\n' + '\t\t$scope.init = function(){\n\n' + '\t\t};\n' + '\t});'; var serviceTemplate = '\'use strict\'\;\n\n' + 'angular.module(\'app\').factory(\'__NG_NAME__Service\',\n' + '\tfunction(HttpService) {\n\n' + '\t\treturn {\n\n' + '\t\t}\n' + '\t});'; var directiveTemplate = '\'use strict\'\;\n\n' + 'angular.module(\'app\')\n' + '\t.directive(\'__NG_NAME__Directive\', function() {\n' + '\t\treturn {\n' + '\t\t\trestrict: \'A\',\n' + '\t\t\tlink: function(scope, iElement, iAttrs){\n\n' + '\t\t\t}\n' + '\t\t}\n' + '\t});'; var filterTemplate = '\'use strict\'\;\n\n' + 'angular.module(\'app\').filter(\'__NG_NAME__Filter\', function(){\n' + '\treturn function(value){\n\n' + '\t}\n' + '});'; var routerTemplate = '\'use strict\'\;\n\n' + 'angular.module(\'app\').config(\n' + '\tfunction($stateProvider, $urlRouterProvider) {\n\n' + '\t\t$stateProvider\n' + '\t\t.state("__NG_NAME_L__", {\n' + '\t\t\turl: "/__NG_NAME_L__",\n' + '\t\t\tcontroller: \'__NG_NAME__Ctrl\',\n' + '\t\t\ttemplateUrl: \'__NG_HTML__\'\n' + '\t\t});\n' + '\t});'; var helpTemplate = '* module generator\n'+ '* gulp module\n' + '* options: \n' + '* -d, --dest <YOUR_MODULE_NAME>, required\n' + '* -r, --router create addtional router.js, optional\n' + '* -i, --insert insert file to existing module, optional\n' + '* -h, --help\n'; var string_src = function(filename, string) { var src = require('stream').Readable({ objectMode: true }) src._read = function () { this.push(new gutil.File({ cwd: "", base: "", path: filename, contents: new Buffer(string) })); this.push(null); } return src; }; var sanitize = function(string){ return string .replace(/\/+/g, '/') // replace consecutive slashes with a single slash .replace(/\/+$/, '') // remove trailing slashes .replace(/^\/+/, ''); }; var extractName = function(dest){ var arr = dest.split('/'); return arr[arr.length-1]; }; var generate = function(suffix, template) { var dest = sanitize(argv.d || argv.dest), insert = argv.i || argv.insert, moduleName = extractName(dest), path = options.rootPath + dest + '/' + moduleName + suffix, ngName = moduleName; if(insert){ fs.exists(path, function(exists){ if(exists) { console.log('skip existing ' + path); }else { gen(); } }); }else { gen(); } function gen(){ if(/\.js$/.test(suffix)){ if(suffix == suffixes.directive || suffix == suffixes.filter){ //do nothing }else { ngName = moduleName.charAt(0).toUpperCase() + moduleName.substring(1); } } var content = template.replace(/__NG_NAME__/g, ngName); if(suffix === suffixes.router) { content = content.replace(/__NG_NAME_L__/g, moduleName) .replace(/__NG_HTML__/, path.substring(options.src.length).replace(suffixes.router, suffixes.html)); } return string_src(path, content) .pipe(gulp.dest('.')); }; }; gulp.task('module', function () { var help = argv.h || argv.help, dest = argv.d || argv.dest, router = argv.r || argv.router, insert = argv.i || argv.insert; if(help){ console.log(helpTemplate); return; } if(dest == undefined || dest == true){ console.error('error: \n\t -d <YOUR_MODULE_NAME> is required.'); return; }else { dest = sanitize(dest); }; var moduleName = extractName(dest), path = options.rootPath + dest; if(insert){ run(); }else { fs.exists(path, function(exists){ if(exists) { console.error('error: ' + path + '\n\tmodule [' + moduleName + '] exists!'); }else { run(); } }); } function run(){ gulp.run('m.scss', 'm.html', 'm.controller', 'm.directive', 'm.service', 'm.filter'); if(router){ gulp.run('m.router'); } //console.log('\n---------------------\nmodule [' + moduleName + '] generated.\n' + path + '\n---------------------\n'); }; }); gulp.task('m.scss', function(){ generate(suffixes.scss, scssTemplate); }); gulp.task('m.html', function(){ generate(suffixes.html, htmlTemplate);; }); gulp.task('m.controller', function(){ generate(suffixes.controller, controllerTemplate);; }); gulp.task('m.directive', function(){ generate(suffixes.directive, directiveTemplate);; }); gulp.task('m.service', function(){ generate(suffixes.service, serviceTemplate);; }); gulp.task('m.filter', function(){ generate(suffixes.filter, filterTemplate);; }); gulp.task('m.router', function(){ generate(suffixes.router, routerTemplate); }); }
'use strict'; const request = require('superagent'); const server = require('../server.js'); const serverToggle = require('../lib/server-toggle.js'); const User = require('../model/user.js'); const PhotoAlbum = require('../model/photoalbum.js'); const PORT = process.env.PORT || 3000; require('jest'); const url = `http://localhost:${PORT}`; const exampleUser = { username: 'exampleuser', password: '2468', email: 'exampleuser@user.com', }; const exampleAlbum = { name: 'test album', desc: 'test photo album desc', }; describe('Photo Album Routes', function(){ beforeAll( done => { serverToggle.serverOn(server, done); }); afterAll( done => { serverToggle.serverOff(server, done); }); beforeEach( done => { new User(exampleUser) .generatePasswordHash(exampleUser.password) .then(user => user.save()) .then(user => { this.tempUser = user; return user.generateToken(); }) .then(token => { this.tempToken = token; done(); }) .catch(done); }); beforeEach( done => { exampleAlbum.userId = this.tempUser._id.toString(); new PhotoAlbum(exampleAlbum).save() .then( album => { this.tempAlbum = album; done(); }).catch(done); }); afterEach( done => { Promise.all([ User.remove({}), PhotoAlbum.remove({}), ]).then( () => done()) .catch(done); }); describe('POST: /api/photoalbum', () => { describe('with a valid body', () => { it('should return a photo album', done => { request.post(`${url}/api/photoalbum`) .send(exampleAlbum) .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { if(err) return done(err); expect(res.status).toEqual(200); expect(res.body.name).toEqual(exampleAlbum.name); expect(res.body.desc).toEqual(exampleAlbum.desc); expect(res.body.userId).toEqual(this.tempUser._id.toString()); done(); }); }); }); describe('with no token provided', () => { it('should return 401 error', done => { request.post(`${url}/api/photoalbum`) .send(exampleAlbum) .end((err, res) => { expect(err.status).toEqual(401); expect(res.status).toEqual(401); done(); }); }); }); describe('with no body or invalid body', () => { it('should return a 400 error', done => { request.post(`${url}/api/photoalbum`) .send('peanut') .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { expect(err.status).toEqual(404); expect(res.status).toEqual(404); done(); }); }); }); }); describe('GET: /api/photoalbum/:photoalbumId', () => { describe('with a valid id', () => { it('should return a photo album', done => { request.get(`${url}/api/photoalbum/${this.tempAlbum._id}`) .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { if(err) return done(err); expect(res.status).toEqual(200); expect(res.body.name).toEqual(exampleAlbum.name); expect(res.body.desc).toEqual(exampleAlbum.desc); expect(res.body.userId).toEqual(this.tempUser._id.toString()); done(); }); }); }); describe('with an invald token', () => { it('should return a 401 error', done => { request.get(`${url}/api/photoalbum/${this.tempAlbum._id}`) .end((err, res) => { expect(err.status).toEqual(401); expect(res.status).toEqual(401); done(); }); }); }); describe('with an invalid id', () => { it('should return a 404 error', done => { request.get(`${url}/api/photoalbum/123`) .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { expect(err.status).toEqual(404); expect(res.status).toEqual(404); done(); }); }); }); }); describe('GET: /api/photoalbum/user/:userId', () => { describe('with a valid id', () => { it.only('should return all the user\'s photo albums', done => { request.get(`${url}/api/photoalbum/user/${this.tempUser._id}`) .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { if(err) return done(err); expect(res.status).toEqual(200); expect(res.body[0].name).toEqual(exampleAlbum.name); expect(res.body[0].desc).toEqual(exampleAlbum.desc); expect(res.body[0].userId).toEqual(this.tempUser._id.toString()); done(); }); }); }); describe('with an invald token', () => { it('should return a 401 error', done => { request.get(`${url}/api/photoalbum/user/${this.tempUser._id}`) .end((err, res) => { expect(err.status).toEqual(401); expect(res.status).toEqual(401); done(); }); }); }); describe('with an invalid id', () => { it('should return a 404 error', done => { request.get(`${url}/api/photoalbum//user/123`) .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { expect(err.status).toEqual(404); expect(res.status).toEqual(404); done(); }); }); }); }); describe('PUT: /api/photoalbum/:photoalbumId', () => { describe('with a valid body', () => { it('should return an updated photo album', done => { request.put(`${url}/api/photoalbum/${this.tempAlbum._id}`) .send({ name: 'new album name'}) .set({ Authorization: `Bearer ${this.tempToken}`, }) .end((err, res) => { if(err) return done(err); expect(res.status).toEqual(200); expect(res.body.name).toEqual('new album name'); expect(res.body.desc).toEqual(exampleAlbum.desc); expect(res.body.userId).toEqual(this.tempUser._id.toString()); done(); }); }); }); describe('with an invalid token', () => { it('should return a 401 error', done => { request.put(`${url}/api/photoalbum/${this.tempAlbum._id}`) .send({ name: 'new album name'}) .end((err, res) => { expect(err.status).toEqual(401); expect(res.status).toEqual(401); done(); }); }); }); // describe('with an invalid body', () => { // it('should return a 400 error', done => { // request.put(`${url}/api/photoalbum/${this.tempAlbum._id}`) // .send({ peanut: 'butter'}) // .set({ // Authorization: `Bearer ${this.tempToken}`, // }) // .end((err, res) => { // console.log(res.body); // expect(err.status).toEqual(400); // expect(res.status).toEqual(400); // done(); // }); // }); // }); }); });
function ScoreSort(arr) { if (arr.length <= 0) return [] return arr.map(v => { if (v.length === 1) return v return v.split("").sort().join("") }) } export default ScoreSort
const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); // define the crawl data model schema const CrawlSchema = new mongoose.Schema({ crawlName: String, crawlOwner: String, //or Number?? either email or ID.. crawlDate: Date, crawlStartTime: Date, crawlEndTime: Date, crawlType: String, crawlStatus: Boolean, crawlPlaces: [ { name: String, lat: Number, lng: Number } ] }, { collection : 'crawls' }); module.exports = mongoose.model('Crawl', CrawlSchema);
'use strict'; var container = $(".displaynone"); app.controller('paymentController', ['$scope', '$filter', 'paymentService', function ($scope, $filter, paymentService) { $scope.Mode = { ListMode: 1, AddEditMode: 2 }; /// Begin Pagin $scope.FirstRecord = 0; $scope.LastRecord = 10; $scope.GoToPage = ''; $scope.NextPage = function () { if ($scope.CurrentPage < $scope.PageCount) { $scope.SetPage($scope.CurrentPage + 1); } }; $scope.PrevPage = function () { if ($scope.CurrentPage > 1) { $scope.SetPage($scope.CurrentPage - 1); } }; $scope.SetPage = function (n) { n = parseInt(n); if ($scope.CurrentPage != n && n > 0) { $scope.CurrentPage = n; $scope.GetPayments($scope.CurrentPage, $scope.PageSize); } }; /// End paging /// <summary> /// Method will get all payments and data of all dlls /// <summary> $scope.GetPayments = function (page, pageSize) { //paging $scope.PageSize = parseInt(pageSize); $scope.CurrentPage = page; //paging $scope.Payments = []; $scope.PeymentTypes = []; $scope.Accounts = []; $scope.Programs = []; $scope.Persons = []; paymentService.getPayments(page, pageSize).success(function (data) { $scope.Payments = data.Payments; $scope.Payments.PaymentToClient=data.Payments.PaymentToClient; $scope.PeymentTypes = data.PaymentTypes; $scope.Persons = data.Persons; $scope.Programs = data.Programs; $scope.Accounts = data.Accounts; //begin paging $scope.PaymentCount = data.PaymentCount; $scope.PageCount = Math.ceil(data.PaymentCount / $scope.PageSize); if (data.PaymentCount > 0) { $scope.FirstRecord = (($scope.CurrentPage - 1) * $scope.PageSize) + 1; $scope.LastRecord = ($scope.Payments.length == $scope.PageSize ? $scope.PageSize * $scope.CurrentPage : $scope.PaymentCount); } //end paging $scope.PageMode = $scope.Mode.ListMode; }).error(function () { alert("Some error occured while getting dropdown's data.") }); } // method will display the payment in add/edit mode $scope.AddEditPayment = function (paymentKey) { $scope.Payment = {}; $scope.PaymentAccounts = []; $scope.PaymentPrograms = []; $scope.AccountTotalAmount = 0; $scope.ProgramTotalAmount = 0; clearValidations(); $scope.PageMode = $scope.Mode.AddEditMode; if (paymentKey != undefined) { $scope.GetPayment(paymentKey); } } $scope.GetPayment = function (paymentKey,viewDetail) { paymentService.getPayment(paymentKey).success(function (data) { $scope.Payment = data; $scope.Payment.PaymentDate = ToJavaScriptDate($scope.Payment.PaymentDate); $scope.PaymentAccounts = data.PaymentAccountsModel; $scope.PaymentPrograms = data.PaymentProgramsModel; GetProgramTotalAmount(); GetAccountTotalAmount(); if (viewDetail != undefined) { $("#PaymentDetailModal").modal("toggle"); } }).error(function () { alert("Some error occured while getting Payment.") }); } //Convert date to javascript date var ToJavaScriptDate = function (value) { if (value == null || value == undefined) { return ""; } return moment(value).format("DD/MM/YYYY"); } ///method will take you back to payment listing $scope.CancelPayment = function () { //$scope.PageMode = $scope.Mode.ListMode; $scope.GetPayments($scope.CurrentPage, $scope.PageSize); } /// <summary> /// Method will save/update parameter detail /// <summary> $scope.SavePayment = function () { if (!$("#PaymentForm").valid()) return; clearValidations(); paymentService.savePayment($scope.Payment).success(function (data) { if (data.PaymentKey != undefined) { if ($scope.Payment.PaymentKey == undefined) { alert("Payment added successfully."); $scope.Payment.PaymentKey = data.PaymentKey; } else { alert("Payment updated successfully."); var paymentObj = $filter('filter')($scope.Payments, { PaymentKey: $scope.Payment.PaymentKey }); if (paymentObj != null) { paymentObj[0].PaymentDate = data.PaymentDate; paymentObj[0].PaymentCheckNumber = data.PaymentCheckNumber; paymentObj[0].PaymentTypeKey = data.PaymentTypeKey; paymentObj[0].PaymentTo = data.PaymentTo; paymentObj[0].PaymentVendorInvoiceNumber = data.PaymentVendorInvoiceNumber; paymentObj[0].PaymentNote = data.PaymentNote; } } } }).error(function () { alert("Some error occured while saving the payment.") }); } ///method will delete specific payment $scope.DeletePayment = function (paymentId, index) { paymentService.deletePayment(paymentId).then(function (response) { if (response.data) { //$scope.Payments.splice(index, 1); $scope.GetPayments($scope.CurrentPage, $scope.PageSize); alert('Payment deleted successfully'); } }, function (response) { alert('Some error occured while deleting the payment.'); }); } // method will display the person popup allowing you to add a new person $scope.AddNewPerson = function () { $scope.Person = {}; clearValidations(); $("#PersonModal").modal("toggle"); } /// <summary> /// method will save detail of person /// <summary> $scope.SavePerson = function () { if (!$("#PersonForm").valid()) return; clearValidations(); paymentService.savePerson($scope.Person).success(function (data) { if (data.PersonKey != undefined) { $scope.Persons.push(data); $scope.Payment.PaymentTo = data.PersonKey; $("#PersonModal").modal("toggle"); } }).error(function () { alert("Some error occured while adding the person.") }); } /// method will display payment account popup, allowing you to add new account for payment $scope.AddNewPaymentAccount = function () { if ($scope.Payment.PaymentKey == undefined) { alert('Please save payment details first.') } else { $scope.PaymentAccount = {}; clearValidations(); $("#PaymentAmountModal").modal("toggle"); } } /// <summary> /// method will save detail of person /// <summary> $scope.SavePaymentAccount = function () { if (!$("#PaymentAmountForm").valid()) return; clearValidations(); $scope.PaymentAccount.PaymentKey = $scope.Payment.PaymentKey; paymentService.savePaymentAccount($scope.PaymentAccount).success(function (data) { if (data.PaymentAccountKey != undefined) { var accountObj = $filter('filter')($scope.Accounts, { AccountKey: $scope.PaymentAccount.AccountKey }); if (accountObj != null) { data.AccountName = accountObj[0].AccountName; } $scope.PaymentAccounts.push(data); GetAccountTotalAmount(); $("#PaymentAmountModal").modal("toggle"); } }).error(function () { alert("Some error occured while saving the payment account.") }); } ///method will delete he specific payment account $scope.DeletePaymentAccount = function (paymentAccountId, index) { paymentService.deletePaymentAccount(paymentAccountId).then(function (response) { if (response.data) $scope.PaymentAccounts.splice(index, 1); GetAccountTotalAmount(); }, function (response) { alert('Some error occured while deleting the account.') }); } /// method will display payment program popup, allowing you to add new account for payment $scope.AddNewPaymentProgram = function () { if ($scope.Payment.PaymentKey == undefined) { alert('Please save payment details first.') } else { $scope.PaymentProgram = {}; clearValidations(); $("#PaymentProgramModal").modal("toggle"); } } /// <summary> /// method will save payment program /// <summary> $scope.SavePaymentProgram = function () { if (!$("#PaymentAmountForm").valid()) return; clearValidations(); $scope.PaymentProgram.PaymentKey = $scope.Payment.PaymentKey; paymentService.savePaymentProgram($scope.PaymentProgram).success(function (data) { if (data.PaymentProgramKey != undefined) { var progObj = $filter('filter')($scope.Programs, { ProgramName: $scope.PaymentProgram.AccountKey }); if (progObj != null) { data.ProgramName = progObj[0].ProgramName; } $scope.PaymentPrograms.push(data); GetProgramTotalAmount(); $("#PaymentProgramModal").modal("toggle"); } }).error(function () { alert("Some error occured while saving the payment program.") }); } ///method will delete he specific payment program $scope.DeletePaymentProgram = function (paymentProgramId, index) { paymentService.deletePaymentProgram(paymentProgramId).then(function (response) { if (response.data) $scope.PaymentPrograms.splice(index, 1); GetProgramTotalAmount(); }, function (response) { alert('Some error occured while deleting the program.') }); } var GetProgramTotalAmount = function () { $scope.ProgramTotalAmount = 0; angular.forEach($scope.PaymentPrograms, function (value, key) { $scope.ProgramTotalAmount = $scope.ProgramTotalAmount + value.PaymentProgramAmount; }); } var GetAccountTotalAmount = function () { $scope.AccountTotalAmount = 0; angular.forEach($scope.PaymentAccounts, function (value, key) { $scope.AccountTotalAmount = $scope.AccountTotalAmount + value.PaymentAccountAmount; }); } var initial = function () { $scope.PeymentTypes = []; $scope.Persons = []; $scope.Accounts = []; $scope.Programs = []; $scope.Payment = {}; $scope.Person = {}; $scope.PaymentAccount = {}; $scope.PaymentPrograms = []; $scope.PaymentAccounts = []; $scope.PageMode = $scope.Mode.ListMode; $scope.Payments = []; $scope.AccountTotalAmount = 0; $scope.ProgramTotalAmount = 0; ////Paging $scope.PaymentCount = 0; $scope.PageSize = 10; $scope.CurrentPage = 1; $scope.PageCount = 0; //paging $scope.GetPayments($scope.CurrentPage, $scope.PageSize); } initial(); var clearValidations = function () { $('.input-validation-error').removeClass('input-validation-error'); $('.field-validation-error').removeClass('field-validation-error').addClass('field-validation-valid'); }; }]);
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/com.ionic.keyboard/www/keyboard.js", "id": "com.ionic.keyboard.keyboard", "clobbers": [ "cordova.plugins.Keyboard" ] }, { "file": "plugins/io.litehelpers.sqliteStorage/www/SQLitePlugin.js", "id": "io.litehelpers.sqliteStorage.SQLitePlugin", "clobbers": [ "SQLitePlugin" ] }, { "file": "plugins/org.apache.cordova.console/www/console-via-logger.js", "id": "org.apache.cordova.console.console", "clobbers": [ "console" ] }, { "file": "plugins/org.apache.cordova.console/www/logger.js", "id": "org.apache.cordova.console.logger", "clobbers": [ "cordova.logger" ] }, { "file": "plugins/org.apache.cordova.device/www/device.js", "id": "org.apache.cordova.device.device", "clobbers": [ "device" ] }, { "file": "plugins/org.apache.cordova.network-information/www/network.js", "id": "org.apache.cordova.network-information.network", "clobbers": [ "navigator.connection", "navigator.network.connection" ] }, { "file": "plugins/org.apache.cordova.network-information/www/Connection.js", "id": "org.apache.cordova.network-information.Connection", "clobbers": [ "Connection" ] }, { "file": "plugins/cordova-plugin-google-analytics/www/analytics.js", "id": "cordova-plugin-google-analytics.UniversalAnalytics", "clobbers": [ "analytics" ] }, { "file": "plugins/org.apache.cordova.inappbrowser/www/inappbrowser.js", "id": "org.apache.cordova.inappbrowser.inappbrowser", "clobbers": [ "window.open" ] }, { "file": "plugins/nl.x-services.plugins.socialsharing/www/SocialSharing.js", "id": "nl.x-services.plugins.socialsharing.SocialSharing", "clobbers": [ "window.plugins.socialsharing" ] } ]; module.exports.metadata = // TOP OF METADATA { "com.ionic.keyboard": "1.0.4", "io.litehelpers.sqliteStorage": "0.7.4", "org.apache.cordova.console": "0.2.13", "org.apache.cordova.device": "0.3.0", "org.apache.cordova.network-information": "0.2.15", "cordova-plugin-google-analytics": "0.7.2", "org.apache.cordova.inappbrowser": "0.6.0", "nl.x-services.plugins.socialsharing": "4.3.18" } // BOTTOM OF METADATA });
import React from "react"; import Wrapper from "./selector/wrapper.view"; import Title from "./selector/title.view"; import Choices from "./selector/choices.view"; import Choice from "./selector/choice.view"; export default function ColorSelector({ total, index }) { const choices = []; for (let current = 1; current <= total; current++) { choices.push( <Choice selected={current === index} key={`color-${current}`}> {`Color ${current}`} </Choice> ); } return ( <Wrapper> <Title>Select color</Title> <Choices> {choices} </Choices> </Wrapper> ); }
import React, { useReducer } from 'react' import reducer, { initialValue, dispatchWrapper } from '@/reducer' import createCtx from '@/utils/createCtx' const [useCtx, Provider] = createCtx() /** * 若使用此种方式一旦state更新,会导致所有用到useStore的子组件渲染,无法避免无效更新。 */ function StoreProvider(props) { const { children } = props const [state, dispatch] = useReducer(reducer, initialValue) return ( <Provider value={{ state, dispatch: dispatchWrapper(dispatch, state) }}> {children} </Provider> ) } export { useCtx as useStore } export default StoreProvider /* 子组件使用方式 import React from 'react' import { useStore } from '@/providers/StoreCtxProvider' export default () => { const { state, dispatch } = useStore() const _add = () => { dispatch({ type: 'home/asyncSetCount', payload: state.home.count + 1 }).then((res) => { console.log(res) }) } return ( <div style={{padding: '10px'}}> <input value={state.home.count} /> <button onClick={_add} >+</button> </div> ) } */
//https://www.hackerrank.com/challenges/anagram //count letter differences in each string, then divide by 2 because only have to change one. function processData(input) { 'use strict'; const strings = input.split('\n'); const t = strings.shift(); const a = 'abcdefghijklmnopqrstuvwxyz'; //could generate this with a for loop but whatever. const addLetters = function(strObj, ai, x){ if(!strObj[ai]){ strObj[ai] = [0,0]; strObj[ai][x]++; }else{ strObj[ai][x]++; } } for (let string of strings){ let strObj = {}; //reset it for each string if(string.length%2 != 0){ //get rid of the odds. strObj = -1; console.log(strObj); }else{ let len = string.length; let h = len/2; for(let i=0;i<h;i++){ //loop through first half. let ai = string[i]; addLetters(strObj, ai, 0); //use letter array[0] for first string letters. } for(let i=h;i<len;i++){ //loop through second half. let ai = string[i]; addLetters(strObj, ai, 1);//use letter array[1] for second string letters. } let total = 0; for(let each in strObj){ if(each === -1){ changes = -1; }else{ let diff = Math.abs(strObj[each][0] - strObj[each][1]); total += diff; } } let changes = total/2; console.log(changes); } } }
import React from 'react'; import ReactDom from 'react-dom'; import './index.css'; //stateless functional component const books = [ { id: 1, img : 'https://images-na.ssl-images-amazon.com/images/I/A1Ee%2BYjn92L._AC_UL200_SR200,200_.jpg', title : 'The Polar Express', author : 'Chris Van Allsburg', }, { id: 2, img : 'https://images-na.ssl-images-amazon.com/images/I/81Kc8OsbDxL._AC_UL200_SR200,200_.jpg', title : 'Greenlights', author : 'Matthew McConaughey', }, { id : 3, img : 'https://images-na.ssl-images-amazon.com/images/I/41cW7tUznyL.__AC_SY300_QL70_ML2_.jpg', title : 'Sky Scout', author : 'Yu-Gi-Oh', }]; function BookList() { //This is our component, React knows with capital letter return ( <section className="booklist"> {books.map((book)=>{ return ( <Book key={book.id} {...book}></Book> ); })} </section> ); } const Book = (props) => { console.log(props); const {img, title, author} = props; const clickHandler = () => { alert('Hello World'); } return ( <article className="book"> <img src={img} alt=""/> <h1 onClick={() => console.log(title)}>{title}</h1> <h4>{author}</h4> <button type='button' onClick={clickHandler}> Hello! </button> </article> ); } //inline styling is more powerful than added css // brackets must return a value ReactDom.render(<BookList />, document.getElementById('root')); /*const Person = () => <h2>Hello World</h2>; const Message = () => { return <p>this is my message</p>; } const Greeting = () => { return React.createElement( 'div', {}, React.createElement('h1',{}, 'Hello World') ); }*/
function getMathImgSrcList (latexArr) { // 因为公式编辑器已经在编辑过滤,所有这里不做filter let doc = document.implementation.createHTMLDocument(); latexArr.forEach(latex => { let div = doc.createElement('div'); div.innerHTML = latex.replace(/>/g, '&gt;').replace(/</g, '&lt;'); doc.body.appendChild(div); }); return new Promise((resolve, reject) => { function rendered () { let area = document.getElementById('drawImage'); let list = []; Array.from(doc.querySelectorAll('.MathJax_SVG')).forEach((svgContainer, index) => { canvg(area, svgContainer.innerHTML); list.push({ src: area.toDataURL('image/png'), latex: latexArr[index].slice(1, latexArr[index].length - 1).replace(/&gt;/g, '>').replace(/&lt;/g, '<') }); }); resolve(list); } MathJax.Hub.Queue( ['Typeset', MathJax.Hub, doc.body], [rendered] ); }); } UE.registerUI('latexeditor', function(editor,uiName){ // console.log(window.location.href.includes('/exam-manage')); console.log(editor.options.UEDITOR_HOME_URL); //创建dialog var dialog = new UE.ui.Dialog({ //指定弹出层中页面的路径,这里只能支持页面,因为跟addCustomizeDialog.js相同目录,所以无需加路径 iframeUrl:editor.options.UEDITOR_HOME_URL + '../static/plugin/ueditor/latex-editor-plugin/latex-editor.html', //需要指定当前的编辑器实例 editor:editor, //指定dialog的名字 name:uiName, //dialog的标题 title:"作业帮理科公式编辑器", //指定dialog的外围样式 cssRules:"width:710px;height:544px;" }); editor.addListener('insertlatex', function (eventName, latex, container) { getMathImgSrcList([latex]) .then(objList => { if (container) { container.outerHTML = `<img class="yk-math-img" data-latex="${objList[0].latex}" src="${objList[0].src}">`; } else { editor.execCommand('inserthtml', `<img class="yk-math-img" data-latex="${objList[0].latex}" src="${objList[0].src}">`); } dialog.close(true); }) }); let results = null; editor.addListener('editsvg', function (eventName, result) { results = result; dialog.render(); dialog.open(); }); editor.addListener('latexeditorload', function () { if (!results) return; editor.fireEvent('initlatexeditor', results); results = null; }); //参考addCustomizeButton.js var btn = new UE.ui.Button({ name:'latex editor', title:'新建公式(ctrl+m)', //需要添加的额外样式,指定icon图标,这里默认使用一个重复的icon // cssRules :'background-image: url("' + 'http://camnpr.com/upload/2014/7/201407011438228175.jpg' + '")!important;', onclick:function () { //渲染dialog dialog.render(); dialog.open(); } }); return btn; }/*index 指定添加到工具栏上的那个位置,默认时追加到最后,editorId 指定这个UI是那个编辑器实例上的,默认是页面上所有的编辑器都会添加这个按钮*/);
import test from 'ava'; import NanoAmountConverter from "../../model/Cryptography/NanoAmountConverter"; test('When nano is converted to raw, then result is correct.', async t => { let NanoAmountConverter = getTestObjects(); let testAmount = 1; let result = NanoAmountConverter.ConvertNanoAmountToRawAmount(testAmount); t.is('1000000000000000000000000000000', result); }); test('When raw is converted to nano, then result is correct.', async t => { let NanoAmountConverter = getTestObjects(); let testAmount = '100000000000000000000000000000'; let result = NanoAmountConverter.ConvertRawAmountToNanoAmount(testAmount); t.is('0.1', result); }); test('When raw amounts are added together, then result is correct.', async t => { let NanoAmountConverter = getTestObjects(); let testAmount1 = '1000000000000000000000000000000'; let testAmount2 = '500000000000000000000000000000'; let result = NanoAmountConverter.AddRawAmounts(testAmount1, testAmount2); t.is('1500000000000000000000000000000', result); }); test('When raw amount to send is subtracted from current balance, then result is correct.', async t => { let NanoAmountConverter = getTestObjects(); let currentBalance = '1000000000000000000000000000000'; let amountToSend = '400000000000000000000000000000'; let result = NanoAmountConverter.SubtractSendAmount(currentBalance, amountToSend); t.is('600000000000000000000000000000', result); }); test('When GetTransactionAmount is called, then difference between pre-tx and post-tx balance is returned in whole Nano.', async t => { let NanoAmountConverter = getTestObjects(); let testAmount1 = '1000000000000000000000000000000'; let testAmount2 = '800000000000000000000000000000'; let result = NanoAmountConverter.GetTransactionAmount(testAmount1, testAmount2); t.is('-0.2', result); }); let getTestObjects = () => { return new NanoAmountConverter(); }
import styled from 'styled-components'; import { colors } from '../../styles/variables'; import { ActionClose } from '../_styled/Actions'; export const Modal = styled.div` position: fixed; top: 0; left: 0; display: flex; align-items: center; justify-content: center; width: 100vw; height: 100vh; z-index: 30; background: rgba(0, 0, 0, .5); visibility: visible; overflow-x: hidden; overflow-y: auto; &::-webkit-scrollbar { width: 7px; border-radius: 30px; } &::-webkit-scrollbar-track { background: rgba(0, 0, 0, .03); border-radius: 30px; } &::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, .4); border-radius: 30px; } `; Modal.Overlay = styled.div` position: absolute; top: 0; left: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; min-height: 100%; padding: 1.5rem; cursor: pointer; `; Modal.Container = styled.div` display: flex; flex-direction: column; align-items: center; justify-content: center; position: relative; width: 100%; max-width: 800px; padding: 1.5rem; margin-bottom: 4rem; color: ${colors.text}; background: ${colors.background}; border-radius: 4px; overflow: hidden; cursor: default; `; Modal.ButtonClose = styled(ActionClose)` margin-left: auto; `; Modal.Content = styled.div` width: 100%; `;
export function checkResponseStatus(response) { return response.json() .then((data) => { if (!response.ok) { return Promise.reject(data); } else { return data; } }); }
import { renderString } from '../../src/index'; describe(`Rewrites the URL of an image in File Manager to a URL that will overlay a play button on request.`, () => { it(`unnamed case 0`, () => { const html = renderString(`{{ video_thumbnail({ url: "http://your.hubspot.site/hubfs/img.jpg", height: 720 }) }}`); }); it(`unnamed case 1`, () => { const html = renderString(`{{ video_thumbnail({ url: "http://your.hubspot.site/hubfs/img.jpg", height: 720, color: "#FF0000" }) }}`); }); it(`unnamed case 2`, () => { const html = renderString(`{{ video_thumbnail({ url: "http://your.hubspot.site/hubfs/img.jpg", height: 720, color: "#FF0000", scale: 0.8 }) }}`); }); });
import React from 'react' import * as Icon from 'react-bootstrap-icons' import './ItemPicture.css' function ItemPicture({ picture, className, styles }) { return ( <div className={className}> {picture ? <div className="item-picture" style={{backgroundImage: `url(${picture})`, ...styles}}> </div>: <div className="item-picture" style={styles}> <Icon.Image size={30}/> </div> } </div> ) } export default ItemPicture
import React from "react"; import "./style.css"; function Form(props){ return ( <div className="card m-4 formCard"> <div className="card-title m-2"> <h4>Search for a book!</h4> </div> <div className="card-body"> <div className="form" validation> <input type="text" onChange={props.handleInputChange} name="search" className="form pb-1" placeholder="Search for a book!" required /> <button className="btn btn-primary form ml-2" onClick={props.handleFormSubmit}>Search</button> </div> </div> </div> ); } export default Form;
/** * 自营商城商品详情页 */ import React, { Component, PureComponent } from "react"; import { StyleSheet, Dimensions, View, Text, TouchableOpacity, ImageBackground, Image, StatusBar, Platform, } from "react-native"; import { connect } from "react-redux"; import { bindActionCreators } from "redux"; import actions from "../../action/actions"; import config from "../../config/config"; import CommonStyles from "../../common/Styles"; import Header from "../../components/Header"; import * as requestApi from "../../config/requestApi"; import FlatListView from "../../components/FlatListView"; import WebViewCpt from "../../components/WebViewCpt"; import ShareTemplate from '../../components/ShareTemplate'; import ShowBigPicModal from '../../components/ShowBigPicModal'; import * as nativeApi from "../../config/nativeApi"; const { width, height } = Dimensions.get("window"); const weibo = require("../../images/share/weibo.png"); const weixin = require("../../images/share/weixin.png"); const qqicon = require("../../images/share/qqicon.png"); const friendsquan = require("../../images/share/friendsquan.png"); const copylian = require("../../images/share/copylian.png"); const friends = require("../../images/share/friends.png"); class SOMGoodsDetailScreen extends Component { static navigationOptions = { header: null }; _willBlurSubscription; _didFocusSubscription; constructor(props) { super(props); this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>{ StatusBar.setBarStyle('dark-content') }); this.state = { goodsData:{}, canGoBack: false, modalVisible: false, modalLists: [ { id: 1, title: "分享", icon: require("../../images/mall/share.png"), // routeName: "SOMShareTemp" routeName: "" }, { id: 2, title: "意见反馈", icon: require("../../images/mall/fankui.png"), routeName: "Feedback" } ], shareModal: false, shareUrl: "", // 分享链接 shareParams: null, showBingPicVisible: false, bigIndex: 0, // 大图索引 bigList: [], // 查看大图所有图片rr goodsId:(global.nativeProps && global.nativeProps.goodsId) || this.props.navigation.getParam('goodsId',''), prohibit: false, // 是否禁止webView加入购物车和立即购买 }; } componentDidMount() { this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload => StatusBar.setBarStyle('light-content') ); const { identityStatuses } = this.props.userInfo let temp = identityStatuses.map(item => item.auditStatus === 'active' ? true : false) if (!temp.includes(true)) { this.setState({ prohibit: true, }) } // if(global.nativeProps){ //如果是从原生到rn,获取用户信息初始化 // this.props.actions.changeState({user:global.loginInfo }) // } } componentWillUnmount () { Loading.hide(); this._didFocusSubscription && this._didFocusSubscription.remove(); this._willBlurSubscription && this._willBlurSubscription.remove(); } getGoodsDetail = () => { Loading.show(); requestApi.goodsDetail({ id: this.state.goodsId, }).then(res => { console.log('商品详情',res) this.props.navigation.navigate('Feedback',{ goodsData:res.base }); }).catch(err => { console.log(err) }) } changeState(key, value) { this.setState({ [key]: value }); } postMessage = () => { }; goBack = () => { const { navigation } = this.props; const { canGoBack } = this.state; if (canGoBack) { this.webViewRef.goBack(); } else { global.nativeProps?nativeApi.popToNative(): navigation.goBack(); } }; //进入结算界面: SOMOrderConfirm jsOpenSOMOrderConfirm = e => { let index = e.indexOf(","); let str = e.substring(index + 1); let data = JSON.parse(str); let goodsList = []; console.log('data', data) if (data) { goodsList[0] = {}; goodsList[0].goodsId = data.goodsAttrs.goodsId; goodsList[0].quantity = data.quantity; goodsList[0].goodsSkuCode = data.base.defaultSku.code; goodsList[0].goodsAttr = data.base.defaultSku.name; goodsList[0].goodsName = data.base.name; goodsList[0].url = data.base.showPicUrl[0]; goodsList[0].price = data.base.defaultSku.price; goodsList[0].buyPrice = data.base.defaultSku.buyPrice; goodsList[0].goodsDivide = data.base.goodsDivide goodsList[0].subscription = data.base.defaultSku.subscription || 0 } this.props.navigation.navigate("SOMOrderConfirm", { goodsList: goodsList }); }; // 打开购物车 jsOpenAppShoppingCart = e => { this.props.navigation.navigate("SOMShoppingCart"); }; // 打开客服 jsOpenAppCustomerService = e => { // Toast.show("开发中"); nativeApi.createXKCustomerSerChat() // this.props.navigation.navigate('NativeCustomerService') }; // 打开图片浏览 jsOpenAppImageBrowser = param => { console.log("打开图片浏览",param); let _params = param.replace('jsOpenAppImageBrowser,',''); let _data = JSON.parse(_params); let { index,list } = _data let temp = []; list.map(item => { if (item.type === 'img') { temp.push({ type: 'images', url: item.url }) } if (item.type === 'video') { temp.push({ mainPic: item.mainPic, url: item.url, type: 'video' }) } }) console.log(temp) StatusBar.setHidden(true); this.setState({ bigIndex: index, bigList: temp, showBingPicVisible: true, }) }; // 打开全部评价 jsOpenAppComments = e => { this.props.navigation.navigate("SOMGoodsComments", { goodsId:this.state.goodsId }); }; // 获取分享路径 pushSharePath = e => { e = JSON.parse(e); console.log(e); this.changeState("shareUrl", e.shareUrl); this.changeState("shareParams", e.param); }; // 加入购物车 addToCart = () => { requestApi.requestGoodsSku({ goodsId }, res => { let goodsSkuCode = res.skuAttrValue[0].code; let quantity = 1; requestApi.requestMallCartCreate( { goodsId, goodsSkuCode, quantity }, () => { Toast.show("加入购物车成功"); } ); }); }; // 获取分析模板,如果没有弹窗 handleGetShareInfo = () => { const { shareParams, prohibit , shareUrl,goodsId } = this.state; // 判断用户身份只有一个的时候是否入驻成功 if (prohibit) { Toast.show('您尚未成功入驻,暂不能分享该商品!') return } requestApi.promotionTemplateQList({ goodsId, }).then(res => { console.log('获取分析模板',res) if (res) { // 如果获取到了模板 this.props.navigation.navigate('SOMShareTemp',{shareParams,shareUrl,goodsId}) } else { if (shareParams) { this.changeState("shareModal",true); } else { Toast.show("获取分享信息失败"); } } }).catch(err => { console.log(err) }); } handleShowpage = () => { const { bigList,bigIndex } = this.state if (bigList.length > 0) { return !(Platform.OS === 'ios' && bigList[bigIndex].type === 'video') } return true } render() { const { navigation, userInfo } = this.props; const { goodsData, modalVisible, modalLists, shareModal, shareParams, shareUrl,goodsId,prohibit } = this.state; let _baseUrl = `${config.baseUrl_h5}goodsdetail`; let referralCode = userInfo.securityCode; let isHiddenPrice = '' if (prohibit) { isHiddenPrice='yes' } else { isHiddenPrice='no' } let _url = `${_baseUrl}?id=${goodsId}&merchantId=${userInfo.merchantId}&securityCode=${referralCode}&prohibit=${isHiddenPrice}` // let _url = `http://192.168.2.115:8080/#/goodsdetail?id=${goodsId}&merchantId=${userInfo.merchantId}&securityCode=${referralCode}&prohibit=${isHiddenPrice}` let source = { uri: _url, showLoading: true, headers: { "Cache-Control": "no-cache" } } console.log('showBingPicVisible',this.state.showBingPicVisible) return ( <View style={styles.container}> <StatusBar barStyle={'dark-content'} /> <WebViewCpt loginInfo={global.loginInfo} webViewRef={e => { this.webViewRef = e; }} isNeedUrlParams={true} source={source} postMessage={() => { this.postMessage(); }} getMessage={data => { let params = data && data.split(","); if (params[0] === "jsOpenAppShoppingCart") { this.jsOpenAppShoppingCart(params); } else if (params[0] === "jsOpenAppCustomerService") { this.jsOpenAppCustomerService(params); } else if (params[0] === "jsOpenAppImageBrowser") { this.jsOpenAppImageBrowser(data); } else if (params[0] === "jsOpenAppComments") { this.jsOpenAppComments(params); } else if (params[0] === "jsOpenIndianaShopOrder") { this.jsOpenSOMOrderConfirm(data); } else if (params[0] === "pushSharePath") { let _data = data.replace("pushSharePath,", ""); this.pushSharePath(_data); } else if (params[0] === "jsHiddenXKHUDView") { Loading.hide(); } else if (params[0] === "jsOpenUsrHome") { let _data = data.replace('jsOpenUsrHome,','') console.log('_data',_data) nativeApi.jumpPersonalCenter(JSON.parse(_data).userId) } else if (params[0] === "jsOpenZyMallStore") { let _data = data.replace('jsOpenZyMallStore,','') navigation.navigate('SOMShopDetail',JSON.parse(_data)) }else { console.log(params); } }} navigationChange={canGoBack => { // this.changeState('canGoBack', canGoBack); }} /> <Header navigation={navigation} headerStyle={styles.headerStyle} leftView={ <TouchableOpacity style={[CommonStyles.flex_center,styles.headerItem]} activeOpacity={0.6} onPress={() => { this.goBack(); }} > <Image source={require("../../images/mall/goback_gray.png")} /> </TouchableOpacity> } rightView={ <TouchableOpacity style={[CommonStyles.flex_center,styles.headerItem]} activeOpacity={0.6} onPress={() => { this.changeState("modalVisible", true); }} > <Image source={require("../../images/mall/more_gray.png")} /> </TouchableOpacity> } /> {/* 点击更多弹窗 */} {modalVisible && ( <TouchableOpacity style={styles.modalOutView} activeOpacity={1} onPress={() => { this.changeState("modalVisible", false); }} > <ImageBackground style={styles.modalInnerView} source={require("../../images/mall/more_gray_modal.png")} > <View style={styles.moreModalWrap}> {modalLists.map((item, index) => { let border = index === modalLists.length - 1 ? null : styles.border; return ( <View style={{flex: 1,width: '100%',paddingHorizontal: 15,...CommonStyles.flex_center}} key={index}> <TouchableOpacity style={[styles.modalInnerItem,border]} activeOpacity={0.6} onPress={() => { this.changeState("modalVisible",false); if (item.routeName) { // 有路由就是反馈,没有就是分享 this.getGoodsDetail() } else { this.handleGetShareInfo() } }} > <Image source={item.icon} /> <Text style={styles.modalInnerItem_text} > {item.title} </Text> </TouchableOpacity> </View> ) })} </View> </ImageBackground> </TouchableOpacity> )} {/* 分享 */} { shareModal && <ShareTemplate type='SOM' onClose={() => { this.changeState("shareModal", false); }} shareParams={shareParams} shareUrl={shareUrl} /> } {/* 查看大图 */} <ShowBigPicModal isShowPage={this.handleShowpage()} ImageList={this.state.bigList} visible={this.state.showBingPicVisible} showImgIndex={this.state.bigIndex} onClose={() => { StatusBar.setHidden(false); this.setState({ showBingPicVisible: false, }) }} /> </View > ); } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding }, headerStyle: { position: "absolute", top: CommonStyles.headerPadding, height: 44, paddingTop: 0, backgroundColor: "transparent" }, headerItem: { width: 50 }, footerView: { flexDirection: "row", justifyContent: "center", alignItems: "center", width: width, height: 50 + CommonStyles.footerPadding, paddingBottom: CommonStyles.footerPadding }, footerItem: { flexDirection: "row", justifyContent: "center", alignItems: "center", height: 50 }, footerItem1: { flex: 1.6, backgroundColor: "#fff" }, footerItem1_imgView: { justifyContent: "center", alignItems: "center", height: "100%", paddingHorizontal: 10 }, footerItem2: { flex: 1, backgroundColor: "#4A90FA" }, footerItem3: { flex: 1, backgroundColor: "#EE6161" }, footerItem_text: { fontSize: 14, color: "#fff" }, modalOutView: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, backgroundColor: "transparent" }, modalInnerView: { position: "absolute", top: 44 + CommonStyles.headerPadding, right: 12, justifyContent: "flex-end", width: 126, height: 93 }, modalInnerItem: { flexDirection: "row", justifyContent: "flex-start", alignItems: "center", width: "100%", height: '100%', borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255,.2)' // height: 41, // paddingLeft: 15 }, modalInnerItem_text: { fontSize: 17, color: "#fff", marginLeft: 8, }, modalOutView2: { justifyContent: "center", alignItems: "center", backgroundColor: "rgba(0,0,0,0.5)" }, shareModalView: { width: width - 55, marginHorizontal: 27.5, borderRadius: 8, backgroundColor: "#fff", overflow: "hidden" }, shareModalView_img: { width: "100%", height: ((width - 55) * 217.5) / 319 }, shareModalView_center: { width: "100%", borderTopWidth: 1, borderTopColor: "#E5E5E5", borderBottomWidth: 1, borderBottomColor: "#E5E5E5" }, shareModalView_center_top: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", width: "100%", height: 80, paddingHorizontal: 10, paddingVertical: 7 }, shareModalView_center_top_left: { justifyContent: "space-between", flex: 1, height: "100%" }, shareModalView_center_top_right: { width: 66, height: "100%" }, shareModalView_center_top_right_img: { width: "100%", height: "100%" }, shareModalView_center_top_left_text1: { fontSize: 12, color: "#777" }, shareModalView_center_top_left_item1: { // paddingHorizontal: 20, // paddingVertical: 2, // borderRadius: 10, // backgroundColor: '#FF545B', }, shareModalView_center_top_left_text2: { fontSize: 12, color: "#FF545B", paddingVertical: 2, borderRadius: 10 }, shareModalView_center_bom: { flexDirection: "row", flexWrap: "wrap", paddingTop: 10 }, shareModalView_center_bom_view: { justifyContent: "center", alignItems: "center", width: "25%", marginBottom: 10 }, shareModalView_center_bom_img: { width: 40, height: 40 }, shareModalView_center_bom_text: { fontSize: 10, color: "#777", marginTop: 5 }, shareModalView_bom: { flexDirection: "row", justifyContent: "center", alignItems: "center", width: "100%", height: 36 }, shareModalView_bom_text: { fontSize: 14, color: "#222" }, moreModalWrap: { height: 93 -12, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }, border: { borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255,.2)' }, }); export default connect( state => ({ userInfo: state.user.user }), dispatch => ({ actions: bindActionCreators(actions, dispatch) }) )(SOMGoodsDetailScreen);
export const Config = { API_URL: 'https://testurl.com/api/', }
function waitFont(fontFamily, callback) { var tester = document.createElement('span'); var testFont = 'Comic Sans MS'; var maxMs = 1000; tester.style.position = 'absolute'; tester.style.top = '-9999px'; tester.style.left = '-9999px'; tester.style.visibility = 'hidden'; tester.style.fontFamily = testFont; tester.style.fontSize = '250px'; tester.innerHTML = 'QW@HhsXJ'; document.body.appendChild(tester); var startWidth = tester.offsetWidth; tester.style.fontFamily = fontFamily + ', ' + testFont; var start = new Date().getTime(); function checkFont() { var loadedFontWidth = tester.offsetWidth; if (startWidth === loadedFontWidth && (new Date().getTime() - start) < maxMs) { setTimeout(checkFont, 100); } else { callback() } } checkFont(); }; function addStyle(name, url) { var s = document.createElement('style'); s.type = "text/css"; document.getElementsByTagName('head')[0].appendChild(s); const css = `@font-face { font-family: ${name}; src: url("${url}.eot"); src: url("${url}.eot?#iefix") format("embedded-opentype"), url("${url}.woff2") format("woff2"), url("${url}.woff") format("woff"), url("${url}.ttf") format("truetype"), url("${url}.svg#webfont") format("svg"); font-weight: normal; font-style: normal; }`; if (s.styleSheet){ s.styleSheet.cssText = css; } else { s.appendChild(document.createTextNode(css)); } } export default function () { return { load: ({ resources, Progress }) => { const totSize = resources.map(it => it.size).reduce((itA, itB) => itA + itB); const progress = Progress(totSize, resources.map((it) => { return { size: it.size }; })); progress.startSimulate(); return Promise.all(resources.map((resource) => { return new Promise(function (resolve) { const name = resource.url.substr(resource.url.lastIndexOf('/') +1, resource.url.lastIndexOf('.') - resource.url.lastIndexOf('/') -1); const url = resource.url.substr(0, resource.url.lastIndexOf('.')); addStyle(resource.name || name, url); return waitFont(resource.name || name, function () { resource.name = resource.name || name; resolve(resource) }) }); })); } } }
function product(){ var x=window.prompt("Enter the first no? : ") var y=window.prompt("Enter the second no? : ") var z=x*y; alert(" Result : " +z) } product();
const express = require('express'); const mongoose = require('mongoose'); const app = express(); app.use(express.urlencoded({ extended: false })); // urlencoder app.use(express.json()); // jsonify app.use(express.static('public')); const Voter = require('./model'); //Schema const URI = "YOUR MONGO URI"; // db connection mongoose.connect(URI, { useNewUrlParser: true, useFindAndModify: false, useUnifiedTopology: true }).then((res) => console.log("connected successfuly")).catch((err) => console.log(err)); //route home app.get('/home',(req,res)=>{ res.sendFile(__dirname+'/public/templates/index.html'); }) //route view (get) app.get('/viewdata',(req,res)=>{ res.sendFile(__dirname+'/public/templates/view.html'); }) //route update (put) app.get('/update',(req,res)=>{ res.sendFile(__dirname+'/public/templates/update.html'); }) //route del (delete) app.get('/del',(req,res)=>{ res.sendFile(__dirname+'/public/templates/del.html'); }) // Send data to db var name, age app.post('/voter', (req, res, next) => { name = req.body.name; age = req.body.age; if (age == 0) { res.json({"info":"Min eligibity is 18yrs old", "result": "invalid age" }); } else if (age <= 17) { res.json({"info":"Min eligibity is 18yrs old", "result": "Your under aged to vote" }); } else { const value = new Voter({ "name": name, "age": age, }); value.save().then((data) => { console.log(data); res.json({ "result": data, "info": `Hello ${name}, since your are ${age} yrs old, your eligible to make your vote.` }); }).catch(next); } }); // get data from db app.get('/voter/get/:id', (req, res,next) => { console.log( req.params.id) Voter.findOne({ "_id": req.params.id }).then((data) => { if(data==null){ res.json({"result":"Data Not found"}); } else{ res.json({"result":data,"info":"Your data:"}); } }).catch(next); }); // // Delete data from db app.delete('/voter/del', (req, res,next) => { Voter.findByIdAndRemove({ "_id": req.body.id }) .then((data) => { if(data==null){ res.json({"info":"Data Not Found","data":"Request success"}); }else{ res.json({"data":data,"info":"Deleted successfully"}); } }).catch(next); }); // // Update data from db app.put('/voter/update', (req, res,next) => { Voter.findByIdAndUpdate({ _id: req.body.id },{"name":req.body.name ,"age":req.params.age} ).then(() => { Voter.findOne({_id: req.body.id }).then((data)=>{ res.json({"result":data,"info":"Updated successfuly!"}) }) .catch(next); }) }); app.listen(5000, () => console.log("Listening to 5000..."));
angular.module('phonecat', ['phonecatFilters', 'phonecatServices']). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/phones', {templateUrl: 'router1.htm', controller: PhoneListCtrl}). when('/phones/:phoneId', {templateUrl: 'router2.htm', controller: PhoneDetailCtrl}). otherwise({redirectTo: '/phones'}); }]); angular.module('phonecatFilters', ['ngRoute']). filter('checkmark', function() { return function(input){ return input ? '\u2713' : '\u2718'; } } ); angular.module('phonecatServices', ['ngResource']). factory('Phone', function($resource){ return $resource('json/:phoneId.json', {}, { query: {method:'GET', params:{phoneId:'phones'}, isArray:true} }); } );
var prompt = require('prompt-sync')(); var myQuestions = [ { text: 'What is our cohort leader\'s name?', answer: 'Eric' }, { text: 'Which part of your HTML should contain no content?', answer: 'head' }, { text: 'What is the color of your soul?', answer: 'black' }, { text: 'What is the name of the base 16 alphanumeric system we commonly use for colors?', answer: 'hexadecimals' }, { text: 'What is our cohort leader\'s favorite side at Cookout?', answer: 'hushpuppies' }, { text: 'What does IP stand for?', answer: 'Internet Protocol' }, { text: 'What is the bin command to create new files?', answer: 'touch' }, { text: 'What sign is used in JavaScript to denote "strictly equals"?', answer: '===' }, { text: 'What is the space between HTML elements?', answer: 'margin' }, { text: 'What is the UASS?', answer: 'User Agent Style Sheet' }, { text: 'What boolean sign is used in JavaScript to denote "not"?', answer: '!' }, { text: 'What do functions evaluate to by default?', answer: 'undefined' }, { text: 'What image element attribute specifies the location of an image to display?', answer: 'src' }, { text: 'What boolean sign is used in JavaScript to denote "or"?', answer: '||' }, { text: 'What boolean sign is used in JavaScript to denote "and"?', answer: '&&' }]; var myQuestions; var answer; var cAnswer = 0; var totalQ = 0; var percentC = cAnswer / totalQ for (var i = 0; i <myQuestions.length; i++) { question = myQuestions[i]; answer = prompt(question.text + ' '); totalQ = totalQ + 1; if (answer === question.answer) { cAnswer = cAnswer + 1; console.log('Correct.'); } else { prompt('Try not to be such a disappointment this time. ' + question.text + ' '); console.log('Correct.'); } var percentC = cAnswer / totalQ * 100; } console.log('Number of correct answers: ' + cAnswer +'. ' + 'Total questions: ' + totalQ + '. ' + 'Grade: ' + percentC + '%.')
function ToRightBlack(){ return( <svg className="toRightBlack" width="7" height="10" viewBox="0 0 7 10" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M2.0332 8.18662L4.7732 5.44662C4.89737 5.32171 4.96706 5.15274 4.96706 4.97662C4.96706 4.80049 4.89737 4.63153 4.7732 4.50662L2.10654 1.83995" stroke="#151515" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="bevel"/> </svg> ) } export default ToRightBlack
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const guardSchema = new Schema({ rut: { type: String, required: true }, name: { type: String, required: true } }); module.exports = mongoose.model('Guard', guardSchema);
// https://stackoverflow.com/questions/44729776/how-can-animation-be-added-to-markers-in-react-google-maps /* global google */ import React, { Component } from 'react' import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from "react-google-maps" import './css/map.css' const MyMapComponent = withScriptjs(withGoogleMap((props) => <GoogleMap defaultZoom={8} zoom={props.results.zoom} defaultCenter={{ lat: -34.397, lng: 150.644 }} center={props.results.center} > {props.results.markers.filter(marker => marker.isRendered).map(marker => { const info = props.results.places.find(place => place.id === marker.placeId) return ( <Marker key={`lat: ${marker.lat} lng: ${marker.lng}`} position={{ lat: marker.lat, lng: marker.lng}} onClick={() => props.markerClickEvent(marker)} animation={marker.showInfo ? google.maps.Animation.BOUNCE : google.maps.Animation.DROP} > {marker.showInfo && ( <InfoWindow> <div className='info'> {info.bestPhoto && ( <img src={`${info.bestPhoto.prefix}150x150${info.bestPhoto.suffix}`} alt={`${info.name}`} /> )} <h1>{info.name}</h1> <p>{info.location.address}</p> <button onClick={() => props.markerZoom(marker.lat, marker.lng)}>Toggle Zoom</button> </div> </InfoWindow> )} </Marker> ) })} </GoogleMap> )) class Map extends Component { render() { return ( <MyMapComponent {...this.props} googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&key=${process.env.REACT_APP_MAPSKEY}`} loadingElement={<div style={{ height: `100%` }} />} containerElement={<div style={{ height: `100%`, width: `75%` }} />} mapElement={<div style={{ height: `100%` }} />} /> ) } } export default Map;
const User = require('../models/User'); const getAll = async () => { return User.find({}).lean(); }; const findByUsername = async (username) => { return User.findOne({ username }).lean(); }; const findById = async (userId) => { return User.findById(userId).lean(); }; const create = async (username, email, salt, hash) => { let newUser = new User({ username, email, salt, hash }); return newUser.save(); }; const updateAvatar = async (userId, avatarData) => { let u = await User.findById(userId); u.avatar = avatarData; return u.save(); }; const addToCreatedRecipes = async (userId, recipeId) => { let u = await User.findById(userId); u.createdRecipes.push(recipeId); return u.save(); }; const addToFavoriteRecipes = async (userId, recipe) => { const u = await User.findById(userId); console.log({ u }); let foundRecipe = u.favoriteRecipes.find((recipeRefId) => { return recipeRefId.equals(recipe._id); }); // let foundRecipe = u.favoriteRecipes.includes(recipeId); if (foundRecipe) { throw new AppError('Recipe is already added to favorites', 400); } u.favoriteRecipes.push(recipe); return u.save(); }; const addShoppingList = async (userId, shoppingList) => { const u = await User.findById(userId); u.shoppingList = shoppingList; await u.save(); return; }; const getShoppingList = async (userId) => { const u = await User.findById(userId); return u.shoppingList; }; const removeFavoriteRecipe = async (userId, recipe) => { const u = await User.findById(userId); let foundRecipeIndex = u.favoriteRecipes.findIndex((recipeRefId) => { return recipeRefId.equals(recipe._id); }); if (foundRecipeIndex < 0) { throw new AppError('This recipe is not in favorites', 400); } u.favoriteRecipes.splice(foundRecipeIndex, 1); return u.save(); }; const getFavoriteRecipes = async (userId) => { let u = await User.findById(userId).populate('favoriteRecipes'); return u.favoriteRecipes; }; const getCreatedRecipes = async (userId) => { let u = await User.findById(userId).populate('createdRecipes'); return u.createdRecipes; }; // const updateOne = async (recipeId, data) => { // return Recipe.updateOne({ _id: recipeId }, data, { runValidators: true }); // }; // const deleteOne = async (recipeId) => { // return Recipe.findByIdAndDelete(recipeId); // }; // const getFiltered = async () => { // return Recipe.find({}).sort({ creationDate: -1 }).limit(3).lean(); // }; module.exports = { getAll, findByUsername, findById, create, updateAvatar, addToCreatedRecipes, getFavoriteRecipes, removeFavoriteRecipe, getCreatedRecipes, addToFavoriteRecipes, addShoppingList, getShoppingList, };
"use strict" const Article = require('../models/article'); class ArticleCtr { static create(req, res, next) { Article.create({ title: req.body.title, content: req.body.content }) .then((article) => { res.status(201).json(article) }) .catch(next); } static read(req, res, next) { Article.find() .then((articles) => { res.status(200).json(articles) }) .catch(next) } static update(req, res, next) { const id = req.params.id; Article.findByIdAndUpdate(id, { title: req.body.title, content: req.body.content }) .then(() => { Article.findById(id) .then((updated) => { res.status(200).json(updated) }) .catch(next) }) .catch(next) } static delete(req, res, next) { const id = req.params.id; Article.findByIdAndDelete(id) .then((result) => { res.status(200).json(result) }) .catch(next) } } module.exports = ArticleCtr;
import React from "react"; import { FaRegThumbsUp, FaRegCommentAlt, FaShareAlt } from "react-icons/fa"; const ShowPost = () => { const [state] = React.useState([ { id: 1, userImg: "/Images/Akash.jpg", name: "Akash", time: "2h", text:"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil nisi,magnam quo illum expedita", postImg: "/Images/Group.jpg", }, { id: 2, userImg: "/Images/Kasalkar.jpg", name: "Kasalkar", time: "4h", text:"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil nisi, magnam quo illum expedita", postImg: "/Images/Baban.jpg", }, { id: 3, userImg: "/Images/Sidd.jpg", name: "Sidd", time: "6h", text:"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil nisi, magnam quo illum expedita", postImg: "/Images/Sidd.jpg", }, { id: 4, userImg: "/Images/Group.jpg", name: "David", time: "7h", text:"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil nisi, magnam quo illum expedita", postImg: "/Images/Group.jpg", }, ]); return ( <div className="show"> {state.map((post) => ( <div key={post.id} className="empty"> <div className="show__header"> <div className="show__header-img"> <img src={post.userImg} alt="user" /> </div> <div className="show__header-name"> {post.name} <div className="date">{post.time}</div> </div> </div> <div className="show__body"> <div className="show__body-text">{post.text}</div> <div className="show__body-img"> <img src={post.postImg} alt="post" /> </div> </div> <div className="show__reactions"> <span className="reactions"> <FaRegThumbsUp /> <span className="reactions-text">Like</span> </span> <span className="reactions"> <FaRegCommentAlt />{" "} <span className="reactions-text">Comments</span> </span> <span className="reactions"> <FaShareAlt /> <span className="reactions-text">Share</span> </span> </div> </div> ))} </div> ); }; export default ShowPost;
import React from 'react'; import Enzyme, {mount} from "enzyme"; import Adapter from "enzyme-adapter-react-16"; import CategoryType from "../component/CategoryType"; import getChipElement from "../utils/botinsaCategory"; import CategoryComponent from "../component/CategoryComponent"; Enzyme.configure({adapter: new Adapter()}); describe('Examining the return of User Role info', () => { it('return a Chip component when category is correct', () => { const component = mount(getChipElement(5)); expect(component.containsMatchingElement(<CategoryComponent category={CategoryType.HUMANITARIAN}/>)).toBe(true); component.unmount(); }); it('return a null component when category is incorrect', () => { expect(getChipElement(0)).toBe(null); expect(getChipElement(11)).toBe(null); expect(getChipElement(100)).toBe(null); expect(getChipElement(null)).toBe(null); expect(getChipElement(undefined)).toBe(null); }); });
function multiplier(factor) { return number => number * factor; } let twice = multiplier(2); console.log(twice(5));
const MODES = { "none": 0, "default": 1, "loading": 2, "saving": 3, "success": 4, "payment": 5, "search": 6, "mysearch": 7, "error": 9 }; const DISP_MODES = { "none": 0, "list": 1, "cards": 2 }; /** * * Need`s masks for toolbar actions (see provide on layouts/default.vue) */ const NEEDS = { none: 0, back: 1, search: 2, myonly: 4 }; /** * @param {Sting} val * @return {Boolean} */ function isEmpty(val) { if (!!val){ return /^$/.test(val); } return true; } function tod(){ var s, h = (new Date()).getHours(); if (((h >= 21)&&(h<24)) || ((h >= 0)&&(h<5))){ s = 'Доброй ночи'; } else if ((h>=5) && (h<12)){ s = 'Доброе утро'; } else if ((h>=12) && (h<18)){ s = 'Добрый день'; } else if ((h>=18) && (h<21)){ s = 'Добрый вечер'; } return s; } //tod function short(s){ var res, n = s.indexOf(' '); if ( n > 0 ){ res = s.charAt(0) + s.charAt(n + 1); } else if (s.length > 2){ res = s.substr(0, 2); } else { res = s; } return res.toUpperCase(); } function fmtCurrency(n){ if (!!n) { return Number(n).toFixed(n < 100 ? 2 : 0).replace(/\d(?=(\d{3})+$)/g, '$& '); } return '0'; } export { MODES, DISP_MODES, NEEDS, isEmpty, tod, short, fmtCurrency };