text
stringlengths
7
3.69M
function elMayor (a,b){ if(a>b){ console.log("El mayor es %s", a); } else if(b>a){ console.log("El mayor es %s", b); } else{ console.log("Los dos números son iguales"); } } elMayor (25,3);
const express = require('express') const multer = require('multer') const router = express.Router() const MenuItem = require('../models/menu_items') const Menu = require('../models/menu') const upload = require('../Utils/fileUpload') //** Create Menu Item router.post('/api/menu_items', upload.file_s3, async (req, res) => { const req_body = Object.keys(req.body) const allowedValues = ['name', 'description', 'price', 'image', 'menu_id'] const isAllowed = req_body.filter((value) => allowedValues.indexOf(value) == -1) if (isAllowed != "") return res.status(400).send({ error: `Invalid field(s) ${isAllowed} in request` }) if (req_body.includes('menu_id')) { const isArr = Object.prototype.toString.call(req.body['menu_id']) == '[object Array]'; if (!isArr) return res.status(400).send({ error: 'menu_id should be an array of strings' }) req.body['menu_id'].forEach(async (element) => { let isMenu = [] const menu = await Menu.findOne({ _id: element }) if (menu == null) isMenu.push(element) if (isMenu.length != 0) { return res.status(400).send({ error: `There are no mathcing records for menu_id(s) ${isMenu}` }) } }); } // ** for api create without images. application/json if (req.headers['content-type'] === 'application/json') { try { if (req_body.includes('image')) return res.status(400).send({ error: 'Unable to create menu item. Use multipart/form-data request to create menu item with images' }) const menuItem = await (new MenuItem(req.body)).save() res.status(201).send(menuItem) } catch (error) { console.log(error) res.status(500).send({ error }) } } else { try { if (req.file == undefined) { const menuitem = new MenuItem(req.body) const menuItem = await menuitem.save() return res.send(menuItem) } const path = req.file.location const menu = new MenuItem({ ...req.body, image: path }) const menuItem = await menu.save() res.send(menuItem) } catch (error) { res.status(500).send({ error }) } } }) // ** Get Menu Item(s) router.get('/api/menu_items', async (req, res) => { try { const menuItems = await MenuItem.find() if (menuItems.length == 0) return res.status(404).send({ message: 'No menu items found' }) res.status(200).send(menuItems) } catch (error) { console.log(error) res.status(500).send(error) } }) router.get('/api/menu_items/:id', async (req, res) => { try { const menuItem = await MenuItem.findOne({ _id: req.params.id }) if (!menuItem) return res.status(404).send({ message: 'The menu item does not exist' }) res.status(200).send(menuItem) } catch (error) { console.log(error) res.status(500).send(error) } }) // ** update menu item router.put('/api/menu_items/:id', async (req, res) => { try { const req_body = Object.keys(req.body) const allowedValues = ['name', 'description', 'price', 'image', 'menu_id'] const isAllowed = req_body.filter((value) => allowedValues.indexOf(value) == -1) if (isAllowed != "") return res.status(400).send({ error: `Invalid field(s) ${isAllowed} in request` }) if (req_body.includes('menu_id')) { const isArr = Object.prototype.toString.call(req.body['menu_id']) == '[object Array]'; if (!isArr) return res.status(400).send({ error: 'menu_id should be an array of strings' }) } req.body['menu_id'].forEach(async (element) => { let isMenu = [] const menu = await Menu.findOne({ _id: element }) if (menu == null) isMenu.push(element) if (isMenu.length != 0) { return res.status(400).send({ error: `There are no mathcing records for menu_id(s) ${isMenu}` }) } }); const menuItem = await MenuItem.findOneAndUpdate({ _id: req.params.id }, { $set: req.body }, { new: true, runValidators: true }) if (!menuItem) return res.status(404).send({ message: 'The menu item you are trying to update does not exist' }) res.status(200).send(menuItem) } catch (error) { res.status(500).send(error) } }) // ** delete menu item router.delete('/api/menu_items/:id', async (req, res) => { try { const menuItem = await MenuItem.findOneAndDelete({ _id: req.params.id }) if (!menuItem) return res.status(404).send({ message: 'The menu item that you are trying to delete does not exist' }) res.status(204).send('No Content') } catch (error) { res.status(500).send(error) } }) module.exports = router
const mongoose = require("mongoose"); const Student = mongoose.model("Students"); // api/students/ // api/students/1537 // api/students/1537/addresses // api/students/1537/addresses/1123 module.exports.studentsGetAll = function(req, res){ Student.find().exec(function(err, students){ if(err){ res.status(500).json(err); }else { res.status(200).json(students) } }) } module.exports.studentsGetOne = function(req, res){ const studentId = req.params.studentId; Student.findById(studentId).exec(function(err, student){ console.log(student); if(err){ res.status(500).json(err); }else if(!student){ res.status(404).json({"message": "Student not found"}); }else { res.status(200).json(student); } }) } module.exports.studentsAddOne = function(req, res){ console.log("POST to add game"); if(req.body && req.body.name && req.body.gpa){ Student.create({ name: req.body.name, gpa : req.body.gpa, address : [ { street : req.body.street, city : req.body.city, state : req.body.status, zip : req.body.zip, buildingNo : req.body.buildingNo } ] }, function(err, student){ const response = { status : 201, message : student } if(err){ response.status = 400; response.message = err } res.status(response.status).json(response.message); }) }else { res.status(400).json({error: "Required data missing from POST"}) } } module.exports.studentsUpdateOne = function(req, res){ const stuendtId = req.params.studentId; Student.findById(stuendtId).exec(function(err, student){ const response = { status: 204, message: student } if(err){ response.status = 500; response.message = err }else if(!student){ response.status = 404; response.message = {"message": "Student ID not found"}; } if(response.status != 204){ res.status(response.status).json(response.message); }else { student.name = req.body.name; student.gpa = req.body.gpa; student.save(function(err, updatedStudent){ response.message = updatedStudent; if(err){ response.status = 500; response.message = err; } res.status(response.status).json(response.message); }); } }); } module.exports.studentsDeleteOne = function(req, res){ const studentId = req.params.studentId; Student.findByIdAndRemove(studentId).exec(function(err, deletedStudent){ const response = { status : 204, message : deletedStudent } if(err){ response.status = 500; response.message = err; }else if(!deletedStudent){ response.status = 404; response.message = {"message": "Student ID not found"}; } res.status(response.status).json(response.message); }) }
var mongoose = require('mongoose'); var Schema = mongoose.Schema, ObjectId = Schema.Schema; var Posts = new Schema({ Comment_ID : String, Comments:String }); module.exports = mongoose.model("Posts",Posts);
(function () { 'use strict'; angular.module('category') .controller('CategoryController', CategoryController); /* ngInject()*/ function CategoryController($mdSidenav, Tweet, Category, $mdDialog) { var vm = this; vm.categories = []; vm.selectedCategory = ''; vm.selectedCategoryId = ''; vm.toggleLeft = buildToggler('left'); vm.close = close; vm.deleteTweetFromCategory = deleteTweetFromCategory; vm.selectTweetByCategory = selectTweetByCategory; vm.addCategory = addCategory; vm.editCategory = editCategory; vm.deleteCategory = deleteCategory; prepareCategory(); //==================================== function deleteTweetFromCategory(tweetId) { Tweet.removeCategoryFromTweet(tweetId, vm.selectedCategoryId); vm.tweets = Tweet.getByCategoryId(vm.selectedCategoryId); } function addCategory() { $mdDialog.show({ controller: 'CategoryDetailsController', controllerAs: 'vm', templateUrl: 'main/category/category-details/category.details.tpl.html', parent: angular.element(document.body), locals: { category: {}, mode: 'add' }, clickOutsideToClose: false }) .then(function (resp) { var category = Category.add(resp.name); if (category) { vm.categories.push(category); } }); } function editCategory(category) { var curCategory = {}; angular.copy(category, curCategory); $mdDialog.show({ controller: 'CategoryDetailsController', controllerAs: 'vm', templateUrl: 'main/category/category-details/category.details.tpl.html', parent: angular.element(document.body), locals: { category: curCategory, mode: 'update' }, clickOutsideToClose: false }) .then(function (item) { Category.update(item); angular.copy(item, category); }); } function deleteCategory(categoryId, index) { var confirm = $mdDialog.confirm() .title('Would you like to delete your category?') .textContent('All information will be lost') .ok('Please do it!') .cancel('Cancel'); $mdDialog.show(confirm).then(function () { Category.deleteItem(categoryId); vm.categories.splice(index, 1); if (categoryId === vm.selectedCategoryId) { vm.selectedCategory = ''; vm.selectedCategoryId = ''; vm.tweets = []; } }); } function selectTweetByCategory(item) { vm.selectedCategory = item.name; vm.selectedCategoryId = item.id; vm.tweets = Tweet.getByCategoryId(item.id); $mdSidenav('left').close(); } function prepareCategory() { var curList = Category.getList(); angular.copy(curList, vm.categories); } function close() { $mdSidenav('left').close(); } function buildToggler(navID) { return function () { $mdSidenav(navID).toggle(); } } } })();
import React from "react" import "./partnerClubCard.css"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faLinkedin, faFacebook, faDiscord, faInstagramSquare } from "@fortawesome/free-brands-svg-icons" import {faGlobe} from "@fortawesome/free-solid-svg-icons" export default class PartnerClubCard extends React.Component { render() { var insta = ""; try {insta = this.props.insta} catch {} var facebook = ""; try {facebook = this.props.facebook} catch {} var discord = ""; try {discord = this.props.discord} catch {} var linkedin = ""; try {linkedin = this.props.linkedin} catch {} var website = ""; try {website = this.props.website} catch {} var linksArr = []; if (insta) { linksArr.push(<a key="1" target="_blank" rel="noopener noreferrer" href={insta}> <FontAwesomeIcon icon={faInstagramSquare} className="club-link-icon"/></a>); } if (facebook) { linksArr.push(<a key="2" target="_blank" rel="noopener noreferrer" href={facebook}> <FontAwesomeIcon icon={faFacebook} className="club-link-icon"/></a>); } if (discord) { linksArr.push(<a key="3" target="_blank" rel="noopener noreferrer" href={discord}> <FontAwesomeIcon icon={faDiscord} className="club-link-icon"/></a>); } if (linkedin) { linksArr.push(<a key="4" target="_blank" rel="noopener noreferrer" href={linkedin}> <FontAwesomeIcon icon={faLinkedin} className="club-link-icon"/></a>); } if (website) { linksArr.push(<a key="5" target="_blank" rel="noopener noreferrer" href={website}> <FontAwesomeIcon icon={faGlobe} className="club-link-icon"/></a>); } return( <div className="club-card-body"> <img src={this.props.pfpLink} alt="" className="club-pfp"></img> <div className="club-card-links"> {linksArr} </div> </div> ); } }
import React from "react"; import PropTypes from 'prop-types'; import { GridPropTypes } from './types'; export default function NoRecordsFound(props) { const { noRecordsFoundText, noRecordsRowClass, columnCount } = props; return ( <thead> <tr className={noRecordsRowClass}> <td colSpan={columnCount}>{noRecordsFoundText}</td> </tr> </thead> ); } NoRecordsFound.propTypes = { noRecordsRowClass: GridPropTypes.noRecordsRowClass, noRecordsFoundText: GridPropTypes.noRecordsFoundText, columnCount: PropTypes.number, }; NoRecordsFound.defaultProps = { columnCount: 1, noRecordsRowClass: "", noRecordsFoundText: "No records found", };
$(document).ready(function () { function limpiar() { }; });
import React from "react"; import fireApp from "../fire.js"; export function siteMessage(messageObj) { const ref = fireApp.firestore().collection("messages"); const newMessage = ref .add(messageObj) .then(newRef => console.log("newref added ", newRef)); }
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import store from '../store/index.js' import Profile from '../components/Member/Profile.vue' import Cart from '../components/Member/Cart.vue' import Privacy from '../components/Member/Privacy.vue' import Track from '../components/Member/Track.vue' import Message from '../components/Manager/Message.vue' import Article from '../components/Manager/Article.vue' import Display from '../components/Manager/Display.vue' import Membership from '../components/Manager/Membership.vue' import Order from '../components/Manager/Order.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home, meta: { login: false, title: '映筑香菇農場' } }, { path: '/about', name: 'About', component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'), meta: { login: false, title: '映筑香菇農場 | 香菇故事' } }, { path: '/contact', name: 'Contact', component: () => import(/* webpackChunkName: "contact" */ '../views/Contact.vue'), meta: { login: false, title: '映筑香菇農場 | 意見回饋' } }, { path: '/member', component: () => import(/* webpackChunkName: "member" */ '../views/Member.vue'), children: [ { path: 'profile', component: Profile, meta: { login: true, title: '會員資料 |個人資訊', route: 'Member' } }, { path: 'privacy', component: Privacy, meta: { login: true, title: '會員資料 | 隱私資訊', route: 'Member' } }, { path: 'track', component: Track, meta: { login: true, title: '會員資料 | 購物追蹤', route: 'Member' } }, { path: 'cart', component: Cart, meta: { login: true, title: '會員資料 |購物清單', route: 'Member' } } ], meta: { login: true, route: 'Member' } }, { path: '/manager', component: () => import(/* webpackChunkName: "manager" */ '../views/Manager.vue'), children: [ { path: 'message', component: Message, meta: { login: true, title: '管理介面 | 用戶訊息', route: 'Manager' } }, { path: 'order', component: Order, meta: { login: true, title: '管理介面 | 訂單管理', route: 'Manager' } }, { path: 'display', component: Display, meta: { login: true, title: '管理介面 | 商品管理', route: 'Manager' } }, { path: 'membership', component: Membership, meta: { login: true, title: '管理介面 | 會員管理', route: 'Manager' } }, { path: 'article', component: Article, meta: { login: true, title: '管理介面 | 發文管理', route: 'Manager' } } ], meta: { login: true, route: 'Manager' } }, { path: '/news', name: 'News', component: () => import(/* webpackChunkName: "news" */ '../views/News.vue'), meta: { login: false, title: '映筑香菇農場 | 最新消息' } }, { path: '/product', name: 'Product', component: () => import(/* webpackChunkName: "product" */ '../views/Product.vue'), meta: { login: false, title: '映筑香菇農場 | 商品介紹' } }, { path: '/login', name: 'Login', component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue'), meta: { login: false, title: '映筑香菇農場 | 用戶登入' } }, { path: '/sign', name: 'Sign', component: () => import(/* webpackChunkName: "sign" */ '../views/Sign.vue'), meta: { login: false, title: '映筑香菇農場 | 用戶註冊' } } ] const router = new VueRouter({ routes }) router.beforeEach(async (to, from, next) => { if (to.meta.login) { if (store.state.user.userAccount.length === 0) { next('/login') } else if (store.state.user.userAccount === process.env.VUE_APP_MANAGER && to.meta.route !== 'Manager') { if (from.path === '/manager/order') { next() } else { next('/manager/order') } } else if (store.state.user.userAccount !== process.env.VUE_APP_MANAGER && to.meta.route === 'Manager') { next(from.path) } else { next() } } else { next() } }) router.afterEach((to, from) => { document.title = to.meta.title }) const originalPush = VueRouter.prototype.push VueRouter.prototype.push = function push (location) { return originalPush.call(this, location).catch(err => err) } export default router
/** * 通用的打开下载对话框方法,没有测试过具体兼容性 * @param url 下载地址,也可以是一个blob对象,必选 * @param saveName 保存文件名,可选 */ function openDownloadDialog(url, saveName) { if (typeof url == 'object' && url instanceof Blob) { url = URL.createObjectURL(url); // 创建blob地址 } var aLink = document.createElement('a'); aLink.href = url; aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效 var event; if (window.MouseEvent) event = new MouseEvent('click'); else { event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); } aLink.dispatchEvent(event); } function getExtIcon(i) { if (["asp", "php", "js", "java", "html", "css", "sql"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><defs/><path fill="#FF8976" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#FFD0C8" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M422 564l-118 46 118 47v37l-163-65v-37l163-65v37zm116-106h37l-89 240h-37l89-240zm64 200l118-47-118-46v-37l163 64v38l-163 64v-36z"/></svg>' } if (["psb", "psd"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#8095FF" d="M168 32c-12 0-25 5-34 14s-14 22-14 34v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L648 32H168z"/><path fill="#CCD5FF" d="M920 304H696c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#C0CAFF" d="M504 550c5-2 10-4 16-4s11 2 16 4l185 108c5 2 8 8 8 13s-3 11-8 14L534 793c-4 2-10 4-16 4s-11-2-16-4L318 686c-5-3-8-8-8-14s3-11 8-14l186-108z"/><path fill="#FFF" d="M504 390c5-2 10-4 16-4s11 2 16 4l185 108c5 2 8 8 8 13s-3 11-8 14L534 633c-4 2-10 4-16 4s-11-2-16-4L318 526c-5-3-8-8-8-14s3-11 8-14l186-108z"/></svg>' } if (["xls", "xlsx", "number", "et", "ett"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#5ACC9B" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#BDEBD7" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M475 538L366 386h76l71 108 74-108h73L549 538l117 161h-76l-79-115-78 116h-75l117-162z"/></svg>' } if (["wps", "wpt", "page", "doc", "docx"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#6CCBFF" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#C4EAFF" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M280 386h65l65 244 72-244h62l72 244 66-244h62l-96 314h-65l-71-242h-1l-72 241h-65l-94-313z"/></svg>' } if (["ppt", "pptx", "key", "dps", "dpt", "wpp"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#FF8976" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#FFD0C8" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M386 386h176c70 0 92 47 92 97 0 48-28 97-92 97H446v120h-60V386zm60 145h96c35 0 53-10 53-47 0-38-25-48-48-48H446v95z"/></svg>' } if (i == "pdf") { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#FF5562" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#FFBBC0" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M696 843c-50 0-95-86-119-142-40-17-84-32-127-43-37 25-100 62-149 62-31 0-52-15-60-42-7-21-1-36 5-44 13-18 40-27 80-27 32 0 72 6 118 17 30-21 59-45 86-70-12-56-25-147 8-188 16-20 40-27 70-18 33 10 45 30 49 45 13 54-49 128-91 171 9 38 21 77 36 113 61 27 133 67 141 111 3 15-1 30-13 42-11 8-22 13-34 13zm-74-121c30 61 59 90 74 90 2 0 6-1 10-5 6-5 6-9 5-13-3-16-29-42-89-72zm-296-83c-40 0-51 10-54 14-1 1-4 5-1 17 3 9 9 19 30 19 25 0 62-15 105-40-31-7-58-10-80-10zm158-5c26 8 52 16 77 26-9-23-16-47-23-70l-54 44zm99-258c-9 0-15 3-21 10-16 20-18 73-5 140 49-52 75-100 69-125-1-4-4-15-27-22l-16-3z"/></svg>' } if (i == "txt") { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#E5E5E5" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#CCC" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M264 376h208c14 0 24-10 24-24s-10-24-24-24H264c-14 0-24 10-24 24s10 24 24 24zm0 160h496c14 0 24-10 24-24s-10-24-24-24H264c-14 0-24 10-24 24s10 24 24 24zm496 112H264c-14 0-24 10-24 24s10 24 24 24h496c14 0 24-10 24-24s-10-24-24-24z"/></svg>' } if (["zip", "rar", "gzip", "7-zip", "zipz", "rarr", "iso"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#5ACC9B" d="M944 944H80c-26 0-48-18-48-41V656h960v247c0 23-22 41-48 41z"/><path fill="#6CCBFF" d="M80 80h864c26 0 48 18 48 41v247H32V121c0-23 22-41 48-41z"/><path fill="#FFD766" d="M32 368h960v288H32z"/><path fill="#FF5562" d="M352 80h320v864H352z"/><path fill="#FFF" d="M444 128h64v48h-64zm64-48h64v48h-64zm0 96h64v48h-64zm-64 48h64v48h-64zm64 48h64v48h-64zm-64 48h64v48h-64zm64 48h64v48h-64zm-64 48h64v48h-64zm64 48h64v48h-64zm-64 48h64v48h-64zm64 48h64v48h-64zm-64 48h64v48h-64zm64 48h64v48h-64zm-64 48h64v48h-64zm64 48h64v48h-64zm-64 48h64v48h-64zm0 96h64v48h-64zm64-48h64v48h-64z"/></svg>' } if (["avi", "wmv", "mpeg", "mp4", "mov", "mkv", "flv", "f4v", "m4v", "rmvb", "rm", "3gp", "dat", "ts", "mts", "vob"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#8095FF" d="M80 34h864v960H80z"/><path fill="#FFF" d="M136 112a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM136 272a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM136 432a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM136 592a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM136 752a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM136 912a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM824 112a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM824 272a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM824 432a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM824 592a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM824 752a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM824 912a40 40 0 1 0 80 0 40 40 0 1 0-80 0zM648 508L436 362c-5-3-11-4-17 0-5 3-9 8-9 14v290c0 6 4 12 9 15 6 3 12 2 17-1l212-146c5-3 7-8 7-13s-3-10-7-13z"/></svg>' } if (["gif", "jpg", "jpeg", "png", "bmp"].indexOf(i) >= 0) { return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><defs/><path fill="#FF5562" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#FFBBC0" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/><path fill="#FFF" d="M758 706L658 550c-3-4-8-7-13-7s-11 3-14 7l-53 84-120-195c-4-5-8-7-14-7s-10 3-14 7L266 706c-4 4-4 11 0 16 3 5 8 8 13 8h466c5 0 11-4 14-8 3-6 3-12-1-16zM622 412a40 40 0 1 0 80 0 40 40 0 1 0-80 0z"/></svg>' } return '<svg xmlns="http://www.w3.org/2000/svg" class="icon" version="1" viewBox="0 0 1024 1024"><path fill="#E5E5E5" d="M160 32a49 49 0 0 0-48 48v864c0 12 5 25 14 34 10 9 22 14 34 14h704c12 0 25-5 34-14 9-10 14-22 14-34V304L640 32H160z"/><path fill="#CCC" d="M912 304H688c-12 0-25-5-34-14s-14-22-14-34V32l272 272z"/></svg>' } (function ($) { var config = { swf: '/lib/webuploader/Uploader.swf', check: 'http://127.0.0.1:16550/blog/public/file/check', server: 'http://127.0.0.1:16550/blog/public/file/upload', merge: 'http://127.0.0.1:16550/blog/public/file/merge', uploadBtn: '#uploadBtn' }; window.Global = window.Global || {}; Global.FileQueueds = []; Global.GetFileQueued = function (id) { var res = []; $.each(Global.FileQueueds, function (idx, row) { if (row.id == id) { res = row; } }) return res; }; WebUploader.Uploader.register({ "before-send-file": "beforeSendFile", "before-send": "beforeSend", "after-send-file": "afterSendFile" }, { beforeSendFile: function (file) { $.each(Global.FileQueueds, function (idx, row) { if (row.id == file.id) { _chunk = row.chunk; } }); var task = new $.Deferred(); task.resolve();//任务继续 return $.when(task); }, beforeSend: function (block) { var blob = block.blob.getSource(), deferred = $.Deferred(); //根据md5与服务端匹配,如果重复,则跳过。 if (block.chunk < _chunk) { deferred.reject(); } else { deferred.resolve(); } return deferred.promise(); }, afterSendFile: function (file) { } }); $(function () { var $wrap = $('#uploader'), $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')), // 图片容器 // 文件总体选择信息。 $info = $('<p class="error"></p>'), // 上传按钮 $upload = $(config.uploadBtn), // 没选择文件之前的内容。 $placeHolder = $wrap.find('.placeholder'), // 添加的文件数量 fileCount = 0, // 添加的文件总大小 fileSize = 0, // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, // 可能有pedding, ready, uploading, confirm, done. state = 'pedding', // 所有文件的进度信息,key为file id percentages = {}, // 判断浏览器是否支持图片的base64 isSupportBase64 = (function () { var data = new Image(); var support = true; data.onload = data.onerror = function () { if (this.width != 1 || this.height != 1) { support = false; } } data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; return support; })(), // 检测是否已经安装flash,检测flash的版本 flashVersion = (function () { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (ex) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch (ex2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1], 10); })(), supportTransition = (function () { var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s; s = null; return r; })(), // WebUploader实例 uploader, GUID = WebUploader.Base.guid(); //当前页面是生成的GUID作为标示 if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) { // flash 安装了但是版本过低。 if (flashVersion) { (function (container) { window['expressinstallcallback'] = function (state) { switch (state) { case 'Download.Cancelled': alert('您取消了更新!') break; case 'Download.Failed': alert('安装失败') break; default: alert('安装已成功,请刷新!'); break; } delete window['expressinstallcallback']; }; var swf = 'Scripts/expressInstall.swf'; // insert flash object var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" '; if (WebUploader.browser.ie) { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; container.html(html); })($wrap); // 压根就没有安转。 } else { $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>'); } return; } else if (!WebUploader.Uploader.support()) { alert('Web Uploader 不支持您的浏览器!'); return; } // 实例化 uploader = WebUploader.create({ pick: { id: '#filePicker', label: '点击选择文件', multiple: false }, formData: { uid: 123 }, paste: '#uploader', swf: config.swf, chunked: true, //分片处理大文件 chunkSize: 1 * 1024 * 1024, server: config.server, disableGlobalDnd: true, threads: 1, //上传并发数 //由于Http的无状态特征,在往服务器发送数据过程传递一个进入当前页面是生成的GUID作为标示 formData: {}, fileNumLimit: 1, compress: false, //图片在上传前不进行压缩 fileSizeLimit: 1024 * 1024 * 1024, // 1024 M fileSingleSizeLimit: 1024 * 1024 * 1024 // 1024 M }); uploader.wait = function(file){ var fileObj = $('#' + file.id); var target = fileObj.find('.progress_check'); target.show().attr('data-checkedcomplete', true).text('等待上传') .css('color', '#aaa').css('text-align','center'); }; uploader.success = function(file){ var fileObj = $('#' + file.id); fileObj.find('.progress_check').show().attr('data-checkedcomplete', true).text('完成上传') .css('color', '#aaa').css('text-align','left').css('left','11%'); fileObj.bind('click',function(){ openDownloadDialog(file.url,file.name); }).css('cursor','pointer');; }; uploader.fail = function(file){ }; //检查MD5的同时,检查文件已经上传过的分片 uploader.check = function(file){ $.extend(uploader.options.formData, { md5: file.md5 }); var fileObj = $('#' + file.id); $.ajax({ url: config.check, async: true, data: { md5: file.md5, ext: file.ext }, success: function (res) { var status = res.header; if (status == "200") { //文件已存在,忽略上传过程,直接标识上传成功; file.url = res.data; uploader.skipFile(file); file.pass = true; uploader.success(file); } else if (status == "201") { //该文件没有上传过,文件不存在,那就正常流程 Global.FileQueueds.push({ id: file.id, md5: file.md5, size: file.size, ext: file.ext, chunk: res.data }); uploader.wait(file); } else if (status == "202") { //该文件上传了一部分,部分已经上传到服务器了,但是差几个模块。 file.chunk = res.data; Global.FileQueueds.push({ id: file.id, md5: file.md5, size: file.size, ext: file.ext, chunk: res.data }); uploader.wait(file); } //uploader.upload(); } }); }; uploader.merge = function(file,res){ var header = res.header; if(header === '203'){ console.log(file); file.url = res.data; var md5 = Global.GetFileQueued(file.id).md5; $.post(config.merge, { md5: md5, name: file.name, ext: file.ext },function (data) { if(data.header === '203'){ uploader.success(file); }else{ alert('文件合并失败!'); } }); }else{ alert('文件合并失败!'); } }; uploader.on('fileQueued', function (file) { uploader.md5File(file) .progress(function (percentage) { //前端显示验证文件MD5 var fileObj = $('#' + file.id); var spanObj = fileObj.find('.progress_check>span').text(parseInt(percentage * 100)); }) // 完成 .then(function (val) { file.md5 = val; uploader.check(file); }); }); // 拖拽时不接受 js, txt 文件。 uploader.on('dndAccept', function (items) { var denied = false, len = items.length, i = 0, // 修改js类型 unAllowed = 'text/plain;application/javascript'; for (; i < len; i++) { // 如果在列表里面 if (~unAllowed.indexOf(items[i].type)) { denied = true; break; } } return !denied; }); uploader.on('dialogOpen', function () { }); uploader.on('filesQueued', function() { uploader.sort(function( a, b ) { if ( a.name < b.name ) return -1; if ( a.name > b.name ) return 1; return 0; }); }); uploader.on('ready', function () { window.uploader = uploader; }); // 当有文件添加进来时执行,负责view的创建 function addFile(file) { if(Global.FileQueueds.length === 1) Global.FileQueueds.pop(); var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '<p class="progress_check" data-checkedcomplete="false">验证文件:<span>0</span>%</p>' + '</li>'), $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li), $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'), showError = function (code) { switch (code) { case 'exceed_size': text = '文件大小超出'; break; case 'interrupt': text = '上传暂停'; break; default: text = '上传失败,请重试'; break; } $info.text(text).appendTo($li); }; if (file.getStatus() === 'invalid') { showError(file.statusText); } else { // @todo lazyload $wrap.text('预览中'); uploader.makeThumb(file, function (error, src) { var img; if (error) { $wrap.text('不能预览'); var icon = $(getExtIcon(file.ext)); icon.css('position','absolute').css('height','50%').css('top','30%').css('left','7%').css('width','100%'); $wrap.empty().append(icon); return; } if (isSupportBase64) { img = $('<img src="' + src + '">'); $wrap.empty().append(img); } else { $.ajax('preview.ashx', { method: 'POST', data: src, dataType: 'json' }).done(function (response) { if (response.result) { img = $('<img src="' + response.result + '">'); $wrap.empty().append(img); } else { $wrap.text("预览出错"); } }); } }, thumbnailWidth, thumbnailHeight); percentages[file.id] = [file.size, 0]; file.rotation = 0; } file.on('statuschange', function (cur, prev) { if (prev === 'progress') { $prgress.hide().width(0); } else if (prev === 'queued') { $li.off('mouseenter mouseleave'); $btns.remove(); } // 成功 if (cur === 'error' || cur === 'invalid') { console.log(file.statusText); showError(file.statusText); percentages[file.id][1] = 1; } else if (cur === 'interrupt') { showError('interrupt'); } else if (cur === 'queued') { $prgress.css('display', 'block'); percentages[file.id][1] = 0; } else if (cur === 'progress') { $prgress.css('display', 'block'); } else if (cur === 'complete') { $prgress.hide().width(0); $li.append('<span class="success"></span>'); } $li.removeClass('state-' + prev).addClass('state-' + cur); }); $li.on('mouseenter', function () { $btns.stop().animate({ height: 30 }); }); $li.on('mouseleave', function () { $btns.stop().animate({ height: 0 }); }); $btns.on('click', 'span', function () { var index = $(this).index(), deg; switch (index) { case 0: uploader.removeFile(file); return; case 1: file.rotation += 90; break; case 2: file.rotation -= 90; break; } if (supportTransition) { deg = 'rotate(' + file.rotation + 'deg)'; $wrap.css({ '-webkit-transform': deg, '-mos-transform': deg, '-o-transform': deg, 'transform': deg }); } else { $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~ ~((file.rotation / 90) % 4 + 4) % 4) + ')'); // use jquery animate to rotation $({ rotation: rotation }).animate({ rotation: file.rotation }, { easing: 'linear', step: function( now ) { now = now * Math.PI / 180; var cos = Math.cos( now ), sin = Math.sin( now ); $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')"); } }); } }); $li.appendTo($queue); } // 负责view的销毁 function removeFile(file) { var $li = $('#' + file.id); delete percentages[file.id]; updateTotalProgress(); $li.off().find('.file-panel').off().end().remove(); } function updateTotalProgress() { var loaded = 0, total = 0, percent; $.each(percentages, function (k, v) { total += v[0]; loaded += v[0] * v[1]; }); percent = total ? loaded / total : 0; updateStatus(); } function updateStatus() { var text = '', stats; if (state === 'ready') { text = '文件大小:' + WebUploader.formatSize(fileSize); } else if (state === 'confirm') { stats = uploader.getStats(); if (stats.uploadFailNum) { text = '已成功上传'; } } else { stats = uploader.getStats(); text = '等待选择'; if (stats.uploadFailNum) { text += '上传失败'; } } } function setState(val) { var file, stats; if (val === state) { return; } $upload.removeClass('state-' + state); $upload.addClass('state-' + val); state = val; switch (state) { case 'pedding': $placeHolder.removeClass('element-invisible'); $queue.hide(); uploader.refresh(); break; case 'ready': $placeHolder.addClass('element-invisible'); $('#filePicker2').removeClass('element-invisible'); $queue.show(); uploader.refresh(); break; case 'uploading': $info.remove(); $('#filePicker2').addClass('element-invisible'); $upload.text('暂停上传'); break; case 'paused': $.each(uploader.getFiles(), function (idx, row) { if (row.getStatus() == "progress") { row.setStatus('interrupt'); } }) $upload.text('继续上传'); break; case 'confirm': $('#filePicker2').removeClass('element-invisible'); $upload.text('开始上传'); stats = uploader.getStats(); if (stats.successNum && !stats.uploadFailNum) { setState('finish'); return; } break; case 'finish': stats = uploader.getStats(); if (stats.successNum) { console.info('finish', uploader, stats); if (window.UploadSuccessCallback) { window.UploadSuccessCallback(); } } else { // 没有成功的图片,重设 state = 'done'; location.reload(); } break; } updateStatus(); } uploader.onUploadProgress = function (file, percentage) { var $li = $('#' + file.id); $li.find('.progress_check').text('正在上传:' + parseInt(percentage * 100) + '%'); percentages[file.id][1] = percentage; updateTotalProgress(); }; uploader.onFileQueued = function (file) { fileCount++; fileSize += file.size; if (fileCount === 1) { $placeHolder.addClass('element-invisible'); } addFile(file); setState('ready'); updateTotalProgress(); }; uploader.onFileDequeued = function (file) { fileCount--; fileSize -= file.size; if (!fileCount) { setState('pedding'); } removeFile(file); updateTotalProgress(); }; //all算是一个总监听器 uploader.on('all', function (type, arg1, arg2) { //console.log("all监听:", type, arg1, arg2); var stats; switch (type) { case 'uploadFinished': setState('confirm'); break; case 'startUpload': setState('uploading'); break; case 'stopUpload': setState('paused'); break; } }); // 文件上传成功,合并文件。 uploader.on('uploadSuccess', function (file, res) { uploader.merge(file,res); }); uploader.onError = function (code) { alert('Eroor: ' + code); }; $upload.on('click', function () { if ($(this).hasClass('disabled')) { return false; } if ($queue.find('.progress_check[data-checkedcomplete=false]').length > 0) { alert('请等待文件验证完成'); return false; } else { //$queue.find('.progress_check').hide(); } if (state === 'ready') { uploader.upload(); } else if (state === 'paused') { uploader.upload(); } else if (state === 'uploading') { uploader.stop(); } }); $upload.addClass('state-' + state); updateTotalProgress(); }); })(jQuery);
var _ = require("underscore"); var ColoringBR = function(obj) { var self = this; self._neighbors = obj.neighbors; self._colorsAllowed = obj.colorsAllowed; self._strict = obj.strict; self._currentState = obj.currentState; self._pickLowestColor = false; self.getCurrentMin = function() { return self._neighbors.filter(function(d) { return d.state == self._currentState; }).length; }; self._currentMin = self.getCurrentMin(); self.updateState = function(obj) { self._neighbors.find(function(d) { return d.nid == obj.nid; }).state = obj.state; self._currentMin = self.getCurrentMin(); }; self.move = function() { var self = this; var colors = _.range(self._colorsAllowed).map(function(d) { return 0; }); for (var i = 0, c = self._neighbors.length; i < c; i++) { colors[self._neighbors[i].state]++; } var min = _.min(colors); if (self._strict && self._currentMin == min) { return self._currentState; } var argmin = []; for (var i = 0; i < self._colorsAllowed; i++) { if (colors[i] == min) argmin.push(i); } var move = (self._pickLowestColor ? argmin[0] : argmin[Math.floor(Math.random() * argmin.length)]); self._currentState = move; self._currentMin = min; return move; }; }; module.exports = ColoringBR;
'use strict'; import { TOGGLE_MODAL } from '../actions/index'; export default function orderFormModal(state = false, action) { switch (action.type) { case TOGGLE_MODAL: // console.log(`Action <${action.type}> registered with payload <(BOOL): ${!state}>`); state = !state; default: return state; } };
export const keyLocalStorage = 'gameStoreCart'; export const DEFAULT_CART = { totalProducts: 0.00, quantityProducts: 0, shipping: 0.00, products: [], }; export const createLocalStorage = () => { const localCart = localStorage.getItem(keyLocalStorage); if (!localCart) { const cart = JSON.stringify(DEFAULT_CART); return localStorage.setItem(keyLocalStorage, cart); } }; export const clearLocalStorage = () => { localStorage.clear(); }; export const updateLocalStorage = (cart) => { const jsonCart = JSON.stringify(cart); localStorage.setItem(keyLocalStorage, jsonCart) };
$(".dropdown .title").click(function () { $(this).parent().toggleClass("closed"); }); $(".dropdown li").click(function () { $(this).parent().parent().toggleClass("closed").find(".title").text($(this).text()); });
import Module from '../core/module'; import throttle from '../utils/throttle'; class ImageResizer extends Module { constructor(quill, options) { super(quill, options); this.imgNode = null; this.wrap = this.quill.container; this.resizer = this.createResizer(); this.prePos = { x: 0, y: 0 }; this.rect = [ // [width, height] [-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], ]; this.wrap.parentNode.addEventListener('click', e => { if ( this.wrap.contains(e.target) && e.target.tagName.toUpperCase() === 'IMG' && !e.target.classList.contains(quill.formulaImgClass) && (!this.imgNode || e.target !== this.imgNode) ) { this.addResizer(e.target); } else { this.removeResizer(); } }); document.addEventListener('mouseup', () => { this.handId = -1; this.imgNode = null; this.wrap.removeEventListener('mousemove', this.mouseMove); }); } addResizer(imgNode) { this.imgNode = imgNode; this.scale = this.imgNode.width / this.imgNode.height; this.showContainer(this.imgNode); this.resizer.addEventListener('mousedown', e => this.mouseDown(e)); } mouseDown(e) { e.preventDefault(); const hand = e.target; if (hand.className.indexOf('ql-image-resizer-hand') > -1) { this.prePos = { x: e.clientX, y: e.clientY, }; this.originSize = { width: this.imgNode.offsetWidth, height: this.imgNode.offsetHeight, }; this.handId = hand.className.slice(-1); this.wrap.addEventListener( 'mousemove', throttle(this.mouseMove, 30).bind(this), ); } } mouseMove(e) { if (this.handId < 0 || !this.imgNode) return; const offset = { x: e.clientX - this.prePos.x, y: e.clientY - this.prePos.y, }; const widthDir = this.rect[this.handId][0]; const heightDir = this.rect[this.handId][1]; let offsetWidth = widthDir * offset.x; let offsetHeight = heightDir * offset.y; // 比例缩放 if (widthDir !== 0 && heightDir !== 0) { // 放大 if (offsetHeight > 0 || offsetWidth > 0) { if (offsetHeight > 0 && offsetWidth > 0) { if (Math.abs(offset.x) / Math.abs(offset.y) > this.scale) { offsetHeight = offsetWidth / this.scale; } else { offsetWidth = offsetHeight * this.scale; } } else if (offsetWidth > 0) { offsetHeight = offsetWidth / this.scale; } else { offsetWidth = offsetHeight * this.scale; } // 缩小 } else if (Math.abs(offset.x) / Math.abs(offset.y) > this.scale) { offsetWidth = offsetHeight * this.scale; } else { offsetHeight = offsetWidth / this.scale; } } const width = this.originSize.width + offsetWidth; const { paddingLeft, paddingRight } = getComputedStyle(this.quill.root); const contentWidth = this.quill.root.offsetWidth - parseInt(paddingLeft, 10) - parseInt(paddingRight, 10); if (width >= contentWidth && widthDir !== 0) { return; } this.resizeImage(width, this.originSize.height + offsetHeight); } resizeImage(width, height) { this.imgNode.width = width; this.imgNode.height = height; this.updateImageStyle(); } updateImageStyle() { const wrapPos = this.wrap.getBoundingClientRect(); const imagePos = this.imgNode.getBoundingClientRect(); this.resizer.style.left = `${imagePos.x - wrapPos.x}px`; this.resizer.style.top = `${imagePos.y - wrapPos.y}px`; this.resizer.style.width = `${this.imgNode.offsetWidth}px`; this.resizer.style.height = `${this.imgNode.offsetHeight}px`; } removeResizer() { this.imgNode = null; this.resizer.style.display = 'none'; } showContainer() { this.resizer.style.display = 'block'; this.updateImageStyle(); } createResizer() { const container = document.createElement('div'); container.style = `position: absolute;border: 1px solid rgb(59, 119, 255);display: none;`; container.classList.add('ql-image-resizer'); let innerHtml = ''; for (let i = 0; i < 8; i += 1) { innerHtml += `<span class="ql-image-resizer-hand${i}"></span>`; } container.innerHTML = innerHtml; this.wrap.appendChild(container); return container; } } export default ImageResizer;
(function () { var tatuiral = require('fs').readFileSync( require("path").resolve(__dirname, "../README"), 'utf8').trim().split("\n\n\n"); return $.lib.riko.M({ threads: { "tatuiral": { id: "tatuiral" , posts: [ { id: "firstPostEver" , user: "iniziador" , trip: "TRIPKOD: IBO VAISTENU" , time: "DATA: FNA4ALOTO" , media: { service: "ipfs" , type: "image" , src: "QmUHAZMsZ5jd6mvtx5QW1HKs9BChyk327joDB2sW2bkhod" } , text: tatuiral[0] } , { id: "firstPostEver2" , user: "iniziador" , trip: "TRIPKOD: IBO VAISTENU" , time: "DATA: FNA4ALOTO" , media: { service: "ipfs" , type: "image" , src: "Qmai5tAvGrgUQSukU5ZTvsknbFnCYCwJu41pHngeS8aaHn" } , text: tatuiral[1] } , { id: "firstPostEver3" , user: "iniziador" , trip: "TRIPKOD: IBO VAISTENU" , time: "DATA: FNA4ALOTO" , media: { service: "ipfs" , type: "image" , src: "QmPkUDfoF1Atdn6dJfVvseGk4oM38GgLt4AgeGhh1FHgK2" } , text: tatuiral[2] } ]} }, people: 0 }) })()
var Insect = (function(){ return{ insect : function(player , type,ini){ this.player = player this.type = type this.pos = ini } } })() //export {Insect}
function renderNumericFilter(numericAttributes,categoryAttribute,dateAttributes){ $('#shapeSize') .append($("<option></option>") .attr("value","None") .text("None")); $('#shapeColor') .append($("<option></option>") .attr("value","None") .text("None")); $('#shapeOrder') .append($("<option></option>") .attr("value","None") .text("None")); $('#subColor') .append($("<option></option>") .attr("value","None") .text("None")); $('#shapeBar') .append($("<option></option>") .attr("value","None") .text("None")); http://localhost:8888 /*$('#subColor') .append($("<option></option>") .attr("value","Deviation") .text("Deviation")); */ if(categoryAttribute.length > 0){ for(var c=0; c < categoryAttribute.length; c++){ $('#shapeColor') .append($("<option></option>") .attr("value",categoryAttribute[c].name) .attr("isCateg",true) .text(categoryAttribute[c].name)); $('#shapeOrder') .append($("<option></option>") .attr("value",categoryAttribute[c].name) .attr("isCateg",true) .text(categoryAttribute[c].name)); } } var dateAttrDiv = d3.select("#attributeQueryView") .selectAll(".dateAttrDiv") .data(dateAttributes) .enter() .append("div") .attr("class",function(d,i){ return "dateAttrDiv dateAttrDiv_" + d.name; }) var dateAttrNameDiv = dateAttrDiv .append("div") .attr("class", function(d,i){ return "mini-header-tab attrNameDiv attrNameDiv_"+ d.name; }) .html(function(d,i){ return "by " + d.name; }) var dateSliderdiv = dateAttrDiv .append("div") .attr("class", function(d,i){ return "sliderDiv sliderDiv"+ d.name; }); var dateSliderInput = dateSliderdiv .append("input") .attr("isDate",true) .attr("type","text") .attr("class",function(d,i){ return "dateSlide dateSlide_" + d.name; }) .attr("id",function(d,i){ return "dateSlide_" + d.name; }); dateSliderInput .each(function(d,i){ $('#shapeSize') .append($("<option></option>") .attr("value",d.name) .attr("isDate",true) .text(d.name)); $('#shapeColor') .append($("<option></option>") .attr("value",d.name) .attr("isDate",true) .text(d.name)); $('#shapeOrder') .append($("<option></option>") .attr("value",d.name) .attr("isDate",true) .text(d.name)); dateAttrDomins[d.name] = { "min":0, "max":0 }; dateAttrMeanDomains[d.name] = { "min":null, "max":null }; dateAttrSliders[d.name] = $("#dateSlide_" + d.name).ionRangeSlider({ type: "double", name:d.name, grid:false, min: 0, max: 0, from: 0, to: 0, force_edges: true, onChange : function (data) { //console.log(data); updateDateAttr(d.name,data); queryElementByAttribute(); }, }); }); var numericAttrDiv = d3.select("#attributeQueryView") .selectAll(".numericAttrDiv") .data(numericAttributes) .enter() .append("div") .attr("class",function(d,i){ return "numericAttrDiv numericAttrDiv_" + d.name; }) var attrNameDiv = numericAttrDiv .append("div") .attr("class", function(d,i){ return "mini-header-tab attrNameDiv attrNameDiv_"+ d.name; }) .html(function(d,i){ return "By " + d.name; }) var sliderdiv = numericAttrDiv .append("div") .attr("class", function(d,i){ return "sliderDiv sliderDiv"+ d.name; }) var sliderInput = sliderdiv .append("input") .attr("type","text") .attr("class",function(d,i){ return "attrSlide attrSlide_" + d.name; }) .attr("id",function(d,i){ return "attrSlide_" + d.name; }) sliderInput .each(function(d,i){ $('#shapeSize') .append($("<option></option>") .attr("value",d.name) .text(d.name)); $('#shapeColor') .append($("<option></option>") .attr("value",d.name) .attr("isCateg",false) .text(d.name)); $('#shapeOrder') .append($("<option></option>") .attr("value",d.name) .text(d.name)); $('#subColor') .append($("<option></option>") .attr("value",d.name) .text("Mean of " + d.name)); $('#shapeBar') .append($("<option></option>") .attr("value",d.name) .text(d.name)); /*numericAttrScales[d.name] = d3.scaleLinear() .range([(side/2),(side)]);*/ numericAttrDomins[d.name] = { "min":0, "max":0 }; numericAttrMeanDomains[d.name] = { "min":null, "max":null }; attrSliders[d.name] = $("#attrSlide_" + d.name).ionRangeSlider({ type: "double", name:d.name, grid:false, min: 0, max: 0, from: 0, to: 0, from_percent:0, to_percent:100, force_edges: true, onChange : function (data) { updateNumericAttrs(d.name,data); queryElementByAttribute(); }, }); }) } function updateNumericAttrs(name,data){ if(data.min != data.from){ numericAttrDomins[name]["isFromChanged"] = true; numericAttrDomins[name]["changedFrom"] = data.from; } else{ numericAttrDomins[name]["isFromChanged"] = false; } if(data.max != data.to){ numericAttrDomins[name]["isToChanged"] = true; numericAttrDomins[name]["changedTo"] = data.to; } else{ numericAttrDomins[name]["isToChanged"] = false; } } function updateDateAttr(name,data){ if(data.min != data.from){ dateAttrDomins[name]["isFromChanged"] = true; dateAttrDomins[name]["changedFrom"] = data.from; } else{ dateAttrDomins[name]["isFromChanged"] = false; } if(data.max != data.to){ dateAttrDomins[name]["isToChanged"] = true; dateAttrDomins[name]["changedTo"] = data.to; } else{ dateAttrDomins[name]["isToChanged"] = false; } } function updateNumericFilter(numericAttrDomins){ for(var attrName in numericAttrDomins){ if(!(numericAttrDomins[attrName].isFromChanged) && !(numericAttrDomins[attrName].isToChanged)){ attrSliders[attrName].data("ionRangeSlider").update({ min:numericAttrDomins[attrName].min, max:numericAttrDomins[attrName].max, from:numericAttrDomins[attrName].min, to:numericAttrDomins[attrName].max, to_percent:100 }); } else{ if((numericAttrDomins[attrName].isFromChanged) && !(numericAttrDomins[attrName].isToChanged)){ attrSliders[attrName].data("ionRangeSlider").update({ min:numericAttrDomins[attrName].min, max:numericAttrDomins[attrName].max, from:(numericAttrDomins[attrName].changedFrom) >= (numericAttrDomins[attrName].min)? (numericAttrDomins[attrName].changedFrom) : (numericAttrDomins[attrName].min), to:numericAttrDomins[attrName].max, }); } else if(!(numericAttrDomins[attrName].isFromChanged) && (numericAttrDomins[attrName].isToChanged)){ attrSliders[attrName].data("ionRangeSlider").update({ min:numericAttrDomins[attrName].min, max:numericAttrDomins[attrName].max, from:numericAttrDomins[attrName].min, to:(numericAttrDomins[attrName].changedTo) <= (numericAttrDomins[attrName].max)? (numericAttrDomins[attrName].changedTo) : (numericAttrDomins[attrName].max), }); } else if((numericAttrDomins[attrName].isFromChanged) && (numericAttrDomins[attrName].isToChanged)){ attrSliders[attrName].data("ionRangeSlider").update({ min:numericAttrDomins[attrName].min, max:numericAttrDomins[attrName].max, from:(numericAttrDomins[attrName].changedFrom) >= (numericAttrDomins[attrName].min)? (numericAttrDomins[attrName].changedFrom) : (numericAttrDomins[attrName].min), to:(numericAttrDomins[attrName].changedTo) <= (numericAttrDomins[attrName].max)? (numericAttrDomins[attrName].changedTo) : (numericAttrDomins[attrName].max), }); } } } } function updateDateFilter(dateAttrDomins){ for(var dateAttr in dateAttrDomins){ if(!(dateAttrDomins[dateAttr].isFromChanged) && !(dateAttrDomins[dateAttr].isToChanged)){ dateAttrSliders[dateAttr].data("ionRangeSlider").update({ min:+dateAttrDomins[dateAttr].min, max:+dateAttrDomins[dateAttr].max, from:+dateAttrDomins[dateAttr].min, to:+dateAttrDomins[dateAttr].max, prettify: function (num) { return moment(num).format("YYYY-MM-DD"); } }); } else{ if((dateAttrDomins[dateAttr].isFromChanged) && !(dateAttrDomins[dateAttr].isToChanged)){ dateAttrSliders[dateAttr].data("ionRangeSlider").update({ min:+dateAttrDomins[dateAttr].min, max:+dateAttrDomins[dateAttr].max, from:+(dateAttrDomins[dateAttr].changedFrom) >= +(dateAttrDomins[dateAttr].min)? +(dateAttrDomins[dateAttr].changedFrom) : +(dateAttrDomins[dateAttr].min), to:+dateAttrDomins[dateAttr].max, prettify: function (num) { return moment(num).format("YYYY-MM-DD"); } }); } else if(!(dateAttrDomins[dateAttr].isFromChanged) && (dateAttrDomins[dateAttr].isToChanged)){ dateAttrSliders[dateAttr].data("ionRangeSlider").update({ min:+dateAttrDomins[dateAttr].min, max:+dateAttrDomins[dateAttr].max, from:+dateAttrDomins[dateAttr].min, to:+(dateAttrDomins[dateAttr].changedTo) <= +(dateAttrDomins[dateAttr].max)? +(dateAttrDomins[dateAttr].changedTo) : +(dateAttrDomins[dateAttr].max), prettify: function (num) { return moment(num).format("YYYY-MM-DD"); } }); } else if((dateAttrDomins[dateAttr].isFromChanged) && (dateAttrDomins[dateAttr].isToChanged)){ dateAttrSliders[dateAttr].data("ionRangeSlider").update({ min:+dateAttrDomins[dateAttr].min, max:+dateAttrDomins[dateAttr].max, from:+(dateAttrDomins[dateAttr].changedFrom) >= +(dateAttrDomins[dateAttr].min)? +(dateAttrDomins[dateAttr].changedFrom) : +(dateAttrDomins[dateAttr].min), to:+(dateAttrDomins[dateAttr].changedTo) <= +(dateAttrDomins[dateAttr].max)? +(dateAttrDomins[dateAttr].changedTo) : +(dateAttrDomins[dateAttr].max), prettify: function (num) { return moment(num).format("YYYY-MM-DD"); } }); } } } }
class Variables { static get boxType() { return "_-MA"; } static get attackerId() { return "_-93f"; } static get attackHp() { return "_-N2B"; } static get attackShd() { return "_-H2B"; } static get attackedId() { return "_-U2r"; } static get moveDuration() { return "_-F3M"; } static get shipDestoyedId() { return "_-L3H"; } static get heroInitMaxHp() { return "_-W3X"; } static get heroInitMaxShd() { return "_-YF"; } static get heroInitHp() { return "_-b2a"; } static get hpUpdateMaxHp() { return "_-v1R"; } static get hpUpdateHp() { return "_-j4O"; } static get selectMaxHp() { return "_-v1R"; } static get selectMaxShd() { return "_-YF"; } static get selectHp() { return "_-j4O"; } static get clanDiplomacy() { return "_-k1p"; } static get resource() { return "_-b1k"; } static get resourceType() { return "_-TR"; } static get gateType() { return "_-et"; } static get gateId() { return "_-i3Q"; } static get assetCreateX() { return "_-54j"; } static get assetCreateY() { return "_-T3y"; } static get battlestationClanDiplomacy() { return "_-P3W"; } }
 $(function () { $("#dialog").dialog({ autoOpen: false, }); $("#opener").click(function () { $("#dialog").dialog("open"); }); });
// Receive and output articles var LoadArticles = () => { GetAjaxData('db_articles.php'); $(document).ajaxComplete(() => { let html = ` <div class=" col-xs-12 col-sm-12"> <div class="p-20"></div> <div class="block-title"> <h2>Articles</h2> </div> `; if (object.length > 0) { object.forEach((e) => { html += ` <p>${e.title}</p> <p>${e.authors}</p> <p>${e.date}</p> <hr> `; }); } html += '</div>'; $('#data').html(html); }); };
// Mode Manager // Note: this plugin requires jQuery.js and hotkeys.js var screenReaderType; $('body').delegate('[tabindex], input', 'focus', function(ev) { console.log('current activeEl = #', document.activeElement.id); console.log('focus target = #', (ev.originalEvent && ev.originalEvent.target ? ev.originalEvent.target.id : (ev.target ? ev.target.id : "(no target)")), "; caught on = #", this.id); }); var pendingFocusJumps = []; function addFocusJump(target) { var existingTimeout; function runNextJump() { existingTimeout = null; if(pendingFocusJumps.length > 0) { var focusTarget = pendingFocusJumps.shift(); window.console && console.log('jumping to... #', $(focusTarget).attr('id'), ": ", pendingFocusJumps.length, " remain"); $(focusTarget).focus(); if(pendingFocusJumps.length > 0) { existingTimeout = setTimeout(runNextJump, 1); } } } pendingFocusJumps.push(target); window.console && console.log("Current Focus jumps pending: ", $(pendingFocusJumps).map(function(){ return typeof this === "string" ? this : (this[0] ? "#" + this[0].id : "#" + this.id)}).get().join(", ")); if(!existingTimeout) { existingtTimeout = setTimeout(runNextJump, 300); } } // temp setter for screen reader. $('#screen-reader').click(function() { var self = $(this); if(self.text() == "none selected.") { self.text('JAWS'); screenReaderType = 'JAWS'; } else if(self.text() == "JAWS") { self.text('NVDA'); screenReaderType = 'NVDA'; } else if(self.text() == "NVDA") { self.text('none selected.'); screenReaderType = undefined; } else { self.text('none selected.'); screenReaderType = undefined; } }); /* create catch function */ function insertCatch(catchId, insertionTarget, finalTarget, mode) { var insertionTarget, finalTarget, newTextfield; if(!catchId || !insertionTarget || !finalTarget || !mode) { console.log('missing parameters for insertCatch function.') } else { createCatch(); delegateCatchBehavior(); } function createCatch() { //finalTarget = $('#' + finalTarget); /* newTextfield = $('<input id="' + catchId + '" type="text" value="-" class="catch ' + ' appmode-' + mode + ' targetid-' + finalTarget + '"><br>'); */ // append a second catch to solve for JAWS 10, 13. newTextfield = $('<input id="' + catchId + '" type="text" value="-" class="catch ' + ' appmode-' + mode + ' targetid-' + finalTarget + '">' + '<input id="' + catchId + '-2' + '" type="text" value="-" class="catch ' + ' appmode-' + mode + ' targetid-' + finalTarget + '"><br>' ); } function delegateCatchBehavior() { //newTextfield.bind('focus', runCatch()); insertionTarget = $('#' + insertionTarget); insertionTarget .append(newTextfield) .delegate('input', 'focus', function() { runCatch(this); }); } } /* catch function */ function runCatch(catchNode, alternateTarget) { // alternateTarget must be an id, not a general selector. // Its purpose is to reset the final target of the catch somewhere other than normal. var bodyTagRoleState = $('body').attr('role'); var classAttr = $(catchNode).attr('class').split(' '); // find appmode-act/deact var appmodePattern = /^appmode\-([\w-]+)/; // ^appmode\-\w+ var appmodeValue = null; var appmodeSubstr = null; var targetidPattern = /^targetid\-([\w-]+)/; var targetidValue = null; var targetidSubstr = null; /* extract all parameters for catch from class attr values */ for(var x=0;x<classAttr.length;x++) { if(appmodeValue == null) { appmodeValue = appmodePattern.exec(classAttr[x]); if(appmodeValue != null) { appmodeSubstr = appmodeValue[1]; } } if(targetidValue == null || alternateTarget == undefined) { targetidValue = targetidPattern.exec(classAttr[x]); if(targetidValue != null) { targetidSubstr = targetidValue[1]; } } else if(alternateTarget != undefined) { targetidSubstr = alternateTarget; } } if(appmodeSubstr == "act") // NOTE: nvda doesn't use body for role=application { if(bodyTagRoleState != "application" && screenReaderType == 'JAWS') { $('body').attr('role', 'application'); } var targetFinal = $('#' + targetidSubstr); addFocusJump(targetFinal); // was working on FF //targetFinal.focus() targetFinal.addClass('selected'); if(screenReaderType == 'JAWS') { addFocusJump('#dummy-textfield'); addFocusJump(targetFinal); } } else if(appmodeSubstr == "deact") { updateModeFix(); var targetFinal = $('#' + targetidSubstr); addFocusJump(targetFinal); if(bodyTagRoleState == "application" && screenReaderType == 'JAWS') { $('body').removeAttr('role'); } addFocusJump(targetFinal); targetFinal.addClass('selected'); if(screenReaderType == 'JAWS') { //$('#dummy-textfield').focus(); updateModeFix(); addFocusJump($('#dummy-textfield')); //addFocusJump($('#iframe-toggle')); //updateModeFix(); //$('#content-entrance-container .entrance').delay(1000).focus(); var test; } addFocusJump(targetFinal); } } function toggleAppMode(whichState, targetFinal) { if(whichMode == "act") // act means active/activate app mode { $('body').attr('role', 'application'); $(targetFinal).focus(); if(screenReaderType == 'JAWS') { $('#dummy-textfield').focus(); $(targetFinal).focus(); } } else if(whichMode == "deact") { $('body').removeAttr('role'); $(targetFinal).focus(); if(screenReaderType == 'JAWS') { $('#dummy-textfield').focus(); updateModeFix(); $(targetFinal).focus(); } } else { console.log('whichState value cannot be', whichState, ', only "act" or "deact"'); } } /* create virtual cursor mode target */ function createReaderModeTarget(targetId, insertionTargetId) { var target, insertionTarget, fixTarget; if(!targetId || !insertionTargetId) { console.log('createReaderModeTarget is missing required args.') } else { target = $('<div id="' + targetId + '" class="entrance test-button" tabindex="0" aria-labeledby="' + targetId + '">Page Begins Here.</div>'); target.bind('keydown', function() { updateModeFix(); $('#' + targetId + '-alternate').focus(); }); fixTarget = $('<div id="' + targetId + '-alternate" tabindex="0" class="entrance-alternate test-button" role="button">blank.</div>'); fixTarget.bind('keydown', function() { updateModeFix(); $('#' + targetId).focus(); }); insertTarget = $('#' + insertionTargetId); insertTarget .append(target) .append(fixTarget) .delegate('div.entrance', 'keydown', function(event) { // include JAWS presence condition if(screenReaderType == 'JAWS' && event.which != 9 && event.shiftKey != true && event.which != 16) { $(this).removeClass('selected'); var targetFix = $(this).siblings('div.entrance-alternate:first'); addFocusJump(targetFix.addClass('selected')); if(screenReaderType == 'JAWS') { updateModeFix(); addFocusJump(targetFix); } } }) .delegate('div.entrance-alternate', 'keydown', function(event) { // include JAWS presence condition if(screenReaderType == 'JAWS' && event.which != 9 && event.shiftKey != true && event.which != 16) { $(this).removeClass('selected'); var targetFix = $(this).siblings('div.entrance:first'); addFocusJump(targetFix.addClass('selected')); // was working on FF //targetFix // .focus() // .addClass('selected'); updateModeFix(); //addFocusJump(targetFix); // was working on FF targetFix.focus(); } }) .delegate('div.entrance', 'focus', function() { console.log('node id=' + $(this).attr('id') + " got focus."); }); } } /* generate update mode fix */ function createModeFix() { var objNew = document.createElement('p'); var objHidden = document.createElement('span'); objHidden.setAttribute('id', 'virtualbufferupdate'); objHidden.setAttribute('class', 'novisual'); objHidden.textContent = "0"; objNew.appendChild(objHidden); document.body.appendChild(objNew); } /* update mode fix function */ function updateModeFix() { if(screenReaderType == 'JAWS') { var objHidden = document.getElementById('virtualbufferupdate'); if (objHidden) { console.log("Started timeout at ", new Date()); if (objHidden.textContent == '1') var testTimer = setTimeout(function() { objHidden.textContent = '0'; console.log("Ended timeout at ", new Date()); }, 1); else var testTimer = setTimeout(function() { objHidden.textContent = '1'; console.log("Ended timeout at ", new Date()); }, 1); } } else { // do nothing. only JAWS requires it. } } function pushContentAndUpdateFocus(selector, finalFocusableContent) { // note: all selectors leverage {selector}:not(.selected, .anchor):first format for focus jumps // .anchor refers to the original focus point which includes widget directions. // find new focus target var focusTarget = $(selector + ':not(.selected):first'); // remove .selected from all matching selectors $(selector) .removeClass('selected') .parent() .removeClass('selected'); focusTarget .addClass('selected') .text(finalFocusableContent); if($('#access-updater').hasClass('nvda') == true) { if(!$.browser.mozilla) { focusTarget.attr('aria-label', finalFocusableContent); focusTarget.focus(); } else { //$('#nvda-screen-reader-updater').focus(); addFocusJump($('#nvda-firefox-updater')); // this is the placeholder, allowing NVDA to read // announcements w/o focus jumps between the nodes. } } else { focusTarget.focus(); } return focusTarget; }
export const backend = 'http://10.55.128.91:8004';
function logNumbers() { console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4); } logNumbers(); output will be :- 1,4,3,2 setTimeOut() will push function execution to an event stack (the call back function).
function loadMenuLink(curId,menuId) { link = ''; //alert(curId + ' ' + menuId); if (curId != menuId) { var menuArray = menuId.split("-"); if (menuId == 'abs-form-po') { link = '/procurement/procurement/poh'; } else if (menuId == 'charts-po') { link = '/procurement/procurement/chart'; //link = '/index'; } else if (menuId == 'abs-form-budget') { link = '/default/report/showbudget'; //link = '/index'; } else if (menuId == 'abs-form-boq3') { link = '/default/report/showboq3'; } else if (menuId == 'abs-form-boq3-revisi') { link = '/default/report/showboq3revisi'; } else if (menuId == 'abs-form-compare-boq') { link = '/default/report/showcompareboq'; } else if (menuId == 'abs-form-pr') { link = '/default/report/showpr'; } else if (menuId == 'abs-form-outprpo') { link = '/default/report/showoutprpo'; } else if (menuId == 'abs-form-arfasf') { link = '/default/report/showarfasf'; } else if (menuId == 'abs-form-porpi') { link = '/default/report/showporpi'; } else if (menuId == 'abs-form-rmdi') { link = '/default/report/showrmdi'; } else if (menuId == 'abs-form-mdimdo') { link = '/default/report/showmdimdo'; } else if (menuId == 'abs-form-mdodo') { link = '/default/report/showmdodo'; } else { if (menuArray[0] == 'project') { link = '/myproject/show/prj_kode/' + menuArray[1]; } } if (link !='') { //window.location = link; cPanel = Ext.getCmp('content-panel'); cPanel.load({ url: link, scripts: true }); } } }
$(function() { var ndUsername = $('#username'), // 用户名 ndPassword = $('#password'), // 密码 ndPromptMsg = $('#prompt-message'), // 页面提示条 ndAlertPromptMsg = $('#alert-prompt-message'); // 页面弹出提示条 // 重置数据 $('#reset-data').click(function() { ndUsername.val(''); ndPassword.val(''); }); function submitData() { if (ndUsername.val() == '' || ndPassword.val() == '') { displayMsg(ndPromptMsg, '用户名或者密码不能为空', 2000); return; } setAjax(PayUrl.loginUrl, { 'user_id': ndUsername.val(), 'password': ndPassword.val() }, ndPromptMsg, function(respnoseText) { ndUsername.val(''); ndPassword.val(''); displayMsg(ndPromptMsg, '页面加载中...请稍后...', 30000); window.location.replace(PayUrl.tableListUrl); }); } // 提交登陆数据 $('#submit-btn').click(function() { submitData(); }); $(window).keydown(function(event) { if (event.keyCode == 13) { submitData(); } }); // 退出系统 $('#exit-system').click(function() { $('#alert-content').html('你确定要退出收银系统吗'); displayAlertMessage('#alert-message', '#cancel-alert'); $('#definite-alert').click(function() { setAjax(PayUrl.logoutUrl, null, ndAlertPromptMsg, function(respnoseText) { layer.close(layerBox); displayMsg(ndPromptMsg, '服务器请求中...请稍候...', 30000); window.location.replace(indexUrl); }); }); }); });
/// <reference types="cypress" /> import { admin } from "../../support/page_objects/admin/adminFunctions" describe('Headless Authorization Admin No Cookies', () => { it('Headless Authorization Admin No Cookies', () => { //admin.headlessLoginAdmin() cy.request({ method: 'POST', url: 'https://store.tcgplayer-'+(Cypress.env("partialRefundPageUrl1"))+'.com/admin/Account/LogOn', form: true, // indicates the body should be form urlencoded and sets Content-Type: application/x-www-form-urlencoded headers body: { UserName: 'admin@auto.com', Password: 'P@ssw0rd!', RequireCaptcha: 'false', CaptchToken: 'literally anything' } }) // to prove we have a session // cy.getCookie('cypress-session-cookie').should('exist') // cy.request('POST', 'https://store.tcgplayer-qa.com/admin/Account/LogOn', userCredentials) // const orderNumber = 'F417072D-61071D-5622D' // cy.log(Cypress.env("partialRefundPageUrl1")) // cy.log(Cypress.env("partialRefundPageUrl2")) // const partialRefundPageUrl1 = (Cypress.env("partialRefundPageUrl1")) // const partialRefundPageUrl2 = (Cypress.env("partialRefundPageUrl2")) // cy.log(partialRefundPageUrl1) // cy.log(partialRefundPageUrl2) // cy.visit(partialRefundPageUrl1 + orderNumber + partialRefundPageUrl2) // admin.verifyAdminLogin() }) })
(function (key, newVal) { var key = "localstorage://" + window.location.host + window.location.pathname + key; if (localStorage.getItem(key)) try { return JSON.parse(localStorage.getItem(key)); } catch (e) { return _.storageSet(key, newVal); } return _.storageSet(key, newVal); })
let biggestZindex = 4; export function addClickListener(els) { clickTochange(els[0], els[1], els[2], els[3]); clickTochange(els[1], els[0], els[2], els[3]); clickTochange(els[2], els[0], els[1], els[3]); clickTochange(els[3], els[0], els[1], els[2]); let buttons = []; els.forEach(function(el, index) { let button = $(el) .find('.circle') .first(); button.click(() => { document.getElementById('desktop').removeChild(el); }); buttons.push(button); }); } function clickTochange(el1, el2, el3, el4) { el1.addEventListener('mousedown', () => { el1.style.zIndex = biggestZindex + 1; biggestZindex++; changeToClickedStyle(el1); changeToUnclickedStyle(el2); changeToUnclickedStyle(el3); changeToUnclickedStyle(el4); }); } function changeToClickedStyle(el) { let header = $(el) .children('.header') .first(); let title = $(el) .find('.title') .first(); let buttons = $(el).find('.circle'); let buttonStyle = ['red', 'yellow', 'green']; toggleclass(header, 'header-unclicked', 'header-clicked'); toggleclass(title, 'title-unclicked', 'title-clicked'); for (let i = 0; i < 3; i++) { toggleclass(buttons[i], 'gray', buttonStyle[i]); } } function changeToUnclickedStyle(el) { let header = $(el) .children('.header') .first(); let title = $(el) .find('.title') .first(); let buttons = $(el).find('.circle'); let buttonStyle = ['red', 'yellow', 'green']; toggleclass(header, 'header-clicked', 'header-unclicked'); toggleclass(title, 'title-clicked', 'title-unclicked'); for (let i = 0; i < 3; i++) { toggleclass(buttons[i], buttonStyle[i], 'gray'); } } function toggleclass(el, class1, class2) { $(el) .removeClass(class1) .addClass(class2); } export function changeEditor(el1, el2) { el1.style.zIndex = 4; el2.style.zIndex = 3; changeToClickedStyle(el1); changeToUnclickedStyle(el2); }
CategoryReport.innerHTML=[ NSB.Grid("grdCatReport", "1", "3", "", "", "Account,Amount,Percentage", "left,right,right", "style=", ""), NSB.HeaderBar_jqm14('catReportTitle', 'Category Report', '', 'arrow-l', 'left', '', 'refresh', 'right', ' style="" class=" "'), ].join('');
import { AUTH_START } from "./actionTypes"; export const authStart = (data) => { return { type: AUTH_START, auth: data } }
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Family = /** @class */ (function () { function Family(familyName) { this.familyName = familyName; } return Family; }()); var Kondapalli = /** @class */ (function (_super) { __extends(Kondapalli, _super); function Kondapalli() { return _super !== null && _super.apply(this, arguments) || this; } Kondapalli.prototype.name = function () { console.log(this.familyName + " Family"); }; return Kondapalli; }(Family)); var Adhi = /** @class */ (function (_super) { __extends(Adhi, _super); function Adhi() { return _super.call(this, 'Adhi') || this; } Adhi.prototype.name = function () { console.log(this.familyName + " Family"); }; return Adhi; }(Family)); var printIt = function (pFamily) { return pFamily.name(); }; printIt(new Kondapalli('Kondapalli')); printIt(new Adhi());
var mongoose = require("mongoose"); var mongoSchema = mongoose.Schema; var consumeSchema = { "supplier" : {type: mongoSchema.Types.ObjectId, ref: 'supplier'}, "item" : String, "noItem" : Number, "quantity" : Number, "uPrice" : Number, "note" : String, "updateDate": { type: Date, default: Date.now }, "insertDate": { type: Date, default: Date.now } }; module.exports = mongoose.model('consume', consumeSchema);;
(function() { const PATH = '../pics/'; const CAT_PICTURES = [ 'cutie.jpg', 'spy.jpg', 'heidiAndHennes.jpg', 'shoes.jpg', ]; class Model { constructor (imageIndex) { this.imageIndex = imageIndex; this.counter = 0; } static init () { this.data = []; for (let index in CAT_PICTURES) { this.data.push(new Model(index)); } return this.data; } static getCats () { return this.data; } } class ListView { static render () { Octopus.getCats().forEach(cat => { let image = document.createElement('img'); image.src = PATH + CAT_PICTURES[cat.imageIndex]; image.height = 100; this.catList.appendChild(image); image.addEventListener('click', (copyCat => { return () => Octopus.onListClick(copyCat); })(cat)); }); } static init () { this.catList = document.getElementById('catList'); } } class FocusView { static init () { var catFocus = document.getElementById('catFocus'); this.catFocusImage = document.createElement('img'); this.catFocusCounter = document.createElement('div'); catFocus.appendChild(this.catFocusImage); catFocus.appendChild(this.catFocusCounter); } static renderImage (cat) { this.catFocusImage.src = PATH + CAT_PICTURES[cat.imageIndex]; this.catFocusImage.onclick = () => Octopus.onFocusClick(cat); } static renderCounter (cat) { this.catFocusCounter.textContent = cat.counter; } } class Octopus { static init () { Model.init(); ListView.init(); FocusView.init(); ListView.render(); this.currentIndex = 0; var cat = Model.getCats()[this.currentIndex]; FocusView.renderImage(cat); FocusView.renderCounter(cat); } static getCats () { return Model.getCats(); } static onListClick(cat) { if (this.currentIndex !== cat.imageIndex) { this.currentIndex = cat.imageIndex; FocusView.renderImage(cat); FocusView.renderCounter(cat); } } static onFocusClick (cat) { cat.counter++; FocusView.renderCounter(cat); } } window.onload = () => { Octopus.init(); }; })();
var searchData= [ ['habilitar_5fapic',['habilitar_apic',['../classMultiproc.html#a5961d7aa4f532236fdfba2728b017277',1,'Multiproc']]], ['habilitar_5fapic_5ftimer',['habilitar_apic_timer',['../classMultiproc.html#af30a44ba460f5ccfcbb5e68713a0f5ef',1,'Multiproc']]] ];
var expect = require('chai').expect; require('./mocks/phaser'); var mockGame = require('./mocks/game'); var Zoom = require('../lib/phaser-zoom-plugin'); describe('The Zoom plugin', function () { var zoom; beforeEach(function () { zoom = new Zoom(mockGame); }); it('should provide an interface to allow zooming', function () { expect(typeof zoom.zoomToXY).to.equal('function'); expect(typeof zoom.zoomTo).to.equal('function'); }); });
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsLocalParking = { name: 'local_parking', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13 3H6v18h4v-6h3c3.31 0 6-2.69 6-6s-2.69-6-6-6zm.2 8H10V7h3.2c1.1 0 2 .9 2 2s-.9 2-2 2z"/></svg>` };
// @ts-nocheck // eslint-disable-next-line no-unused-vars import elementCreator from './elementCreator'; const style = document.createElement('template'); style.innerHTML = ` <style> .number-label { display: flex; align-items: center; font-weight: bold; padding-right: 0.45em; margin-top: 0.5em; } /* For tablets */ @media (max-width: 768px) { .number-label { margin-top: 0.6em; font-size: small; } } </style> `; class NumberDisplay extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.appendChild(style.content.cloneNode(true)); this.shadowRoot.appendChild( <div className="number-label"> <span><slot /></span> <span id="numberPlace" /> </div>, ); } set value(newVal) { this.shadowRoot.querySelector('#numberPlace').innerText = newVal; } get value() { return this.shadowRoot.querySelector('#numberPlace').innerText; } } window.customElements.define('number-display', NumberDisplay);
const chaiHttp = require('chai-http'); const chai = require('chai'); const assert = chai.assert; const server = require('../server'); chai.use(chaiHttp); suite('Functional Tests', function() { suite('/api/stock-prices', function() { test('Viewing one stock', function(done){ chai.request(server) .get('/api/stock-prices') .query({stock: 'goog'}) .end(function(err,res){ let stockData = res.body.stockData; assert.equal(stockData['stock'],'GOOG') assert.isNumber(stockData['price']) assert.isNumber(stockData['likes']) done() }) }); test('Viewing one stock and liking it', function(done){ chai.request(server) .get('/api/stock-prices') .query({stock: 'goog',like: 'true'}) .end(function(err,res){ let stockData = res.body.stockData; assert.equal(stockData['stock'],'GOOG') assert.isNumber(stockData['price']) assert.equal(stockData['likes'],1) done() }) }); test('Viewing the same stock and liking it again', function(done){ chai.request(server) .get('/api/stock-prices') .query({stock: 'goog',like: 'true'}) .end(function(err,res){ assert.equal( res.body, 'Error: Only 1 Like per IP Allowed' ) done() }) }); test('Viewing two stocks', function(done){ chai.request(server) .get('/api/stock-prices') .query({stock: ['aapl','msft']}) .end(function(err,res){ let stockData = res.body.stockData; assert.isArray(stockData) if(stockData[0]['stock'] === 'AAPL'){ assert.equal(stockData[0]['stock'],'AAPL') assert.isNumber(stockData[0]['price']) assert.equal(stockData[0]['rel_likes'],0) assert.equal(stockData[1]['stock'],'MSFT') assert.isNumber(stockData[1]['price']) assert.equal(stockData[1]['rel_likes'],0) }else{ assert.equal(stockData[1]['stock'],'AAPL') assert.isNumber(stockData[0]['price']) assert.equal(stockData[0]['rel_likes'],0) assert.equal(stockData[0]['stock'],'MSFT') assert.isNumber(stockData[1]['price']) assert.equal(stockData[1]['rel_likes'],0) } done() }) }); test('Viewing two stocks and liking them', function(done){ chai.request(server) .get('/api/stock-prices') .query({stock: ['aapl','msft'],like: 'true'}) .end(function(err,res){ let stockData = res.body.stockData; assert.isArray(stockData) if(stockData[0]['stock'] === 'AAPL'){ assert.equal(stockData[0]['stock'],'AAPL') assert.isNumber(stockData[0]['price']) assert.equal(stockData[0]['rel_likes'],0) assert.equal(stockData[1]['stock'],'MSFT') assert.isNumber(stockData[1]['price']) assert.equal(stockData[1]['rel_likes'],0) }else{ assert.equal(stockData[1]['stock'],'AAPL') assert.isNumber(stockData[0]['price']) assert.equal(stockData[0]['rel_likes'],0) assert.equal(stockData[0]['stock'],'MSFT') assert.isNumber(stockData[1]['price']) assert.equal(stockData[1]['rel_likes'],0) } done() }) }); }) });
import { useReducer } from 'react' import {BrowserRouter as Router, Route} from 'react-router-dom' import {DataContext} from './store/context' import reducers, {initialState} from './store/reducers' import Home from './screen/Home' const App = () => { const [state, dispatch] = useReducer(reducers, initialState) return ( <DataContext.Provider value={{state, dispatch}}> <Router> <Route path='/page/:pageNumber' component={Home} exact /> <Route path='/' component={Home} exact /> </Router> </DataContext.Provider> ) } export default App;
function rot13(str) { let newArr = str.split('') let ans = [] let abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for (let letter in newArr){ let posIni = abc.indexOf(newArr[letter]) if(posIni == -1){ ans.push(newArr[letter]) continue} let posFin = posIni+13 if (posFin > 25){ posFin = posFin-26 } console.log(posIni, posFin) ans.push(abc[posFin]) } return ans.join('') }
import React, {Component} from 'react'; import {View, Text, StyleSheet, Image} from 'react-native'; import Styles from '../Constants/styles'; import GlobalWrapper from '../Components/GlobalWrapper'; export default class About extends Component { constructor(props) { super(props); this.state = { about: 'Harsh Farms Mission is to supply the best tasting and finest Quality Fruits, Fresh Vegetables, Fresh Leafy Vegetables, Fresh Beans, Dry Items, Powder Items directly from farm to our customers. Through our farming farmers, we aiming to have a maximum amount of organic produce as possible. Our farm provides online bookings and online payments only. Our farm provides delivery service to your residence or designated pick up points depending on your location.', }; } render() { const {about} = this.state; return ( <GlobalWrapper navigation={this.props.navigation}> <View style={styles.wrapper}> <Text style={Styles.heading}>About us</Text> <View style={styles.mainSubWrapper}> <Image source={{ uri: 'https://images.unsplash.com/photo-1539799827118-e091578f7011?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=751&q=80', }} style={styles.image} /> <Text>{about}</Text> </View> </View> </GlobalWrapper> ); } } const styles = StyleSheet.create({ wrapper: { margin: 10, padding: 20, }, mainSubWrapper: { justifyContent: 'center', alignItems: 'center', }, image: { width: 200, height: 200, borderRadius: 10, marginBottom: 40, }, subHeading: { marginBottom: 30, fontWeight: 'bold', fontSize: 18, color: 'grey', textAlign: 'center', }, });
// to update whether message is 'trashed'/archived.
const prod1 = {} // Representa um objeto - e a forma literal de escrever um objeto prod1.nome = 'Celular Ultra Mega' // Criado dinamicamento dentro do objeto - O que é OBJ? - Em JavaScript e uma coleção de Chaves e Valores prod1.preco = 4998.90 prod1['Desconto Legal'] = 0.40 // Evite atributos com espaço console.log(prod1) const prod2 = { nome: 'Camisa Polo', preco: 79.90 } // JSON é um formato TEXTUAL | JSON - JAVASCRIPT OBJECT NOTACION // OBJETO é uma coleção de Chave e Valor console.log(prod2)
const sequelizePaginate = require('sequelize-paginate') module.exports = (Sequelize,DataTypes) => { const Categories = Sequelize.define('categories',{ name: { type: DataTypes.STRING, allowNull: false, }, user_id: { type: DataTypes.INTEGER, allowNull: true, }, createdAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP()') }, updatedAt: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP()') } }) Categories.associate = model => { Categories.hasMany(model.ProductCategories,{ foreignKey: "category_id", as: "categories_products", onDelete: 'CASCADE' }) } sequelizePaginate.paginate(Categories) return Categories; }
Lesson 62 $('p'); //is selecting by tag name $('#main_h1'); //is selecting by id $('.maindiv'); //is selecting by class Lesson 63 $('p strong'); //is selecting STRONG tag in P tag $('#main_h1 + p'); //is selecting next P tag after #MAIN_H1 $('#div_for_img > img'); //is selecting all IMG children tags of #DIV_FOR_IMG Lesson 64 $('img[width = 200]'); //is selecting tag by atribute $('a[href ^= http]'); //is selecting tag by atribute which is BEGINING by this parameter $('img[src $= .jpg]'); //is selecting tag by atribute which is ENDING by this paramater $('img[src *= moto]'); //is selecting tag by atribute which CONTAINS this parameter Homework 64 $('#my_links a[href ^= documents]'); $('#forfooter img[title = Производители]'); Lesson 65 $('#moto_table tr:odd'); //even or odd is selecting double or not $('img:not(#div_for_img img)'); //selecting becides that one $('div:has(fieldset)'); // selecting all DIV's which contains tag FIELDSET $('p:contains(Мотоцикл)'); //selecting all P tags which contains text Мотоцикл $('#div_for_img img:first'); //selecting only the first image in the tag $('#div_for_img img:last'); //selecting only the last image in the tag $('div:hidden'); //selecting all DIV tags which are hidden $('div:visibility'); //selecting all DIV tags which are visible Lesson 66 $(document).ready(function() { }); // End of ready
module.exports = app => { const controller = require('../controller/heroes')(); app.route('/api/heroes') .get(controller.getHeroes) .post(controller.insertHero) app.route('/api/heroes/:id') .get(controller.getHero) .put(controller.updateHero) .delete(controller.deleteHero) return app; }
// common import EventIn from '../../common/source/EventIn'; // client only import AudioInBuffer from './AudioInBuffer'; import AudioInNode from './AudioInNode'; import SocketReceive from './SocketReceive'; export default { EventIn, AudioInBuffer, AudioInNode, SocketReceive, };
var http=require('http'); var myServer=http.createServer(function(req,res){ res.writeHead(200,{'content-type':'text/plain'}); res.write("hello\n"); setTimeout(function(){ res.end("world \n"); },2000); }); myServer.listen(8000);
$(document).ready(function(){ //Tab栏 $("#tablan_shouye").on("click",function(){ window.location="index.html"; }) $("#tablan_remai").on("click",function(){ window.location="sales.html"; }) $("#tablan_zhuanti").on("click",function(){ window.location="subject.html"; }) $("#tablan_wode").on("click",function(){ window.location='mine.html'; }) })
const chai = require('chai'); const assert = chai.assert; describe('/lib/appid-sdk', function(){ console.log("Loading appid-sdk-test.js"); var AppIdSDK; before(function(){ AppIdSDK = require("../lib/appid-sdk"); }) describe("#AppIdSDK", function(){ it("Should return APIStrategy and WebAppStrategy", function(){ assert.isFunction(AppIdSDK.WebAppStrategy); assert.isFunction(AppIdSDK.APIStrategy); }); }); });
$(document).ready(function () { GOVUK.toggle.init(); // Initialise auto-suggest fields //$('.auto-suggest').selectToAutocomplete(); // Uses radio buttons to emulate a more usable select box $(".js-form-select label").click(function() { $(this).closest('.js-form-select').toggleClass("open"); }); // Postcode lookup // Hide address list if user changes postcode var lastValue = ''; $("#postcode").on('change keyup paste mouseup', function () { if ($(this).val() != lastValue) { lastValue = $(this).val(); $("#address-list").addClass("js-hidden"); $("#submit-postcode").removeClass("js-hidden"); } }); //LIS function updateStatus() { if(document.getElementById("about_you_status") && document.getElementById("about_partner_status") && document.getElementById("property_status") && document.getElementById("where_you_live_status")) { var aboutYouStatus = document.getElementById("about_you_status"), aboutPartnerStatus = document.getElementById("about_partner_status"), propertyStatus = document.getElementById("property_status"), whereYouLiveStatus = document.getElementById("where_you_live_status"), sections = [aboutYouStatus, aboutPartnerStatus, propertyStatus, whereYouLiveStatus]; for (var section in sections) { if (sections[section].innerHTML === "Started") { sections[section].classList.add("incomplete-text"); sections[section].classList.remove("notstarted-text"); } else if (sections[section].innerHTML === "Completed") { sections[section].classList.add("complete-text"); sections[section].classList.remove("notstarted-text", "incomplete-text"); } } } } updateStatus(); //formatting for the list added in routes.js function updateList() { if(document.getElementById("people-list")) { var peopleList = document.getElementById("people-list").innerHTML; console.log(document.getElementById("people-list").innerHTML); peopleList = peopleList.replace(/\,/g, "</li> <li>"); document.getElementById("people-list").innerHTML = peopleList; } } updateList(); var buildRow = function(q, a, url) { return '<tr>' + '<td>' + q + '</td>' + '<td>' + a + '</td>' + '<td><a href="' + url + '">Change this</a></td>' + '</tr>'; }; if(document.getElementById('pension_answer')) { var pensionAnswer = document.getElementById('pension_answer').innerHTML; var creditAnswer = document.getElementById('credit_answer').innerHTML; var stateAnswer = document.getElementById('state_answer').innerHTML; var stateAmount = document.getElementById('state_amount').innerHTML; var stateFrequency = document.getElementById('state_frequency').innerHTML; var privateAnswer = document.getElementById('private_answer').innerHTML; var privateFrequency = document.getElementById('private_frequency').innerHTML; var privateAmount = document.getElementById('private_amount').innerHTML; var pensionSummary = []; var pensionTable = document.getElementById('pension_table'); pensionSummary.push(buildRow( 'Do you get a pension?', pensionAnswer, 'pension/newpension')); if(pensionAnswer === 'Yes') { pensionSummary.push(buildRow( 'Do you get Pension Credit Savings Credit?', creditAnswer, 'pension/newpen-credit')); if(creditAnswer === 'Yes') { pensionSummary.push(buildRow( 'Pension Credit Savings Credit payments', '£121 per week', 'pension/newpen-credit')); } pensionSummary.push(buildRow( 'Do you get a state pension?', stateAnswer, 'pension/pension')); if(stateAnswer === 'Yes') { pensionSummary.push(buildRow( 'State pension payments', '£' + stateAmount + ' ' + stateFrequency, 'pension/other-pension')); } pensionSummary.push(buildRow( 'Do you get another pension?', privateAnswer, 'pension/other-pension')); } if(privateAnswer === 'Yes') { pensionSummary.push(buildRow( 'First pension payments', '£' + privateAmount + ' ' + privateFrequency, 'pension/other-pension')); } pensionTable.innerHTML = pensionSummary.toString().replace(/,/g, ''); } }); jQuery(document).ready(function($) { $(".clickable-row").click(function() { window.document.location = $(this).data("href"); }); });
Template.activity.events({ 'submit form' : function(e) { e.preventDefault(); Activities.update( {_id:Template.currentData()._id}, {$push:{comments:{ user: { _id: Meteor.user()._id, email: Meteor.user().emails[0].address }, date: new Date(), text: $('#comment').val() }}}); } }); Template.activity.helpers({ activities: function(){ return Activities.findOne({}); }, haveAlink : function(){ //console.log("hl",Template.currentData().url != "undefined"); //return typeof Template.currentData().url != "undefined"; return true; }, like : function() { console.log("hi !"); //var like = Activities.findOne({ // _id: Template.currentData().likers.length}); //return like; return Template.currentData().likers.length; } }); Template.activity.events({ 'click #nL' : function(event){ console.log("j'aime !"+ this.name); console.log("data:",Template.currentData()); console.log("user:",Meteor.user()) if(Meteor.userId() === null){ }else{ var like = Activities.findOne({ _id: Template.currentData()._id, likers: Meteor.user()._id }); if(typeof like == "undefined") Activities.update({_id: Template.currentData()._id}, {$push:{likers: Meteor.user()._id}}); else Activities.update({_id: Template.currentData()._id}, {$pull:{likers: Meteor.user()._id}}); } } });
var React = require('react'), _ = require('underscore'); /* * Wrapper for children components * Used to cache the size of elements */ var InfiniteListItem = React.createClass({ getInitialState : function () { return {}; }, render : function () { var style; if (!this.props.rendered) { return false; } style = {}; style.overflow = 'hidden' return (<div style={style}>{this.props.children}</div>); } }); module.exports = InfiniteListItem;
import "./Poll.css"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { handleAnswerQuestion } from "../../actions/questions"; import { isPollAnswered, sortQuestions } from "../../utils/helpers"; import NotFound from "./NotFound"; import Avatar from "../Avatar"; import PropTypes from "prop-types"; const AnsweredQuestion = (props) => { const votesA = props.question.optionOne.votes.length; const votesB = props.question.optionTwo.votes.length; const totalVotes = votesA + votesB; return ( <div className="view"> <h1>Answered question</h1> <div className="list-item"> <p className="user-info"> Created by {props.author.name} <Avatar src={props.author.avatarURL} /> </p> <div className="question-label">Would You Rather</div> <table className="question-row"> <tbody> <tr> <td className={`question-data${ props.answer === "optionOne" ? " user-answer" : "" }`} > <p className="question">{props.question.optionOne.text}</p> <div> {votesA} users chose this answer ( {Math.round((votesA / totalVotes) * 100)}%) </div> </td> <td className={`question-data${ props.answer === "optionTwo" ? " user-answer" : "" }`} > <p className="question">{props.question.optionTwo.text}</p> <div> {votesB} users chose this answer ( {Math.round((votesB / totalVotes) * 100)}%) </div> </td> </tr> </tbody> </table> <div className="next-question"> {props.nextQuestionId == null ? ( <button disabled className="view"> You have answered all available questions! </button> ) : ( <Link to={`/questions/${props.nextQuestionId}`}> <button className="view">Answer another question</button> </Link> )} </div> </div> </div> ); }; AnsweredQuestion.propTypes = { question: PropTypes.object, author: PropTypes.object, answer: PropTypes.string, dispatch: PropTypes.func, nextQuestionId: PropTypes.string, }; const UnansweredQuestion = (props) => { function handleAnswer(answer) { const { dispatch } = props; dispatch(handleAnswerQuestion(props.question.id, answer)); } return ( <div className="view"> <h1>Answer Question</h1> <div className="list-item"> <p className="user-info"> <Avatar src={props.author.avatarURL} /> {props.author.name} asked: </p> <p className="question-label">Would You Rather</p> <div className="question"> <button className="view vote" onClick={() => handleAnswer("optionOne")} > {props.question.optionOne.text} </button> </div> <p className="question-label">OR</p> <div className="question"> <button className="view vote" onClick={() => handleAnswer("optionTwo")} > {props.question.optionTwo.text} </button> </div> </div> </div> ); }; UnansweredQuestion.propTypes = { question: PropTypes.object, author: PropTypes.object, dispatch: PropTypes.func, }; const Poll = (props) => { return props.question == null ? ( <NotFound /> ) : props.answer != null ? ( <AnsweredQuestion question={props.question} author={props.author} answer={props.answer} dispatch={props.dispatch} nextQuestionId={props.nextQuestionId} /> ) : ( <UnansweredQuestion question={props.question} author={props.author} dispatch={props.dispatch} /> ); }; Poll.propTypes = { question: PropTypes.object, author: PropTypes.object, answer: PropTypes.string, nextQuestionId: PropTypes.string, }; function mapStateToProps({ questions, users, authedUser }, props) { const { id } = props.match.params; const question = questions[id]; const answer = authedUser == null ? null : users[authedUser].answers[id]; const author = question == null ? null : users[question.author]; const nextQuestion = sortQuestions(questions).find( (poll) => !isPollAnswered(poll, authedUser) ); const nextQuestionId = nextQuestion != null ? nextQuestion.id : null; return { question, author, answer, nextQuestionId }; } export default connect(mapStateToProps)(Poll);
export function getDogPhoto() { return dispatch => { // экшен с типом REQUEST (запрос начался) // диспатчится сразу, как будто-бы перед реальным запросом dispatch({ type: 'REQUEST_DOG_PHOTO', payload: 'request_photo_started', }) // наши данные загружались из сети fetch('https://dog.ceo/api/breeds/image/random') .then((response) => { if (!response.ok) { throw Error(response.statusText); }; return response; }) .then((response) => response.json()) .then((items) => { dispatch({ type: 'PUT_NEW_DOG_PHOTO', payload: items.message, }) }) .catch(() => { dispatch({ type: 'ERROR_LOADING_DOG_PHOTO', payload: 'https://steamuserimages-a.akamaihd.net/ugc/421440132200635177/B1F9168CB157C3FA4907FA7F23F0069AF14FE1C1/', }) }); }; };
/** * 新建订单 */ import React, { Component, PureComponent } from "react"; import { StyleSheet, Dimensions, View, Text, Image, ScrollView, TouchableOpacity, } from "react-native"; import { connect } from "rn-dva" import CommonStyles from '../../../common/Styles' import Header from '../../../components/Header' import * as orderRequestApi from '../../../config/Apis/order' import math from '../../../config/math'; import { keepTwoDecimal } from "../../../config/utils"; const { width, height } = Dimensions.get("window") function getwidth(val) { return width * val / 375 } export default class CreateOrderScreen extends Component { constructor(props){ super(props) this.state=props.navigation.state.params || {} } renderXiwei = () => { const { canAddGoods, serviceData } = this.state if (canAddGoods) { return serviceData.map((item, index) => { let seat = item.seat return ( <View style={styles.xiweiView} key={index}> <View style={styles.serviceTitle}> <View style={styles.xiweiItemTitle} > <Text style={styles.c2f14}>席位:{seat && seat.seatName}</Text> </View> </View> <View style={styles.goodsViewStyle}> { this.renderServiceGoods(index) } </View> </View> ) }) } } renderServiceGoods = (index) => { const { serviceData } = this.state let data = [] if (serviceData[index].goods) { data = serviceData[index].goods } return data.map((item, index) => { let borderBt = styles.borderBt if (index === data.length - 1) { borderBt = null } return ( <View style={[styles.serviceItem, borderBt]} key={index}> <View style={styles.serviceItemimg}> <Image source={{ uri: item.mainPic }} style={{ width: getwidth(80), height: 80 }} /> </View> <View style={{ flex: 1, height: 80, marginLeft: 15, alignSelf: 'center' }}> <View style={styles.textItem}> <View style={{ flex: 1 }}> <Text style={styles.c2f14}>{item.goodsName}</Text> </View> </View> <View style={{ marginTop: 13 }}> <Text style={styles.c7f12}>{item.skuName}</Text> </View> <View style={{ flexDirection: 'row', marginTop: 15, alignItems: 'center' }}> <Text style={styles.credf14}>¥{keepTwoDecimal(math.divide(item.platformShopPrice , 100))} </Text><Text style={[styles.ccf10, { textDecorationLine: 'line-through' }]}> (市场价¥{keepTwoDecimal(math.divide(item.originalPrice,100)) })</Text> </View> </View> </View> ) }) } renderServiceData = () => { const { serviceData } = this.state return serviceData.map((item, index) => { let borderBt = styles.borderBt if (index === serviceData.length - 1) { borderBt = null } return ( <View style={[styles.serviceItem, borderBt]} key={index}> <View style={styles.serviceItemimg}> <Image source={{ uri: item.mainPic }} style={{ width: getwidth(80), height: 80 }} /> </View> <View style={{ flex: 1, height: 80, marginLeft: 15, alignSelf: 'center' }}> <View style={styles.textItem}> <View style={{ flex: 1 }}> <Text style={styles.c2f14}>{item.goodsName}</Text> </View> </View> <View style={{ marginTop: 13 }}> <Text style={styles.c7f12}>{item.skuName}</Text> </View> <View style={{ flexDirection: 'row', marginTop: 15, alignItems: 'center' }}> <Text style={styles.credf14}>¥{keepTwoDecimal(item.platformShopPrice / 100)} </Text><Text style={[styles.ccf10, { textDecorationLine: 'line-through' }]}> (市场价¥{keepTwoDecimal(math.divide(item.originalPrice,100)) })</Text> </View> </View> </View> ) }) } saveData = () => { Loading.show() orderRequestApi.fetchBcleMUserOrderCreate(this.state.fetchParam).then((res) => { const { navigation } = this.props Toast.show('新增成功') navigation.navigate('CreateOrderSucess',{orderParams:{ ...res, orderId:res.orderIdByString || res.orderId, ...this.state.fetchParam }}) }).catch(err => { console.log(err) }); } render() { const { navigation } = this.props console.log(this.state) return ( <View style={styles.container}> <Header navigation={navigation} goBack={true} title='生成订单' rightView={ <TouchableOpacity onPress={()=>navigation.goBack()} style={{ width: 50, height: 44 + CommonStyles.headerPadding, justifyContent: 'center', alignItems: 'center' }} ><Text style={styles.cff17}>编辑</Text> </TouchableOpacity> } /> <View style={styles.mainstyle}> <ScrollView showsVerticalScrollIndicator={false}> <View style={styles.serviceview} contentContainerStyle={{paddingBottom:20}}> <View style={styles.serviceTitle}> <View><Text style={styles.c2f14}>服务</Text></View> </View> <View style={{ paddingHorizontal: 15 }}> { this.renderServiceData() } </View> </View> <View style={styles.serviceview}> <View style={styles.serviceTitle}> <Text style={styles.c2f14}>席位选择</Text> <Text style={styles.c2f14}>已选{this.state.serviceData.length}个</Text> </View> </View> { this.renderXiwei() } </ScrollView> </View> <View style={{marginTop:10, backgroundColor:'#fff',borderRadius:6,width:getwidth(355),paddingHorizontal:15,paddingVertical:15}}> <View style={styles.row}> <Text style={{color:'#777'}}>总金额:</Text> <Text style={{color:CommonStyles.globalRedColor}}>¥{this.state.realTotalPrice}</Text> </View> <View style={[styles.row,{marginTop:10}]}> <Text style={{color:'#777'}}>实际支付:</Text> <Text style={{color:CommonStyles.globalRedColor}}>¥{this.state.totalPrice}</Text> </View> </View> <TouchableOpacity style={styles.bottomView} onPress={this.saveData}> <Text style={{color:'#fff',fontSize:17}}>确认生成订单</Text> </TouchableOpacity> </View > ) } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, alignItems: 'center', backgroundColor: CommonStyles.globalBgColor, }, row:{ flexDirection:'row', alignItems:'center', justifyContent:'space-between' }, serviceItem: { // width: getwidth(325), height: 110, flexDirection: 'row', backgroundColor: '#fff' }, borderBt: { borderBottomColor: '#D7D7D7', borderBottomWidth: 0.5 }, serviceItemimg: { width: getwidth(80), height: 110, justifyContent: 'center', alignItems: 'center' }, textItem: { width: '100%', flexDirection: 'row', justifyContent: 'space-between' }, cff17: { color: '#FFFFFF', fontSize: 17 }, c7f12: { color: '#777777', fontSize: 12 }, c2f14: { color: '#222222', fontSize: 14 }, cbluef14: { color: '#4A90FA', fontSize: 14 }, c9f12: { color: '#999999', fontSize: 12 }, credf14: { color: '#EE6161', fontSize: 14 }, ccf14: { color: '#CCCCCC', fontSize: 14 }, ccf10: { color: '#CCCCCC', fontSize: 10, }, c7f14: { color: '#777777', fontSize: 14 }, mainstyle: { width: width, flex: 1, paddingHorizontal: 10, }, serviceview: { width: getwidth(355), backgroundColor: '#fff', marginTop: 10, borderRadius: 8, borderColor: '#F1F1F1', borderWidth: 1 }, serviceTitle: { width: getwidth(355), height: 40, borderBottomColor: '#F1F1F1', borderBottomWidth: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 15 }, serviceTitleBtn: { width: 100, height: 40, justifyContent: 'center', alignItems: 'flex-end', }, addService: { width: getwidth(355), height: 67, justifyContent: 'center', alignItems: 'center' }, infoItem: { width: getwidth(325), height: 40, flexDirection: 'row' }, infoItemtitle: { flex: 4, height: 40, justifyContent: 'center' }, infoItemexpand: { flex: 6, height: 40, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }, xiweiView: { width: getwidth(355), backgroundColor: '#fff', marginTop: 10, borderRadius: 6, borderColor: '#F1F1F1', borderWidth: 1, overflow:'hidden' }, goodsViewStyle: { width: getwidth(355), paddingHorizontal: 15 }, xiweiTitle: { width: getwidth(355), height: 40, borderColor: '#F1F1F1', borderWidth: 1, paddingHorizontal: 15, flexDirection: 'row', alignItems: 'center' }, xiweiItemTitle: { flex: 4, height: 40, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }, xiweiItemRight: { flex: 6, height: 40, alignItems: 'flex-end', justifyContent: 'center' }, noGoods: { width: getwidth(355), height: 67, justifyContent: 'center', alignItems: 'center' }, bottomView:{ justifyContent:'center', alignItems:'center', backgroundColor:CommonStyles.globalHeaderColor, width:width, marginBottom:CommonStyles.footerPadding, height:50, marginTop:20 }, })
const React = require('react'); const hashHistory = require('react-router').hashHistory; const SessionStore = require('../../stores/session_store'); const ErrorStore = require('../../stores/error_store'); const SessionActions = require('../../actions/session_actions'); const ErrorActions = require('../../actions/error_actions'); const LoginForm = React.createClass({ getInitialState(){ return ({username: "", password: "", errors: ErrorStore.formErrors("login")}); }, componentDidMount(){ this.errorListener = ErrorStore.addListener(this.trackErrors); this.sessionListener = SessionStore.addListener(this.checkLogin); if (this.state.errors) { this.state.errors.forEach (error => { ErrorActions.clearErrors(error); }); } }, componentWillUnmount(){ this.errorListener.remove(); this.sessionListener.remove(); }, trackErrors(){ this.setState({errors: ErrorStore.formErrors("login")}); }, checkLogin(){ if(SessionStore.isUserLoggedIn){ hashHistory.push("index"); } }, updateName(e){ e.preventDefault(); this.setState({username: e.target.value}); }, updatePassword(e){ e.preventDefault(); this.setState({password: e.target.value}); }, handleSubmit(e){ e.preventDefault(); SessionActions.login({username: this.state.username, password: this.state.password}); }, render(){ let errors = ""; if(this.state.errors){ errors = this.state.errors.map(error => { return (<div className="error" key={error}>{error}<br/></div>); }); } return ( <div> {errors} <form onSubmit={this.handleSubmit} className="form"> <input type="text" onChange={this.updateName} placeholder="Username"/> <br /> <input type="password" onChange={this.updatePassword} placeholder="Password"/> <br /> <input type="submit" value="Log In" className="entry"/> </form> </div> ); } }); module.exports = LoginForm;
"use strict" var tileSpacing = 10; $(document).ready(function(){ $(".tile-content").on('click mouseleave touchend', function(e){ console.log('content test'); $('.tile-content').animate({ scrollTop: $('.tile-content img').offset().bottom -20 }, 'slow'); }); $('.sortLink').on('click', function(e){ e.preventDefault(); $('.sortLink').removeClass('selected'); $(this).addClass('selected'); var keyword = $(this).attr('data-keyword'); console.log('call sorttiles') sorttiles(keyword); }); //sets margin of tile spacing $('.tiles-gallery .sortBySubject').css('margin-bottom', window.tileSpacing + 'px'); $('.tile-container .tile').addClass('showMe'); console.log('call positiontiles'); // This is called once on document ready. positiontiles(); }); function sorttiles(keyword){ $('.tile').each(function(){ console.log('test ' + keyword) // console.log('sort tiles by ' + keyword); // This gets called 12 times? var tileKeywords = $(this).attr('data-keywords'); if(keyword == 'all'){ $(this).addClass('showMe').removeClass('hideMe'); // console.log('show all'); } else { if(tileKeywords.indexOf(keyword) != -1){ // console.log('show ' + keyword); $(this).addClass('showMe').removeClass('hideMe'); } else { // console.log('hide ' + keyword); $(this).addClass('hideMe').removeClass('showMe'); } } }); positiontiles(); } function positiontiles(){ $('debug-remainder').html(''); $('.tile.hideMe').animate({opacity: 0}, 500, function(){ $(this).css({ 'display': 'none', 'top': '0px', 'left': '0px' }); }); var containerWidth = $('.tiles').width(); var tile_R = 10; var tile_C = 10; var tileWidth = $('.tile img:first-child').outerWidth() + 70 + window.tileSpacing; var tileHeight = $('.tile img:first-child').outerHeight() + 70 + window.tileSpacing; var max_C = Math.floor(containerWidth/ tileWidth); // measuring the tiles and the container $('.tile-container .tile.showMe').each(function(index){ var remainder = (index%max_C)/100; var maxIndex = 0; // calculate the remainders $('.debug-remainder').append(remainder + ' - '); // calculate rows and columns if(remainder == 0){ if(index != 0){ tile_R += tileHeight; } tile_C = 0; } else { tile_C +=tileWidth; } // position and animate the tiles $(this).css('display', 'block').animate({ 'opacity': 1, 'top':tile_R + 'px', 'left': tile_C + 'px' }, 500); // Reset the size of the photo container var newWidth = max_C * tileWidth; var newHeight = tile_R + tileHeight; $('.tile-container').css({'width': newWidth + 'px', 'height': newHeight + 'px'}); }); }
import React from 'react'; import $ from 'jquery'; import Editor from './editor'; import Item from './item'; import galleryActions from '../action/galleryActions'; import itemStore from '../store/itemStore'; /** * @func getItemStoreState * @private * @return {object} * @desc Factory for getting the current state of the ItemStore. */ function getItemStoreState() { return { items: itemStore.getAll() }; } class Gallery extends React.Component { constructor(props) { super(props); var items = window.SS_ASSET_GALLERY[this.props.name]; // Manually bind so listeners are removed correctly this.onChange = this.onChange.bind(this); galleryActions.setStoreProps({ data_url: props.data_url, update_url: props.update_url, delete_url: props.delete_url, initial_folder: props.initial_folder, limit: props.limit }); // Populate the store. for (let i = 0; i < items.length; i += 1) { galleryActions.create(items[i], true); } // Set the initial state of the gallery. this.state = $.extend(getItemStoreState(), { editing: false, currentItem: null }); } componentDidMount () { // @todo // if we want to hook into dirty checking, we need to find a way of refreshing // all loaded data not just the first page again... var $content = $('.cms-content-fields'); if ($content.length) { $content.on('scroll', (event) => { if ($content[0].scrollHeight - $content[0].scrollTop === $content[0].clientHeight) { galleryActions.page(); } }); } itemStore.addChangeListener(this.onChange); } componentWillUnmount () { itemStore.removeChangeListener(this.onChange); } render() { if (this.state.editing) { let editorComponent = this.getEditorComponent(); return ( <div className='gallery'> {editorComponent} </div> ); } else { let items = this.getItemComponents(); let button = null; if (itemStore.hasNavigated()) { button = <button type='button' onClick={this.handleNavigate.bind(this)}> Back </button>; } return ( <div className='gallery'> {button} <div className='gallery__items'> {items} </div> </div> ); } } handleNavigate() { let navigation = itemStore.popNavigation(); galleryActions.navigate(navigation[1]); } /** * @func onChange * @desc Updates the gallery state when somethnig changes in the store. */ onChange() { this.setState(getItemStoreState()); } /** * @func setEditing * @param {boolean} isEditing * @param {string} [id] * @desc Switches between editing and gallery states. */ setEditing(isEditing, id) { var newState = { editing: isEditing }; if (id !== void 0) { let currentItem = itemStore.getById(id); if (currentItem !== void 0) { this.setState($.extend(newState, { currentItem: currentItem })); } } else { this.setState(newState); } } /** * @func getEditorComponent * @desc Generates the editor component. */ getEditorComponent() { var props = {}; props.item = this.state.currentItem; props.setEditing = this.setEditing.bind(this); return ( <Editor {...props} /> ); } /** * @func getItemComponents * @desc Generates the item components which populate the gallery. */ getItemComponents() { var self = this; return Object.keys(this.state.items).map((key) => { var item = self.state.items[key], props = {}; props.attributes = item.attributes; props.id = item.id; props.setEditing = this.setEditing.bind(this); props.title = item.title; props.url = item.url; props.type = item.type; props.filename = item.filename; return ( <Item key={key} {...props} /> ); }); } } export default Gallery;
var Sudok = Sudok || {} const Default_nums = {1: true,2: true,3: true,4: true,5: true,6: true,7: true,8: true,9: true} Sudok.Shu = function(id, x, y) { this.id = id this.x = x this.y = y this.aNum = null this.hasANum = false this.avaNums = {...Default_nums} this.group = this.calcGroup() this.relation = [] } Sudok.Shu.prototype.getANum = function() { return this.aNum } Sudok.Shu.prototype.generateANum = function() { let temp_arr = [] Object.keys(this.avaNums).forEach(k => { if (this.avaNums[k]) temp_arr.push(k) }) let ii = Math.floor(Math.random() * temp_arr.length) if (ii >= temp_arr.length) { console.log(temp_arr.length, ii, temp_arr.length > ii) // throw new Error('invalid ava num length') } this.aNum = parseInt(temp_arr[ii]) this.hasANum = true // this.dissANum(num) this.relation.forEach(ss => { ss.dissANum(this.aNum) }) return this.aNum } Sudok.Shu.prototype.setANum = function(num) { this.aNum = parseInt(num) this.hasANum = true this.relation.forEach(ss => { ss.dissANum(this.aNum) }) return this.aNum } Sudok.Shu.prototype.resetANum = function(num) { this.aNum = null this.hasANum = false this.relation.forEach(ss => { // ss.dissANum(this.aNum) ss.avaNums[this.aNum] = true }) return this.aNum } Sudok.Shu.prototype.avaANum = function(n) { return this.avaNums[n] } // only one ava num Sudok.Shu.prototype.checkAvaiable = function(n) { let temp_arr = [] Object.keys(this.avaNums).forEach(k => { if (this.avaNums[k]) { temp_arr.push(k) } }) return temp_arr.length === 1 } Sudok.Shu.prototype.dissANum = function(n) { this.avaNums[n] = false } Sudok.Shu.prototype.calcGroup = function() { return Math.floor((this.y) / 3 ) * 3 + Math.floor((this.x) / 3 ) * 1 } Sudok.Shu.prototype.genRelation = function(sm) { let rel = [] // x 不变,y取 1-9 for (let j = 0; j < Sudok.MAXLEN; j++) { if (j !== this.y) { // rel.push({ x: this.x, y: j}) rel.push(sm.get(this.x, j)) } } // y 不变,x取 1-9 for (let i = 0; i < Sudok.MAXLEN; i++) { if (i !== this.x) { // rel.push({ x: i, y: this.y}) rel.push(sm.get(i, this.y)) } } // 当前组 sm.forEach(shu => { if (shu.group === this.group && (shu.x !== this.x || shu.y != this.y)) { if (!rel.some(({ x, y }) => x === shu.x && y === shu.y)) { // rel.push({ x: shu.x, y: shu.y }) rel.push(shu) } } }) this.relation = rel return rel }
function getPhone(evt) { evt.preventDefault(); var yelpID = $(this).data()['yelpid']; $('#td-' + yelpID).append('<div id="sms-form-' + yelpID + '"><form action="#" \ method="POST"><input type="number" \ id="sms-' + yelpID + '" \ placeholder="e.g. 14158872215" maxlength="11" \ required><input type="submit" value="Send" \ id="submit-sms-' + yelpID + '"></form><span \ class="incorrect-input">Please input exactly 11 \ digits.</span></div>'); $('#sms-' + yelpID).focus(); $('#submit-sms-' + yelpID).click( function(evt){ evt.preventDefault(); var recipient = $('#sms-' + yelpID).val(); if (recipient.length === 11) { sendSMS(yelpID, recipient); $('#sms-form-' + yelpID + ' .incorrect-input').removeClass("revealed"); } else { $('#sms-form-' + yelpID + ' .incorrect-input').addClass("revealed"); } }); } function sendSMS(yelpID, recipient) { var params = {'yelpID': yelpID, 'recipient': recipient}; $.post('/send-sms', params, processSMSResponse); $('#sms-form-' + yelpID).html("Sending message..."); } function processSMSResponse(result) { $('#sms-form-' + result.yelpID).html(result.success_result).fadeOut(3000); var container = document.getElementById('sms-form-' + result.yelpID); setTimeout(function(){ removeFormDiv(container) }, 4000); } // removeFormDiv() is stored in send_mail.js file
import React from 'react'; export default class Menu extends React.Component { render() { return ( <div className={'col-s-3 col-l-3 menu'}> <ul> <li>menu one</li> <li>menu two</li> <li>menu three</li> </ul> </div> ); } }
import TicketsTable from '../../components/tickets-table/tickets-table'; const LandingPage = ({ currentUser, tickets }) => ( <div> <h1>Tickets</h1> <TicketsTable tickets={tickets} /> </div> ); export default LandingPage;
describe('pixi/loaders/AssetLoader', function () { 'use strict'; var expect = chai.expect; var AssetLoader = PIXI.AssetLoader; it('Module exists', function () { expect(AssetLoader).to.be.a('function'); }); });
var _ = require('lodash'); var uuid = require('node-uuid'); var Page = require('./neo4j/page'); const _manyPages = function (result) { return result.records.map(r => new Page(r.get('p'))); }; const getAll = function(session) { return session.run('MATCH (p:Page) RETURN p') .then(_manyPages); }; // Create profile const createPage = function (session, {name}) { return session.run('MATCH (page:Page {name: {name}}) RETURN page', {name: name}) .then(results => { if (!_.isEmpty(results.records)) { throw {name: 'name already in use', status: 400} } else { return session.run('CREATE (page:Page {id:{id}, name: {name}}) RETURN page', { id: uuid.v4(), name: name } ).then(results => { return new Page(results.records[0].get('page')); } ) } }); }; module.exports = { getAll: getAll, createPage: createPage };
//soal 1 console.log("SOAL PERTAMA") var kataPertama = "saya"; var kataKedua = "senang"; var kataKetiga = "belajar"; var kataKeempat = "javascript"; var kedua=kataKedua.toUpperCase().charAt(0)+kataKedua.toLowerCase().slice(1); var blank=" "; console.log(kataPertama.concat(blank.concat(kedua.concat(blank.concat(kataKetiga.concat(blank.concat(kataKeempat.toUpperCase()))))))) console.log("--------------------------------------------------") //soal 2 console.log("SOAL KEDUA") var kataPertama = "1"; var kataKedua = "2"; var kataKetiga = "4"; var kataKeempat = "5"; var angkapertama=parseInt(kataPertama); var angkakedua=parseInt(kataKedua); var angkaketiga=parseInt(kataKetiga); var angkakeempat=parseInt(kataKeempat); var total=angkapertama+angkakedua+angkaketiga+angkakeempat; console.log(total.toString()) console.log("--------------------------------------------------") //soal 3 console.log("SOAL KETIGA") var kalimat = 'wah javascript itu keren sekali'; var kataPertama = kalimat.substring(0, 3); var kataKedua=kalimat.substring(4,14); // do your own! var kataKetiga=kalimat.substring(15,18); // do your own! var kataKeempat=kalimat.substring(19,24); // do your own! var kataKelima=kalimat.substring(25,31); // do your own! console.log('Kata Pertama: ' + kataPertama); console.log('Kata Kedua: ' + kataKedua); console.log('Kata Ketiga: ' + kataKetiga); console.log('Kata Keempat: ' + kataKeempat); console.log('Kata Kelima: ' + kataKelima); console.log("--------------------------------------------------") //soal 4 console.log("SOAL KEEMPAT") var nilai=67; if(nilai>=80){ console.log("A"); } else if(nilai>=70&&nilai<80){ console.log("B"); } else if(nilai>=60&&nilai<70){ console.log("C"); } else if(nilai>=50&&nilai<60){ console.log("D"); } else if(nilai<50){ console.log("E"); } console.log("--------------------------------------------------") //soal 5 console.log("SOAL KELIMA") var tanggal = 30; var bulan = 1; var tahun = 2001; switch(bulan) { case bulan=1: console.log(tanggal.toString().concat(blank.concat("Januari".concat(blank.concat(tahun))))); break; case bulan=2: console.log(tanggal.toString().concat(blank.concat("Februari".concat(blank.concat(tahun))))); break; case bulan=3: console.log(tanggal.toString().concat(blank.concat("Maret".concat(blank.concat(tahun))))); break; case bulan=4: console.log(tanggal.toString().concat(blank.concat("April".concat(blank.concat(tahun))))); break; case bulan=5: console.log(tanggal.toString().concat(blank.concat("Mei".concat(blank.concat(tahun))))); break; case bulan=6: console.log(tanggal.toString().concat(blank.concat("Juni".concat(blank.concat(tahun))))); break; case bulan=7: console.log(tanggal.toString().concat(blank.concat("Juli".concat(blank.concat(tahun))))); break; case bulan=8: console.log(tanggal.toString().concat(blank.concat("Agustus".concat(blank.concat(tahun))))); break; case bulan=9: console.log(tanggal.toString().concat(blank.concat("September".concat(blank.concat(tahun))))); break; case bulan=10: console.log(tanggal.toString().concat(blank.concat("Oktober".concat(blank.concat(tahun))))); break; case bulan=11: console.log(tanggal.toString().concat(blank.concat("November".concat(blank.concat(tahun))))); break; case bulan=12: console.log(tanggal.toString().concat(blank.concat("Desember".concat(blank.concat(tahun))))); break; default: console.log("Bulan tidak valid"); }
var assert = require('chai').assert; var birthday = require('../src/filters/birthday'); describe('Filters', function () { describe('birthday', function () { it('appends no properties when $birthday is undefined', function () { var results = {}; birthday.visit(results, {}); assert.deepEqual(results, {}); }); }); });
import StudentListImporting from '@/views/adminViews/import/StudentListImporting.vue' import TimetableImporting from '@/views/adminViews/import/TimetableImporting.vue' import TeacherListImporting from '@/views/adminViews/import/TeacherListImporting.vue' import ViewEvaluationBG from '@/views/adminViews/view/ViewEvaluationBG.vue' import ViewStudentEvaluationResults from '@/views/adminViews/view/ViewStudentEvaluationResults.vue' import ViewAllEvaluationResults from '@/views/adminViews/view/ViewAllEvaluationResults.vue' import Classes from '@/views/adminViews/view/Classes.vue' import ViewStudentEvaluationResultsDetails from '@/views/adminViews/view/ViewStudentEvaluationResultsDetails.vue' import modifyTeacherEvaluationForm from '@/views/adminViews/manage/ModifyTeacherEvaluationForm.vue' import modifyStudentEvaluationForm from '@/views/adminViews/manage/ModifyStudentEvaluationForm' import releaseStudentComments from '@/views/adminViews/manage/ReleaseStudentComments' import releaseTeacherComments from '@/views/adminViews/manage/ReleaseTeacherComments' let adminRouter = [ { path: '/studentListImporting', component: StudentListImporting }, { path: '/timetableImporting', component: TimetableImporting }, { path: '/teacherListImporting', component: TeacherListImporting }, // 二级 { path: '/viewEvaluation', redirect: '/viewStudentEvaluationResults' }, { path: '/viewEvaluation', component: ViewEvaluationBG, children: [ // 查看学生 { path: '/viewStudentEvaluationResults', name: 'ViewStudentEvaluationResults', component: ViewStudentEvaluationResults }, { path: '/viewStudentEvaluationResultsDetails/:tcId:courseName:teacherName', name: 'ViewStudentEvaluationResultsDetails', component: ViewStudentEvaluationResultsDetails }, // 查看所有 { path: '/viewAllEvaluationResults', name: 'ViewAllEvaluationResults', component: ViewAllEvaluationResults }, { path: '/Classes', name: 'Classes', component: Classes } ] }, // 结束 { path: '/modifyTeacherEvaluationForm', component: modifyTeacherEvaluationForm }, { path: '/modifyStudentEvaluationForm', component: modifyStudentEvaluationForm }, { path: '/releaseStudentComments', component: releaseStudentComments }, { path: '/releaseTeacherComments', component: releaseTeacherComments }] export default adminRouter
import isDefined from '../type-checking/is-defined' function isPropertyWritable(object, propertyName) { const descriptor = Object.getOwnPropertyDescriptor(object, propertyName) if (descriptor) { return isDefined(descriptor.writable) ? descriptor.writable : true } else { return true } } function isPropertyEnumerable(object, propertyName) { return object.propertyIsEnumerable(propertyName) } export default function extend(original, ...overrides) { if (!overrides.length) { return original } const override = overrides.shift() const props = Object.getOwnPropertyNames(override) props.forEach((prop) => { if ( isPropertyEnumerable(override, prop) && isPropertyWritable(original, prop) ) { original[prop] = override[prop] } }) return extend(original, ...overrides) }
import { apiEndpoint } from '@constants' import { redux } from '@utils' export const initialState = { list: [], code: null, error: null, isFetching: false, } export const endpoints = { highlight: `http://${apiEndpoint}/highlight` } export const actionTypeConst = { getHighlight: redux.actionTypes('GET_HIGHLIGHT_LIST'), clearup: 'CLEAR_HIGHLIGHT_LIST' }
const calculateTotalWithTip = (totalWithoutTip, tipPercent) => { return Number(tipPercent) / 100 * Number(totalWithoutTip) + Number(totalWithoutTip); } const splitAmongDiners = (calculateTotalWithTip, numOfDiners) => { return Number(calculateTotalWithTip) / Number(numOfDiners); } calculateTotalWithTip(100, 15); splitAmongDiners(50,5);//should return '10' console.log(calculateTotalWithTip);
import React from 'react'; import logo from './logo.png'; import profile from './profile.jpg'; import './Header.css'; function Header() { return ( <div id="header"> <div className="header-background"></div> <div className="header-gardient"></div> <div className="header-content"> <div className="picture-and-logo"> <img src={profile} className="profile-picture" alt="profile" /> <img src={logo} className="app-logo" alt="logo" /> </div> <span className="vertical-divider" /> <div className="about-me"> <h1>Tali Volf</h1> <h2>Bio:</h2> <p className="bio"> Tali, 25, Israel <span role="img" aria-label="emoji">✌</span> <br /> Shooting with my Canon 100D. <span role="img" aria-label="emoji">📷</span> <br /> “Only photograph what you love.” <span role="img" aria-label="emoji">🖤</span> <br /> – Tim Walker</p> <p> <a href="https://www.facebook.com/mytree.xx">Facebook</a> | <a href="https://www.instagram.com/talivolf/"> Instagram</a> | <a href="mailto:tali.vulf@gmail.com"> tali.vulf@gmail.com</a> </p> </div> </div> </div> ); } export default Header;
'use strict'; const Tree = require('../BST'); const fizzBuzz = require('../fizzBuzzTree/fizz-buzz') describe( 'FizzBuzz can take in a tree and calculate fizz or buzz', ()=>{ it('should be able to take in tree and calculate fizz or buzz', ()=>{ let tree = new Tree.BinaryTree; let a = new Tree.Node(30); let b = new Tree.Node(15); let c = new Tree.Node(27); let d = new Tree.Node(5); let e = new Tree.Node(18); let f = new Tree.Node(20); a.left = b; a.right = c; b.right = d; b.left = e; c.right = f; tree.root = a; fizzBuzz(a); expect(tree.preOrder(a)).toEqual(["FizzBuzz", "FizzBuzz", "Fizz", "Buzz", "Fizz", "Buzz"]) }) it('it ignores all other numbers', ()=>{ let tree = new Tree.BinaryTree; let a = new Tree.Node(30); let b = new Tree.Node(15); let c = new Tree.Node(27); let d = new Tree.Node(5); let e = new Tree.Node(4); let f = new Tree.Node(20); a.left = b; a.right = c; b.right = d; b.left = e; c.right = f; tree.root = a; fizzBuzz(a); expect(tree.preOrder(a)).toEqual(["FizzBuzz", "FizzBuzz", 4, "Buzz", "Fizz", "Buzz"]) }) it('should ignore string values', ()=>{ let tree = new Tree.BinaryTree; let a = new Tree.Node(30); let b = new Tree.Node(15); let c = new Tree.Node(27); let d = new Tree.Node(5); let e = new Tree.Node('hello'); let f = new Tree.Node(20); a.left = b; a.right = c; b.right = d; b.left = e; c.right = f; tree.root = a; fizzBuzz(a); expect(tree.preOrder(a)).toEqual(["FizzBuzz", "FizzBuzz", 'hello', "Buzz", "Fizz", "Buzz"]) }) })
var roleSuicider = { run: function(creep) { var targets = creep.room.find(FIND_STRUCTURES, { filter: (structure) => { return (structure.structureType == STRUCTURE_SPAWN); } }); if (Game.spawns['Spawn1'].recycleCreep(creep) === ERR_NOT_IN_RANGE) { creep.moveTo(targets[0].pos); } } }; module.exports = roleSuicider;
import "./navbar.scss" import { Link, useHistory } from "react-router-dom"; export default function Navbar() { const history = useHistory(); //Re routes back to the homepage when the navbar text is clicked const handleHomeRoute = () => { history.push({ pathname: `/test-project`, }); } return ( <div className="navbar"> <span onClick={() => handleHomeRoute()}>Products Store</span> </div> ) }
const fs = require('fs'); const csv = require('csv-parser'); const pgh = require('./db'); // Читаем и записываем информацию по объектам адресов. Функция для разбора 1 файла const readCSVAddrObj = (filename) => new Promise(async (resolve, reject) => { try { let result = []; // console.log(filename); const readStream = fs.createReadStream(`./files/csv/addrobj/${filename}`) .pipe(csv()) .on("data", (data) => { result.push(data); }) .on('error', reject) .on("end", async () => { console.log(`Read ${filename} finished. Rows:`, result.length); console.log(); readStream.pause(); let pginstance; let index = 1; const limit = 5000; const scope = result.length; try { pginstance = await pgh.instance(); await pginstance.begin(); let values = ''; let recordPart = [] for (let record of result) { recordPart.push(record); if (index%limit == 0 || index >= scope) { console.log("Длина части", recordPart.length); console.time("write part") values = recordPart.map( item => ( `(${sortField(item, index)})` )).join(','); recordPart = []; console.log("index: ", index) console.log() await pginstance.query(` insert into fias_addr_obj (actstatus, aoguid, aoid, aolevel, areacode, autocode, cadnum, centstatus, citycode, code, ctarcode, currstatus, divtype, enddate, extrcode, formalname, ifnsfl, ifnsul, livestatus, nextid, normdoc, offname, okato, oktmo, operstatus, parentguid, placecode, plaincode, plancode, postalcode, previd, regioncode, sextcode, shortname, startdate, streetcode, terrifnsfl, terrifnsul, updatedate) values ${values}`); console.timeEnd("write part") } index++; } } catch (error) { pginstance && await pginstance.rollback(); return reject(error); } finally { readStream.resume() pginstance && await pginstance.close(true); } return resolve() }); } catch (error) { console.log(error); reject(error); } }); // Читаем и записываем информацию по домам. Функция для разбора 1 файла const readCSVHouse = (filename) => new Promise(async (resolve, reject) => { try { let result = []; console.log(filename); const readStream = fs.createReadStream(`./files/csv/house/${filename}`) .pipe(csv()) .on("data", (data) => { result.push(data); }) .on('error', reject) .on("end", async () => { console.log(`Read ${filename} finished. Rows:`, result.length); console.log(); readStream.pause(); let pginstance; let index = 1; const limit = 5000; const scope = result.length; try { pginstance = await pgh.instance(); await pginstance.begin(); let values = ''; let recordPart = [] for (let record of result) { // console.log((Object.keys(record)).sort()); recordPart.push(record); if (index%limit == 0 || index >= scope) { console.log("Длина части", recordPart.length); console.time("write part") values = recordPart.map( item => ( `(${sortField(item, index)})` )).join(','); recordPart = []; console.log("index: ", index) console.log() await pginstance.query(` insert into fias_house (aoguid, buildnum, cadnum, counter, divtype, enddate, eststatus, houseguid, houseid, housenum, ifnsfl, ifnsul, normdoc, okato, oktmo, postalcode, startdate, statstatus, strstatus, strucnum, terrifnsfl, terrifnsul, updatedate) values ${values}`); console.timeEnd("write part") } index++; } } catch (error) { pginstance && await pginstance.rollback(); return reject(error); } finally { readStream.resume(); pginstance && await pginstance.close(true); } return resolve() }); } catch (error) { console.log(error); reject(error); } }); const ParserCSVtoDB = async () => { console.log("===== Start read ====="); console.time("Common timer"); // Получаем массив файлов по объектам адресов const filenameArrAddrObj = fs.readdirSync('./files/csv/addrobj', () => { console.log('read addrobj finished'); }); for (const filename of filenameArrAddrObj) { if ((/ADDROB72/gi).test(filename)) { // загрузка конкретного региона (файл может состоять из нескольких частей) console.time(`${filename}`) await readCSVAddrObj(filename); console.timeEnd(`${filename}`) } console.log(filename); } // Получаем массив файлов по домам const filenameArrHouse = fs.readdirSync('./files/csv/house', () => { console.log('read addrobj finished'); }); for (const filename of filenameArrHouse) { if ((/HOUSE72/gi).test(filename)) { // загрузка конкретного региона (файл может состоять из нескольких частей) console.time(`${filename}`) await readCSVHouse(filename); console.timeEnd(`${filename}`) } console.log(filename); } console.timeEnd("Common timer"); console.log("===== Finish read ====="); }; // readAllCSV(); function sortField(array, i) { let str = ''; const keys = (Object.keys(array)).sort(); let couter_key = 0 for (let key of keys) { str += (couter_key == 0) ? `'${array[key]}'` : `, '${array[key]}'` couter_key++; } return str } module.exports = ParserCSVtoDB; // await pginstance.query(` // insert into fias_addr_obj (actstatus, aoguid, aoid, aolevel, areacode, autocode, cadnum, centstatus, citycode, code, ctarcode, currstatus, divtype, enddate, extrcode, formalname, ifnsfl, ifnsul, livestatus, nextid, normdoc, offname, okato, oktmo, operstatus, parentguid, placecode, plaincode, plancode, postalcode, previd, regioncode, sextcode, shortname, startdate, streetcode, terrifnsfl, terrifnsul, updatedate) // values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39) // `, [ // record.ACTSTATUS , // record.AOGUID , // record.AOID , // record.AOLEVEL , // record.AREACODE , // record.AUTOCODE , // record.CADNUM , // record.CENTSTATUS, // record.CITYCODE , // record.CODE , // record.CTARCODE , // record.CURRSTATUS, // record.DIVTYPE , // record.ENDDATE , // record.EXTRCODE , // record.FORMALNAME, // record.IFNSFL , // record.IFNSUL , // record.LIVESTATUS, // record.NEXTID , // record.NORMDOC , // record.OFFNAME , // record.OKATO , // record.OKTMO , // record.OPERSTATUS, // record.PARENTGUID, // record.PLACECODE , // record.PLAINCODE , // record.PLANCODE , // record.POSTALCODE, // record.PREVID , // record.REGIONCODE, // record.SEXTCODE , // record.SHORTNAME , // record.STARTDATE , // record.STREETCODE, // record.TERRIFNSFL, // record.TERRIFNSUL, // record.UPDATEDATE, // ]);
import React from 'react'; // Import Style import styles from '../../../App/App.css'; const logo = require('./aalam-tree2.jpg'); export function MsgBox() { return ( <div id="main-container" > <div className="index-content "> <div className="container"> <div className="row"> {/* <div id="home-content" className="column col-md-12 col-md-push-1 col-md-pull-1 col-xs-12 col-sm-12"> <h1>AALAM - Reconnect- Engage- Develop </h1> */} <div id="home-content" className="column col-lg-11 col-md-12 col-xs-12 col-sm-12"> <h1>AALAM - Reconnect- Engage- Develop</h1> <img src={logo} alt="" className="img-responsive" /> </div> </div> </div> </div> </div> ); } export default MsgBox;
var React = require('react'); var DefaultLayout = require('../layouts/default'); class GlobalNavbar extends React.Component { render() { return ( <div class="global-nav"> <div class="logo"> <img class="logo-img" src="/hr_logo.png" /> <span>HUMAN RESOURCE MANAGEMENT SYSTEM</span> </div> <div class="right"> <div class="profile"> <a href="/profile"> <img class="profile-img" src="/user_profile.png" /> <p> User Profile </p> </a> </div> <div class="logout"> <a href="/logout"> <img class="logout-img" src="/logout.png" /> <p> Logout </p> </a> </div> </div> </div> ); }; }; module.exports = GlobalNavbar;
'use strict'; import React from 'react'; require('styles/news/NewsList.sass'); class NewsListComponent extends React.Component { render() { var content = this.props.tweets.map( function (tweet) { return ( <NewsItemComponent key={news.twid} tweet={tweet} /> ) }); return ( <div> <button onClick={this.props.onShowNewTweets}>Click here to see them.</button> <ul className="newslist-component"> Please edit src/components/news//NewsListComponent.js to update this component! </ul> </div> ); } } NewsListComponent.displayName = 'NewsNewsListComponent'; // Uncomment properties you need // NewsListComponent.propTypes = {}; // NewsListComponent.defaultProps = {}; export default NewsListComponent;
require( 'dotenv' ).config(); const express = require('express'); const logger = require('morgan'); const path = require('path'); const bodyParser = require('body-parser'); const pgp = require('pg-promise')({}); const cors = require('cors'); const app = express(); app.use(cors()); /* app setting */ const port = process.env.PORT || 8080; const server = app.listen(port); const request = require('request'); // express server settings app.use(logger('dev')); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.set('views', './views'); app.set('view engine', 'ejs'); // routes const userRoutes = require(path.join(__dirname, '/routes/users')); const ApplicantsRoutes = require(path.join(__dirname, '/routes/applicants')); const EmployersRoutes = require(path.join(__dirname, '/routes/employers')); const JobsRoutes = require(path.join(__dirname, '/routes/jobs')); // api routes app.use('/api/users', userRoutes); app.use('/api/applicants', ApplicantsRoutes); app.use('/api/employers', EmployersRoutes); app.use('/api/jobs', JobsRoutes); app.get('/', function(req, res){ res.render('pages/index') })
/* * Author: Santhosh Nandhakumar * eMail ID: nsanthosh2409@gmail.com */ function renderCategoryFilter(categoryAttrs){ var card = d3.select("#category-attribute-accordion") .selectAll("div") .data(categoryAttrs) .enter() .append("div") .attr("class",function(d,i){ return "new-row card card_"+d.name; }); var card_header = card.append("div") .attr("class",function(d,i){ return "new-row mini-header-tab card-header card-header_"+d.name; }); var card_symbol = card_header.append("div") .attr("class",function(d,i){ return "card_symbol pull-left card_symbol_"+d.name; }) .attr("data-toggle","collapse") .attr("data-target",function(d,i){ return "#CategoryList_"+d.name; }) .append("i") .attr("class",function(d,i){ return "fa fa-plus"; }) .attr("aria-hidden","true"); var card_name = card_header.append("div") .attr("class",function(d,i){ return "card-name pull-left card-name_"+d.name; }) .text(function(d,i){ return "By " +d.name; }); var card_check = card_header.append("div") .attr("class",function(d,i){ return "card-name pull-right card-name_"+d.name; }) .append("input") .attr("type","checkbox") .attr("id",function(d,i){ return "category-attr-"+d.name; }) .attr("name",function(d,i){ return "category-attr-"+d.name; }) .attr("class",function(d){ return "categoryCheck categoryCheck_"+d.name; }) .attr("catName",function(d,i){ return d.name; }) .attr("checked","true"); var categoryListDiv = card.append("div") .attr("class","new-row card-block pull-left collapse") .attr("id",function(d,i){ return "CategoryList_"+d.name; }) .attr("aria-expanded","false"); var option = categoryListDiv .selectAll(".options") .data(function(d,i){ return d.categories; }) .enter() .append("div") .attr("class","new-row categoryOptions"); var categoryLabel = option.append("div") .attr("class","col-9 categoryLabel pull-left") .text(function(d,i){ return d; }) var optionCheck = option .append("div") .attr("class","col-3 pull-right optionCheckDiv") .append("input") .attr("type","checkbox") .attr("class",function(d){ //console.log(d3.select((this.parentNode).parentNode.parentNode).datum().name); return "optionCheck pull-rights optionCheck_" + d3.select((this.parentNode).parentNode.parentNode).datum().name; }) .attr("catName",function(d){ return d3.select((this.parentNode).parentNode.parentNode).datum().name; }) .attr("id",function(d,i){ return "categoryOption_"+d.replace(/\s/g, ''); }) .attr("name",function(d,i){ return "categoryOption_"+d.replace(/\s/g, ''); }) .attr("value",function(d,i){ return d; }) .attr("checked","true"); $('.categoryCheck').change(function(){ if(this.checked){ $(".optionCheck.optionCheck_"+$(this).attr("catName")).prop('checked', true); } else{ $(".optionCheck.optionCheck_"+$(this).attr("catName")).prop('checked', false); } queryElementByAttribute(); }); $(".optionCheck").change(function(){ var catName = $(this).attr("catName"); if(this.checked){ if ($(".optionCheck_"+catName+":checked").length == $(".optionCheck_"+catName).length) { $(".categoryCheck_"+catName).prop("indeterminate", false); $(".categoryCheck_"+catName).prop('checked', true); } else{ $(".categoryCheck_"+catName).prop("indeterminate", true); } } else{ if($(".optionCheck_"+catName+":checked").length > 0){ $(".categoryCheck_"+catName).prop('checked', false); $(".categoryCheck_"+catName).prop("indeterminate", true); } else{ $(".categoryCheck_"+catName).prop('checked', false); $(".categoryCheck_"+catName).prop("indeterminate", false); } } queryElementByAttribute(); }) d3.selectAll(".card_symbol").on("click",function(d){ if(d3.select(this).select("i").classed("fa-minus")){ d3.select(this).select("i").classed("fa-minus",false); d3.select(this).select("i").classed("fa-plus",true); } else if(d3.select(this).select("i").classed("fa-plus")){ d3.select(this).select("i").classed("fa-plus",false); d3.select(this).select("i").classed("fa-minus",true); } }) }
/* Your car is old, it breaks easily. The shock absorbers are gone and you think it can handle about 15 more bumps before it dies totally. Unfortunately for you, your drive is very bumpy! Given a string showing either flat road ("_") or bumps ("n"), work out if you make it home safely. 15 bumps or under, return "Woohoo!", over 15 bumps return "Car Dead". */ function bump(x) { var amountOfBumps = 0; var bumpsOrFlatRoad = x.split(''); bumpsOrFlatRoad.forEach(function(el) { if (el === 'n') { amountOfBumps += 1; } }); return amountOfBumps <= 15 ? 'Woohoo!' : 'Car Dead'; }
import styled from "styled-components"; export const SampleSaleCSS = styled.div` height:100%; .sampleSale{ height:100%;width:100%;font-family: PingFangSC;background:#eee; } .headerAll{ background: url("https://img.alicdn.com/imgextra/i3/2053469401/O1CN01p3C4Lj2JJhz3YaJEa_!!2053469401.png") no-repeat top center; background-size:100%; height:1.7rem;width:100%; position:sticky; top:0; left:0; z-index:20; } .header{ display: flex; justify-content: space-between; align-items: center; height:.8rem; width:100%; color:#fff; font-size:.4rem; font-weight:bold; } .icon{ margin-left:.15rem;font-size:.3rem; } .kong{ margin-right:.15rem; } .nav{ height:.9rem;width:100%;white-space:nowrap;overflow:auto; >div{ width:290%; } span{ line-height:.8rem;color:rgba(255,255,255,0.6);font-size:.28rem;padding:0 .34rem; float:left; } } .main{ position:absolute; top:0; bottom:0;left:0;right:0; padding-top:1.7rem; overflow:auto; background:url("https://img.alicdn.com/imgextra/i3/2053469401/O1CN01p3C4Lj2JJhz3YaJEa_!!2053469401.png") no-repeat top center; z-index:0; background-size:100%; } .mainTitle{ height:1.28rem;width:100%;text-align:center;color:#fff; h2{ font-size:.4rem;padding:.2rem 0 .04rem; } p{ font-size:.24rem; } } ul{ width:100%;margin-bottom:.2rem; } li{ margin-left:.15rem;margin-right:.15rem; border-radius:.05rem; } .liTopL{ display:flex;justify-content:center;align-items:center; } .liTop{ height:1.1rem;width:100%;background:#fff;border-radius:.2rem .2rem 0 0; display:flex;justify-content:space-between;align-items:center; } .logo{ height:.8rem;width:.8rem;margin-left:.15rem;background:#fff; img{ height:.4rem;width:.8rem;margin-top:.2rem; } } .details{ font-size:.32rem;margin-left:.2rem; span{ font-size:.2rem;color:#fff;background:#f00;padding:0 .1rem;margin-left:.15rem; } } .liTopR{ display:flex;justify-content:center;align-items:center;margin-right:.15rem; } .timeDetails{ font-size:.2rem; } .time{ font-size:.2rem;color:#f44;background:orange; } .liCenter{ width:100%;background:#fff; } .bj{ margin:0 .2rem;background:url("https://img.alicdn.com/imgextra/i4/2053469401/O1CN01ftQhJX2JJhzLGaW0k_!!2053469401.jpg") no-repeat center; background-size:100%;border-radius:.1rem; height:2rem;overflow:hidden; position:relative; } .center{ margin:.2rem .25rem;height:1.56rem;border-radius:.1rem;overflow:hidden; div:nth-of-type(1){ font-size:.32rem;color:#fff;margin-bottom:.16rem;margin-top:.1rem; } div:nth-of-type(2){ font-size:.24rem;color:#fff;margin-bottom:.16rem; } div:nth-of-type(3){ font-size:.24rem;color:#fff; } } .position{ position:absolute;right:0;bottom:0;background: linear-gradient(276deg,#ff1e2f 0,#e51698 100%); height:.38rem;padding:0 .16rem;border-radius:.1rem; } .liBottom{ height:4.64rem;width:100%;background:#fff; border-radius:0 0 .2rem .2rem; } .center1{ padding:.2rem .2rem 0; height:4.34rem;display:flex;justify-content:space-between;align-items:center;overflow:auto; >div{ width:200%;display:flex;justify-content:center;align-items:center; } } .li{ width:2.3rem;height:100%;display:flex;flex-direction:column; justify-content:center;align-items:center;padding:0 .2rem 0;overflow:hidden; img{ height:2.02rem;width:2.02rem; } } .price{ margin-bottom:.08rem;width:100%;margin-top:.2rem; } .newPrice{ color:#ff3b32;font-size:.32rem;margin-right:.18rem;margin-left:.1rem; } .oldPrice{ color:#aaa;font-size:.22rem;text-decoration:line-through; } .tag{ width:100%;margin-left:.1rem; img{ height:.26rem;width:.26rem;margin-right:.08rem;display:inline-block; } span{ font-size:.18rem; border:1px solid #fe3a33;color:#fe3a33;padding:0 .1rem; border-radius:.06rem; } } .saleNumber{ width:100%; font-size:.2rem;color:#666;line-height:.28rem;margin-top:.08rem; } .discount{ width:100%;margin-top:.12rem;margin-bottom:.1rem; span{ color:#f57523;font-size:.22rem;background: rgba(245,166,35,.2);height:.3rem;padding:0 .12rem;white-space:nowrap;width:100%;overflow:hidden; text-overflow: ellipsis; } } .active{ color:rgba(255,255,255,1) !important;border-bottom:2px solid #fff;font-weight:900; } `
import { Router } from 'express'; import { validationMiddleware } from '../middlewares'; import { AuthController } from '../controllers'; import { loginValidator } from '../validators'; const authRoutes = Router(); authRoutes.post('/', validationMiddleware(loginValidator), AuthController.store); export default authRoutes;
// // // // function delay2s (callback) { // // setTimeout(callback, 2000) // // } // // // // function delay3s (callback) { // // setTimeout(callback, 3000) // // } // // // // delay2s(function () { // // console.log('after 2s'); // // }); // // // const fn = function () { // // // // console.log('exec after 2s'); // // // // }; // // // // delay2s(fn); // // // // // delay2s(function () { // // // console.log('after 2s'); // // // delay3s(function () { // // // console.log('after 3s'); // // // // // }); // // // }); // // // // // console.log('now pending'); // // // const fn = function () { // // // console.log('after 2s'); // // // resolve('result'); // // // }; // // // delay2s(fn); // // // // // // // const pr = new Promise(function (resolve, reject) { // // // delay2s(function () { // // // // reject(1); // // // }) // // // }); // // // // // // pr.then(function (result) { // // // console.log('get resolved: ', result); // // // }); // // // // // // pr.catch(function (error) { // // // console.log('get error: ', error); // // // }); // // // // // // function delay (delay) { // // return new Promise (function (resolve, reject) { // // setTimeout(resolve, delay); // // }) // // } // // // // delay(2000) // // .then(function () { // // console.log('after 2s'); // // // // return delay(3000); // // }) // // .then(function () { // // throw new Error() // // console.log('after 3s'); // // }) // // .catch(function (error) { // // console.log('error: ', error); // // }); // // // const p1 = new Promise(function (resolve, reject) { // // setTimeout(() => reject(new Error('fail')), 1000) // // }) // // // // const p2 = new Promise(function (resolve, reject) { // // setTimeout(() => resolve(p1), 3000) // // }) // // // // p2 // // .then(result => console.log(result)) // // .catch(error => console.log(error)) // // // function Fun (name) { // this.name = name; // Fun.count += 1; // } // Fun.count = 0; // // Fun.prototype.getMyName = function () { // console.log(this.name); // return this.name; // }; // // Fun.dosth = function () { // console.log('dosth'); // }; // // const instance = new Fun('lily'); // instance.getMyName(); // // // Fun.dosth(); // // // function getFoo () { // return new Promise(function (resolve, reject){ // resolve('foo'); // }); // } // // const g = function* () { // try { // const foo = yield getFoo(); // console.log(foo); // } catch (e) { // console.log(e); // } // }; // // function run (generator) { // const it = generator(); // // function go(result) { // if (result.done) return result.value; // // return result.value.then(function (value) { // return go(it.next(value)); // }, function (error) { // return go(it.throw(error)); // }); // } // // go(it.next()); // } // // run(g); // // textPromises.reduce( // (chain, textPromise) => { // return chain.then(() => textPromise) // .then(text => console.log(text)); // }, Promise.resolve() // ); // // function indexOf(arr, item) { // for(let i=0; i<arr.length;i++){ // if(arr[i]===item){ // return i; // } // } // return -1; // } // // console.log(indexOf([1,2,3,4,5], 4)); // // // function remove(arr, item) { // return arr.map(function(x){ // if(x!==item){ // return x; // } // }) // } // // function remove(arr, item) { // var newArr = []; // for(var i=0; i<newArr.length; i++){ // if(arr[i]!==item){ // newArr.push(arr[i]); // } // } // return newArr; // } // // console.log(removeWithoutCopy([3,45,2,6,6], 6)); // // function removeWithoutCopy(arr, item) { // var index = 0; // while(index !==-1){ // index = arr.indexOf(item); // arr.splice(index, 1); // } // return arr; // // } // // function truncate(arr) { // arr.pop(); // return arr.map(function(x){return x}); // } // console.log(truncate([3,4,5,6,7])); // // function duplicates(arr) { // // var result = arr.filter(function (x, index){ // //find the repeated elements // if(arr.indexOf(x)!==index){ // return x; // } // }) // return result; // } // // console.log(duplicates([1, 2, 4, 4, 3, 3, 1, 5, 3])); // function parse2Int(num) { // var arr = num.split(","); // console.log(arr); // if(arr.indexOf("x")!=-1){ // arr.splice(arr.indexOf("x"), 1); // console.log(arr); // } // return parseInt(arr.join()); // } // console.log(parse2Int("0x12")); // // function functionFunction(str) { // return function(word){ // console.log(str + ", " + word); // } // } // console.log(functionFunction("hello")("world")); // function makeClosures(arr, fn) { // var result = []; // for(var i=0; i<arr.length; i++){ // function closure (val) { // result[i] = function(){ // return fn(val); // } // } // closure(arr[i]); // } // return result; // } // // var result = makeClosures([1,2,3], function (x) { // return x; // }); // console.log(result[2]()); // function useArguments(...rest) { // return rest.reduce(function(x,y){ // return x+y; // }) // } // // console.log(useArguments(1,2,3,4)) // (function(){ // console.log( Array.from(arguments).slice(1)); // })(1,2,3,4,5,6); //convert arguments to an array to use the slice method // // (function(){ // console.log( [].slice.call(arguments, 1)); // })(1,2,3,4,5,6); // //equals to arguments.slice, but since arguments is not an array and does // //not have access to slice(), must use call to run it // // function partialUsingArguments(fn) { // var args = Array.from(arguments).slice(1); // return result = function(){ // return fn.apply(null, args.concat(Array.from(arguments))); // } // } // // function valueAtBit(num, bit) { // var pos = 1; // while(pos < bit){ // num = Math.floor(num/2); // pos++; // console.log(num); // } // if(num%2===0){ // return 0; // } // return 1; // } // // function captureThreeNumbers(str) { // arr = /(\d{3})/.exec(str); // if(arr[1]){ // return arr[1]; // } // else{ // return false; // } // } //extract attributes from an url // function getUrlParam(sUrl, sKey) { // var result = {}; // var reg = /(\w+)=(\w+)&?/g; // sUrl.replace(reg, function(a, k, v){ // if(!result[k]) //if new key-value // result[k] = v; // else { //if repeated key // result[k]=[].concat(result[k],v); // } // }); // // if(sKey){//if no para // return result[sKey] || ""; // }else{ // return result; // } // } // // var url = "https://www.google.com.hk/search?newwindow=1&safe=strict&safe=nw0aW8n6N4K70AT-9JHYAg&q=function.length&oq=function.le&gs_l=psy-ab.3.0.0l3j0i30k1l7.13041612.13045514.0.13047032.16.15.1.0.0.0.218.1367.10j3j1.14.0..3..0...1.1j4.64.psy-ab..3.13.1068...0i67k1j0i10k1j0i12k1.0.6sJZyAz8Dkw"; // console.log(getUrlParam(url)); function namespace(oNamespace, sPackage) { var obj = oNamespace; sPackage.replace(/(\w+)\.?/g, function(a,path){ console.log(path); if(!obj[path] || typeof obj[path] !== "object"){ obj[path] = {}; } obj = obj[path]; console.log(oNamespace); }) return oNamespace; } //var result = namespace({a: {test: 1, b: 2}}, 'a.b.c.f.t'); //console.log(JSON.stringify(result)); Array.prototype.uniq = function () { var self = this; return this.filter(function(e, i){ return self.indexOf(e) === i; }) }; function cssStyle2DomStyle(sName) { return sName.replace(/(\-)(\w)(\w+)/g, function(s, remv, cap, low){ return cap.toUpperCase() + low; }).replace(/\-/g, ""); } function digPow(num, start){ var length = num.toString().length, arr = num.toString().split(""), index=0, sum=0; while(index<length) { sum += Math.pow(parseInt(arr[index]), start); start++; index++; } return sum%num === 0 ? sum/num : -1; //shorthand for boolean } //console.log(digPow(46288, 3)); function removeSmallest(numbers) { //throw "TODO: removeSmallest"; var min = numbers[0], result = []; for(let num of numbers){ min = num<min? min = num:min; result.push(num); } result.splice(result.indexOf(min), 1); return result; } console.log(removeSmallest([32,5,6,3,4,5,3]));
'use strict'; describe('commentsSrv', function () { var srv, $httpBackend, configMock; beforeEach(module('talkpointsApp.services', function ($provide) { configMock = { baseurl: 'http://foobar.com/talkpoints', api: '/api/v1', instanceid: 8, talkpointid: 17 }; $provide.value('CONFIG', configMock); })); beforeEach(inject(function (commentsSrv, _$httpBackend_) { srv = commentsSrv; $httpBackend = _$httpBackend_; })); afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); describe('method getPageOfComments', function () { it('should exist', function () { expect(angular.isFunction(srv.getPageOfComments)).toBeTruthy(); }); it('should handle errors', function () { $httpBackend.expectGET('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment?limitfrom=0&limitnum=5'). respond(500, 'something bad happened'); var promise = srv.getPageOfComments(0, 5); var spy = jasmine.createSpy(); promise.then(function () { // empty }, spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalledWith('something bad happened'); }); it('should should fetch data from the server', function () { var data = { comments: [ { id: 6, talkpointid: 42, userid: 3, userfullname: "Tyrion Lannister", is_owner: true, textcomment: "How fantastic!", nimbbguidcomment: null, finalfeedback: false, timecreated: 1384538546, timemodified: 1384788955 }, { id: 9, talkpointid: 42, userid: 3, userfullname: "Tyrion Lannister", is_owner: true, textcomment: "Actually, it's not that great afterall.", nimbbguidcomment: null, finalfeedback: false, timecreated: 1384538546, timemodified: 1384788955 } ], total: 2 }; $httpBackend.expectGET('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment?limitfrom=0&limitnum=5'). respond(data); var promise = srv.getPageOfComments(0, 5); var spy = jasmine.createSpy(); promise.then(spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalledWith(data); }); }); describe('method postTextComment', function () { it('should exist', function () { expect(angular.isFunction(srv.postTextComment)).toBeTruthy(); }); it('should handle errors', function () { var textcomment = 'What a great thing you have there!'; var data = { textcomment: textcomment, finalfeedback: false }; $httpBackend.expectPOST('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment', data). respond(500, 'something bad happened'); var promise = srv.postTextComment(textcomment, false); var spy = jasmine.createSpy(); promise.then(function () { // empty }, spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalledWith('something bad happened'); }); it('should POST data to the server', function () { var textcomment = 'What a great thing you have there!'; var data = { textcomment: textcomment, finalfeedback: false }; $httpBackend.expectPOST('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment', data). respond(204); var spy = jasmine.createSpy(); var promise = srv.postTextComment(textcomment, false); promise.then(spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalled(); }); }); describe('method postNimbbComment', function () { it('should exist', function () { expect(angular.isFunction(srv.postNimbbComment)).toBeTruthy(); }); it('should handle errors', function () { var nimbbguidcomment = 'abc123'; var data = { nimbbguidcomment: nimbbguidcomment, finalfeedback: false }; $httpBackend.expectPOST('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment', data). respond(500, 'something bad happened'); var spy = jasmine.createSpy(); var promise = srv.postNimbbComment(nimbbguidcomment, false); promise.then(function () { // empty }, spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalledWith('something bad happened'); }); it('should POST data to the server', function () { var nimbbguidcomment = 'abc123'; var data = { nimbbguidcomment: nimbbguidcomment, finalfeedback: false }; $httpBackend.expectPOST('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment', data). respond(204); var spy = jasmine.createSpy(); var promise = srv.postNimbbComment(nimbbguidcomment, false); promise.then(spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalled(); }); }); describe('method putTextComment', function () { it('should exist', function () { expect(angular.isFunction(srv.putTextComment)).toBeTruthy(); }); it('should handle errors', function () { var textcomment = 'What a great thing you have there!'; var data = { textcomment: textcomment }; $httpBackend.expectPUT('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment/21', data). respond(500, 'something bad happened'); var spy = jasmine.createSpy(); var promise = srv.putTextComment(21, textcomment); promise.then(function () { // empty }, spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalledWith('something bad happened'); }); it('should PUT data to the server', function () { var textcomment = 'What a great thing you have there!'; var data = { textcomment: textcomment }; $httpBackend.expectPUT('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment/21', data). respond(200); var spy = jasmine.createSpy(); var promise = srv.putTextComment(21, textcomment); promise.then(spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalled(); }); }); describe('method deleteComment', function () { it('should exist', function () { expect(angular.isFunction(srv.deleteComment)).toBeTruthy(); }); it('should handle errors', function () { $httpBackend.expectDELETE('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment/21'). respond(500, 'something bad happened'); var promise = srv.deleteComment(21); var spy = jasmine.createSpy(); promise.then(function () { // empty }, spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalledWith('something bad happened'); }); it('should DELETE data from the server', function () { $httpBackend.expectDELETE('http://foobar.com/talkpoints/api/v1/talkpoint/8/17/comment/21'). respond(200); var promise = srv.deleteComment(21); var spy = jasmine.createSpy(); promise.then(spy); expect(spy).not.toHaveBeenCalled(); $httpBackend.flush(); expect(spy).toHaveBeenCalled(); }); }); });
import jsdom from 'jsdom' import React from 'react' import { expect } from 'chai' import { renderIntoDocument } from 'react-addons-test-utils' global.document = jsdom.jsdom() global.window = global.document.defaultView function renderComponent(Component, props = {}, state = {}) { let component = renderIntoDocument(<Component {...props} />) if (state) { component.state = state } return component } export { expect, renderComponent }
/* * Copyright (c) 2021 SailPoint Technologies, Inc. * * SPDX-License-Identifier: MIT */ const AWS = require('aws-sdk'); const util = require('util'); // get reference to S3 client const s3 = new AWS.S3(); // This is our S3 bucket const s3bucket = "sailpoint-audit-records"; exports.handler = async (event, context, callback) => { // Our initial response var response = { statusCode: 200, body: JSON.stringify('Success'), }; console.log( "Event input: " + JSON.stringify( event ) ); // Get the audit data... we'll use a preview for our demo console.log( "Event Detail: " + JSON.stringify( event.detail ) ); //const auditData = event.detail.searchResultsEvent.preview; const time = event.time; // Now upload the audit data into S3 try { const dest_params = { Bucket: s3bucket, Key: time, Body: auditData, ContentType: "application/json" }; const putResult = await s3.putObject(dest_params).promise(); } catch (error) { console.log(error); return; } return response; };
import React from 'react' import Form from './Form' import Conditions from './Conditions' import Duration from './Duration' import Location from './Location' import Content from './Content' import Links from './Links' import Partners from './Partners' import WhereToBegin from './WhereToBegin' import Footer from './Footer' import Opportunities from './Opportunities' import './landing.css' import NavBar from '../Platform/NavBar/NavBar'; class LandingPage extends React.Component { render () { return ( <div className='landing-page-container'> <Links /> <NavBar /> <Form /> <Conditions /> <WhereToBegin /> <Duration /> <Location /> <Content /> <Opportunities /> <Partners /> <Footer /> </div> ) } } export default LandingPage
const models = require('../models/admin'); const getAllOrders = async () => models.getAllOrders(); const markAsDelivered = async (orderId) => models.markAsDelivered(orderId); const getOrderDetailsById = async (id) => models.getOrderDetailsById(id); module.exports = { getAllOrders, markAsDelivered, getOrderDetailsById, };
import shortid from "shortid"; import * as actionTypes from "../actions/actionTypes"; const cachedLists = localStorage.getItem("lists"); const getLists = cachedLists => { if (cachedLists === null) { return []; } const parsedLists = JSON.parse(cachedLists); parsedLists.forEach(element => { if (element.isOpen === undefined) { element.isOpen = false; } }); return parsedLists; }; const initialState = { lists: getLists(cachedLists) }; const updateCache = state => { localStorage.setItem("lists", JSON.stringify(state.lists)); return state; }; const addHero = (state, action) => { const listIndex = state.lists.findIndex(list => list.id === action.listId); if (listIndex === -1) { return state; } return { ...state, lists: [ ...state.lists.slice(0, listIndex), { ...state.lists[listIndex], heroes: [...state.lists[listIndex].heroes, action.heroNameId] }, ...state.lists.slice(listIndex + 1) ] }; }; const removeHero = (state, action) => { const listIndex = state.lists.findIndex(list => list.id === action.listId); if (listIndex === -1) { return state; } return { ...state, lists: [ ...state.lists.slice(0, listIndex), { ...state.lists[listIndex], heroes: [ ...state.lists[listIndex].heroes.slice(0, action.heroIndex), ...state.lists[listIndex].heroes.slice(action.heroIndex + 1) ] }, ...state.lists.slice(listIndex + 1) ] }; }; const addList = (state, action) => { return { ...state, lists: [ { id: shortid.generate(), title: action.title, description: action.description, heroes: [...action.heroes], isOpen: true }, ...state.lists ] }; }; const removeList = (state, action) => { const listIndex = state.lists.findIndex(list => list.id === action.listId); if (listIndex === -1) { return state; } return { ...state, lists: [ ...state.lists.slice(0, listIndex), ...state.lists.slice(listIndex + 1) ] }; }; const editList = (state, action) => { const listIndex = state.lists.findIndex(list => list.id === action.listId); if (listIndex === -1) { return state; } return { ...state, lists: [ ...state.lists.slice(0, listIndex), { ...state.lists[listIndex], title: action.title, description: action.description }, ...state.lists.slice(listIndex + 1) ] }; }; const setListIsOpen = (state, action) => { const listIndex = state.lists.findIndex(list => list.id === action.listId); if (listIndex === -1) { return state; } return { ...state, lists: [ ...state.lists.slice(0, listIndex), { ...state.lists[listIndex], isOpen: action.isOpen }, ...state.lists.slice(listIndex + 1) ] }; }; const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.ADD_HERO: return updateCache(addHero(state, action)); case actionTypes.REMOVE_HERO: return updateCache(removeHero(state, action)); case actionTypes.ADD_LIST: return updateCache(addList(state, action)); case actionTypes.REMOVE_LIST: return updateCache(removeList(state, action)); case actionTypes.EDIT_LIST: return updateCache(editList(state, action)); case actionTypes.SET_LIST_IS_OPEN: return updateCache(setListIsOpen(state, action)); default: return state; } }; export default reducer;
#pragma strict public var explosionPrefab : GameObject; public var playerShip : GameObject; var rotateSpeed = 75.0; var speed = 50.0; var yPos = 0.0f; var floatingSpeed = 1; var amplitude = 1; function Start(){ yPos = transform.position.y; } function Update() { var transAmount = speed * Time.deltaTime; var rotateAmount = rotateSpeed * Time.deltaTime; if (Input.GetKey("up")) { transform.Rotate(rotateAmount, 0, 0); } if (Input.GetKey("down")) { transform.Rotate(-rotateAmount, 0, 0); } if (Input.GetKey("left")) { transform.Rotate(0, -rotateAmount, 0); } if (Input.GetKey("right")) { transform.Rotate(0, rotateAmount, 0); } if (Input.GetKey ("z")) { transform.Rotate(0, 0, rotateAmount); } if (Input.GetKey ("x")) { transform.Rotate(0, 0, -rotateAmount); } if (Input.GetKey ("left shift") || (Input.GetKey("a"))) { transform.Translate(0, 0, (transAmount * 2)); yPos = transform.position.y; } else { if (transform.position.y > 20) { GetComponent.<Rigidbody>().Sleep(); var temp = transform.position; temp.y = yPos + amplitude * Mathf.Sin (floatingSpeed * Time.time); transform.position = temp; } } } function OnCollisionEnter (col : Collision) { if( (col.gameObject.name == "Terrain") && (col.impulse.magnitude > 10000)) { Instantiate(explosionPrefab, gameObject.transform.position, gameObject.transform.rotation); Destroy (playerShip, 0); GetComponent.<Rigidbody>().isKinematic = true; var gameOverUI = GameObject.FindWithTag ("Canvas").transform.GetChild (2).gameObject; gameOverUI.GetComponent.<UnityEngine.UI.Text>().text = "GAME OVER \n\n SCORE " + GameObject.FindWithTag("PlayerManager").GetComponent.<ManageScore>().currentScore; gameOverUI.SetActive (true); } }
//module.exports = {}; var async = require("async"); var FastMap = require("collections/fast-map"); var Player = require("./player"); var Pathfinding = require("./pathfinding"); var PriorityQueue = require("./priorityqueue"); function Match(_map, _gameWorld, _rows, _cols, _roomId, _io) { this.io = _io; this.map = _map; this.gameWorld = _gameWorld; this.rows = _rows; this.cols = _cols; this.roomId = _roomId; this.players = new FastMap(); this.movementPool = new FastMap(); this.playerColors = [ {color: "red", code: 0xbc2721}, {color: "blue", code: 0x204fbc}, {color: "teal", code: 0x1dd1c7}, {color: "purple", code: 0x8430a5}, {color: "orange", code: 0xff8316}, {color: "brown", code: 0x6b3405}, {color: "yellow", code: 0xe8c500}, {color: "green", code: 0x11540c} ]; this.tick = 10; this.tickTimer = null; this.tickInterval = null; this.movementPool = new FastMap(); this.hexOwnershipAmounts = {}; let self = this; this.joinPlayer = function(_id) { let color = self.playerColors.pop(); let ply = new Player(color); self.players.set(_id, ply); _io.to(self.roomId).send("PJOIN", color); self.hexOwnershipAmounts[_id] = 1; } this.leavePlayer = function(_id) { let ply = self.players.get(_id); self.playerColors.push(ply.colorData); self.players.delete(_id); _io.to(self.roomId).send("PLEAV", ply.colorData); self.hexOwnershipAmounts[_id] = null; } this.startIncrementingUnits = function() { var now = Date(); var delay = (3 * 1000) - now % (3 * 1000); self.tickTimer = setTimeout(function() { self.tickInterval = setInterval(function() { //if(self.stop) { clearInterval(this); } async.each(self.gameWorld, function (row, rowLoop) { async.each(row, function (hex, colLoop) { if(hex != null) { if(hex.owner == null) { hex.units += 1; } else { hex.units += 3; } } colLoop(); }, function(err) { //Finished looping through cols rowLoop(); }); }, function(err) { //Finished looping through rows self.tick += 1; console.log(self.tick); _io.to(self.roomId).send("INC"); }); }, 3*1000); }, delay); } this.getHex = function(r, c) { return({ row: self.gameWorld[r][c].row, col: self.gameWorld[r][c].col, units: self.gameWorld[r][c].units, owner: self.gameWorld[r][c].owner, checksum: self.gameWorld[r][c].checksum }); } this.isValidHexPosition = function(row, col) { return((row >= 0 && col >= 0 && row < self.rows && col < self.cols) && (self.map[row] != null && self.map[row][col] != null)); } this.getNeighbors = function(row, col) { let neighbors = []; if(self.isValidHexPosition(row-1, col)) { neighbors.push(self.getHex(row-1, col)); } // UP if(self.isValidHexPosition(row, col+1)) { neighbors.push(self.getHex(row, col+1)); } // RIGHT if(self.isValidHexPosition(row+1, col)) { neighbors.push(self.getHex(row+1, col)); } // DOWN if(self.isValidHexPosition(row, col-1)) { neighbors.push(self.getHex(row, col-1)); } // LEFT if(col % 2 == 0) //even col, get the hexes to the NE and NW { if(self.isValidHexPosition(row-1, col-1)) { neighbors.push(self.getHex(row-1, col-1)); } if(self.isValidHexPosition(row-1, col+1)) { neighbors.push(self.getHex(row-1, col+1)); } } else { if(self.isValidHexPosition(row+1, col-1)) { neighbors.push(self.getHex(row+1, col-1)); } if(self.isValidHexPosition(row+1, col+1)) { neighbors.push(self.getHex(row+1, col+1)); } } return(neighbors); } this.getVisibleWorld = function(id) { console.time("GENERATE_VISIBLE_WORLD"); var visible = JSON.parse(JSON.stringify(self.map)); var r = 0; var c = -1; async.each(self.gameWorld, function (row, rowLoop) { async.each(row, function (hex, colLoop) { c++; if(self.players.has(id) && (hex != null && hex.owner == id)) { //visible[r][c] = {"row":hex.row,"col":hex.col,"units":hex.units,"owner":hex.owner}; visible[r][c] = self.getHex(r, c); visible[r][c].color = self.players.get(id).colorData.code; var neighbors = self.getNeighbors(r, c); neighbors.forEach(function(n) { visible[n.row][n.col] = self.getHex(n.row, n.col); //visible[n.row][n.col] = {"row":self.gameWorld[n.row][n.col].row,"col":self.gameWorld[n.row][n.col].col,"units":self.gameWorld[n.row][n.col].units,"owner":gameWorld[n.row][n.col].owner}; if(((self.gameWorld[n.row][n.col] != null) && (self.gameWorld[n.row][n.col].owner != null)) && self.players.has(self.gameWorld[n.row][n.col].owner)) { visible[n.row][n.col].color = self.players.get(self.gameWorld[n.row][n.col].owner).colorData.code; if(self.gameWorld[n.row][n.col].owner != id) { visible[n.row][n.col].owner = "^"; } } }); } colLoop(); }, function(err) { c = -1; r++; rowLoop(); }); }, function(err) { }); console.timeEnd("GENERATE_VISIBLE_WORLD"); console.log("id: " + id); return(visible); } this.getUnclaimedHexes = function(single, callback) { var unclaimed = []; async.each(self.gameWorld, function (row, rowLoop) { async.each(row, function (hex, colLoop) { if(hex != null && hex.owner == null) { unclaimed.push(hex); } colLoop(); }, function(err) { //Finished looping through cols rowLoop(); }); }, function(err) { if(single) { callback(unclaimed[Math.floor(Math.random()*unclaimed.length)]); } else { callback(unclaimed); } }); } this.changeHexOwner = function(_row, _col, _newOwner) { let previousOwner = self.gameWorld[_row][_col].owner; if(previousOwner != null) { self.hexOwnershipAmounts[previousOwner] -= 1; } if(_newOwner != null) { self.hexOwnershipAmounts[_newOwner] += 1; } self.gameWorld[_row][_col].owner = _newOwner; } this.freeHexesFromOwner = function(_owner, callback) { var i = 0; async.each(self.gameWorld, function (row, rowLoop) { async.each(row, function (hex, colLoop) { if(hex != null && hex.owner == id) { i++ self.changeHexOwner(hex.row, hex.col, null); } colLoop(); }, function(err) { rowLoop(); }); }, function(err) { callback(i); }); } this.findPath = function(origin, destination) { let frontier = new PriorityQueue((a, b) => a[1] > b[1]); let cameFrom = {}; let costSoFar = {}; frontier.push([{row: origin.row, col: origin.col, checksum: origin.checksum},0]); cameFrom[origin.checksum] = "NONE"; costSoFar[origin.checksum] = 0; let last = null; while(!frontier.isEmpty()) { let current = frontier.pop()[0]; if(current.row == destination.row && current.col == destination.col) { return self.rebuildPath([current.row, current.col], cameFrom); break; } self.getNeighbors(current.row, current.col).forEach(function(n) { if((n.checksum != destination.checksum) && (n.owner != origin.owner)) { return; } let newCost = costSoFar[current.checksum] + (Pathfinding.moveCost(current, n)); if(costSoFar[n.checksum] == null || newCost < costSoFar[n.checksum]) { costSoFar[n.checksum] = newCost; let priority = -(newCost + (Pathfinding.moveCost(destination, n) * 3)); frontier.push([n, priority]); cameFrom[[n.row,n.col]] = [current.row, current.col]; } }); } } this.rebuildPath = function(current, cameFrom) { let finalPath = []; var that = this; finalPath.push(current); while(cameFrom[current] != null) { current = cameFrom[current]; finalPath.push(current); } return(finalPath.reverse()); } this.RouteQueue = function(_route, _units, _owner, _id) { //this.owner = _owner; let route = _route; let units = _units; let owner = _owner; let progress = 0; let id = _id; let moveInterval; let moveTimeOut; let destroy = function() { clearTimeout(moveTimeOut); clearInterval(moveInterval); self.movementPool.delete(id); } let init = function() { currentNode = route[0]; moveToNextNode(); } let moveToNextNode = function() { let now = Date(); let delay = (3 * 1000) - now % (3 * 1000); moveTimeOut = setTimeout(function() { let sentOut = []; self.gameWorld[route[0][0]][route[0][1]].units -= units; let curNeighbors = self.getNeighbors(route[0][0], route[0][1]); _io.to(owner).emit("moveUnits", {initial: true, originRow: route[0][0], originCol: route[0][1], destinationRow: route[1][0], destinationCol: route[1][1], units: units, unitOwner: owner}); for(let i = 0; i < curNeighbors.length; i++) { if(curNeighbors[i].owner == owner) { continue; } if(!sentOut.includes(curNeighbors[i].owner)) { _io.to(curNeighbors[i].owner).emit("moveUnits", {initial: true, originRow: route[0][0], originCol: route[0][1], destinationRow: route[1][0], destinationCol: route[1][1], units: units, unitOwner: owner}); sentOut.push(curNeighbors[i].owner); } } moveInterval = setInterval(function() { if(self == null) { clearInterval(moveInterval); clearTimeout(moveTimeOut); //destroy(); return; } if(progress >= route.length - 1) { clearInterval(moveInterval); clearTimeout(moveTimeOut); destroy(); } else { progress += 1; let fromRow = route[progress-1][0]; let fromCol = route[progress-1][1]; let toRow = route[progress][0]; let toCol = route[progress][1]; let sent = []; if(progress != route.length - 1) { self.getNeighbors(toRow, toCol).forEach(function(n) { if(sent.includes(n.owner)) { return; } sent.push(n.owner); _io.to(n.owner).emit("moveUnits", {originRow: route[progress][0], originCol: route[progress][1], destinationRow: route[progress+1][0], destinationCol: route[progress+1][1], units: units, unitOwner: owner}); }); } else { if(self.gameWorld[toRow][toCol].owner == owner) { self.gameWorld[toRow][toCol].units += units; } if(self.gameWorld[toRow][toCol].owner != owner) { if(self.gameWorld[toRow][toCol].units - units < 0) { self.changeHexOwner(toRow, toCol, owner); } self.gameWorld[toRow][toCol].units = Math.abs(self.gameWorld[toRow][toCol].units - units); } } let neighbors = self.getNeighbors(toRow, toCol).concat(self.getNeighbors(fromRow, fromCol)); let sentUpdate = []; for(var i = 0; i < neighbors.length; i++) { let neighborOwner = self.gameWorld[neighbors[i].row][neighbors[i].col].owner; if(sentUpdate.includes(neighborOwner)) { continue; } if(neighborOwner != null) { _io.to(neighborOwner).emit("updateWorld", self.getVisibleWorld(neighborOwner)); sentUpdate.push(neighborOwner); } } } }, 3*1000); }, delay); } init(); } this.moveUnits = function(_fromOwner, _fromRow, _fromCol, _toRow, _toCol, _amount) { if((_amount > 0) && (self.gameWorld[_fromRow][_fromCol].owner == _fromOwner)) { if(_amount > self.gameWorld[_fromRow][_fromCol].units) { _amount = self.gameWorld[_fromRow][_fromCol].units; } let path = self.findPath(self.getHex(_fromRow, _fromCol), self.getHex(_toRow, _toCol)); if(path != null) { let randomId = Math.floor((Math.random() * 9999) + 1000); self.movementPool.add(new self.RouteQueue(path, _amount, _fromOwner, randomId), randomId); console.log("[MOVE]: " + _fromOwner + " moved " + _amount + " UNITS from [" + _fromRow + ", " + _fromCol + "] to [" + _toRow + ", " + _toCol + "]"); } else { console.log("[MOVE ERROR]: " + _fromOwner + " tried to move " + _amount + " UNITS from [" + _fromRow + ", " + _fromCol + "] to [" + _toRow + ", " + _toCol + "]. Denied: No valid path."); } } else { console.log("[MOVE ERROR]: " + _fromOwner + " tried to move " + _amount + " UNITS from [" + _fromRow + ", " + _fromCol + "] to [" + _toRow + ", " + _toCol + "]. Denied: not enough units."); } } this.destroy = function() { clearInterval(self.tickInterval); clearTimeout(self.tickTimer); self.map = null; self.gameWorld = null; self.rows = null; self.cols = null; self.roomId = null; self.players = null; self.movementPool = null; self.playerColors = null; self.tick = null; self.tickTimer = null; self.tickInterval = null; self = null; } } module.exports = Match;
var searchData= [ ['vbe_5fsign_5finit',['VBE_SIGN_INIT',['../v__macros_8h.html#a80719ab0d551ac4046ae50541616d747',1,'v_macros.h']]], ['vid_5fcard_5fi_5fvec',['VID_CARD_I_VEC',['../v__macros_8h.html#a8073f281265f9f7dbdd4280a9fe7b5e8',1,'v_macros.h']]], ['video_5fmode_5fterm_5fword',['VIDEO_MODE_TERM_WORD',['../v__macros_8h.html#a613ce195c34d1fa5925e350335e55a25',1,'v_macros.h']]] ];
import React from "react"; import "./NineGLogoStyles.css"; const NineGlogo = props => { return ( <div className="container"> <div className="text">9g</div> </div> ); }; export default NineGlogo;
export {default} from './TaskDetailsScreen';
import React from 'react' import { URL_IMG, IMG_SIZE_LARGE } from '../constants/const' import { Image } from 'react-bootstrap' const Poster = ({ id, path }) => <Image key={id} src={URL_IMG + IMG_SIZE_LARGE + path} responsive className="poster" /> export default Poster
import React, { Component } from 'react'; import { connect } from 'react-redux'; import AccountHOC from '../../components/AccountHOC'; import { getPurchaseHistory } from '../../actions/userActions'; import css from './styles.module.scss'; import { Link } from 'buttermilk'; class PurchaseHistory extends Component { state = {}; componentDidMount() { if (!this.props.user.purchaseHistory) { this.props.getPurchaseHistory(this.props.user.id); } } render() { return ( <AccountHOC> {this.props.user.purchaseHistory && this.props.user.purchaseHistory.length > 0 ? ( <div className={CSS.container}> <div className={css.container__Header}> <h2 className={css.container__HeaderText}>Purchase History</h2> <p>Date</p> <p>Total</p> <p>Status</p> <p>Actions</p> </div> {this.props.user.purchaseHistory.map((e, i) => ( <div className={css.purchaseHistory}> <h2 className={css.container__HeaderText}>1 item purchased</h2> <p>{new Date(e.date_created).toISOString().slice(0, 10)}</p> <p>Total</p> <p>shipping</p> <Link href={`/account/purchase-history/${e.id}`}>Details</Link> </div> ))} </div> ) : ( <p>No Purchase History Recorded</p> )} </AccountHOC> ); } } export default connect( state => state, { getPurchaseHistory }, )(PurchaseHistory);