text
stringlengths
7
3.69M
function loadCommits() { let username = $('#username').val(); let repo = $('#repo').val(); let url = `https://api.github.com/repos/${username}/${repo}/commits`; $.ajax({ method:"GET", url }).then(handleSuccess).catch(handleError); function handleSuccess(res) { for (let entity of res) { let author = entity.commit.author.name; let message = entity.commit.message; let li = $('<li>').text(`${author}: ${message}`); $('#commits').append(li); } } function handleError(res) { let commits = $('#commits'); commits.empty(); commits.append($('<li>').text(`Error: ${res.status} (${res.statusText})`)); } }
import axios from 'axios' export const FETCH_DATA = 'FETCH_DATA' export const UPDATE_FACTS = 'UPDATE_FETCH' export const SET_ERROR = 'SET_ERROR' export const FETCH_FOX = 'FETCH_FOX' export const UPDATE_FOX = 'UPDATE_FOX' const cors = 'https://cors-anywhere.herokuapp.com/' const cat_fact = 'https://cat-fact.herokuapp.com/facts' const fox_picture = 'https://randomfox.ca/floof/' export const getData = () => dispatch => { dispatch({ type: FETCH_DATA }) axios .get(`${cors+cat_fact}`) .then(res => { dispatch({ type: UPDATE_FACTS, payload: res.data }) }) .catch(err => { console.error('There was a problem getting data from the API', err) dispatch({ type: SET_ERROR, payload: 'There was a problem getting data from the API' }) }) } export const getFox = () => dispatch => { dispatch({ type: FETCH_FOX }) axios .get(`${cors+fox_picture}`) .then(res => { dispatch({ type: UPDATE_FOX, payload: res.data }) }) .catch(err => { console.error('There was a problem getting data from the API', err) dispatch({ type: SET_ERROR, payload: 'There was a problem getting data from the API' }) }) }
const CONF = require('../config/config') const util = require('../common/util') const userMod = require('../models/userMod') const userService = require('../service/user') // 获取用户账户 exports.getUserInfo = async (ctx, next) => { var user = ctx.USER console.log("取出来的用户是", user) } // 获取邀请的好友列表 exports.getFriendsList = async (ctx, next) => { var friends = await userService.getUserFriends(ctx.USER.wechat_openid) console.log("朋友列表", friends) } exports.userBindInfo = async (ctx, next) =>{ var bind_type = ctx.body.bind_type var value = ctx.body.value switch (bind_type) { case CONF.type.user.bind.PHONE: break; case CONF.type.user.bind.IDCARD: break; } }
const cmd = require("discord.js-commando"); const discord = require('discord.js'); class BanCommand extends cmd.Command { constructor(client) { super(client,{ name: "ban", group: "management", memberName: "ban", description: "Bans a user! example: ban @USERNAME [REASON]" }); } async run(message, args) { let target = message.guild.member(message.mentions.users.first()); if(!target){ message.channel.send("You have to mention a user!"); return; } if(!message.member.hasPermission("BAN_MEMBERS")) { message.channel.send("Not enough Permissions!"); return; } if(target == message.author) { message.channel.send("You can not ban yourself!"); return; } if(target.hasPermission("BAN_MEMBERS")) return message.channel.send("That person can't be banned!") let banreasonpre = args.split(' '); let banreason = banreasonpre.slice(1).join(' '); message.guild.member(target).ban(banreason); let banEmbed = new discord.RichEmbed() .setDescription("~Ban~") .setColor("#bc0000") .addField("Banned User", `${target.username} with ID ${target}`) .addField("Banned By", `${message.author} with ID ${message.author.id}`) .addField("Banned In", message.channel) .addField("Time", message.createdAt) .addField("Reason", banreason); console.log("Banned " + target + " with reason: " + banreason); let logChannel = message.guild.channels.find(`name`, "╒-ʟᴏɢs"); if(!logChannel) return; logChannel.send(banEmbed); } } module.exports = BanCommand;
const should = require('should'); const sinon = require('sinon'); const Promise = require('bluebird'); // Stuff we are testing const pipeline = require('../../../../core/server/lib/promise/pipeline'); // These tests are based on the tests in https://github.com/cujojs/when/blob/3.7.4/test/pipeline-test.js function createTask(y) { return function (x) { return x + y; }; } describe('Pipeline', function () { afterEach(function () { sinon.restore(); }); it('should execute tasks in order', function () { return pipeline([createTask('b'), createTask('c'), createTask('d')], 'a').then(function (result) { result.should.eql('abcd'); }); }); it('should resolve to initial args when no tasks supplied', function () { return pipeline([], 'a', 'b').then(function (result) { result.should.eql(['a', 'b']); }); }); it('should resolve to empty array when no tasks and no args supplied', function () { return pipeline([]).then(function (result) { result.should.eql([]); }); }); it('should pass args to initial task', function () { const expected = [1, 2, 3]; const tasks = [sinon.spy()]; return pipeline(tasks, 1, 2, 3).then(function () { tasks[0].calledOnce.should.be.true(); tasks[0].firstCall.args.should.eql(expected); }); }); it('should allow initial args to be promises', function () { const expected = [1, 2, 3]; const tasks = [sinon.spy()]; const Resolver = Promise.resolve; return pipeline(tasks, new Resolver(1), new Resolver(2), new Resolver(3)).then(function () { tasks[0].calledOnce.should.be.true(); tasks[0].firstCall.args.should.eql(expected); }); }); it('should allow tasks to be promises', function () { const expected = [1, 2, 3]; const tasks = [ sinon.stub().returns(new Promise.resolve(4)), sinon.stub().returns(new Promise.resolve(5)), sinon.stub().returns(new Promise.resolve(6)) ]; return pipeline(tasks, 1, 2, 3).then(function (result) { result.should.eql(6); tasks[0].calledOnce.should.be.true(); tasks[0].firstCall.args.should.eql(expected); tasks[1].calledOnce.should.be.true(); tasks[1].firstCall.calledWith(4).should.be.true(); tasks[2].calledOnce.should.be.true(); tasks[2].firstCall.calledWith(5).should.be.true(); }); }); it('should allow tasks and args to be promises', function () { const expected = [1, 2, 3]; const tasks = [ sinon.stub().returns(new Promise.resolve(4)), sinon.stub().returns(new Promise.resolve(5)), sinon.stub().returns(new Promise.resolve(6)) ]; const Resolver = Promise.resolve; return pipeline(tasks, new Resolver(1), new Resolver(2), new Resolver(3)).then(function (result) { result.should.eql(6); tasks[0].calledOnce.should.be.true(); tasks[0].firstCall.args.should.eql(expected); tasks[1].calledOnce.should.be.true(); tasks[1].firstCall.calledWith(4).should.be.true(); tasks[2].calledOnce.should.be.true(); tasks[2].firstCall.calledWith(5).should.be.true(); }); }); });
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import mainNew from "./images/mainnew.png" import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Typography from '@material-ui/core/Typography'; import AttractiveNew from "./attractiveNews" import {Link} from "react-router-dom" const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, paper: { padding: theme.spacing(2), textAlign: 'center', color: theme.palette.text.secondary, }, media:{ height:'100vh' } })); export default function CenteredGrid() { const classes = useStyles(); return ( <div className={classes.root}> <Grid container spacing={3}> <Grid item xs={12} md={8}> <Link to="/detailNews" style={{textDecoration:'none'}}> <Card> <CardActionArea> <CardMedia className={classes.media} image={mainNew} title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom component="p" style={{fontWeight:'bold',fontSize:'2.0em'}}> Mannchester United chính thức vô địch Premier League mùa giải 2020 - 2021 sớm 3 vòng đấu... </Typography> </CardContent> </CardActionArea> </Card> </Link> </Grid> <Grid item xs={12} md={4}> <AttractiveNew/> </Grid> </Grid> </div> ); }
export default function Car(param){ return[ { id: 1, name: "Audi", speed: 230, weight: 1.4, img: 'https://apr.su/data/media/images/59d1f72dd2dd8.jpg' }, { id: 2, name: "BMW", speed: 250, weight: 1.1, img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQaHxCG6F2ASWvqo0IV0mgNVDiOC-7GX35YJDvEAupDpLGXJ9Ko' } ] }
// FILENAME : User.js const mongoose = require("mongoose"); const UserSchema = mongoose.Schema({ username: { type: String, required: true, }, email: { type: String, required: true, }, password: { type: String, required: true, }, createdAt: { type: Date, default: Date.now(), }, groups: [{ id: String, owner: Boolean, }], location: { lat: { type: Number, required: true, }, long: { type: Number, required: true, }, address: { type: String, required: true, } }, friends: { requests: { outgoing: [{ id: { type: String, }, }], incoming: [{ id: { type: String, } }] }, actual: [{ id: { type: String, }, fav: { type: Boolean, } }] } }); // export model user with UserSchema module.exports = mongoose.model("user", UserSchema);
import React from 'react' import './index.css' import Bubbles from './Bubbles' import Lines from './Lines' import { createNodes } from './utils' const receiveProps = async (data) => { let result = [] if (data && data.result){ const years = data.year const keywords = data.result.keyword const promises = Object.keys(keywords).map(function(key){ let node = {} keywords[key].forEach((v, i) => { node[years[i]] = v }) return {"key": key, ...node} }) result = await Promise.all(promises) } return result } export default class KeywordComponent extends React.Component { state = { data: [], grouping: 'all', year: 2017, years: [2017] } handleYearChange = (year) => { this.setState({year: year}); this.updateBubble(); this.updateLine(); } updateLine = () => { this.refs.Lines.updateLine() } updateBubble = () => { this.refs.bubbles.updateBubbles(this.state.data) } async componentWillReceiveProps(nextProps) { if (nextProps.data !== this.props.data) { this.setState({ years: nextProps.data.year, data: createNodes(await receiveProps(nextProps.data)) }) } } render() { const {data, years, year} = this.state; return ( <div className="Keyword"> <h3 className="text-left ml-3">Keywords</h3> <h1>{ year }</h1> <Lines ref="Lines" width={960} height={480} data={data} onHandleYearChange={this.handleYearChange} years={years} year={year} /> <Bubbles ref="bubbles" width={960} height={480} data={data} onHandleYearChange={this.handleYearChange} forceStrength={0.03} center={{x: 480, y: 240}} years={years} year={year} /> </div> ) } }
function contar() { let ini = document.getElementById("inicio") let final = document.getElementById("fim") let pas = document.getElementById("passo") let res = document.getElementById("res") res.innerHTML = 'sim ' if (ini.value.length == 0 ||final.value.length == 0 ||pas.value.length == 0){ window.alert('Falta dados') res.innerHTML = "Impossivel contar!" } else { res.innerHTML = "contando: <br> " let i= Number(ini.value) let f= Number(final.value) let p= Number(pas.value) if (p <= 0) { alert('Passo invalido! Considerando PASSO 1 ') p =1 } if (i<f){ //contagem crescente for(let c =i; c <= f; c+= p){ res.innerHTML += `${c} ⏩ \u{1f449}` } }else { //contagem regressiva for (let c = i; c >=f; c-=p) { res.innerHTML += `${c} \u{1f449}` } } res.innerHTML +=`\u{1f3c1}` } }
//error message function errorMsg(str) { var comp = Qt.createComponent("Message.qml"); var obj = comp.createObject(main); obj.titleText = qsTr("Mena'an"); obj.dataText = str+qsTr("\n\nClick to close."); }
function alert(string1,string2,idAlert,typeMSG, animation){ document.getElementById(idAlert).innerHTML = "";//clear all msgs var div = document.createElement("div"); var anim = "animated " + animation; if(typeMSG == 0){ div.setAttribute("class", "alert alert-danger " + anim); }// 0 - danger if(typeMSG == 1){ div.setAttribute("class", "alert alert-success " + anim); }// 1 - sucess if(typeMSG == 2){ div.setAttribute("class", "alert alert-warning " + anim); }// 2 - warning if(typeMSG == 3){ div.setAttribute("class", "alert alert-info " + anim); }// 3 - info var s1 = document.createElement("strong"); var s1Txt = document.createTextNode(string1); s1.appendChild(s1Txt); var s2 = document.createElement("small"); var s2Txt = document.createTextNode(string2); s2.appendChild(s2Txt); div.appendChild(s1); div.appendChild(s2); var msg = document.getElementById(idAlert); msg.insertBefore(div, msg.childNodes[0]); }
import gulp from "gulp"; import {spawn} from "child_process"; import hugoBin from "hugo-bin"; import sass from 'gulp-sass'; import BrowserSync from "browser-sync"; const browserSync = BrowserSync.create(); // Hugo arguments const hugoArgsDefault = ["-d", "../dist", "-s", "site", "-v"]; const hugoArgsPreview = ["--buildDrafts", "--buildFuture"]; // Development tasks gulp.task("hugo", (cb) => buildSite(cb)); gulp.task("hugo-preview", (cb) => buildSite(cb, hugoArgsPreview)); // Build/production tasks gulp.task("build", ["styles"], (cb) => buildSite(cb, [], "production")); gulp.task("build-preview", ["styles"], (cb) => buildSite(cb, hugoArgsPreview, "production")); // Compile CSS with PostCSS gulp.task("styles", () => ( gulp.src("./styles/main.sass") .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest("./dist/styles")) .pipe(browserSync.stream()) )); // Development server with browsersync gulp.task("server", ["hugo", "styles"], () => { browserSync.init({ ui: false, open: false, server: { baseDir: "./dist" } }); gulp.watch("./src/css/**/*.css", ["styles"]); gulp.watch("./site/**/*", ["hugo"]); }); /** * Run hugo and build the site */ function buildSite(cb, options, environment = "development") { const args = options ? hugoArgsDefault.concat(options) : hugoArgsDefault; process.env.NODE_ENV = environment; return spawn(hugoBin, args, {stdio: "inherit"}).on("close", (code) => { if (code === 0) { browserSync.reload(); cb(); } else { browserSync.notify("Hugo build failed :("); cb("Hugo build failed"); } }); }
import dbFactory from "../../dbFactory"; const getDbRef = collectionName => { const db = dbFactory.create("firebase"); const ref = db.firestore().collection(collectionName); return ref; }; export const getChatFromDB = (senderId,recieverId) => { return getDbRef("chat").doc(`${senderId}${recieverId}`); } export const saveIndividualChatToDB = (senderId, recieverId, chatData) => { return getDbRef("chat") .doc(senderId + recieverId) .set({messageList: chatData}); };
Ext.define('cfa.proxy.ChromeFile', { extend : 'Ext.data.proxy.Client', alias : 'proxy.chromefile', alternateClassName : 'cfa.data.ChromeFileProxy', config : { formId : null }, constructor : function(config) { this.callParent(arguments); }, requestFileSystem : function(type, size, successCallBack, failCallBack){ window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; requestFileSystem(type, size,successCallBack, failCallBack ); }, //inherit docs create: function (operation, callback, scope) { var records = operation.getRecords(); operation.setStarted(); this.setRecord(records, function () { operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }); }, // inherit docs read : function(operation, callback, scope) { var records = [], me = this, data = {}, Model = this.getModel(), params = operation .getParams() || {}, record; // read a single record var formId = this.getFormId(); if (formId) { me.getImagesByFormId(formId, function(objs) { me.applyDataToModels(objs, Model, function(records) { me.completeRead(operation, callback, scope, records); }); }, function(error) { console.log(error) }); } operation.setSuccessful(); }, //inherit docs update: function (operation, callback, scope) { var records = operation.getRecords(); operation.setStarted(); this.setRecord(records, function () { operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }); }, //inherit destroy: function (operation, callback, scope) { var records = operation.getRecords(); this.removeRecord(records, function () { operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }); }, /** * Destroys all records stored in the proxy and removes all keys and values * used to support the proxy from the storage object. */ clear : function() { var me = this; var success = function() { console.log("remove successfully"); } var fail = function(error) { console.log(error); } me.deleteAllImagesByFormId(formId, success, fail); }, /**/ getRecord : function(id) { return null; }, /** * Saves the given record in the Proxy. Runs each field's encode function * (if present) to encode the data. * * @param {Ext.data.Model} * record The model instance * @param {String} * [id] The id to save the record under (defaults to the value of * the record's getId() function) */ setRecord : function(records, callback) { var me = this; var length = records.length; var record; var rawData; var data; var formId = this .getFormId(); var fail = function(error) { console.log(error); }; var setData = function(index) { if (index < length) { record = records[index]; data = record.getData(); me.addImageByFullPath(formId, data.srcImage, function() { index++; setData(index); }, fail); } else { if (typeof callback == 'function') { callback(); } } }; setData(0); }, removeRecord : function(records, callback, scope) { var i = 0; var formId = this.getFormId(); var length = records.length; var me = this; var fail = function(error) { console.log(error); } var remove = function(index) { if (index < length) { me.deleteImageByFullPath(formId, records[index].getData().fullPath, function() { index++; remove(index); }, fail); } else { if (typeof callback == 'function') { callback.call(scope || this); } } } remove(0); }, applyDataToModels : function(objs, Model, callback) { if (!objs || objs == undefined) { objs = []; } var records = [], data = {}, length = objs.length, i = 0, obj, engine, formId = this .getFormId(); var fail = function(error) { console.log(error); failCallBack(error); } var apply = function(index) { if (index < length) { obj = objs[index]; data['formId'] = formId; data['fullPath'] = obj.fullPath; obj.file(function(file) { var reader = new FileReader(); reader.onloadend = function(evt) { data['srcImage'] = evt.target.result; index++; record = new Model(data, index); records.push(record); apply(index); }; reader.readAsText(file); }, fail); } else { if (typeof callback == 'function') { callback(records); } } } apply(0); }, // Phonegap Helper getImagesByFormId : function(formId, success, failCallBack) { var me = this; var fail = function(error) { console.log(error); failCallBack(error); } var onFileSystemSuccess = function(fileSytem) { var imagePath = "/images/"; fileSytem.root.getDirectory(imagePath, { create : true }); imagePath = imagePath + formId; fileSytem.root.getDirectory(imagePath, { create : true }, function(parent) { var directoryReader = parent.createReader(); directoryReader.readEntries(function(entries) { success(entries); }, fail) }, fail); } me.requestFileSystem(window.PERSISTENT, 0, onFileSystemSuccess, fail); }, deleteAllImagesByFormId : function(formId, success, failCallBack) { var me = this; var imagePath = "/images/" + formId; var fail = function(error) { console.log(error); failCallBack(error); } me.requestFileSystem(window.PERSISTENT, 0, function( fileSys) { fileSys.root.getDirectory(imagePath, { create : false, exclusive : false }, function(directory) { directory.removeRecursively(success, fail); }, fail); }, fail); }, deleteImageByFullPath : function(formId, fullPath, success, failCallBack) { var me = this; var fail = function(error) { console.log(error); failCallBack(error); } var onFileSystemSuccess = function(fileSytem) { var imagePath = "/images/"; fileSytem.root.getDirectory(imagePath, { create : false }); imagePath = imagePath + formId; fileSytem.root.getDirectory(imagePath, { create : false }, function(directory) { var directoryReader = directory.createReader(); directoryReader.readEntries(function(entries) { var i; for (i = 0; i < entries.length; i++) { if (entries[i].fullPath == fullPath) { entries[i].remove(Ext.emptyFn); success(); break; } } }, fail) }, fail); } me.requestFileSystem(window.PERSISTENT, 0, onFileSystemSuccess, fail); }, addImageByFullPath : function(formId, imageData, success, failCallBack) { var me = this; var fail = function(error) { console.log(error); failCallBack(error); } var gotFileEntry = function(fileEntry) { fileEntry.createWriter(gotFileWriter, fail); } var gotFileWriter = function(writer) { writer.onwrite = function(evt) { success(); }; writer.onError = function(){ } if (!window.BlobBuilder && window.WebKitBlobBuilder) window.BlobBuilder = window.WebKitBlobBuilder; var bb = new window.BlobBuilder(); bb.append(imageData); writer.write(bb.getBlob('text/plain')); } var onFileSystemSuccess = function(fileSytem) { var imagePath = "/images/"; fileSytem.root.getDirectory(imagePath, { create : true }); imagePath = imagePath + formId; fileSytem.root.getDirectory(imagePath, { create : true }, function(parent) { var fileName = "" + new Date().getTime() + ".cfaimage"; parent.getFile( fileName,{ create : true }, gotFileEntry, fail); }, fail); } me.requestFileSystem(window.PERSISTENT, 0, onFileSystemSuccess, fail); }, completeRead : function(operation, callback, scope, records) { operation.setCompleted(); operation.setResultSet(Ext.create('Ext.data.ResultSet', { records : records, total : records.length, loaded : true })); operation.setRecords(records); if (typeof callback == 'function') { callback.call(scope || this, operation); } } });
const Discord = require("discord.js"); module.exports = { name: 'clear', description: "Clear Messages!", async execute(message, args, client) { if (!message.member.hasPermission('ADMINISTARTOR')) return message.channel.send(`You do not have Administartor permission`).then(m => m.delete({ timeout: 5000 })); if (!args[0]) return message.reply("Please Enter A Amount Of Messages") if (isNaN(args[0])) return message.reply("Please Enter A Real Number") if (args[0] > 100) return message.reply("You Cant Delete More Then 100 Messages!") if (args[0] < 1) return message.reply("You Cant Not Do Any Number Less Then 1!") await message.channel.messages.fetch({limit: args[0]}).then(messages => { message.channel.bulkDelete(messages) }); } }
/** * Created by timothyfranzke on 2/17/17. */
module.exports = { findLongestWordLength: require('./algorithms/find-longest-word-length'), findLargestNum: require('./algorithms/find-largest-num'), confirmEnding: require('./algorithms/confirmEnding'), repeatStr: require('./algorithms/repeatStr'), truncateStr: require('./algorithms/truncateStr'), findersKeepers: require('./algorithms/findersKeepers'), booWho: require('./algorithms/booWho'), titleWords: require('./algorithms/titleWords'), sliceSplice: require('./algorithms/sliceSplice'), falsy: require('./algorithms/falsy'), belong: require('./algorithms/belong'), mutations: require('./algorithms/mutations'), chunkyMonkey: require('./algorithms/chunkyMonkey'), rmDuplicates: require('./algorithms/rmDuplicates') };
#!/usr/bin/node if (process.argv.length <= 2) { console.log(parseInt(process.argv[2])); } else { add(parseInt(process.argv[2]), parseInt(process.argv[3])); } function add (a, b) { console.log(a + b); }
import axios from 'axios'; import qs from 'qs'; var PRM = { getAll: function(){ return axios.get(window.apiDomainUrl+'/projects/get-all', qs.stringify({})) }, getById: function(id){ return axios.get(window.apiDomainUrl+'/projects/get-by-id?id='+id, qs.stringify({})); }, create: function(data){ return axios.post(window.apiDomainUrl+'/projects/create', qs.stringify(data)); }, update: function(data){ return axios.post(window.apiDomainUrl+'/projects/update', qs.stringify(data)); }, delete: function(data){ return axios.post(window.apiDomainUrl+'/projects/delete', qs.stringify(data)); }, }; export function ProjectsManager() { return PRM; }
'use strict' const ExceptionPool = require('express-deliver').ExceptionPool const exceptionPool = new ExceptionPool({ ValidationFailed: { code: 1001, message: 'Authentication failed', statusCode: 403 }, ValidationPublicKeyFailed: { code: 1002, message: 'Authentication failed', statusCode: 403 }, ValidationDeviceFailed: { code: 1003, message: 'You must set a device', statusCode: 403 }, ValidationTokenExpired: { code: 1004, message: 'Token expired', statusCode: 403 }, ValidationEmail: { code: 1005, message: 'Invalid email', statusCode: 403 }, ValidationUsername: { code: 1006, message: 'Invalid username', statusCode: 403 }, ValidationPassword: { code: 1007, message: 'Invalid password', statusCode: 403 }, ValidationRegistration: { code: 1500, message: 'something was wrong', statusCode: 403 }, ValidationLogin: { code: 1501, message: 'Invalid login', statusCode: 403 }, ValidationChangePassword: { code: 1502, message: 'Invalid change password', statusCode: 403 }, DatabaseError: { code: 2001, message: 'something was wrong', statusCode: 500 } }) module.exports = exceptionPool
const logic = require('../../../logic') const { expect } = require('chai') const { database, models } = require('wannadog-data') const { Wish, User } = models describe('logic - unregister wish', () => { before(() => database.connect('mongodb://172.17.0.2/wannadog-test')) let breed, gender, size, age, neutered, withDogs, withCats, withChildren, distance let userName, surname, email, password, userLongitude, userLatitude, id, wishId beforeEach(() => { const breedArray = ['Sussex Spaniel', 'Swedish Vallhund', 'Tibetan Mastiff'] const sizeArray = ['small', 'medium', 'large', 'xl'] return (async () => { await Wish.deleteMany() await User.deleteMany() userName = `name-${Math.random()}` surname = `surname-${Math.random()}` email = `email-${Math.random()}@mail.com` password = `name-${Math.random()} ` userLongitude = Number((Math.random() * (-180, 180)).toFixed(3) * 1) userLatitude = Number((Math.random() * (-90, 90)).toFixed(3) * 1) const user = await User.create({ name: userName, surname, email, password, location: { coordinates: [userLongitude, userLatitude] } }) id = user.id let wishList = [] for (let i = 0; i < 3; i++) { breed = `${breedArray[Math.floor(Math.random() * breedArray.length)]}` gender = Boolean(Math.round(Math.random())) size = `${sizeArray[Math.floor(Math.random() * sizeArray.length)]}` age = '2019/01' const dogAge = new Date(age) neutered = Boolean(Math.round(Math.random())) withDogs = Boolean(Math.round(Math.random())) withCats = Boolean(Math.round(Math.random())) withChildren = Boolean(Math.round(Math.random())) distance = Number((Math.floor(Math.random() * 1000))) const wish = await Wish.create({ breed, gender, size, dogAge, neutered, withDogs, withCats, withChildren, distance }) wishList.push(wish) } wishList.forEach(wish => user.wishes.push(wish)) wishId = user.wishes[Math.floor(Math.random() * 3)].id await user.save() })() }) it('should remove an existing wish on correct data', async () => { await logic.unregisterWish(id, wishId) const user = await User.findById(id) expect(user.wishes.indexOf(wishId)).to.equal(-1) }) after(() => database.disconnect()) })
// Options const CLIENT_ID = '204769852414-ifcd24agsmn1js3s8et2u8leadt0e1v4.apps.googleusercontent.com'; const DISCOVERY_DOCS = [ 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest' ]; const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly'; const authorizeButton = document.getElementById('authorize-button'); const signoutButton = document.getElementById('signout-button'); const content = document.getElementById('content'); const channelForm = document.getElementById('channel-form'); const channelInput = document.getElementById('channel-input'); const videoContainer = document.getElementById('video-container'); const chartContainer= document.getElementById('chartContainer'); const defaultChannel = 'techguyweb'; // Form submit and change channel channelForm.addEventListener('submit', e => { e.preventDefault(); const channel = channelInput.value; getChannel(channel); }); // Load auth2 library function handleClientLoad() { gapi.load('client:auth2', initClient); } // Init API client library and set up sign in listeners function initClient() { gapi.client .init({ discoveryDocs: DISCOVERY_DOCS, clientId: CLIENT_ID, scope: SCOPES }) .then(() => { // Listen for sign in state changes gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle initial sign in state updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton.onclick = handleSignoutClick; }); } // Update UI sign in state changes function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; content.style.display = 'block'; videoContainer.style.display = 'block'; chartContainer.style.display='block' getChannel(defaultChannel); } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; content.style.display = 'none'; videoContainer.style.display = 'none'; chartContainer.style.display='none' } } // Handle login function handleAuthClick() { gapi.auth2.getAuthInstance().signIn(); } // Handle logout function handleSignoutClick() { gapi.auth2.getAuthInstance().signOut(); } // Display channel data function showChannelData(data) { const channelData = document.getElementById('channel-data'); channelData.innerHTML = data; } // Get channel from API function getChannel(channel) { gapi.client.youtube.channels .list({ part: 'snippet,contentDetails,statistics', forUsername: channel }) .then(response => { console.log(response); const channel = response.result.items[0]; const output = ` <ul class="collection"> <li class="collection-item">Title: ${channel.snippet.title}</li> <li class="collection-item">ID: ${channel.id}</li> <li class="collection-item">Subscribers: ${numberWithCommas( channel.statistics.subscriberCount )}</li> <li class="collection-item">Views: ${numberWithCommas( channel.statistics.viewCount )}</li> <li class="collection-item">Videos: ${numberWithCommas( channel.statistics.videoCount )}</li> </ul> <p>${channel.snippet.description}</p> <hr> <a class="btn grey darken-2" target="_blank" href="https://youtube.com/${ channel.snippet.customUrl }">Visit Channel</a> `; showChannelData(output); //charts const playlistId = channel.contentDetails.relatedPlaylists.uploads; requestVideoPlaylist(playlistId); }) .catch(err => alert('No Channel By That Name')); } // Add commas to number function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function requestVideoPlaylist(playlistId) { const requestOptions = { playlistId: playlistId, part: 'snippet', maxResults: 10 }; const request = gapi.client.youtube.playlistItems.list(requestOptions); // const data=gapi.client.youtube.channels // .list({ // part: 'snippet,contentDetails,statistics', // forUsername: channel // }) // .then(response => { // console.log(response); // const channel = response.result.items[0]; // const data={ // videocount:channel.videoCount, // views:channel.viewCount, // subscribers:channel.subscriberCount // } // }) request.execute(response => { console.log(response); const playListItems = response.result.items; if (playListItems) { let output = '<br><h4 class="center-align">Latest Videos</h4>'; // Loop through videos and append output playListItems.forEach(item => { const videoId = item.snippet.resourceId.videoId; output += ` <div class="col s3"> <iframe width="100%" height="auto" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> `; }); // Output videos videoContainer.innerHTML = output; } else { videoContainer.innerHTML = 'No Uploaded Videos'; } }); } //chart onload = function () { var chart = new CanvasJS.Chart("chartContainer", { exportEnabled: true, animationEnabled: true, title:{ text: "METRICES comparision" }, subtitles: [{ text: "Views,Subscribers,Likes" }], axisX: { title: "Comparision of growth between Channels" }, axisY: { title: "", titleFontColor: "#4F81BC", lineColor: "#4F81BC", labelFontColor: "#4F81BC", tickColor: "#4F81BC", includeZero: true }, axisY2: { title: "", titleFontColor: "#C0504E", lineColor: "#C0504E", labelFontColor: "#C0504E", tickColor: "#C0504E", includeZero: true }, toolTip: { shared: true }, legend: { cursor: "pointer", itemclick: toggleDataSeries }, data: [{ type: "column", name:"myPage" , showInLegend: true, yValueFormatString: "#,##0.# Units", dataPoints: [ { label: "ViewCounts", y: 19034.5 }, { label: "subscribers", y: 20015 }, { label: "Likes", y: 25342 }, ] }, { type: "column", name: "Comparing page", axisYType: "secondary", showInLegend: true, yValueFormatString: "#,##0.# Units", dataPoints: [ { label: "viewCounts", y: 210.5 }, { label: "subscribers", y: 135 }, { label: "Likes", y: 425 }, ] }] }); chart.render(); function toggleDataSeries(e) { if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { e.dataSeries.visible = false; } else { e.dataSeries.visible = true; } e.chart.render(); } }
function vérifierLogin() { var login = document.getElementById("login"), confirmlogin = document.getElementById("confirmlogin"); if (login.value != confirmlogin.value) { confirmlogin.setCustomValidity("Les logins ne correspondent pas"); confirmlogin.style.backgroundColor = "#D04C3E"; } else { confirmlogin.setCustomValidity(''); confirmlogin.style.backgroundColor = "#6B9949"; } }
#!/usr/bin/env node // enables ES6 support require('../../compiler'); var rsvp = require('rsvp'); var config = require('../../config'); var mongoose = require('mongoose'); console.log('------ Open mongoose connection ------'); // console.log(config.database); // mongoose.connect(config.database); // connect to database // console.log(config.database);
/** * 仿微信支付密码, Written by CFei, 2016/10/08 */ var PasswordForge = function() { // 密码 this.check_pass_word=''; // 指针 this.index = 0; // 回调函数 this.cbFunc; // 密码输入panel的html this.htmlPassword = '\ <div id="mask" class="mask" style="display: none;"></div>\ <div id="password_panel">\ <div style="text-align:center; padding-top:0.1rem;"><span id="_text" style="font-size: 0.16rem;">{title}</span></div>\ <div>{dynamicHtml}</div>\ <div id="passwords" class="umar-ts ub ub-pc">\ <div class="pass"></div><input value="" type="hidden"/>\ <div class="pass"></div><input value="" type="hidden"/>\ <div class="pass"></div><input value="" type="hidden"/>\ <div class="pass"></div><input value="" type="hidden"/>\ <div class="pass"></div><input value="" type="hidden"/>\ <div class="pass pass_right"></div><input value="" type="hidden"/>\ </div>\ <div style="font-size: 0.12rem; text-align:center; margin-top:0.1rem; color:#fe0000;">{message}</div>\ </div>\ '; // 键盘 this.htmlKeyboard = '\ <div id="key" style="position:fixed;background-color:#A8A8A8;width:99.5%;bottom:0;z-index:10001">\ <ul id="keyboard" style="font-size:0.3rem; margin:0.1rem 0.05rem">\ <li class="symbol"><span class="off">1</span></li>\ <li class="symbol"><span class="off">2</span></li>\ <li class="symbol btn_number_"><span class="off">3</span></li>\ <li class="tab"><span class="off">4</span></li>\ <li class="symbol"><span class="off">5</span></li>\ <li class="symbol btn_number_"><span class="off">6</span></li>\ <li class="tab"><span class="off">7</span></li>\ <li class="symbol"><span class="off">8</span></li>\ <li class="symbol btn_number_"><span class="off">9</span></li>\ <li class="delete lastitem button">←退格</li>\ <li class="symbol"><span class="off">0</span></li>\ <li class="cancle btn_number_ button">取消</li>\ </ul>\ </div>\ '; } //------------------------------------------------- // 供内部使用的方法 //------------------------------------------------- // 弹框代码 PasswordForge.prototype.inputPassword = function(cbFunc, title, message, dynamicHtml) { this.cbFunc = cbFunc; this.showPasswordPanel(title, message, dynamicHtml); this.showKeyboardPanel(); } // 密码输入面板 PasswordForge.prototype.showPasswordPanel = function(title, message, dynamicHtml) { if(!title) { title = ""; } if(!message) { message = ""; } if(!dynamicHtml) { dynamicHtml = ""; } var html = this.htmlPassword.replace("{title}", title); html = html.replace("{message}", message); html = html.replace("{dynamicHtml}", dynamicHtml); // 自定义html $("body").append(html); $("#mask").addClass("mask").fadeIn("slow"); $("#password_panel").show(); //$("input.pass").attr("disabled", true); //$("#passwords").attr("disabled", true); } // 键盘面板 PasswordForge.prototype.showKeyboardPanel = function() { $("body").append(this.htmlKeyboard); $("#keyboard li").bind("click", {"self": this}, this.myClickHandler); $("#keyboard li").bind("touchstart", {"self": this}, this.myClickHandler); // touchstart处理 $('#keyboard li').on('touchstart',function(e) { // 禁止click事件执行 $(this).unbind("click"); // 禁止冒泡 e.stopPropagation(); // 样式设置 $(this).addClass("ontouch"); }); $('#keyboard li').on('touchend',function(e) { $(this).removeClass("ontouch"); }); } PasswordForge.prototype.myClickHandler = function(parms) { // 类对象自身 var self = parms.data.self; if ($(this).hasClass('delete')) { if(self.index == 0) { return; } $("#passwords input").eq(--self.index).val('').prev(".pass").html(""); } else if ($(this).hasClass('cancle')) { // 延迟关闭,由于ontouchstart太快了,可能会触发下一层的按钮 window.setTimeout(function(){ self.cancel(); }, 500); } else if ($(this).hasClass('symbol') || $(this).hasClass('tab')) { var character = $(this).text(); $("#passwords input").eq(self.index++).val(character).prev(".pass").html("●"); if(self.index == 6) { self.index = 0; var temp_rePass_word = ''; for (var i = 0; i < 6; i++) { temp_rePass_word += $("#passwords input").eq(i).val(); } self.check_pass_word = temp_rePass_word; // 延迟结束,最后一个密码的展示事件要能显示出来 window.setTimeout(function(){ self.fireComplete(); }, 500); } } } // 输入完毕 PasswordForge.prototype.fireComplete = function() { // 这里关闭了,如果希望在主调方法中关闭,可以注释掉该行 this.cancel(); // 交给回调函数处理 if(this.cbFunc) { this.cbFunc(this.check_pass_word); } } // 取消 PasswordForge.prototype.cancel = function() { this.index = 0; //$("#mask").addClass("mask").fadeOut("slow"); $("#mask").remove(); $("#password_panel").remove(); $("#key").remove(); } // Singleton var _simulator; PasswordForge.getInstance=function() { if(!_simulator) { _simulator = new PasswordForge(); } return _simulator; } //------------------------------------------------- // 供外部调用的2个静态方法 //------------------------------------------------- // **** 校验密码 PasswordForge.verifyPassword = function(cbFunc, message) { var pwdForge = PasswordForge.getInstance(); pwdForge.inputPassword(cbFunc, "请输入支付密码", message); } // **** 设置密码 var _cbFuncSetPassword; PasswordForge.setPassword=function(cbFunc, message) { _cbFuncSetPassword = cbFunc; // 回调函数最后一步才用 var pwdForge = PasswordForge.getInstance(); pwdForge.inputPassword(PasswordForge.cbPwd1, "请输入支付密码", message); } /**以下为setpassword服务*/ var _pwd1; PasswordForge.cbPwd1=function(password) { _pwd1 = password; var pwdForge = PasswordForge.getInstance(); pwdForge.inputPassword(PasswordForge.cbPwd2, "请再次输入支付密码"); } PasswordForge.cbPwd2=function(password) { var _pwd2 = password; if(_pwd2 != _pwd1) { // try again PasswordForge.setPassword(_cbFuncSetPassword, "两次输入密码不一致!"); } else { if(_cbFuncSetPassword) { _cbFuncSetPassword(password); } } }
const fs = require('fs'); const data = JSON.parse(fs.readFileSync(__dirname + '/../json-rpc.json')); const tpMap = {}; tpMap['AccountNumber'] = 'AccountNumber|Number|String'; tpMap['AccountNumberArray'] = 'AccountNumber[]|Number[]|String[]'; tpMap['StringArray'] = 'String[]'; tpMap['AccountName'] = 'AccountName|String'; tpMap['PublicKey'] = 'String|BC|PublicKey|WalletPublicKey|PrivateKey|KeyPair'; tpMap['Block'] = 'Number'; tpMap['ChangerArray'] = 'Object[]|Changer[]'; tpMap['SenderArray'] = 'Object[]|Sender[]'; tpMap['ReceiverArray'] = 'Object[]|Receiver[]'; function cap(string) { return string.charAt(0).toUpperCase() + string.slice(1); } var ccUS = function (str) { return str.split(/(?=[A-Z])/).join('_').toLowerCase(); }; var usCC = (function () { var DEFAULT_REGEX = /[-_]+(.)?/g; function toUpper(match, group1) { return group1 ? group1.toUpperCase() : ''; } return function (str, delimiters) { return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper); }; })(); const NL = '\n'; let gen = '# @pascalcoin-sbx/json-rpc docs' + NL + NL; gen += 'This documentation is autogenerated. It should not be edited manually.' + NL + NL; Object.keys(data.methods).forEach((m) => { const md = data.methods[m]; gen += '### ' + md.camel + NL + NL; gen += md.description + NL + NL; gen += '```' + NL + md.camel + '('; if (md.params.length > 0) { gen += '{' + NL; } md.params.forEach((p, i) => { gen += ' '; if (!p.required) { gen += '['; } if (tpMap[p.type] !== undefined) { gen += tpMap[p.type]; } else { gen += p.type; } gen += ' ' + usCC(p.name); if (!p.required) { gen += ']'; } if (i < md.params.length - 1) { gen += ', '; } gen += NL; }); if (md.params.length > 0) { gen += '}'; } gen += ') : ' + md.action + ' -> ' + md.return_type; if (md.return_array === true) { gen += '[]'; } gen += NL + '```' + NL + NL; gen += '| Parameter | Type | Required | Description |' + NL; gen += '|---|---|---|---|' + NL; md.params.forEach((p, i) => { gen += '|'; gen += usCC(p.name) + '|'; if (tpMap[p.type] !== undefined) { gen += tpMap[p.type].replace(/\|/g, '\\|') + '|'; } else { gen += p.type.replace(/\|/g, '\\|') + '|'; } if (p.required) { gen += 'yes|'; } else { gen += 'no|'; } gen += (p.description || '') + '|'; gen += NL; }); if (md.action === 'BaseAction') { gen += '**Example:**' + NL + NL; gen += '```js' + NL + "const sbxRpc = require('@pascalcoin-sbx/json-rpc');" + NL + NL + '// create an rpc client for a local wallet' + NL + "const rpcClient = sbxRpc.Client.factory('http://127.0.0.1:4003');" + NL + NL; gen += '// create action instance' + NL; gen += `const action = rpcClient.${md.camel}(`; if (md.params.length > 0) { gen += '{' + NL; } md.params.forEach((p, i) => { gen += ' ' + usCC(p.name) + ': '; if (data.examples[usCC(p.name)] !== undefined) { gen += data.examples[usCC(p.name)]; } else if (data.examples[p.type] !== undefined) { gen += data.examples[p.type]; } if (i < md.params.length - 1) { gen += ', '; } gen += NL; }); if (md.params.length > 0) { gen += '}'; } gen += ');' + NL + NL; gen += '// execute and handle promise' + NL; gen += 'const promise = action.execute();' + NL; gen += 'promise.then(([data, transform]) => {' + NL; gen += ' console.log(data); // raw' + NL; gen += ' console.log(transform(data)); // mapped to rich object' + NL; gen += '}).catch((err) => {' + NL; gen += ' console.log(err); // something went wrong' + NL; gen += '});'; gen += NL + '```' + NL + NL; } if (md.action === 'PagedAction') { gen += '**Example to fetch all data:**' + NL + NL; gen += '```js' + NL + "const sbxRpc = require('@pascalcoin-sbx/json-rpc');" + NL + NL + '// create an rpc client for a local wallet' + NL + "const rpcClient = sbxRpc.Client.factory('http://127.0.0.1:4003');" + NL + NL; gen += '// // create action instance of type PagedAction' + NL; gen += `const action = rpcClient.${md.camel}(`; if (md.params.length > 0) { gen += '{' + NL; } md.params.forEach((p, i) => { gen += ' ' + usCC(p.name) + ': '; if (data.examples[usCC(p.name)] !== undefined) { gen += data.examples[usCC(p.name)]; } else if (data.examples[p.type] !== undefined) { gen += data.examples[p.type]; } if (i < md.params.length - 1) { gen += ', '; } gen += NL; }); if (md.params.length > 0) { gen += '}'; } gen += ');' + NL + NL; gen += '// execute and handle promise' + NL; gen += 'const promise = action.executeAll();' + NL; gen += 'promise.then(([data, transform]) => {' + NL; gen += ' console.log(data); // raw' + NL; gen += ' console.log(transform(data)); // mapped to rich object' + NL; gen += '}).catch((err) => {' + NL; gen += ' console.log(err); // something went wrong' + NL; gen += '});'; gen += NL + '```' + NL + NL; gen += '**Example for custom paging:**' + NL + NL; gen += '```js' + NL + "const sbxRpc = require('@pascalcoin-sbx/json-rpc');" + NL + NL + '// create an rpc client for a local wallet' + NL + "const rpcClient = sbxRpc.Client.factory('http://127.0.0.1:4003');" + NL + NL; gen += '// create action instance of type PagedAction' + NL; gen += `const action = rpcClient.${md.camel}(`; if (md.params.length > 0) { gen += '{' + NL; } md.params.forEach((p, i) => { gen += ' ' + usCC(p.name) + ': '; if (data.examples[usCC(p.name)] !== undefined) { gen += data.examples[usCC(p.name)]; } else if (data.examples[p.type] !== undefined) { gen += data.examples[p.type]; } if (i < md.params.length - 1) { gen += ', '; } gen += NL; }); if (md.params.length > 0) { gen += '}'; } gen += ');' + NL + NL; gen += '// change start and max if you need control' + NL; gen += 'action.start = 0;' + NL; gen += 'action.max = 10;' + NL + NL; gen += '// execute and handle promise' + NL; gen += 'const promise = action.execute();' + NL; gen += 'promise.then(([data, transform]) => {' + NL; gen += ' console.log(data); // raw' + NL; gen += ' console.log(transform(data)); // mapped to rich object' + NL; gen += '}).catch((err) => {' + NL; gen += ' console.log(err); // something went wrong' + NL; gen += '});'; gen += NL + '```' + NL + NL; gen += '**Example to fetch all data but getting paged data reported.:**' + NL + NL; gen += '```js' + NL + "const sbxRpc = require('@pascalcoin-sbx/json-rpc');" + NL + NL + '// create an rpc client for a local wallet' + NL + "const rpcClient = sbxRpc.Client.factory('http://127.0.0.1:4003');" + NL + NL; gen += '// create action instance of type PagedAction' + NL; gen += `const action = rpcClient.${md.camel}(`; if (md.params.length > 0) { gen += '{' + NL; } md.params.forEach((p, i) => { gen += ' ' + usCC(p.name) + ': '; if (data.examples[usCC(p.name)] !== undefined) { gen += data.examples[usCC(p.name)]; } else if (data.examples[p.type] !== undefined) { gen += data.examples[p.type]; } if (i < md.params.length - 1) { gen += ', '; } gen += NL; }); if (md.params.length > 0) { gen += '}'; } gen += ');' + NL + NL; gen += '// execute and handle promise' + NL; gen += 'const promise = action.executeAllReport(([data, transform]) => {' + NL; gen += ' // gets called whenever a chunk was loaded' + NL; gen += ' console.log(data); // raw' + NL; gen += ' console.log(transform(data)); // mapped' + NL; gen += '});' + NL + NL; gen += 'promise.then(() => {' + NL; gen += " console.log('finished');" + NL; gen += '}).catch((err) => {' + NL; gen += ' console.log(err); // something went wrong' + NL; gen += '});'; gen += NL + '```' + NL + NL; } }); fs.writeFileSync(__dirname + '/../docs/rpc.md', gen);
import React from 'react'; const Header = () => { return( <header className="header sticky sticky-nav" id="sticky-header"> <nav className="nav-user section__content"> <span className="nav-user__item section__content"><a className="nav-user__item--link" href="#about">About</a></span> <span className="nav-user__item section__content"><a className="nav-user__item--link" href="#work">Experience</a></span> <span className="nav-user__logo"><a href="#home"><img className="nav-user__logo--icon" src="img/profile_icon.jpg" alt=""/></a></span> <span className="nav-user__item section__content"><a className="nav-user__item--link" href="#projects">Projects</a></span> <span className="nav-user__item section__content"><a className="nav-user__item--link" href="#interest">Interest</a></span> </nav> </header> ); } export default Header;
const defaultState = { sale_list:[] } export default (state=defaultState,action)=>{ switch(action.type){ case "HOME_SALE": let saleState = JSON.parse(JSON.stringify(state)); saleState.sale_list=action.data; return saleState; } return state; }
var x = "neha"; function y(){ alert("x"); alert(x); x = 'Jyoti'; } y(); function toTitleCase() { alert("hello"); // return false; // var str = document.myForm.username.value; // document.myForm.username.value = str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); // document.myForm.username.value = "hello"; return false; } // alert(form.username); // document.getElementById("myForm").onsubmit = function() { // alert(document.getElementById("size").value); // } list = []; function result() { var display = ''; for (var i in list) { display += list[i] + "<br>"; // document.write(list[i] + "<br>"); document.getElementById('result').innerHTML = display; } } window.onload = function() { document.getElementById("button1").onclick = function add() { list.push(document.getElementsByName('first')[0].value); result(); } document.getElementById("button2").onclick = function add() { list.push(document.getElementsByName('second')[0].value); result(); } document.getElementById("sorta").onclick = function add() { list.sort(); result(); } document.getElementById("sortb").onclick = function add() { list.reverse(); result(); } } // function sortA() { // }
const empleados = [ { id: 1, nombre: 'Fernando' }, { id: 2, nombre: 'Linda' }, { id: 3, nombre: 'Karen' } ]; const salarios = [ { id: 1, salario: 1000 }, { id: 2, salario: 1500 } ]; const getEmpleado = ( id ) => { return new Promise( ( resolve, reject ) => { const empleado = empleados.find( (e) => e.id === id )?.nombre; ( empleado ) ? resolve( empleado ) : reject(`No existe empleado con id ${ id }`); }); } const getSalario = ( id ) => { return new Promise( ( resolve, reject ) => { const salario = salarios.find( (s) => s.id === id )?.salario; ( salario ) ? resolve( salario ) : reject(`No existe salario para el id ${ id }`); }) } // async transforma una función para que regrese una promesa const getInfoUsuario = async( id ) => { try { const empleado = await getEmpleado( id ); const salario = await getSalario( id ); return `El salario del empleado ${ empleado } es de ${ salario }`; } catch (error) { return error; } } const id = 4; getInfoUsuario( id ) .then( msg => console.log( msg ) ) .catch( err => console.log( err ) );
/** this is the file for configure Apollo GraphQL extension for VSCode */ module.exports = { service: { localSchemaFile: "generated/schema.graphql", }, };
Template.propertiesLocationFilter.events({ "click .location-filter": function(event, template) { event.preventDefault() var city = template.data.city; Session.set('location-filter', city) } });
var express = require("express") var cors = require("cors") var bodyParser = require("body-parser") var app = express() var port = process.env.PORT || 5000 app.use(bodyParser.json()) app.use(cors()) var Users = require('./routes/Users') var Atributes = require('./routes/Atributes') var Widgets = require('./routes/Widgets') var WidgetsHasAtt = require('./routes/WidgetHasAtts') var World = require('./routes/World') var WorldHasWidgets = require('./routes/WorldHasWidgets') var Images = require('./routes/Images') var BoxText = require('./routes/BoxText') app.use('/users', Users) app.use('/atributes', Atributes) app.use('/widgets', Widgets) app.use('/widgetsHasAtts', WidgetsHasAtt) app.use('/world', World) app.use('/worldHasWidgets', WorldHasWidgets) app.use('/images', Images) app.use('/boxText', BoxText) app.listen(port, () => { console.log("Server is running on port: " + port) })
angular.module('angularTest') .directive('overlayComponent', function ($compile) { var linker = function(scope, element, attrs) { // Position the overlay component to center by default scope.position(); }; var controller = function($scope, $element) { $scope.position = function() { var left = Math.ceil((window.innerWidth - $($element).width())/2)+"px", top = Math.ceil((window.innerHeight - $($element).height())/2)+"px"; $($element).css({"left": left, "top": top}); }; var anc = document.createElement("a"); anc.href = "#"; anc.innerHTML = "<i class=\"fa fa-times\"></i>"; anc.className = "btn closeOverlay"; // anc.onclick = function(ev, el) { // debugger; // $(ev.target.parentNode.parentNode).hide(); // $(".overlayScreen").remove(); // }; // $($element).append(anc); $(window).resize($.proxy($scope.position, $scope)); }; return { restrict: "AE", link: linker, controller: controller, scope: true, templateUrl: function(el, attrs) { return "/src/app/directive/renderTemplate/"+attrs.ngTemplate; } }; }) ;
var PanelBase = (function (_super) { __extends(PanelBase, _super); function PanelBase(viewParent) { _super.call(this); /** * 资源是否加载完成 * @type {boolean} * @private */ this._isResLoaded = false; this._viewParent = viewParent; this.touchEnabled = true; this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap, this); this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAdded, this); this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemoved, this); } var d = __define,c=PanelBase;p=c.prototype; /** * 当添加到舞台上 */ p.onAdded = function () { this.removeEventListener(egret.Event.ADDED_TO_STAGE, this.onAdded, this); }; /** * 当添加到舞台上 */ p.onRemoved = function () { this.removeEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemoved, this); this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchTap, this); UIUtils.removeButtonScaleEffects(this); this.destroy(); }; /** * 销毁 */ p.destroy = function () { RES.destroyRes(this._resGroup); }; d(p, "viewParent",undefined ,function (val) { this._viewParent = val; if (!this._resGroup || !this.uiSkinName) { this._viewParent.addChild(this); } } ); p.init = function (resGroup) { if (resGroup) { this._resGroup = resGroup; this._isResLoaded = false; egret.setTimeout(this.showPreLoading, this, 50); RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onGroupResourceLoaded, this); RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onGroupResourceLoaded, this); RES.loadGroup(resGroup); } else { this.onGroupResourceLoadedThenAddToStage(); } }; p.showPreLoading = function () { if (!this._isResLoaded) { PanelLoading.instance.show(); } }; d(p, "animate_startPos",undefined /** * 设置动画起始位置 * @param val */ ,function (val) { if (val) { this._startPos = val; } } ); p.onGroupResourceLoaded = function (event) { if (event.groupName == this._resGroup) { this._isResLoaded = true; PanelLoading.instance.hide(); RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onGroupResourceLoaded, this); RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onGroupResourceLoaded, this); this.onGroupResourceLoadedThenAddToStage(); } }; p.onGroupResourceLoadedThenAddToStage = function () { this.skinName = null; if (this.uiSkinName) { this.skinName = this.uiSkinName; } if (this._viewParent) { this._viewParent.addChild(this); } else { GameLayerManager.instance.popLayer.addChild(this); } }; p.createChildren = function () { _super.prototype.createChildren.call(this); UIUtils.addButtonScaleEffects(this); this.onShow(); }; p.onTouchTap = function (e) { var target = e.target; if (target == this.closeBtn) { this.onHide(); } }; p.onShow = function () { this.x = Const.WIN_W; this.y = Const.WIN_H / 2; if (this._startPos) { this.x = this._startPos.x; this.y = this._startPos.y; } var toX = (Const.WIN_W - this.width) / 2; var toY = (Const.WIN_H - this.height) / 2; this.scaleX = this.scaleY = 0; egret.Tween.get(this) .to({ x: toX, y: toY, scaleX: 1, scaleY: 1 }, 250, egret.Ease.backOut) .call(this.onShowAnimateOver, this); }; /** * 显示动画完成后 */ p.onShowAnimateOver = function () { }; p.onHide = function () { var toX = Const.WIN_W; var toY = Const.WIN_H / 2; if (this._startPos) { toX = this._startPos.x; toY = this._startPos.y; } egret.Tween.get(this).to({ x: toX, y: toY, scaleX: 0, scaleY: 0 }, 250, egret.Ease.backIn).call(UIUtils.removeSelf, this, [this]); }; p.hide = function () { this.onHide(); }; return PanelBase; })(eui.Panel); egret.registerClass(PanelBase,"PanelBase");
Ext.define('eapp.store.Unemploymentreply', { extend :'Ext.data.Store', config: { model:'eapp.model.Unemploymentreply', } });
import './App.css'; import MemeGenerator from './components/MemeGenerator'; function App() { return ( <div className="App"> <h2 className="text-center">Make Cool Memes !</h2> <MemeGenerator /> </div> ); } export default App;
import { makeStyles } from '@material-ui/styles'; export default makeStyles(theme => ({ font1:{ fontFamily: "Oswald", fontSize: "1.9em" }, font2:{ fontFamily: "Fira Code", [theme.breakpoints.down('sm')] : { fontSize: "3em" }, }, font3:{ fontFamily: "Lato", [theme.breakpoints.down('md')] : { fontSize: "1.2em" }, [theme.breakpoints.down('sm')] : { fontSize: "1.2em" }, }, font4:{ fontFamily: "Lato", [theme.breakpoints.down('md')] : { fontSize: "1em" }, [theme.breakpoints.down('sm')] : { fontSize: ".8em" }, }, tipsContainer : { display: "flex", alignItems: "center", justifyContent: "center", flexWrap: "wrap", height: "80vh", width: "80vw", [theme.breakpoints.down('md')] : { width: "100vw", }, [theme.breakpoints.down('sm')] : { height: "100%", width: "80vw", }, }, tipsWrapper : { display: "flex", alignItems: "flex-start", justifyContent: "center", width: 350, margin: "0px 52px", [theme.breakpoints.down('md')] : { width: 300, }, [theme.breakpoints.down('sm')] : { width: 250, textAlign: "center", margin: "35px 0px", }, }, icon : { background: "#9DB4FA", color: "#FFFFFF", height: 30, width: 30, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: 50, marginTop: 12, marginRight: 6 }, }));
/*global alert: true, console: true, ODSA */ // Written by Bailey Spell and Jesse Terrazas $(document).ready(function() { "use strict"; $(function() { $(window).bind("storage", () => { var encryptedMsg = localStorage.encryptedText; $(".encryptedMsg").val(encryptedMsg); }); }); function decryptMessage() { var crypt = new JSEncrypt(); var privateKey = $(".privateKey").val(); crypt.setPrivateKey(privateKey); var encryptMsg = $(".encryptedMsg").val(); var decodedText = crypt.decrypt(encryptMsg); // since library only encrypts with public key and decrypts // private key, lets try the reverse if (decodedText === null) { crypt.setPublicKey(privateKey); var e = crypt.encrypt(localStorage.secretMsg); crypt.setPrivateKey(localStorage.publicKey); decodedText = crypt.decrypt(e) } $(".decryptMsg").val(decodedText); } $(".decrypt").click(decryptMessage); });
import React, { Component } from 'react'; import HouseDash from './HouseDash' import LocationDash from './LocationDash' import Panel from '../presentation/Panel' import Hallows from '../presentation/Hallows'; import FooterNav from '../presentation/FooterNav' class CastleDash extends Component { constructor(props){ super(props) this.state = { view : 'home' } } changeView = newView => { this.setState({view: newView}) } render() { return( <div className="CastleDash"> {this.state.view === 'location' && ( <LocationDash castleView={this.state.view} changeView={this.changeView} students={this.props.students} staff={this.props.staff} locations={this.props.locations} sendUpdate={this.props.sendUpdate}/> )} {this.state.view === 'house' && ( <HouseDash castleView={this.state.view} changeView={this.changeView} students={this.props.students} staff={this.props.staff} houses={this.props.houses}/> )} {this.state.view === 'home' && ( <div> <Hallows /> <FooterNav home={e=>this.changeView('home')} house={e => this.changeView('house')} location={e => this.changeView('location')} /> </div> )} </div> ) } } export default CastleDash;
import Head from 'next/head' import Image from 'next/image' import styles from '../styles/Home.module.css' export async function getStaticProps() { const res = await fetch('http://meme-service-team2-final-project.itzroks-100000kr1k-fz0n6p-6ccd7f378ae819553d37d5f2ee142bd6-0000.ams03.containers.appdomain.cloud/memes?count=10') // internal OPENSHIFT URL const memes = await res.json() return { props: { memes, }, } } export default function Home({memes}) { return ( <div className={styles.container}> <Head> <title>Create Next App</title> <meta name="description" content="Generated by create next app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main className={styles.main}> <h1 className={styles.title}> Hey all </h1> <div className={styles.gallery}> {memes.map((meme) => ( <img src={meme} className={styles.gallery__img}/> ))} </div> </main> </div> ) }
/*jshint globalstrict:false, strict:false */ /*global assertEqual, assertNotEqual */ //////////////////////////////////////////////////////////////////////////////// /// @brief test the skip-list index /// /// @file /// /// DISCLAIMER /// /// Copyright 2010-2013 triagens GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler, Lucas Dohmen /// @author Copyright 2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var jsunity = require("jsunity"); var internal = require("internal"); //////////////////////////////////////////////////////////////////////////////// /// @brief test suite: Creation //////////////////////////////////////////////////////////////////////////////// function SkipListSuite() { 'use strict'; var cn = "UnitTestsCollectionSkiplist"; var collection = null; return { //////////////////////////////////////////////////////////////////////////////// /// @brief set up //////////////////////////////////////////////////////////////////////////////// setUp : function () { internal.db._drop(cn); collection = internal.db._create(cn); }, //////////////////////////////////////////////////////////////////////////////// /// @brief tear down //////////////////////////////////////////////////////////////////////////////// tearDown : function () { // try...catch is necessary as some tests delete the collection itself! try { collection.unload(); collection.drop(); } catch (err) { } collection = null; internal.wait(0.0); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test: index creation //////////////////////////////////////////////////////////////////////////////// testCreation : function () { var idx = collection.ensureSkiplist("a"); var id = idx.id; assertNotEqual(0, id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(false, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(true, idx.isNewlyCreated); idx = collection.ensureSkiplist("a"); assertEqual(id, idx.id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(false, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(false, idx.isNewlyCreated); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test: index creation //////////////////////////////////////////////////////////////////////////////// testCreationSparseUniqueSkiplist : function () { var idx = collection.ensureSkiplist("a", { sparse: true }); var id = idx.id; assertNotEqual(0, id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(true, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(true, idx.isNewlyCreated); idx = collection.ensureSkiplist("a", { sparse: true }); assertEqual(id, idx.id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(true, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(false, idx.isNewlyCreated); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test: index creation //////////////////////////////////////////////////////////////////////////////// testCreationSkiplistMixedSparsity : function () { var idx = collection.ensureSkiplist("a", { sparse: true }); var id = idx.id; assertNotEqual(0, id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(true, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(true, idx.isNewlyCreated); idx = collection.ensureSkiplist("a", { sparse: false }); assertNotEqual(id, idx.id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(false, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(true, idx.isNewlyCreated); id = idx.id; idx = collection.ensureSkiplist("a", { sparse: false }); assertEqual(id, idx.id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(false, idx.sparse); assertEqual(["a"], idx.fields); assertEqual(false, idx.isNewlyCreated); }, //////////////////////////////////////////////////////////////////////////////// /// @brief test: permuted attributes //////////////////////////////////////////////////////////////////////////////// testCreationPermutedSkiplist : function () { var idx = collection.ensureSkiplist("a", "b"); var id = idx.id; assertNotEqual(0, id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(false, idx.sparse); assertEqual(["a","b"], idx.fields); assertEqual(true, idx.isNewlyCreated); idx = collection.ensureSkiplist("b", "a"); assertNotEqual(id, idx.id); assertEqual("skiplist", idx.type); assertEqual(false, idx.unique); assertEqual(false, idx.sparse); assertEqual(["b","a"], idx.fields); assertEqual(true, idx.isNewlyCreated); } }; } //////////////////////////////////////////////////////////////////////////////// /// @brief executes the test suites //////////////////////////////////////////////////////////////////////////////// jsunity.run(SkipListSuite); return jsunity.done();
import React from 'react'; export default class EmployeeForm extends React.Component { constructor (props) { super(); this.state = { employee: {...props.employee} } } componentWillReceiveProps (nextProps) { this.setState({ employee: {...nextProps.employee} }) } onSubmit (e) { e.preventDefault(); this.props.onEmployeeFormChage({...this.state.employee}); } onDeptChange (e) { this.setState({ employee: { ...this.state.employee, department: e.target.value } }) } render () { return ( <div> <h4>Employee Details</h4> <form onSubmit={this.onSubmit.bind(this)} > <div className='well well-sm'> <label>Name:</label> <input ref={(ele) => this.nameInputEl = ele} value={this.state.employee.name} onChange={(event) => this.onNameChange(event)} /> </div> <div className='well well-sm'> Department: { ' ' } <select value={this.state.employee.department} onChange={this.onDeptChange.bind(this)} > { this.props.departments.map(item => { return ( <option value={item.name} key={item.name} > {item.name} </option> ) }) } </select> </div> <div> <input type='submit' className='btn btn-primary' value='save'/> </div> </form> </div> ) } onNameChange (event) { this.setState({ employee: { ...this.state.employee, name: event.target.value } }) } } EmployeeForm.defaultProps = { employee: { name: '', id: null, departmentId: null } }
if(Posts.find().count() === 0){ Posts.insert({ title:"Introducing Telescope", author:"Sacha Greif", url:"http://sachagreif.com/introducing-telescope/" }); Posts.insert({ title:"Meteor", author:"Tom Colema", url:"http://meteor.com" }); Posts.insert({ title:"Meteor book", author:"Tom white", url:"http://themeteorbook.com" }); }
const { v4: uuidv4 } = require('uuid'); const TaskModel = require('../models/task.model'); const hipsumApi = require('./hipsum-api.service'); const createTask = async ({ title }) => { if (!await TaskModel.exists({ title })) { const task = new TaskModel({ uuid: uuidv4(), title, }); await task.save(); return task; } return {}; }; const getNewTasksAndFetchAll = async (qty) => { const allDbTasks = await TaskModel.find({ completed: false }).exec(); if (allDbTasks.length >= qty) { return allDbTasks.filter((_, index) => index < qty); } const requiredTasksQty = Number(qty) - allDbTasks.length; const newTasks = []; do { // This particular API does not support parallel executions, // it returns a cached response. So we need to retry // eslint-disable-next-line no-await-in-loop const task = await hipsumApi.getParagraph(); if (!newTasks.some((t) => t === task) && !allDbTasks.some((t) => t.title === task)) { newTasks.push(task); } } while (newTasks.length < requiredTasksQty); const tasksDbPromises = []; for (let j = 0; j < newTasks.length; j += 1) { const element = newTasks[j]; tasksDbPromises.push(createTask({ title: element })); } await Promise.all(tasksDbPromises); return TaskModel.find({ completed: false }).exec(); }; const completeTask = async ({ id }) => TaskModel.updateOne({ id }, { completed: true }); module.exports = { createTask, getNewTasksAndFetchAll, completeTask, };
import IdeaForm from './IdeaForm'; export default IdeaForm;
const express = require('express'); const api = require('../controllers'); const router = express.Router(); const { services } = api; router.route('/').get((req, res) => { res.json({ success: true, data: services }); }); router.route('/:serviceId').get((req, res) => { const { serviceId } = req.params; res.json({ success: true, data: services.services[serviceId - 1] || {} }); }); router.route('/near-me/:locationId').get((req, res) => { const { locationId } = req.params; const popularServices = services.popularServices(locationId); res.json({ success: true, data: popularServices }); }); module.exports = router;
/* * This contains the JavaScript functions used in index.html */ $(document).ready(function () { //Back-End Validation CSS Changer JS var errorMsg = document.getElementById("errorMsg").innerHTML; if(errorMsg.match("First Name")){ $('#fname').addClass('errorMessage'); } if(errorMsg.match("Last Name")){ $('#lname').addClass('errorMessage'); } if(errorMsg.match("Email") || errorMsg.match("Email (Exists)")){ $('#email').addClass('errorMessage'); } if(errorMsg.match("Password")){ $('#pass').addClass('errorMessage'); $('#pass_c').addClass('errorMessage'); } $('#fname').keypress(function(){ $('#fname').removeClass('errorMessage'); }); $('#lname').keypress(function(){ $('#lname').removeClass('errorMessage'); }); $('#email').keypress(function(){ $('#email').removeClass('errorMessage'); }); $('#pass').keypress(function(){ $('#pass').removeClass('errorMessage'); }); $('#pass_c').keypress(function(){ $('#pass_c').removeClass('errorMessage'); }); //Back-End Validation CSS Changer JS //Birth Year JS var currentYear = (new Date()).getFullYear(); var minimumYear = currentYear - 70; for(i = currentYear; i >= minimumYear; i--) { $("#b_year").get(0).options[$("#b_year").get(0).options.length] = new Option(i, i); } //Birth Year JS //Modal JS var modal = document.getElementById('myModal'); var btn = document.getElementById("myBtn"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //Modal JS } );
import React from 'react'; import Joi from 'joi-browser'; import Form from './Form'; import './Contact.scss'; class Contact extends Form { state ={ fields: {name:'', email:'', message:''}, errors: {} }; schema = { name:Joi.string().required().label('Name'), email:Joi.string().required().label('Email'), message:Joi.string().required().label('Message') }; doSubmit = () => { console.log('Submitted'); } render() { return ( <section className="contact"> <div className="contact-me"> <h2>Contact Me</h2> </div> <form onSubmit={this.handleSubmit} className="form"> {this.renderInput('name', 'Name')} {this.renderInput('email', 'Email')} {this.renderInput('message', 'Message')} {this.renderButton("Submit")} </form> </section> ); } } export default Contact;
import styled from 'styled-components' import { Heading as BaseHeading } from 'rebass' const Heading = styled(BaseHeading)`` Heading.defaultProps = { fontSize: 6, lineHeight: 1.125 } Heading.displayName = 'Heading' export default Heading
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(2); /***/ }), /* 2 */ /***/ (function(module, exports) { 'use strict'; // { // let regex=new RegExp('xyz', 'i'); // let regex2=new RegExp(/xyz/i); // console.log(regex.test('xyz123'),regex2.test('xyz123')); // } { //数组扩展 var arr = Array.of(1, 2, 2); console.log(arr); } { var p = document.querySelectorAll('strong'); var pArr = Array.from(p); console.log(p); pArr.forEach(function (item) { console.log(item.textContent); }); } /***/ }) /******/ ]);
export const ADD_REMINDER = "ADD_REMINDER" export const REMOVE_REMINDER = "REMOVE_REMINDER" export const CLEAR_REMINDER = "CLEAR_REMINDER"
import React, { useState, useEffect } from 'react'; export default ({ ...props }) => { const [state, setstate] = useState() document.getElementsByClassName("content-fadable A")[0].addEventListener("scroll", function(){ setstate(document.getElementsByClassName("content-fadable A")[0].scrollTop) }); return ( <h3>{props.text}</h3> ) }
ui.Image = function() { ui.Image.base.constructor.call(this); // for user, init before create this.userClass = ""; this.src = ""; }; wr.inherit(ui.Image, wr.View); ui.Image.prototype.create = function() { this.img = wr.createElement("img"); this.setSrc(this.src); this.node = wr.div_cc("ui_image", [ this.img ]); wr.addClass(this.node, this.userClass); }; ui.Image.prototype.setSrc = function(src) { this.src = src; if (this.src.length > 0) { this.img.src = src; } };
const path = require('path'); // Lets us use __dirname as the relative filepath from this file require('dotenv').config('../../.env'); console.log(process.env.TEST_DATABASE_URL); module.exports = { development: { username: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: 'agiletodos2_dev', details: { host: 'localhost', port: 3306, dialect: 'mysql' } }, test: { use_env_variable: 'TEST_DATABASE_URL', //add this back if I try to use the coverage tests in CI again username: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: 'agiletodos2_test', details: { host: '127.0.0.1', // use 'localhost' if go back to using this step in CI port: 3306, dialect: 'mysql' } }, production: { use_env_variable: 'JAWSDB_URL', details: { host: 'c584md9egjnm02sk.cbetxkdyhwsb.us-east-1.rds.amazonaws.com', username: 'ewmlyqjt30a4ewi0', password: 'jzmpiwgyslmbh41g', database: 'g1xlb2hedlnspfme', port: 3306, dialect: 'mysql' } } };
// JS工具库 // 计算任意参数之和 function sum() { var s = 0; for (var i = 0; i < arguments.length; i++) { s += arguments[i]; } return s; } // 求任意数的最大值 function maxNum() { var max = arguments[0]; for (var i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i] } } return max } // 求任意数的最小值 function minNum() { var min = arguments[0]; for (var i = 0; i < arguments.length; i++) { if (arguments[i] < min) { min = arguments[i] } } return min } //求n-m之间的随机整数 function randomNum(n, m) { if (n > m) { return parseInt(Math.random() * (n - m + 1) + m) } else { return parseInt(Math.random() * (m - n + 1) + n) } } //冒泡排序 function bubbleSort(arr) { for (var i = 0; i < arr.length - 1; i++) { for (var j = 0; j < arr.length - (i + 1); j++) { if (arr[j] > arr[j + 1]) { var t = arr[j] arr[j] = arr[j + 1] arr[i + 1] = t } } } } //选择排序 function selectionSort(arr) { for (var i = 0; i < arr.length; i++) { var index = i; var min = i; for (var j = i + 1; j < arr.length; j++) { if (arr[i] < arr[index]) { index = i } } if (min !== index) { var temp = arr[min] arr[min] = arr[index] arr[index] = temp } } } //数组去重 function arrayHeavy(arr) { var arr1 = [] arr.forEach(function(item) { if (arr1.indexOf(item) == -1) { arr1.push(item); } }) return arr1 } //把url的参数转化为对象 function urlObj(url) { var index = url.indexOf("?") var res = url.substr(index + 1) // console.log(res); // 把字符串分割成数组 var arr = res.split("&"); console.log(arr); // 循环数组,拿到数组中的每一个数据,以“=”分割 var obj = {} //定义一个空对象 arr.forEach(function(item) { var arr2 = item.split("=") obj[arr2[0]] = arr2[1] // console.log(obj); }) return obj } //随机颜色 function randomColor() { return "rgb(" + randomNum(0, 255) + "," + randomNum(0, 255) + ",+randomNum(0, 255)+)" } //验证码(6位数字) function numberCode(n) { var arr = [] for (var i = 0; i < n; i++) { var num = parseInt(Math.random() * 10) arr.push(num) } return arr.join("") } //验证码(数字+字母) function textCode(n) { var arr = [] for (var i = 0; i < n; i++) { var num = parseInt(Math.random() * 123) if (num >= 0 && num <= 9) { arr.push(num) } else if (num >= 97 && num <= 122 || num >= 65 && num <= 98) { arr.push(String.fromCharCode(num)) } else { i-- } } return arr.join("") } //时间转化为2020-01-01 15:30:22 星期六 格式化 function formatTime(time, fuhao) { var arr = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] var str = "" var year = time.getFullYear() var month = time.getMonth() + 1 var day = time.getDate() var hours = time.getHours() var min = time.getMinutes() var sec = time.getSeconds() var week = arr[time.getDay()] //如果日期是10之后的直接输出,如果日期小于10需要在前面加0 month >= 10 ? month : "0" + month day >= 10 ? day : "0" + day hours >= 10 ? hours : "0" + hours min >= 10 ? min : "0" + min sec >= 10 ? sec : "0" + sec //如果没有符号这个参数,需要做一个处理 fuhao = fuhao ? fuhao : "/" str = `${year}${fuhao}${month}${fuhao}${day} ${hours}:${min}:${sec} ${week} ` return str } //两个时间的时间差 function timeDifference(time1, time2) { var t1 = Math.abs(time1.getTime() - time2.getTime()) var day = parseInt(t1 / 1000 / 3600 / 24) //求出相差的天数 var hours = parseInt((t1 / 1000 / 3600) % 24) //求出相差的小时数 var min = parseInt((t1 / 1000 / 60) % 60) //求出相差的分钟数 var sec = parseInt((t1 / 1000) % 60) //求出相差的秒数 var obj = { day: day, hours: hours, min: min, sec: sec } return obj } //兼容获取元素的样式 function getCompatibilityStyle(ele, attr) { //ele:元素,attr:属性 var res; if (window.getComputedStyle) { res = window.getComputedStyle(ele)[attr] } else { res = ele.currentStyle[attr] } return res } //兼容监听事件 function monitorEvent(ele, event, fun) { //判断ele.addEventListener是否存在 if (ele.addEventListener) { ele.addEventListener(event, fun) } else { ele.attachEvent("on" + event, fun) } } //封装一个单属性动画函数,参数:给那个元素做动画、做什么样的动画(css属性)、目标值 function animation(ele, attr, target) { clearInterval(ele.move) //获取元素的当前值 let style style = parseInt(style) let speed //定义一个定时器执行动画 ele.move = setInterval(() => { style = getCompatibilityStyle(ele, attr) speed = (target - style) / 10 speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed) style += speed if (target == style) { clearInterval(ele.move) } ele.style[attr] = style + "px" }, 100); } //封装一个多属性动画 function animationAll(ele, obj, callback) { let length = 0 for (var key in obj) { length++ let attr = key let target = obj[key] clearInterval(ele[attr]) //获取元素的当前值 let style style = parseInt(style) let speed //定义一个定时器执行动画 ele[attr] = setInterval(() => { if (attr == "opcity") { style = getCompatibilityStyle(ele, attr) * 100 } else { style = getCompatibilityStyle(ele, attr) } speed = (target - style) / 10 speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed) style += speed if (target == style) { clearInterval(ele[attr]) length-- } if (attr == "opacity") { ele.style[attr] = style / 100 } else { ele.style[attr] = style + "px" } //当length=0时所有动画都结束 if (length == 0) { callback && callback() } }, 100); } } // 拖拽头部元素移动整个元素,ele:大盒子里的头部,bigEle:大盒子 function drags(ele, bigEle) { ele.onmousedown = (event) => { let e1 = event || window.event; let x = e1.offsetX; let y = e1.offsetY; document.onmousemove = (e) => { let left = e.clientX - x; let top = e.clientY - y; if (left <= 0) { left = 0; } if (top <= 0) { top = 0; } if (left >= innerWidth - bigEle.offsetWidth) { left = innerWidth - bigEle.offsetWidth } if (top >= innerHeight - bigEle.offsetHeight) { top = innerHeight - bigEle.offsetHeight; } bigEle.style.left = left + 'px'; bigEle.style.top = top + 'px'; } } document.onmouseup = () => { document.onmousemove = null; } } //封装拖拽元素的函数 //面向对象 //1.创建对象 //2.描述对象 //3.使用对象 //创建对象 let Drag = function(ele) { //描述静态属性 // this.ele 谁被拖拽 this.ele = ele this.init() } //描述动态方法 //init() 初始化,一般用来创建元素,添加事件 //down() 鼠标按下时执行的功能 //move() 鼠标移动时执行的功能 //up() 鼠标抬起时执行的功能 Drag.prototype.init = function() { this.ele.onmousedown = () => { this.down(); }; document.onmouseup = () => this.up() } Drag.prototype.down = function() { let e = window.event this.x = e.offsetX this.y = e.offsetY document.onmousemove = () => { this.move() } } Drag.prototype.move = function() { let event = window.event let left = event.clientX - this.x let top = event.clientY - this.y //判断边界值 if (left <= 0) { left = 0 } if (top <= 0) { top = 0 } if (left >= innerWidth - this.ele.clientWidth) { left = innerWidth - this.ele.clientWidth } if (top >= innerHeight - this.ele.clientHeight) { top = innerHeight - this.ele.clientHeight } this.ele.style.left = left + "px" this.ele.style.top = top + "px" } Drag.prototype.up = function() { document.onmousemove = null } //封装tab切换 class Tab { // 1. 创建对象 class Tab {} // 2. 描述对象 // this.ele = document.querySelect(ele) 需要做tab切换的盒子 // this.btn = this.ele.querySelectAll("ul li") // this.content = this.ele.querySelectAll(".tab-conent") // 3. 动态方法 // init()创建元素和绑定事件 // changeActive() // changeContent() // 4. new Tab(ele) constructor(ele, obj) { this.ele = document.querySelector(ele) this.btn = this.ele.querySelectorAll("ul li") this.content = this.ele.querySelectorAll(".tab-content") //如果obj存在,obj.index this.index = obj ? obj.index || 0 : 0 this.init() } init() { this.btn[this.index].classList.add("active") this.content[this.index].classList.add('current') this.btn.forEach((item, index) => { item.onclick = () => { this.changeAcitve(item, index) } }); } changeAcitve(curBtn, idx) { this.btn.forEach(item => item.classList.remove("active")) curBtn.classList.add("active") this.changeContent(idx) } changeContent(idx) { this.content.forEach(item => item.classList.remove("current")) this.content[idx].classList.add("current") } } //放大镜 //放大镜+切换图片 class Enlarge { //结构:参考day19-面向对象3的放大镜.html // 放大镜盒子的大小需要动态设置,根据show盒子和mask遮罩层和放大镜的背景图决定 //show/mask===放大镜的背景图/放大镜盒子的宽高 //放大镜的宽高===mask*放大镜背景图/show //1.创建对象 class Enlarge{} //2.描述对象 // 静态属性 // 页面中存在的元素 // 动态方法 // init()初始化 // setStyle()设置放大镜的宽高 // showEnlarge()显示放大镜 // move()移动 // changeImg()改变图片 constructor(ele) { this.ele = document.querySelector(ele) this.show = this.ele.querySelector(".show") this.showImg = this.show.querySelector("img") this.mask = this.show.querySelector(".mask") this.btn = this.ele.querySelectorAll(".list p") this.enlarge = this.ele.querySelector(".enlarge") this.init() } init() { this.show.onmouseover = () => { this.mask.style.display = this.enlarge.style.display = "block" this.setStyle() } this.show.onmouseout = () => { this.mask.style.display = this.enlarge.style.display = 'none'; } this.show.onmousemove = () => { this.maskmove() } this.btn.forEach((item) => { item.onclick = () => { let e = window.event this.changeImg(item, e.target) } }) } setStyle() { this.showW = this.show.offsetWidth this.showH = this.show.offsetHeight this.maskW = this.mask.offsetWidth this.maskH = this.mask.offsetHeight let style = getCompatibilityStyle(this.enlarge, "backgroundSize") this.styleX = parseInt(style.split(" ")[0]) this.styleY = parseInt(style.split(" ")[1]) this.enlargeW = (this.maskW * this.styleX) / this.showW this.enlargeH = (this.maskH * this.styleH) / this.showH this.enlarge.style.width = this.enlargeW + "px" this.enlarge.style.height = this.enlargeH + "px" } maskmove() { let e = window.event //求光标在show元素中的left和top //求光标在页面中x和y pageX pageY //求大盒子的左边上边的距离(偏移量) offsetLeft offsetTop let x = e.pageX - this.ele.offsetLeft / 2 let y = e.pageY - this.ele.offsetTop / 2 let left = x - this.maskW / 2 let top = y - this.maskH / 2 //边界值判断 if (left <= 0) { left = 0 } if (top <= 0) { top = 0; } if (left >= this.showW - this.maskW) { left = this.showW - this.maskW } if (top >= this.showH - this.maskH) { top = this.showH - this.maskH } this.mask.style.left = left + 'px'; this.mask.style.top = top + 'px'; this.enlargemove(left, top) } enlargemove(x, y) { // 比例:mask在show盒子移动的距离/show盒子的宽度=背景图移动的距离/背景的宽度 // 背景图移动的距离=mask在show盒子移动的距离*背景的宽度/show盒子的宽度 //背景图定位:background-position:x,y let bigX = x * this.styleX / this.showW let bigY = y * this.styleY / this.showH this.enlarge.style.backgroundPosition = `${-bigX}px ${-bigY}px` } //target是当前点击的这个元素 changeImg(curItem, target) { this.btn.forEach(item => { item.classList.remove("active") }) curItem.classList.add("active") let midelImg = target.getAttribute("midelimg") let bigImg = target.getAttribute("bigimg") this.showImg.src = midelImg this.enlarge.style.backgroundImage = `url(${bigImg})` } } //cookie设置,可以添加、删除、修改,expires是分钟数 function setCookie(key, value, expires) { //当没有过期时间时,默认为会话时间,不设置expires时间 if (expires) { let date = new Date() let time = date.getTime() - 8 * 60 * 60 * 1000 + expires * 60 * 1000 date.setTime(time) document.cookie = `${key}=${value};expires=${date}` return } document.cookie = `${key}=${value};` } //获取cookie的值 function getCookie(key) { let cookie = document.cookie //先把字符串分割成数组,再把数组转化为对象 let arr = cookie.split("; ") let obj = {} arr.forEach(item => { let newArr = item.split("=") obj[newArr[0]] = newArr[1] }) // console.log(obj); return obj[key] } //封装ajax,请求类型type,请求地址url,请求携带的参数,回调函数 /*obj={ type:"get", 可选,默认为get url:url地址, 必填 data:{name:"aaa",password:"123" }|| name="aaa"&password="123" 可选 async:true||false 可选,默认为true success:fun 必填,获取数据成功时执行的函数 }*/ function ajaxFun(option) { // 【1】判断url是否传递参数 if (!option.url) { // 手动抛出一个错误, throw new Error('url的参数时必填的'); } // 设置默认值 let defOption = { type: 'get', async: true } // 把传递过去来的参数写入默认值当中 for (let key in option) { defOption[key] = option[key] } //【1】如果传递的type不是 get 或者post的时候,抛出错误提示使用者,type的值只能为get 或者 post if (!(defOption.type == 'get' || defOption.type == 'post')) { throw new Error('type参数只能为get 或者 post'); } // 【3】判断async 是否布尔值 // console.log(Object.prototype.toString.call(defOption.async)); if (Object.prototype.toString.call(defOption.async) != '[object Boolean]') { throw new Error('async 的值只能为布尔值'); } if (defOption.data) { // 【4】判断参数 data 是否是对象 和字符串的数据类型 let dataType = Object.prototype.toString.call(defOption.data); if (!(dataType == '[object String]' || dataType == '[object Object]')) { throw new Error('data的格式只能为key=value&key=value 或者 {key:value}'); } // 判断data参数是否 是对象,如果是对象需要把参数处理为 key=value&key=value if (dataType == '[object Object]') { let str = ''; for (let key in defOption.data) { str += key + '=' + defOption.data[key] + '&'; } defOption.data = str.substr(0, str.length - 1); } // 当参数为字符串的时候,判断是否有=号 if (dataType == '[object String]' && !defOption.data.includes('=')) { throw new Error('data格式只能为key=value') } } // 【5】判断success回调函数 if (!defOption.success) { throw new Error('success是必须存在的参数') } // 判断success 是否是函数 if (Object.prototype.toString.call(defOption.success) != '[object Function]') { throw new Error('success必须是函数') } try { let xhr = new XMLHttpRequest(); // 判断请求的是类型 来写请求携带参数 if (defOption.type == 'get') { xhr.open(defOption.type, defOption.url + (defOption.data ? '?' + defOption.data : ''), defOption.async); xhr.send() } else if (defOption.type == 'post') { xhr.open(defOption.type, defOption.url, defOption.async); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(defOption.data); } // 判断请求异步还是同步 if (defOption.async) { xhr.onload = function() { defOption.success(xhr.responseText) } } else { defOption.success(xhr.responseText) } } catch (err) { defOption.error(err) } } //封装promise的ajax function pAjax(params) { return new Promise(function(resolve, reject) { // 执行异步程序 ajaxFun({ type: params.type || 'get', url: params.url, data: params.data, async: params.async || true, success: function(res) { // res是ajax的请求结果 resolve(res) }, //error当执行请求数据出错时执行的方法 error: function(res) { reject(res) } }) }) }
import React, { useEffect } from "react"; import { useDispatch } from "react-redux"; import { loadData } from "./user-data/actions/usersListActions"; import UserProfile from "./main-layout/UserProfile"; import UsersList from "./main-layout/UsersList"; import { createMuiTheme } from "@material-ui/core"; import { green, lightGreen } from "@material-ui/core/colors"; import { ThemeProvider } from "@material-ui/core"; const theme = createMuiTheme({ palette: { primary: { main: green[500], }, secondary: { main: lightGreen[500], }, }, typography: { h1: { fontSize: 35, margin: 20, }, h3: { fontSize: 25, margin: 20, }, h5: { fontSize: 15, fontWeight: "bolder", }, }, }); export default function AppLogic() { const dispatch = useDispatch(); useEffect(() => { fetch("https://gorest.co.in/public-api/users") .then((res) => res.json()) .then((res) => dispatch(loadData(res.data))); }); return ( <ThemeProvider theme={theme}> <UsersList /> <UserProfile /> </ThemeProvider> ); }
let id = 0; import {pushTarget,popTarget} from './dep' import { observe } from '.'; import { util } from '../util'; class Watcher{//每次产生一个watcher 都要有一个唯一的标识 /** * @param {*} vm 当前组件的实例 * @param {*} exprOrFn 用户可能传入的是一个表达式,也有可能传入的是一个函数 * @param {*} cb 用户传入的回调函数 vm.$watch('msg',cb) * @param {*} opts //一些其他参数 */ // vm ()=>{this.firName+..} ()=>{} lazy:true constructor(vm,exprOrFn,cb=()=>{},opts={}){ this.vm = vm; this.exprOrFn = exprOrFn; if(typeof exprOrFn === 'function'){//getter 就是 new Watcher传入的第二个函数 this.getter = exprOrFn }else{ this.getter = function () {//调用此方法 会将vm上对应的表达式取出来 return util.getValue(vm,exprOrFn) } } if(opts.user){//标识是用户自己写的watch this.user = true; } this.lazy = opts.lazy;//如果这个值是计算属性 this.dirty = this.lazy; this.cb = cb; this.deps = []; this.depsId = new Set(); this.opts = opts; this.id = id++; this.immediate = opts.immediate //创建watcher 现将表达式对应的值取出来 oldValue this.value = this.lazy?undefined:this.get(); //默认创建watcher 会调用自身的方法 if(this.immediate){ this.cb(this.value); } } get(){//创建watcher 默认执行 //Dep.target = 用户的watcher pushTarget(this);//渲染watcher Dep.target = watcher //fullName(){ return this.firstName + this.lastName} let value = this.getter.call(this.vm);//让当前传入的函数执行 popTarget(); return value } evaluate(){ this.value = this.get(); this.dirty = false;//值求过了 下次渲染不需要再求 } addDep(dep){//同一个watcher 不应该重复记录dep let id = dep.id;//msg的dep if(!this.depsId.has(id)){ this.depsId.add(id) this.deps.push(dep);//让watcher 记住当前dep dep.addSub(this); } } depend(){ let i = this.deps.length; while(i--){ this.deps[i].depend(); } } update(){ if(this.lazy){//如果是计算属性 this.dirty = true;//计算属性依赖的值变化了 稍后取值重新计算 }else{ queueWatcher(this); } } run(){ let value = this.get();//新值 if(this.value !== value){ this.cb(value,this.value); } } } let has = {}; let queue = []; function flushQueue(){ //等待当前这一轮全部更新后 再让watcher依次执行 queue.forEach((watcher)=>{ watcher.run() }) has = {}; queue = []; } function queueWatcher(watcher){//对重复的watcher进行过滤操作 let id = watcher.id; if(has[id]==null){ has[id] = true; queue.push(watcher)//相同watcher只会存一个到queue中 } //延迟清空队列 nextTick(flushQueue); } //渲染使用他 计算属性也要用它 vm.watch也用他 let callbacks = []; function flushCallbacks(){ callbacks.forEach(cb=>cb()); } function nextTick(cb){//cb就是flushQueue callbacks.push(cb); //要异步刷新这个callbacks ,获取一个异步方法 let timeFunc = ()=>{ flushCallbacks(); } if(Promise){//优先微任务 =>宏任务 Promise.resolve().then(timeFunc) } if(MutationObserver){ let observe = new MutationObserver(timeFunc); let textNode = document.createTextNode(1); observe.observe(textNode,{characterData:true}); textNode.textContent = 2; return } if(setImmediate){ return setImmediate(timeFunc,0); } if(setTimeout){ return setTimeout(timeFunc,0); } } //等待页面更新再去获取dom元素 export default Watcher
/* If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write out the names of each digit in a single word (instead of the proper name of the number in English). For example, write 12 as "onetwo" (instead of twelve), and 999 as "nineninenine" (instead of nine hundred and ninety-nine). For any integer between 0 and 999, return an array showing the path from that integer to a stable equilibrium: e.g. numbersOfLetters(60) --> ["sixzero", "seven", "five", "four"] e.g. numbersOfLetters(1) --> ["one", "three", "five", "four"] */ const writtenForm = { "0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine" }; function numbersOfLetters(num) { let arr = []; let currStr = ""; let strNum = num.toString(); currStr = reciteDigitsAloud(strNum); arr.push(currStr); while (true) { let currLen = grabLength(currStr); if (writtenForm[currLen] === currStr) break; let digitsAloud = reciteDigitsAloud(currLen); arr.push(digitsAloud); currStr = digitsAloud; } return arr; }; function reciteDigitsAloud(num) { let currStr = ""; let strDigits = num.toString().split(''); for (let i = 0; i < strDigits.length; i++) { let strDigit = strDigits[i]; currStr = currStr + writtenForm[strDigit]; } return currStr; }; function grabLength(str) { let len = str.length; return len; };
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.controls.Table', 'rd.services.Alert','css!base/css/demo' ]; var extraModules = [ ]; var controllerDefination = ['$scope', main]; function main($scope) { $scope.setting = { "columnDefs" :[ { title : function(data, target) { //自定义表头设置 return '<span>自定义带select的列</span>\ <select ng-change="titleExtraSelecteHandler(titleExtraSelected)"\ ng-model="titleExtraSelected"\ ng-options="optionItem.label as optionItem.label for optionItem in titleOptions">\ <option value="">-- choose an item --</option>\ </select>' }, targets : 1 }, { title : function(data, target) { $scope.data=data.data; return '<span>'+data.header[target]+'</span>\ <select ng-change="titleExtraSelecteHandler(titleExtraSelected)"\ ng-model="titleExtraSelected"\ ng-options="item[2] as item[2] for item in data">\ <option value="">-- choose an item --</option>\ </select>' }, targets : 2 } ], //多级表头设置 additionalHeader: '<tr class="test1"><th colspan=4>合并列1</th><th colspan=3>合并列2</th></tr>' + '<tr class="test2"><th colspan=1>复选框</th><th colspan=2>身份信息</th><th colspan=4>基本信息</th></tr>' }; //titleOptions的数据结构根据自身业务逻辑来定 $scope.titleOptions = [ {label: 'item1', id: 1}, {label: 'item2', id: 2}, {label: 'item3', id: 3}, {label: 'item4', id: 4} ]; //变化后的处理逻辑 $scope.titleExtraSelecteHandler = function(selected) { alert("你选择了"+selected); } } var controllerName = 'DemoController'; //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== define(/*fix-from*/application.import(imports)/*fix-to*/, start); function start() { application.initImports(imports, arguments); rdk.$injectDependency(application.getComponents(extraModules, imports)); rdk.$ngModule.controller(controllerName, controllerDefination); } })();
/*Mostrar datos de usuario*/ /*Dar la opcion de ver sus direcciones redirigue a direcciones*/ import React from "react"; import { Dimensions, Alert, Image, StyleSheet } from "react-native"; import { Container, Header, Title, Content, Button, Left, Right, Body, Text, Card, CardItem, Spinner, Item, Toast, H1, Footer, FooterTab, } from "native-base"; import Ionicons from "react-native-vector-icons/Ionicons"; import Icon from "react-native-vector-icons/FontAwesome"; import IP_DB from "../../ip_address"; import * as SecureStore from "expo-secure-store"; import { LinearGradient } from "expo-linear-gradient"; const windowWidth = Dimensions.get("window").width; const windowHeight = Dimensions.get("window").height; export default class PerfilScreen extends React.Component { //Constructor constructor(props) { super(props); this.state = { id: "", nombre: "", apellido: "", email: "", deseos: [], carrito: [], direccion: [], cargar: false, }; this.goGeneros = this.goGeneros.bind(this); } //Montar componentDidMount() { this.setState({ id: this.props.route.params.id }); this.obtenerDatosPerfil(); } obtenerDatosPerfil = () => { fetch(`http://${IP_DB}:3000/Usuario/Ver/${this.props.route.params.id}`, { method: "GET", headers: { "Content-Type": "application/json", }, }) .then((res) => res.json()) .then((data) => { this.setState({ nombre: data.Nombre, apellido: data.Apellido, email: data.Email, deseos: data.Deseos, carrito: data.Carrito, direccion: data.Direccion, cargar: true, }); }) .catch((error) => console.error(error)); }; goDirecciones = () =>{ this.props.navigation.navigate("Direcciones",{id: this.state.id}); } goPedidos = () =>{ this.props.navigation.navigate("Pedidos",{id: this.state.id}); } goHome = () =>{ this.props.navigation.navigate("Home",{id: this.state.id}); } goGeneros = () => { this.props.navigation.navigate("Generos", {userId: this.state.id}); } //WishList goWishL = () => { this.props.navigation.navigate("Deseos", {id: this.state.id}); } render() { if (this.state.cargar == false) { return ( <Container> <Spinner color="green" /> </Container> ); } else { return ( <Container> <Header transparent androidStatusBarColor="#C0FFC0" style={styles.Header} > <Left> <Icon name="user-circle-o" size={30} /> </Left> <Body> <Title style={styles.Header}> PERFIL </Title> </Body> <Right ></Right> </Header> <Content> <Card> <CardItem> <Text> Nombre</Text> <Right> <Text>{this.state.nombre}</Text> </Right> </CardItem> </Card> <Card> <CardItem> <Text> Apellido </Text> <Right> <Text>{this.state.apellido}</Text> </Right> </CardItem> </Card> <Card> <CardItem> <Text> Correo </Text> <Right> <Text>{this.state.email}</Text> </Right> </CardItem> </Card> <Card> <CardItem> <Text> Ver direcciones</Text> <Right> <Button transparent style={styles.Button} onPress={this.goDirecciones} > <Icon name="angle-right" size={30} /> </Button> </Right> </CardItem> </Card> <Card> <CardItem> <Text> Ver Pedidos</Text> <Right> <Button transparent style={styles.Button} onPress={this.goPedidos} > <Icon name="angle-right" size={30} /> </Button> </Right> </CardItem> </Card> <Card> <CardItem> <Text> Salir</Text> <Right> <Button transparent style={styles.Button} onPress={() => { SecureStore.deleteItemAsync('token').then(() => { this.setState({ error: false }) }) .catch((error) => { console.error(error); this.setState({ error: true }); }).finally(() => { if(!this.state.error) this.props.navigation.navigate('Login'); }); }} > <Icon name="sign-out" size={30} /> </Button> </Right> </CardItem> </Card> </Content> <Footer> <FooterTab style={{ backgroundColor: "#FFF" }}> <Button style={styles.Button} onPress={() => { this.props.navigation.navigate("Perfil", { id: this.state.id, }); }} > <Icon name="user-circle-o" size={30} /> </Button> <Button style={styles.Button} onPress={() => { this.props.navigation.navigate("Carrito", { id: this.state.id, }); }} > <Ionicons name="cart" size={30} /> </Button> <Button active style={styles.Button} onPress={this.goHome}> <Icon name="home" size={30} /> </Button> <Button style={styles.Button} onPress={this.goGeneros}> <Icon name="list-ul" size={30} /> </Button> <Button style={styles.Button} onPress={this.goWishL}> <Icon name="heart" size={30} /> </Button> </FooterTab> </Footer> </Container> ); } } } const styles = StyleSheet.create({ Container: { flex: 1, flexDirection: "column", alignItems: "stretch", justifyContent: "center", fontFamily: "Dosis", color: "white", }, Text2: { fontWeight: "300", fontSize: 15, color: "white", fontFamily: "Dosis", }, Text3: { marginTop: 10, fontSize: 15, color: "#C4EFFF", marginLeft: 5, fontFamily: "Dosis", }, Button: { alignSelf: "center", backgroundColor: "#BB8FCE", fontFamily: "Dosis", fontWeight: "400", }, background: { position: "absolute", left: 0, right: 0, top: 0, height: 100, }, Button: { alignSelf: "flex-end", fontFamily: "Dosis", backgroundColor: "white", fontWeight: "400", }, Header: { fontFamily: "Dosis", color: "black", fontSize: 40, fontWeight: "600", alignSelf: "center", }, });
import * as lfo from 'waves-lfo/client'; import * as controllers from 'basic-controllers'; const _2PI = Math.PI * 2; const $scene = document.querySelector('#scene'); const ctx = $scene.getContext('2d'); const width = window.innerWidth; const height = window.innerHeight; const halfWidth = width * 0.5; const halfHeight = height * 0.5; ctx.canvas.width = width; ctx.canvas.height = height; const eventIn = new lfo.source.EventIn({ frameType: 'vector', frameSize: 2, frameRate: 0, }); const movingAverage = new lfo.operator.MovingAverage({ order: 20, }); const bridge = new lfo.sink.Bridge(); eventIn.connect(movingAverage); movingAverage.connect(bridge); eventIn.init().then(() => { eventIn.start(); // push values into graph on event $scene.addEventListener('mousemove', (e) => { const now = new Date().getTime(); const x = e.clientX - halfWidth; const y = e.clientY - halfHeight; eventIn.process(now, [x, y]); }); let simpleDisplay = true; // cheap resampler const smooth = new lfo.operator.MovingAverage({ order: 10 }); smooth.initStream({ frameSize: 2, frameType: 'vector' }); // pull values from graph at `requestAnimationFrame` interval (function draw() { const smoothedValues = smooth.inputVector(bridge.frame.data); const x = smoothedValues[0]; const y = smoothedValues[1]; const opacity = simpleDisplay ? 0.2 : 1; ctx.fillStyle = `rgba(0, 0, 0, ${opacity})`; ctx.fillRect(0, 0, width, height); ctx.save(); ctx.translate(halfWidth, halfHeight); if (simpleDisplay) ctx.beginPath(); ctx.fillStyle = 'white'; ctx.arc(x, y, 5, 0, _2PI, true); ctx.fill(); if (simpleDisplay) ctx.closePath(); ctx.restore(); requestAnimationFrame(draw); }()); new controllers.Toggle({ label: 'alternative display', default: false, container: '#controllers', callback: (value) => simpleDisplay = !value, }); });
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withInfo } from '@storybook/addon-info'; import { checkA11y } from '@storybook/addon-a11y'; import Button from './Button'; const buttonEvents = { onClick: action('onClick'), onFocus: action('onFocus'), className: '', }; storiesOf('Buttons', module) .add('Primary Buttons', withInfo( ` Buttons are used to initialize an action, either in the background or foreground of an experience. Primary buttons should be used for the principle call to action on the page. Modify the behavior of the button by changing its event properties. Small buttons may be used when there is not enough space for a regular sized button. This issue is most found in tables. Small button should have three words or less. The example below shows Primary Button component . `, ) (() => ( <div> <Button {...buttonEvents} className=""> Primary </Button> &nbsp; <Button {...buttonEvents} kind="link" href="#" className=""> Link </Button> &nbsp; </div> )) ) .add('Basic Buttons', withInfo( ` Basic Buttons may be used when the user has a series of options. `, )(() => ( <div> <Button {...buttonEvents} kind="basic"> Basic </Button> </div> )) ) .add('Success Buttons', withInfo( ` Buttons are used to initialize an action, either in the background or foreground of an experience. Success buttons should be used for a completed actions on each page. Modify the behavior of the button by changing its property events. The example below shows a Success Button component. `, )(() => ( <div> <Button kind="success" {...buttonEvents} className=""> Success </Button> </div> )) ) .add('Disabled Buttons', withInfo( ` Disabled Buttons may be used when the user cannot proceed until input is collected. `, )(() => ( <div> <Button {...buttonEvents} disabled> Disabled </Button> </div> )) ) .add('Danger Buttons', withInfo( ` Buttons are used to initialize an action, either in the background or foreground of an experience. Danger buttons should be used for a negative action (such as Delete) on the page. Modify the behavior of the button by changing its event properties. The example below shows an enabled Danger Button component. `, )(() => ( <div> <Button kind="danger" {...buttonEvents}> Danger </Button> </div> )) ) .add('Set of Buttons', withInfo( ` When an action required by the user has more than one option, always use a a negative action button (secondary) paired with a positive action button (primary) in that order. Negative action buttons will be on the left. Positive action buttons should be on the right. When these two types buttons are paired in the correct order, they will automatically space themselves apart. `, )(() => ( <div> <Button kind="primary" {...buttonEvents}> Primary </Button> &nbsp; <Button {...buttonEvents} kind="basic"> Basic </Button> &nbsp; <Button kind="success" {...buttonEvents}> Success </Button> &nbsp; <Button {...buttonEvents} disabled> Disabled </Button> &nbsp; <Button {...buttonEvents} kind="danger"> Danger </Button> </div> )) ) .add('Set of Small Buttons', withInfo( ` Small buttons may be used when there is not enough vertical space for a regular sized button. This issue is most commonly found in tables. Small buttons should have three words or less. `, )(() => ( <div> <Button {...buttonEvents} className="enc-btn-sm"> Primary </Button> &nbsp; <Button {...buttonEvents} kind="basic" className="enc-btn-sm"> Basic </Button> &nbsp; <Button kind="success" {...buttonEvents} className="enc-btn-sm"> Success </Button> &nbsp; <Button {...buttonEvents} disabled className="enc-btn-sm"> Disabled </Button> &nbsp; <Button {...buttonEvents} kind="danger" className="enc-btn-sm"> Danger </Button> </div> )) ) .add('Set of Buttons Uppercased', withInfo( ` When an action required by the user has more than one option, always use a a negative action button (secondary) paired with a positive action button (primary) in that order. Negative action buttons will be on the left. Positive action buttons should be on the right. When these two types buttons are paired in the correct order, they will automatically space themselves apart. `, )(() => ( <div> <Button kind="primary" {...buttonEvents} className="enc-btn-uppercase"> Primary </Button> &nbsp; <Button {...buttonEvents} kind="basic" className="enc-btn-uppercase"> Basic </Button> &nbsp; <Button kind="success" {...buttonEvents} className="enc-btn-uppercase"> Success </Button> &nbsp; <Button {...buttonEvents} disabled className="enc-btn-uppercase"> Disabled </Button> &nbsp; <Button {...buttonEvents} kind="danger" className="enc-btn-uppercase"> Danger </Button> </div> )) );
const Joi = require('joi'); const aws = require('aws-sdk'); const appConfig = rootRequire('/config/app'); const awsConfig = rootRequire('/config/aws'); class RuntimeConfig { constructor(initObject) { const runtimeConfig = Object.assign({}, appConfig.defaults.runtimeConfig, initObject); Joi.assert(runtimeConfig, Joi.object({ publicId: Joi.string().allow(null), bundleId: Joi.string().allow(null), name: Joi.string().allow(null), displayName: Joi.string().allow(null), css: Joi.object().required(), })); Object.assign(this, runtimeConfig); } uploadToS3(app) { const s3 = new aws.S3(); return s3.upload({ ACL: 'public-read', Body: JSON.stringify(this), Bucket: awsConfig.s3AppsBucket, ContentType: 'application/json', Key: `${app.bundleId}/runtimeConfig.json`, }).promise(); } } module.exports = RuntimeConfig;
module.exports = { events: { GREET: 'greet', FILESAVED: 'filesaved', FILEOPENED: 'fileopened' } } //Different pattern to help with typos. Centralized all string and used property //in different places. Having a central place to keep the property
// https://www.freecodecamp.org/challenges/symmetric-difference function sym(args) { var r = []; for (var i = 0; i < arguments.length; i++){ r.push(arguments[i]); } function diff(e, f) { var vals = []; e.forEach(function(val){ if (vals.indexOf(val) === -1 && f.indexOf(val) === -1){ vals.push(val); } }); f.forEach(function(val){ if (vals.indexOf(val) === -1 && e.indexOf(val) === -1){ vals.push(val); } }); return vals; } return r.reduce(diff); } sym([1, 2, 3], [5, 2, 1, 4]);
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. // Write your JavaScript code. $(".menu-toggle").on("click", function () { $(".mobile-menu").toggleClass("hidden"); }); $(".auth-toggle").on("click", function () { $(".auth-menu").toggleClass("hidden"); }); $("#range").on("input", function () { var range = document.getElementById("range"); var val = range.value; var display = document.getElementById("range-label"); display.innerHTML = "Discount " + val * 100 + "%"; });
import classes from "./NavigationItems.module.css"; import React from "react"; import NavigationItem from "./NavigationItem/NavigationItem"; const NavigationItems = (props) => { return ( <div className={classes.NavigationItems}> <NavigationItem link="/">Home</NavigationItem> {/* <NavigationItem link="/offers">Offers</NavigationItem> */} <NavigationItem link="/gallery">Gallery</NavigationItem> <NavigationItem link="/contact">Book Now</NavigationItem> <NavigationItem link="/contact">Contact Us</NavigationItem> </div> ); }; export default NavigationItems;
import { createRouter, createWebHashHistory } from 'vue-router' import Dashboard from '../views/Dashboard.vue' const routes = [ { path: '', component: Dashboard, children: [ { path: '', component: () => import(/* webpackChunkName: "sales" */ '../views/Sales') }, { path: '/orders', component: () => import(/* webpackChunkName: "orders" */ '../views/Orders') }, { path: '/products', component: () => import(/* webpackChunkName: "products" */ '../views/Products') }, { path: '/services', component: () => import(/* webpackChunkName: "services" */ '../views/Services') }, { path: '/clients', component: () => import(/* webpackChunkName: "clients" */ '../views/Clients') } ] } ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router
import React, { useEffect, useState, useRef } from "react"; import TableReusable from "../components/Tablereusable"; import { useLocation } from "react-router-dom"; import Header from "../components/Header"; function View({ history }) { const socket = useRef(null); const [rrbf, setRrbf] = useState(null); const [callput, setCallput] = useState(null); const [rrbfhead, setRrbfhead] = useState(true); const [callputhead, setCallputhead] = useState(false); const tablelabels = [ "Time", "Expdate", "Atm", "25d R/R", "10d R/R", "25d B/F", "10d B/F", ]; useEffect(() => { async function checker() { try { console.log("in"); const data = await fetch("http://localhost:1337/", { method: "GET", }).then((t) => t.json()); setRrbf(data.rrbfdata); setCallput(data.callputdata); console.log(callput); } catch (e) { console.log(e); } } checker(); }, []); useEffect(() => { connect(); socket.current.onopen = onOpen; socket.current.onclose = onClose; socket.current.onmessage = onMessage; return () => { socket.current.close(); }; }, []); function connect() { socket.current = new WebSocket("ws://127.0.0.1:3002"); } function onOpen(e) { console.log("socket ready state", socket.current.readyState); socket.current.send( JSON.stringify({ type: "connect", }) ); } function onClose(e) {} function onMessage(e) { const data = JSON.parse(e.data); switch (data.type) { case "rrbf": setRrbf((prev) => [...prev, data]); break; case "callput": setCallput((prev) => [...prev, data]); break; default: break; } } return ( <> {callput && ( <div style={{ display: "flex", backgroundColor: "#0A1640" }}> <div style={{ width: "100%" }}> <Header /> <div style={{ display: "flex", justifyContent: "space-evenly", width: "98%", marginLeft: "1%", }} > <div onClick={() => { setRrbfhead(true); setCallputhead(false); }} style={{ backgroundColor: rrbfhead ? "#ABA8FE" : "", color: rrbfhead ? "#000" : "#fff", border: rrbfhead ? "1px solid #ABA8FE" : "0.5px solid #ddd", borderRadius: "3px 0px 0px 3px", }} className="view-header-container" > <p>RR/BF Table</p> </div> <div onClick={() => { setRrbfhead(false); setCallputhead(true); }} style={{ backgroundColor: callputhead ? "#ABA8FE" : "", color: callputhead ? "#000" : "#fff", border: callputhead ? "1px solid #ABA8FE" : "0.5px solid #ddd", }} className="view-header-container" > <p>Call/Put Table</p> </div> <div className="view-header-container"> <p>Vol Curve</p> </div> <div className="view-header-container"> <p>Vol Smile</p> </div> <div className="view-header-container" style={{ borderRadius: "0px 3px 3px 0px" }} > <p>Heatmaps</p> </div> </div> <div style={{ minHeight: "100vh", backgroundColor: "#0A1640" }}> {rrbfhead && rrbf && ( <TableReusable tablelabels={tablelabels} flag="allcontacts" tablelist={rrbf} /> )} {callputhead && callput && ( <TableReusable tablelabels={tablelabels} flag="allcontacts" tablelist={callput} /> )} </div> </div> </div> )} </> ); } export default View;
var express = require('express'); var router = express.Router(); var models = require('../models'); // 扫码加入购物车接口,前端传商品条形码code router.post('/', function (req, res, next) { var code = req.body.code; // res.json(code);return models.Product.findOne({ where: { code: code, } }).then(product => { // res.json(product);return; if (!product) { res.json({success: false, message: '此商品不存在!'}) return; } models.Cart.findOrCreate({ where: { productId: product.id, userId: req.decoded.user.id, }, defaults: { number: 1, userId: req.decoded.user.id, productId: product.id } }).spread((cart, created) => { // spread 把数组转换成对象,方便下面的取值 // res.json(!created);return; if (!created) { //如果为fasle,则说明carts表里面已经有了该商品,只需增加它的数量 models.Cart.findOne({where: {id: cart.id}}).then(cart => { cart.increment('number'); res.json({success: true, message: '添加成功'}) }) } res.json({success: true, message: '添加购物车成功', data: cart}) }) }) }); // 购物车首页,关联查出当前用户的商品信息 router.get('/', function (req, res, next) { models.Cart.findAll({ include: [ models.Product, ], where: {userId: req.decoded.user.id} }).then(cart => { // console.log(cart) let total_price = 0; let number = 0; cart.map(item => { total_price += item.number * item.Product.price; number += item.number; }); res.json({ success: true, message: '查询成功', data: cart, total: total_price, number: number, }) }) }); // 购物车数量加减,前端传增减type和购物车的id router.put('/', function (req, res, next) { let type = req.body.type; let cart_id = req.body.cart_id; models.Cart.findByPk(cart_id).then(cart => { if (type === 'inc') { cart.increment('number') return res.json({success: true, message: '修改成功'}) } if (cart.number > 1) { cart.decrement('number') return res.json({success: true, message: '修改成功'}) } cart.destroy() res.json({success: true, message: '清除成功'}) }) }); module.exports = router;
angular.module('myapp', ['ui']); function Controller($scope) { $scope.list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; }
countSpaces = function(object, row){ var count = 0 for (var i in object[row]) { if (object[row][i] === ' ') { count += 1; }; }; return count; }
import express from 'express'; import cors from 'cors'; import mongoose from 'mongoose'; import dotenv from 'dotenv'; dotenv.config(); const app = express(); // Model import User from './models/UserModel.js'; // Midilwares app.use(cors()); app.use(express.json()); const PORT = process.env.PORT; // Connecting to mongoDB mongoose .connect(process.env.MONGODB_URI) .then((result) => app.listen(PORT, () => console.log( `((: Connected to mongoDB. Server is running on port ${PORT} ` ) ) ) .catch((err) => console.log(err)); // ROUTES // GET: test app.get('/', (req, res) => res.send('API is running...')); // GET: get all users app.get('/users', async (req, res) => { try { let users = await User.find({}); if (users) { res.send(users); } } catch (err) { console.log(err); } }); // POST: create new user/ add user to db app.post('/users', async (req, res) => { if (!req.body) return res.status(400).json({ message: 'missing user input' }); const users = await User.find(); const userExists = users.some((user) => user.email === req.body.email); if (userExists) { res.json({ status: 'failed', message: 'User with provided email already exists!', }); } else { try { const user = new User(req.body); await user.save(); const users = await User.find(); res.json({ status: 'success', users: users, }); } catch (error) { console.log(error); } } }); // PUT: update user info based on id app.put('/users', async (req, res) => { try { if (!req.body) { return res.status(400).json({ message: 'missing user input' }); } // deconstucted userId from request body console.log(req.body); const { _id } = req.body; let update = req.body; // let user = await User.findById(id); await User.findOneAndUpdate({ _id: _id }, update); const users = await User.find(); res.json({ message: 'user updated', users: users }); } catch (error) { console.log(error); } }); // DELETE: Delete single user based on id app.delete('/users/:id', async (req, res) => { try { const userId = req.params.id; const deletedUser = await User.findByIdAndDelete(userId); res.json({ message: 'user deleted' }); } catch (err) { console.log(err); res.json({ message: 'delete failed' }); } });
import Component from '@ember/component'; const VISIBILITIES = [ {label: 'Everyone', name: 'public'}, {label: 'Free and paying members', name: 'members'}, {label: 'Only paying members', name: 'paid'} ]; export default Component.extend({ // public attrs post: null, init() { this._super(...arguments); this.availableVisibilities = VISIBILITIES; }, actions: { updateVisibility(newVisibility) { this.post.set('visibility', newVisibility); } } });
import axios from 'axios' export const API = new axios({ baseURL: 'http://localhost:8080/eduhubapi/v1' })
export const breakpoints = [ {name: "xs", min: 0}, {name: "lg", min: 900}, ]; export const classMap = (staticClasses, ...classes) => { for (const c of classes) if (c) staticClasses += " " + c.trim(); return [...new Set(staticClasses.split(" "))].join(" "); }; export const rad = deg => deg/180*Math.PI; export const deg = rad => rad/Math.PI*180; export const MDeg = { sin: i => Math.sin(rad(i)), cos: i => Math.cos(rad(i)), tan: i => Math.tan(rad(i)) }; export const trackFile = "tracks.json"; export const framerate = 30; export const playerSize = {w: 14.0 * 1.5, h: 8.0 * 1.5}; export const imageSize = {w: 16.0 * 1.5, h: 10.0 * 1.5}; export const debug = process.env.NODE_ENV === "development";
// import { login, register } from '@/api' import * as api from '@/api/user' export default { namespaced: true, state: { // info: JSON.parse(localStorage.getItem('user')), info: null, }, mutations: { initUserInfo: state => { try { let data = JSON.parse(localStorage.getItem('user')) state.info = data } catch (e) { throw e } }, updateUserInfo: (state, data) => { state.info = data localStorage.setItem('user', JSON.stringify(data)) }, removeUserInfo: state => { state.info = null localStorage.removeItem('user') }, }, actions: { register: ({}, data) => { return api.register(data) }, login: async ({ commit }, data) => { try { let res = await api.login(data) commit('updateUserInfo', { id: res.data.id, name: res.data.name, authorization: res.headers.authorization, }) return res } catch (e) { throw e } }, logout: async ({ commit }) => { // try { // let res = await logout() // } catch (e) { // throw e // } console.log('logou') commit('removeUserInfo') }, }, }
export const SET_USER_ANSWER = 'SET_USER_ANSWER'; export const INCREMENT_NUM_ATTEMPTS = 'INCREMENT_NUM_ATTEMPTS'; export const RESET_QUIZ = 'RESET_QUIZ';
import marked from 'marked'; export default { format, match }; function format(args, value, options) { for (let i = 0; i < options.length; i += 1) { value = value.replace(options[i], marked(args[0], { breaks: true, sanitize: true })); } return value.replace(/%/g, '%%'); } function match(value) { return typeof value === 'string' && value.match(/%md/g); }
// create our angular app and inject ngAnimate and ui-router // ============================================================================= var app = angular.module('lolInfi', ['ngAnimate','ngSanitize', 'ui.router', 'react', 'angularVideoBg']); // our controller for the form // ============================================================================= app.controller('formController', function($scope, facebookService) { // var bgImages = ['bg1.jpg', 'bg2.jpg', 'bg3.jpg']; // // var backstretchArray =[] // for(var i=0;i<bgImages.length;i++){ // backstretchArray.push("images/" + bgImages[i]) // } // // $("#homeBg").backstretch(backstretchArray, { // fade: 750, // duration: 4000 // }); $scope.config = {"searchToggle":true,"url":"HOME"}; $scope.fbLogin = {"btn": true, "image": false, "imageUrl": "", "name": ""}; /** * initialize twitch api */ Twitch.init({clientId: '3i5rtey5q5ipvmjmctz5s7lbf0m2h0g'}, function(error, status) { console.log("!!!!!twtich init called"); console.log(error+"error"); console.log(JSON.stringify(status)+"status"); if (error) { // error encountered while loading console.log(error); console.log("twitch api load fail"); } // the sdk is now loaded }); /** * get called from checkLoginState in index.html script */ $scope.statusChangeCallback = function(response) { if (response.status === 'connected') { facebookService.getFaceBookInfo().then(function(response){ $scope.fbLogin = {"btn": false, "image": true, "imageUrl": "http://graph.facebook.com/" + response.id + "/picture?type=normal", "name": response.name}; }); } else if (response.status === 'not_authorized') { } else { } }; $scope.setHome = function(){ $scope.config.searchToggle=true; $scope.config.url='HOME'; } });
var searchData= [ ['enigmes',['enigmeS',['../structenigmeS.html',1,'']]], ['ennemi',['ennemi',['../structennemi.html',1,'']]] ];
// gameSpan is needed to determine if the user won after 10 years const gameSpan = 10; // needed to pass when creating a new farmer let queryURL; let loanAmount; let loanPaymentYearly; // farmer object let farmer; // needed to get farmer object from localStorage (and then still create a new farmer to add methods) let farmerFromLocalStorage; // to start the game a new barn is purchased const barnPrice = 45000; // flag to alert the user that plants can be grown only once (for enableField() function) // let flagEnabled = false; // factories to produce animals and plants let chickenFactory; let cowFactory; let goatFactory; let sheepFactory; let potatoFactory; let cornFactory; let lettuceFactory; let broccoliFactory; // class Farmer class Farmer { constructor (loanAmount, loanPaymentYearly, weatherCoef, farmCity, queryURL, farmerAccount, earnedThisYear, yearsInBusiness, fieldEnabled) { this.barn = []; this.field = []; this.fieldEnabled = fieldEnabled || false; this.yearsInBusiness = yearsInBusiness || 0; this.loanAmount = loanAmount; this.loanPaymentYearly = loanPaymentYearly; this.farmerAccount = farmerAccount || 0; this.earnedThisYear = earnedThisYear || 0; this.farmCity = farmCity; this.tempFahrenheit = tempFahrenheit; this.weatherCoef = weatherCoef; this.queryURL = queryURL; } // function to buy animals from the store (when the animal is clicked) ui object is needed for drag-drop functionality buyAsset = (event, ui) => { // console.log('this=', this); // console.log('farmer=', farmer); // console.log('ui=', $(ui)); // console.log('event.type=', event.type); // console.log('buyasset event =', $(event).eq(0).attr('class')); // console.log('buyasset ui=', $(ui.draggable)); // console.log('buyasset ui class=', $(ui.draggable).eq(0).attr('class').match(/[a-z]+/)[0]) // console.log('buyAsset event type=', $(event)[0].type); // get class of clicked element let clickedClass; let typeOfEvent = event.type; if (typeOfEvent === 'click') { clickedClass = $(event.currentTarget).attr('class').match(/[a-z]+/)[0]; // otherwise, typeOfEvent === 'drop' } else { clickedClass = $(ui.draggable).eq(0).attr('class').match(/[a-z]+/)[0]; // console.log('dragged class=', clickedClass); // event now needs to reference ui for appendPicture() function event = ui; } // console.log('costtobuy=', chickenFactory.costToBuy); // console.log('clicked', clickedClass); // check the class of clicked picture and generate a corresponding animal or plant + append corresponding picture to the barn or to the field if (clickedClass === 'chicken') { if (chickenFactory.costToBuy <= this.farmerAccount) { chickenFactory.generateAnimal(farmer); appendPicture(event, clickedClass, typeOfEvent); // this.farmerAccount -= chickenFactory.costToBuy; } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'cow') { if (cowFactory.costToBuy <= this.farmerAccount) { cowFactory.generateAnimal(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'goat') { if (goatFactory.costToBuy <= this.farmerAccount) { goatFactory.generateAnimal(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'sheep') { if (sheepFactory.costToBuy <= this.farmerAccount) { sheepFactory.generateAnimal(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'potato') { if (potatoFactory.costToBuy <= this.farmerAccount) { potatoFactory.generatePlant(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'corn') { if (cornFactory.costToBuy <= this.farmerAccount) { cornFactory.generatePlant(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'lettuce') { if (lettuceFactory.costToBuy <= this.farmerAccount) { lettuceFactory.generatePlant(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } else if (clickedClass === 'broccoli') { if (broccoliFactory.costToBuy <= this.farmerAccount) { broccoliFactory.generatePlant(farmer); appendPicture(event, clickedClass, typeOfEvent); } else { alert('You do not have enough money in your account for the purchase'); } } // update the farmer account status after each purchase $('.farmerAccount').text(`${Math.floor(this.farmerAccount)}`); // console.log('event.currentTarget=', $(event.currentTarget).attr('class')); // const clickedImgSrc = $(event.currentTarget).attr('src'); // const $newImg = $('<img>').attr('src', clickedImgSrc); // $('.barn > .barn_field_contents').append($newImg); // console.log('farmer=', this); // chickenFactory.generateAnimal(farmer) console.log('farmer=', this); } // function to buy a barn from the borrowed money buyBarn () { alert('You bought a barn for $45000, now you can buy chikens, cows, goats or sheep and earn income each year'); this.farmerAccount = this.loanAmount - barnPrice; } // function to perform calculations when button 'Next year' is clicked nextYear = () => { // set earnedThisYear to 0 before the function runs this.earnedThisYear = 0; // calculate earnedThisYear from animals in the barn for (let animal of this.barn) { // console.log('this.barn=', this.barn); // console.log('animal.profitYearly=', animal); this.earnedThisYear += animal.profitYearly * this.weatherCoef; } // calculate earnedThisYear from plants in the field for (let plant of this.field) { this.earnedThisYear += plant.profitYearly * this.weatherCoef; } // subtract payment for the loan (loanPaymentYearly) from loanAmount this.loanAmount *= 1.04; this.loanAmount -= this.loanPaymentYearly; // add (earnedThisYear - loanPaymentYearly) to farmerAccount this.farmerAccount += this.earnedThisYear - this.loanPaymentYearly; console.log(this); // increase yearsInBusiness counter this.yearsInBusiness++; // update game statistics on the screen this.showStatistics(); $('.barn_field_contents').empty(); if (this.yearsInBusiness > 5) { enableField(); determineBarnFieldHeight(); } // remove all elements from barn and field arrays to start new year this.barn.splice(0, (this.barn).length); this.field.splice(0, (this.field).length); const endOfGame = this.didWin(); // if it is end of game localStorage needs to be cleared, else save farmer object to localStorage as a string if (endOfGame) { localStorage.clear(); } else { localStorage.setItem('farmer', JSON.stringify(farmer)); } } // function to update game statistics on the screen showStatistics = () => { $('.loan').text(`${Math.floor(this.loanAmount)}`); $('.loanPaymentYearly').text(`${Math.floor(this.loanPaymentYearly)}`) $('.earnedThisYear').text(`${this.earnedThisYear}`); $('.weatherCoef').text(`${this.weatherCoef}`); $('.farmerAccount').text(`${Math.floor(this.farmerAccount)}`); $('.yearsInBusiness').text(`${this.yearsInBusiness}`); } // function to check if the user has won // clear localStorage after alerts // in case the game ended return true, otherwise false didWin = () => { if (this.yearsInBusiness === gameSpan) { if (this.farmerAccount >= 1000000) { alert('Great job! You won! You are a retired millionaire!'); return true; } else { alert('You did not reach you goals for retirement. You have either picked the wrong place for farming or have not worked hard enough.'); return true; } } else if (this.farmerAccount < 4000) { alert('You went bankrupt! You either picked the wrong place for farming or have not worked hard enough.'); return true; } // if it is not end of game return false; } } // class FarmAsset to later construct all animals and plants the user can buy class FarmAsset { constructor (costToBuy, profitYearly) { this.costToBuy = costToBuy; this.profitYearly = profitYearly; } } // specify that the user doesn't need to buy new farm animals each year, they just produce income (to be implemented) class BarnFarmAsset extends FarmAsset { constructor(animal, costToBuy, profitYearly) { super(costToBuy, profitYearly); this.animal = animal this.needToBuyEachYear = false; } } // specify that the user needs to buy new seeds to grow plants yearly (to be implemented) class FieldFarmAsset extends FarmAsset { constructor(plant, costToBuy, profitYearly) { super(costToBuy, profitYearly); this.plant = plant; this.needToBuyEachYear = true; } } // create a factory to generate new animals class FactoryAnimal { constructor(animal, costToBuy, profitYearly, farmer) { this.animal = animal; this.costToBuy = costToBuy; this.profitYearly = profitYearly; this.animals = farmer.barn; } generateAnimal (farmer) { const newAnimal = new BarnFarmAsset(this.animal, this.costToBuy, this.profitYearly); this.animals.push(newAnimal); // when a new animal is generated, that means farmer bought it farmer.farmerAccount -= this.costToBuy; } // findAnimal (index) { // return this.animals[index]; // } } // function to generate plants class FactoryPlant { constructor(plant, costToBuy, profitYearly, farmer) { this.plant = plant; this.costToBuy = costToBuy; this.profitYearly = profitYearly; this.plants = farmer.field; } generatePlant (farmer) { const newPlant = new FieldFarmAsset(this.plant, this.costToBuy, this.profitYearly); this.plants.push(newPlant); // when a new animal is generated, that means farmer bought it farmer.farmerAccount -= this.costToBuy; } // findPlant (index) { // return this.plants[index]; // } } // get user input: loan amount const getLoanAmount = (event) => { event.preventDefault(); // const loanAmount = prompt('To start a farming business you can borrow up to $100,000 at 4% for 10 years. How much do you want to borrow?'); loanAmount = parseInt($("input[type='text']").val()); // console.log('loanAmount=', loanAmount); calculateLoanPayment(loanAmount); // return parseInt(loanAmount); $(event.currentTarget).parent().remove(); } // calculate yearly payment for your 30-year loan (4%) based on user input const calculateLoanPayment = (loanAmount) => { loanPaymentYearly = loanAmount * 0.04 * Math.pow( (1 + 0.04), gameSpan ) / ( Math.pow((1 + 0.04), gameSpan) - 1 ); // console.log('loanPaymentYearly=', Math.ceil(loanPaymentYearly)); // return loanPaymentYearly; getDataFromWeather(queryURL); } // function to append picture to barn when it is clicked in store const appendPicture = (event, clickedClass, typeOfEvent) => { console.log('appendPicture event', $(event)); let clickedImgSrc; // typeOfEvent may be either 'click' or 'drop' if (typeOfEvent === 'click') { clickedImgSrc = $(event.currentTarget).attr('src'); } else { clickedImgSrc = $(event.draggable).eq(0).attr('src'); } const $newImg = $('<img>').attr('src', clickedImgSrc); if (clickedClass === 'chicken' || clickedClass === 'cow' || clickedClass === 'goat' || clickedClass === 'sheep') { $('.barn_field_contents').eq(0).append($newImg); } else { $('.barn_field_contents').eq(1).append($newImg); } } // console.log(calculateLoanPayment(100000)); // function to set weather_coef that affects the user's income const setWeatherCoef = (tempFahrenheit) => { if (tempFahrenheit >= 60) { alert('The temperatures in the region your farm is located are too high. You will only be able to earn 80% of maximum income'); return 0.8; } else if (tempFahrenheit <= 50) { alert('The temperatures in the region your farm is located are too low. You will only be able to earn 70% of maximum income'); return 0.7; } else { alert('Your farm is located in a nice climate. You will earn maximum possible income.') return 1; } } //function to enable field after year 5 or to check if the field needs to be displayed when farmer is loaded from localStorage const enableField = () => { if (!farmer.fieldEnabled) { alert('Congrats! You have enough experience to grow plants now!'); farmer.fieldEnabled = true; $('.field').css('display', 'block'); $('.pick_crops > div').css('display', 'block'); // $('.barn_field_contents').css('height', 'calc(50vh - 1em * 1.2)'); } } // build query to send API request const buildQueryForWeather = (event) => { event.preventDefault(); // console.log('I am building query for weather API') const baseURL = "https://api.openweathermap.org/data/2.5/weather?"; const apiKEY = "APPID=9cb8c52c107e169c583442deeb0a7c0d"; // console.log($(event.currentTarget)); const cityName = $("input[type='text']").val(); // console.log('cityname=', cityName); queryURL = baseURL + 'q=' + cityName + '&' + apiKEY; // return queryURL; console.log('queryURL=', queryURL); // return getDataFromWeather(queryURL); // remove the modal to ask for user input (city) $(event.currentTarget).parent().remove(); // display the modal to ask for user input (loan amount) $('div.form_container.loan').css('display', 'flex'); }; // get data from API (weather) const getDataFromWeather = (queryURL) => { $.ajax({ url: queryURL, type: "GET", data: { } }).then((data) => { // alert("Retrieved " + data.length + " records from the dataset!"); // console.log(data); let weather = data; console.log('data from API =', weather); tempKelvin = parseInt(weather.main.temp); tempFahrenheit = (tempKelvin - 273.15) * 9/5 + 32; console.log('tempKelvin=', tempKelvin); console.log('tempFahrenheit=', tempFahrenheit); let weatherCoef = setWeatherCoef(tempFahrenheit); const farmCity = data.name; console.log('farmCity=', farmCity); // // get user input (loan amount) // let loanAmount = getLoanAmount(); // let loanPaymentYearly = calculateLoanPayment(loanAmount); // if there is no farmerFromLocalStorage object (the new game was started) if (typeof farmerFromLocalStorage === 'undefined') { // create a farmer farmer = new Farmer(loanAmount, loanPaymentYearly, weatherCoef, farmCity, queryURL); // console.log('farmer=', farmer); // notify that the user has enough money to purchase a barn for $45000 farmer.buyBarn(); // if farmerFromLocalStorage exists load all the properties (except weatherCoef that was calculated in AJAX request) } else { farmer = new Farmer(farmerFromLocalStorage.loanAmount, farmerFromLocalStorage.loanPaymentYearly, weatherCoef, farmerFromLocalStorage.farmCity, farmerFromLocalStorage.queryURL, farmerFromLocalStorage.farmerAccount, farmerFromLocalStorage.earnedThisYear, farmerFromLocalStorage.yearsInBusiness, farmerFromLocalStorage.fieldEnabled); // enable field to buy plants if farmer is more than 5 years in business if (farmer.yearsInBusiness > 5 && farmer.fieldEnabled === true) { // the line is needed to run enableField() function properly farmer.fieldEnabled = false; enableField(); determineBarnFieldHeight(); } } // create chicken, cow, goat, and sheep factory (to be able to click on corresponding picture from the store and it will be added to the barn) chickenFactory = new FactoryAnimal('chicken',4000, 6000, farmer); cowFactory = new FactoryAnimal('cow', 7000, 10500, farmer); goatFactory = new FactoryAnimal('goat', 6000, 9000, farmer); sheepFactory = new FactoryAnimal('sheep', 5000, 7500, farmer); // create potato, corn, lettuce and broccoli factory potatoFactory = new FactoryPlant('potato', 8000, 12000, farmer); cornFactory = new FactoryPlant('corn', 9000, 13500, farmer); lettuceFactory = new FactoryPlant('lettuce', 10000, 15000, farmer); broccoliFactory = new FactoryPlant('broccoli', 11000, 16500, farmer); // console.log(chickenFactory); // event listeners on all animals and plants $(".img_container > img").on("click", farmer.buyAsset); // event listener on 'next year' button $('.btn_next_year').on('click', farmer.nextYear) // event listener to resize the 'game rules' window (to make it mobile friendly) $(window).on("resize", determineBarnFieldHeight); console.log('farmer=', farmer); // return farmer; // show game statistics farmer.showStatistics(); // barnFieldHeight should be determined after farmer object is created to check if field is enabled (farmer.fieldEnabled) determineBarnFieldHeight(); }); // end of .then AJAX reguest } // end of getDataFromWeather function const onLoadFunction = () => { // console.log('onload fired'); // console.log('localStorage is empty:', localStorage.getItem('farmer') === null); const isLocalStorageEmpty = localStorage.getItem('farmer') === null; console.log('localStorage is empty:', isLocalStorageEmpty); if (isLocalStorageEmpty) { $("div.form_container.city").css("display", "flex"); } else { $("div.form_container.localStorage").css("display", "flex"); } // on load --vh needs to be set based on viewport height excluding URL bar // let windowInnerHeight = $(window).height(); // console.log('window.innerHeight=', windowInnerHeight); // $(".barn_field_contents").css("--vh", `${windowInnerHeight}px`); // console.log($(".barn_field_contents").css("--vh")); // determineBarnFieldHeight(); } // to determine .barn_field_contents fields height dinamically (on resizing the window) const determineBarnFieldHeight = () => { let windowInnerHeight = $(window).height(); let barnFieldHeaderHeight = $(".barn > p:first-child").height(); console.log("barnHeaderHeight =", barnFieldHeaderHeight); console.log('window.innerHeight=', windowInnerHeight); let heightWhenTwoFields = windowInnerHeight / 2 - barnFieldHeaderHeight; console.log('heightWhenTwoFields=', heightWhenTwoFields); if (farmer.fieldEnabled === false) { $(".barn_field_contents").css("--vh", `${windowInnerHeight}px`); } else { $(".barn_field_contents").css("--vh", `${heightWhenTwoFields}px`) } // console.log($(".barn_field_contents").css("--vh")); } const manageModalsGameStart = (event) => { event.preventDefault(); // console.log($(event.currentTarget).attr('id')); const clickedID = $(event.currentTarget).attr('id'); // if start a new game was clicked, we remove the modal from the screen and start the game (with selecting a city etc.) if (clickedID === 'start_new') { $(event.currentTarget).parent().parent().remove(); $(".city").css("display", "flex"); // otherwise, 'continue previous game' was clicked } else { // load farmer object from localStorage, parse it // assign it to 'farmer' variable farmerFromLocalStorage = JSON.parse(localStorage.getItem('farmer')); $(event.currentTarget).parent().parent().remove(); console.log(farmerFromLocalStorage); getDataFromWeather(farmerFromLocalStorage.queryURL); } } const toggleGame_info = () => { // height of container of the 'next year' button const btn_containerHeight = $(".btn_container").height(); // height of 'game rules' window let game_infoHeight = $(window).height() - btn_containerHeight; // height of 'game rules' header let headerHeight = $(".game_info > h3").height(); // console.log("calculteHeight=", game_infoHeight); // toggle 'game rules' window when clicked if ($(".game_info > div").height() === 0) { $(".right_container").css("position", "relative"); $(".game_info").css("position", "absolute").css("bottom", btn_containerHeight).css("height", `${game_infoHeight}`).css("background", "rgb(248, 163, 4)"); $(".game_info > div").css("height", `${game_infoHeight - headerHeight - btn_containerHeight}`).css("overflow", "scroll").css("cursor", "pointer"); } else { $(".right_container").css("position", "static"); $(".game_info").css("position", "static").css("bottom", "").css("height", "auto").css("background", "").css("cursor", "auto"); $(".game_info > div").css("height", "0").css("overflow", ""); } } // document onready function $( () => { // event listeners on modals displayed in the beginning of the game $(".city > form").on("submit", buildQueryForWeather); $(".loan > form").on("submit", getLoanAmount); $(".localStorage > form > input[type='submit']").on("click", manageModalsGameStart); // event listener to check if the user wants to load the previous game from localStorage or start a new one $(document).ready(onLoadFunction); // event listener to toggle 'game rules' $(".game_info").on("click", toggleGame_info); // event listeners on 'next year' button and on all animals and plants are set after farmer object is created // $('.btn_next_year').on('click', farmer.nextYear) // $(".img_container > img").on("click", farmer.buyAsset); // event listener to resize the 'game rules' window (to make it mobile friendly) // $(window).on("resize", determineBarnFieldHeight); ///////////////////////////////////////// ///////Drag and Drop Animals and Plants ///////////////////////////////////////// // // drag-drop functionality (to drag and drop animals from the store to barn or field) // make all images in the game draggable (background image is not under <img> tag). myHelper() is needed to preserve the size of the image when dragging starts. revert:true returns the image after dropping $("img").draggable({ revert: true, helper: myHelper }); function myHelper (event) { console.log('helper=', $(event.currentTarget).eq(0).css("width")); // return `<img src='${$(event.currentTarget).eq(0).attr('src')}' width='${$(event.currentTarget).eq(0).css("width")}'` // console.log(`<img src=${$(event.currentTarget).eq(0).attr("src")}> width="${$(event.currentTarget).eq(0).css("width")}" height="${$(event.currentTarget).eq(0).css("height")}"`); // return the div we want to see when the picture is dragged return `<img src=${$(event.currentTarget).eq(0).attr("src")} width=${$(event.currentTarget).eq(0).css("width")} height=${$(event.currentTarget).eq(0).css("height")}>`; } // make tow divs with class .barn_field_contents droppable $(".barn_field_contents").droppable({ drop: handleDropEvent }) // we want to invoke buyAsset() and pass it both arguments $(event.currentTarget) - droppable object, and $(ui.draggable) - draggable object function handleDropEvent (event, ui) { // console.log('handLeDrop event=', $(event)); // console.log('ui.draggable=', $(ui.draggable).attr("class")); return farmer.buyAsset(event, ui); } }) // end of document onready function // used in conjunction with accordion() // // event listener to close the game rules when clicking outside // $(document).on('click', function(e) { // if (!$(e.target).is('.container')) { // $('.ui-accordion-content').hide(); // } // $(document).off('click'); // }); // $( function() { // let icons = { // header: "ui-icon-circle-arrow-e", // activeHeader: "ui-icon-circle-arrow-s" // }; // $(".game_info").accordion({ // icons: icons, // collapsible: true // }); // }); // get user input (city name) // const queryURL = buildQueryForWeather(); // get weather data from the API // getDataFromWeather(queryURL); /////////////////////////// // erase if it doesn't work /////////////////////////// ////////////////////////////// // // create chicken, cow, goat, and sheep factory (to be able to click on corresponding picture from the store and it will be added to the barn) // const chickenFactory = new Factory('chicken',4000, 14000, farmer); // const cowFactory = new Factory('cow', 7000, 17000, farmer); // const goatFactory = new Factory('goat', 6000, 16000, farmer); // const sheepFactory = new Factory('sheep', 5000, 15000, farmer); // console.log(chickenFactory); // // get user input (loan amount) // let loanAmount = getLoanAmount(); // let loanPaymentYearly = calculateLoanPayment(loanAmount); // // create a farmer // const farmer = new Farmer(loanAmount, loanPaymentYearly); // // console.log('farmer=', farmer); // // notify that the user has enough money to purchase a barn for $45000 // farmer.buyBarn(); // console.log('farmer=', farmer); // // create chicken, cow, goat, and sheep factory (to be able to click on corresponding picture from the store and it will be added to the barn) // const chickenFactory = new Factory('chicken',4000, 14000, farmer); // const cowFactory = new Factory('cow', 7000, 17000, farmer); // const goatFactory = new Factory('goat', 6000, 16000, farmer); // const sheepFactory = new Factory('sheep', 5000, 15000, farmer); // console.log(chickenFactory); // console.log($('.barn').css('line-height')); // $('.img_container > .chicken').on('click', farmer.buyAsset); // $('.img_container > .cow').on('click', farmer.buyAsset); // $('.img_container > .goat').on('click', farmer.buyAsset); // $('.img_container > .sheep').on('click', farmer.buyAsset); // $('.btn_next_year').on('click', farmer.nextYear) // chickenFactory.generateAnimal(); // chickenFactory.generateAnimal(); // console.log('farmer=', farmer); // console.log(chickenFactory); // (event) => { // // get clicked image src attribute // const clickedImgSrc = $(event.currentTarget).attr('src'); // // console.log(clickedImgSrc); // // create new img tag with clicked image source attribute // const $newImg = $('<img>').attr('src', clickedImgSrc); // // console.log($newImg); // // append newImg to barn // $('.barn > .barn_field_contents').append($newImg); // // generate a new chicken belonging to the farmer // chickenFactory.generateAnimal(farmer); // console.log('farmer=', farmer); // } // Example of API response: // {"coord": // {"lon":145.77,"lat":-16.92}, // "weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}], // "base":"cmc stations", // "main":{"temp":293.25,"pressure":1019,"humidity":83,"temp_min":289.82,"temp_max":295.37}, // "wind":{"speed":5.1,"deg":150}, // "clouds":{"all":75}, // "rain":{"3h":3}, // "dt":1435658272, // "sys":{"type":1,"id":8166,"message":0.0166,"country":"AU","sunrise":1435610796,"sunset":1435650870}, // "id":2172797, // "name":"Cairns", // "cod":200} // Pseudocode
/** * @author Sven Koelpin */ const yup = require('yup'); const validate = async ({shape, what, req, res, next}) => { try { const toValidate = req[what]; const validated = await yup.object().shape(shape).validate(toValidate, {stripUnknown: true, abortEarly: false}); Object.assign(req, { [what]: validated, [`orig${what}`]: toValidate, }); next(); } catch (validationErrors) { const allErrors = validationErrors.inner.reduce((errors, currentValidation) => Object.assign(errors, { [currentValidation.path]: currentValidation.errors[0], //first error is enough for this demo }), {}); res.send(400, allErrors); } }; const validateQueryParams = shape => (req, res, next) => { validate({what: 'query', shape, req, res, next}); }; const validatePostBody = shape => (req, res, next) => { validate({what: 'body', shape, req, res, next}); }; module.exports = {validatePostBody, validateQueryParams};
/* eslint-disable no-undef */ import Polygon from '../src/polygon'; import Vec2 from '../src/vec2'; test('flip triangle points order if it is clockwise', () => { const triangle = new Polygon([new Vec2(2, 1), new Vec2(1, 4), new Vec2(4, 5)]); expect(triangle) .toEqual( new Polygon([new Vec2(4, 5), new Vec2(1, 4), new Vec2(2, 1)]), ); triangle.makeAntiClockwise(); expect(triangle).toEqual( new Polygon([new Vec2(4, 5), new Vec2(1, 4), new Vec2(2, 1)]), ); }); test('flip quadrilateral points order if it is clockwise', () => { const quadrilateral = new Polygon([ new Vec2(2, 1), new Vec2(1, 4), new Vec2(2, 6), new Vec2(4, 5), ]); expect(quadrilateral) .toEqual( new Polygon([ new Vec2(4, 5), new Vec2(2, 6), new Vec2(1, 4), new Vec2(2, 1), ]), ); quadrilateral.makeAntiClockwise(); expect(quadrilateral).toEqual( new Polygon([ new Vec2(4, 5), new Vec2(2, 6), new Vec2(1, 4), new Vec2(2, 1), ]), ); }); test('flip square points order if it is clockwise', () => { const quadrilateral = new Polygon([ new Vec2(-1, -1), new Vec2(-1, 1), new Vec2(1, 1), new Vec2(1, -1), ]); expect(quadrilateral) .toEqual(new Polygon([ new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1), new Vec2(-1, -1), ])); quadrilateral.makeAntiClockwise(); expect(quadrilateral).toEqual(new Polygon([ new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1), new Vec2(-1, -1), ])); }); test('flip pentagon points order if it is clockwise', () => { const quadrilateral = new Polygon([ new Vec2(2, 1), new Vec2(1, 4), new Vec2(-6, 5), new Vec2(2, 6), new Vec2(4, 5)]); expect(quadrilateral) .toEqual( new Polygon([ new Vec2(4, 5), new Vec2(2, 6), new Vec2(-6, 5), new Vec2(1, 4), new Vec2(2, 1)]), ); quadrilateral.makeAntiClockwise(); expect(quadrilateral).toEqual( new Polygon([ new Vec2(4, 5), new Vec2(2, 6), new Vec2(-6, 5), new Vec2(1, 4), new Vec2(2, 1)]), ); }); test('flip points of clockwise order polygon', () => { const points = [...Array(100).keys()].map( (num) => Vec2.fromAngle((Math.PI * 2 * num) / 100), ).reverse(); expect(new Polygon(points)).toEqual(new Polygon(points.reverse())); }); test('returns the correct side vector', () => { const triangle = new Polygon([new Vec2(4, 5), new Vec2(1, 4), new Vec2(2, 1)]); expect(triangle.getSideVector(0)).toEqual(new Vec2(-3, -1)); expect(triangle.getSideVector(1)).toEqual(new Vec2(1, -3)); expect(triangle.getSideVector(2)).toEqual(new Vec2(2, 4)); expect(triangle.getSideVector(3)).toEqual(new Vec2(-3, -1)); expect(triangle.getSideVector(-1)).toEqual(new Vec2(2, 4)); }); test('throw error if number of points is not enough', () => { const createPolygon = (points) => () => new Polygon(points); expect(createPolygon([])).toThrow(); expect(createPolygon([new Vec2(1, 1)])).toThrow(); expect(createPolygon([new Vec2(1, 1), new Vec2(2, 2)])).toThrow(); expect(createPolygon([ new Vec2(1, 1), new Vec2(2, 2), new Vec2(3, 1), ])).not.toThrow(); }); test('right intersection for different polygon orientations', () => { const square1 = new Polygon([ new Vec2(-1, -1), new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1), ]); const poly2 = new Polygon([ new Vec2(-12, -14), new Vec2(16, -12), new Vec2(12, 18), new Vec2(-13, 18), ]); const poly3 = new Polygon([ new Vec2(-12, -14), new Vec2(-16, -12), new Vec2(-12, -18), new Vec2(-13, -18), ]); const poly4 = new Polygon([ new Vec2(1, 2), new Vec2(4, 2), new Vec2(4, 3), new Vec2(1, 3), ]); const poly5 = new Polygon([ new Vec2(2, -1), new Vec2(3, -1), new Vec2(3, 5), new Vec2(2, 5), ]); const poly6 = new Polygon([ new Vec2(2, 3), new Vec2(3, 3), new Vec2(3, 2), new Vec2(2, 2), ].reverse()); const poly7 = new Polygon([ new Vec2(-2, 3), new Vec2(2, 3), new Vec2(2, -3), new Vec2(-2, -3), ]); const poly8 = new Polygon([ new Vec2(-1, -1), new Vec2(-1, -5), new Vec2(-5, -5), new Vec2(-5, -1), ]); const poly9 = new Polygon([ new Vec2(-1, -3), new Vec2(-2, -3), new Vec2(-2, -1), new Vec2(-1, -1), ]); const poly10 = new Polygon([ new Vec2(0, 0), new Vec2(4, 0), new Vec2(4, 4), new Vec2(0, 4), ]); const poly11 = new Polygon([ new Vec2(-2, 1), new Vec2(2, 1), new Vec2(2, 3), new Vec2(-2, 3), ]); const poly12 = new Polygon([ new Vec2(2, 1), new Vec2(2, 3), new Vec2(0, 3), new Vec2(0, 1), ]); expect(Polygon.intersection(square1, poly2)).toEqual(square1); expect(Polygon.intersection(square1, poly3)).toBe(undefined); expect(Polygon.intersection(poly4, poly5)).toEqual(poly6); expect(Polygon.intersection(poly7, poly8)).toEqual(poly9); expect(Polygon.intersection(poly10, poly11)).toEqual(poly12); }); test('fractures the plane well', () => { const fractures = Polygon.fracture([ new Vec2(0, 0.4), new Vec2(-2.2, 0.3), new Vec2(2.5, 0.01), new Vec2(0.1, 2.2), new Vec2(0, -2.32), ]); });
//First Problem function feetToMile(ft){ var ft; if( ft >0 ) { // 1 Feet = 0.00018939 miles var convertFeetToMile = ft * 0.00018939; return convertFeetToMile; } else{ return " Please Enter the Correct Number" } } //Second Problem function woodCalculator(chair,table,bed){ if ( chair > 0 && table > 0 && bed > 0){ var chair = 1 * chair; var table = 3 * table; var bed = 5 * bed; var calculateWood = chair + table + bed; return calculateWood; }else{ return "Please Enter the correct Number" } } //Third Problem function brickCalculator(floor){ const brick =1000; if(floor <= 10){ var numberOfBrick = 15 * brick * floor; return numberOfBrick; }else if(floor <= 20){ numberOfBrick = (15 * 1000 * 10) + (12*1000 *(floor - 10)); // (15 * 1000 * 10)=150000, 1 to 10th floor brick return numberOfBrick; }else{ numberOfBrick = (15 * 1000 * 10) + (12 * 1000 * 10) + (10*1000 *(floor - 20)); // (15 * 1000 * 10) + (12 * 1000 * 10) = 1 to 10th floor brick and 10th to 20th floor brick return numberOfBrick; } } // Fourth problem function tinyFriend(names){ var shortestName = names[0]; for(var i=0; i<names.length;i++){ var currentName = names[i]; currentName=currentName.trim(); // trim() function Remove the space. if(currentName.length < shortestName.length) { shortestName=currentName; } } return shortestName; }
var lodash=require('lodash')/* lodash是一个函数的类库 */ function reducer(state=[],action){ switch(action.type){ case 'ADD_TO_CART': var pos=lodash.findIndex(state,{id:action.payload.id}); if(pos !== -1){ state[pos].quantity = state[pos].quantity+1; return [...state] }else{ action.payload.quantity = 1; return [...state,action.payload] } return state; case 'DELETEPRO': state.splice(action.payload,1) return [...state]; case 'CHANGEQ': state[action.payload[0]].quantity=action.payload[1]; return [...state] default: return state; } } export default reducer;
const hbs = require('express-hbs'); // HBS // return name enterprise hbs.registerHelper('name_enterprise', () => process.env.NAME_ENTERPRISE); // return anio hbs.registerHelper('anio', () => new Date().getFullYear()); // return month hbs.registerHelper('month', () => new Date().getMonth() + 1); // return day hbs.registerHelper('day', () => new Date().getDate()); // return tru if user is admin hbs.registerHelper('admin', (role) => (role === 'ADMIN_ROLE') ? true : false);
var gulp = require('gulp'), open = require('gulp-open'), connect = require('gulp-connect'), babel = require('gulp-babel'); gulp.task('babel', function () { return gulp.src('src/es6practice.js') .pipe(babel()) .pipe(gulp.dest('dist')); }); gulp.task('open', function(){ var options = { url: 'http://localhost:3000' }; //When this page launches it goes to a selection page - select the file gulp.src('./index.html') .pipe(open('',options)); }); gulp.task('connect', function() { connect.server({ // root: 'src', // root: './', port: 3000, livereload: true }); }); gulp.task('html', function () { //This actually loads the file only if it's first selected on open. //WTF // gulp.src('./src/Portfolio.html') // .pipe(connect.reload()); gulp.src('./index.html') .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch(['src/**.js', './index.html' ], [ 'babel', 'html']); // gulp.watch(['src/challenges.js'], [ 'babel', 'html']); // gulp.watch(['./index.html'], [ 'babel', 'html']); }); gulp.task('default', [ 'babel', 'connect', 'open', 'watch']); gulp.task('build', [ 'babel']);
const url = new URLSearchParams(location.search); const id = url.get('gameid'); function handleFormSubmit(form) { //this loop goes through each element of the form and adds the information to an object const formDataObj = {}; for (let element of form.elements) { if (element.id) { formDataObj[element.id] = element.value; } } const formDataString = JSON.stringify(formDataObj); const xhr = new XMLHttpRequest(); //this section of code sends an api call to the database with the information provided in the form xhr.onload = () => { console.log('load success'); location.href = "DisplayGames.html"; }; xhr.open('PUT', "http://34.89.59.112:9000/Games/" + id); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(formDataString); return false; } function displayGames() { location.href = "DisplayGames.html"; }
class ElearningConst { close = 'close'; } export const CATEGORY = { HEADING: 'Category Management', SUBHEADING: 'Category', ACTIONS: { GET: 'GET', MANAGE: 'MANAGE', ERROR: 'ERROR' }, TYPE: { ADD: 'ADD', EDIT: 'EDIT', DELETE: 'DELETE' }, EMPTY_MSG: 'Please Enter Category Name', DELETE_MSG: 'Are You Sure You Want to Delete this Category?', DASHBOARD_TYPE: { STUDENT: 'STUDENT', TEACHER: 'TEACHER' } }; export const TEACHER_DASHBOARD_LINKS = [ { name: 'Dashboard', link: '/teacher', icon: 'fa fa-tachometer', title: 'Dashboard', style: { marginLeft: '5px' } }, { name: 'Video', link: '/videos', icon: 'fa fa-video-camera', title: 'Video', style: { marginLeft: '5px' } }, { name: 'My Request', link: '/notification', icon: 'fa fa-bell', title: 'My Request', style: { marginLeft: '5px' } }, { name: 'Blog-List', link: '/blog/list', icon: 'fa fa-newspaper-o', title: 'Blog List', style: { marginLeft: '5px' } } ]; export const STUDENT_DASHBOARD_LINKS = [ { name: 'Dashboard', link: '/student', icon: 'fa fa-graduation-cap', title: 'Dashboard', style: { marginLeft: '5px' } }, { name: 'Teacher', link: '/student/teacher', icon: 'fa fa-search', title: 'Teacher', style: { marginLeft: '5px' } }, { name: 'My Request', link: '/notification', icon: 'fa fa-bell', title: 'My Request', style: { marginLeft: '5px' } }, { name: 'Video', link: '/videos', icon: 'fa fa-play', title: 'Videos', style: { marginLeft: '5px' } }, { name: 'Blog-List', link: '/blog/list', icon: 'fa fa-newspaper-o', title: 'Blog List', style: { marginLeft: '5px' } } ]; export const VIDEO_TABS = { teacher: [ { id: 'pendingreview', name: 'Pending' }, { id: 'reviewed', name: 'Reviewed' }, { id: 'myvideo', name: 'My Video' } ], student: [ { id: 'pendingreview', name: 'Pending' }, { id: 'reviewed', name: 'Reviewed' }, { id: 'rejected', name: 'Rejected' } ] }; export const COLOR = ['primary','secondary','success','danger','warning','info','dark','light'] export default ElearningConst;
/** * Created by wert on 20.04.16. */ 'use strict'; const expect = require('chai').expect, flatten = require('../src/flatten'); describe("flatten", () => { it('should convert keys to arrays with one item for plain objects', () => { const input = { name: "John", age: 30 }; const output = flatten(input); expect(output).to.be.deep.equal({ ['name']: input.name, ['age']: input.age }); }); it('should convert keys to arrays with one item for plain objects with dates', () => { const input = { name: "John", age: 30, now: new Date() }; const output = flatten(input); expect(output).to.be.deep.equal({ ['name']: input.name, ['age']: input.age, ['now']: input.now }); }); });
$showArea.mousedown(function(e){ var position = $(this).position(); divLeft = parseInt(position.left); divTop = parseInt(position.top); InitialX = e.pageX; InitialY = e.pageY; $(document).mousemove(function(event){ divLeft = event.pageX-InitialX; divTop = event.pageY-InitialY; //判断是否超出父容器 if(divLeft >= ($controlMap.width()-$showArea.width())){ $showArea.css({ "top":divTop+"px" }) }else if(divTop >= ($controlMap.height()-$showArea.height())){ $showArea.css({ "left":divLeft+"px" }) }else{ $showArea.css({ "top":divTop+"px", "left":divLeft+"px" }) } console.log("event.pageX:"+event.pageX+"--------"+"event.pageY:"+event.pageY) console.log("InitialX:"+InitialX+"--------"+"InitialY:"+InitialY) console.log("divLeft:"+divLeft+"--------"+"divTop:"+divTop) }) }); $(document).mouseup(function() { $(document).unbind('mousemove'); });
import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'http://localhost:3693', namespace: 'api', defaultSerializer: 'JSONSerializer' });
const mongoose = require('mongoose'); const aleUsersSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, isTwoAuth: { type: Boolean, required: true }, twoAuthRecovery: { type: String, required: false }, walletsList: { type: Array, required: false }, rating: { type: Number, required: true }, competence: { type: Array, required: false }, change_token: { type: String, required: false }, email_token: { type: String, required: false }, disabled_wallets: { type: Array, required: false }, lastUpdatedPassword: { type: Number, required: false }, avatar: { type: String, required: false }, __v: { type: Number, select: false } }); module.exports = mongoose.model('Aleusers', aleUsersSchema);
import React from 'react' function SearchBeer (props) { let searchHandler = (event) => { let currentInputValue = event.target.value props.onSearchCallBack(event) } return ( <div> <input type="text" value={props.currentSearchTerm} onChange={searchHandler} /> </div> ) } export default SearchBeer
"use strict"; var multiparty = require('multiparty'); var gm = require('gm'); var fs = require('fs'); var _ = require('lodash'); module.exports = function _callee(req, res) { var form; return regeneratorRuntime.async(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: form = new multiparty.Form(); res.set('Content-Type', 'image/jpeg'); form.parse(req, function (err, fields, files) { if (_.has(files, 'file[0].pathname')) { var s = fs.createReadStream('./pdf_thumbnail.png'); s.on('open', function () { req.set('Content-Type', 'image/png'); s.pipe(res); }); s.on('error', function () { res.set('Content-Type', 'text/plain'); res.status(500).end({ message: 'Pdf failed' }); }); } else { res.set('Content-Type', 'text/plain'); res.status(500).end({ message: 'Data not sent in proper format, should be multipaprty form with field: file' }); } }); case 3: case "end": return _context.stop(); } } }); };
import React, {Component} from 'react'; import { Link } from 'react-router-dom'; import { connect } from "react-redux"; import ArticlesList from '../Components/ArticlesList'; // import articleContent from './article-content'; import { getData } from "../actions/index"; class ArticlesListPage extends Component { componentDidMount() { // calling the new action creator this.props.getData(); } render() { return ( <> <h1>Articles List</h1> <Link title="Add New" to="/article/add" >Add New</Link> <ArticlesList articles={this.props.articleContent} num={80} ></ArticlesList> </> ) } } function mapStateToProps(state) { return { articleContent: state.remoteArticles }; } export default connect( mapStateToProps, { getData } )(ArticlesListPage);
import React, { Component } from 'react'; import { View, StyleSheet } from 'react-native'; import { connect } from 'react-redux'; import { Navigation } from 'react-native-navigation'; import InputField from '../../common/InputField'; import { ShowList } from './ShowList/index'; import { ChangeViewButton } from './ChangeViewButton/index'; import { TRAILER_VIEW } from '../../../utils/constants'; import { fetchTvShows, tvShowsFetched, trailersFetched, getTvShowsTrailer, } from "../../../actions/index"; class SearchTvShowsView extends Component { constructor(props) { super(props); this.state = { itemNumbersByLine: 1 } } changeView = () => { this.setState( state => { return { itemNumbersByLine: state.itemNumbersByLine === 1 ? 2 : 1 } }) } componentWillUnmount() { this.props.tvShowsFetched([]) } onPress = id => { this.props.getTvShowsTrailer(id); Navigation.push(this.props.componentId, { component: { name: TRAILER_VIEW, options: { topBar: { title: { text: 'Trailer' } } } } }); }; onChangeText = text => { this.props.fetchTvShows(text) }; render() { const { tvShows } = this.props; const { itemNumbersByLine } = this.state; return ( <View style={styles.wrapperStyle}> <InputField onChangeText={this.onChangeText} placeholder='Type to search TV Shows...' /> <ChangeViewButton itemNumbersByLine={itemNumbersByLine} changeView={this.changeView} /> <ShowList tvShows={tvShows} onPress={this.onPress} itemNumbersByLine={itemNumbersByLine} /> </View> ) } } const styles = StyleSheet.create({ wrapperStyle: { flex: 1 } }); const stateToProps = ( {tvShows} ) => ({tvShows}); export default connect(stateToProps, {fetchTvShows, getTvShowsTrailer, trailersFetched, tvShowsFetched})(SearchTvShowsView)