text
stringlengths
7
3.69M
import { URLPATTERN } from "./constants"; const verifyUrl = url => URLPATTERN.test(url); const getVideoId = url => url.replace(URLPATTERN, '$1'); const getVideoDetails = async url => { const res = await fetch(`https://www.youtube.com/oembed?url=${url}&format=json`); const data = await res.json(); return data; } export { verifyUrl, getVideoId, getVideoDetails }
import React from 'react' const PopularCard = () => { return ( <div className="col-12 col-md-6 col-lg-4 classCard mb-2 rounded"> <img src="img/image1.jpg" className="img-fluid" alt="" /> <div className="classTite p-2"> <h6>Categorie</h6> <span>Nb de classe</span> </div> </div> ) } export default PopularCard
/** * App升级 * @constructor */ function AppUpgrade(main) { this.main = main; this.pageIndex = 1; this.dataMap = new Map(); let that = this; this.pagination = new Pagination(function (pageIndex) { that.findList(pageIndex); }); } /** * 查询数据列表 * @param pageIndex */ AppUpgrade.prototype.findList = function (pageIndex) { let that = this; that.pageIndex = pageIndex; let data = $('#qform_appUpgrade').serializeJSONNoNull(); data.page = pageIndex; data.rows = 10; let ly = layer.load(1, {shade: [0.1,'#000']}); that.main.postData('queryAppUpgrade', JSON.stringify(data), function (result, res) { layer.close(ly); if(result){ if(res.code==='200'){ let pageFooter = $('#footer_page_appUpgrade'); that.pagination.initPageData(res.data.recordTotal, res.data.pageTotal, pageFooter); let list = res.data.list; let table = $('#tb_appUpgrade tbody'); table.empty(); that.dataMap.clear(); $.each(list, function (index, upgrade) { let row = that.createTable(upgrade); row.appendTo(table); that.dataMap.set(upgrade.id, upgrade); }); }else{ layer.alert(res.message); } } }); } AppUpgrade.prototype.createTable = function (upgrade) { let that = this; let row = $("<tr></tr>"); let cellVersion = that.createTitleColumn(upgrade.version); cellVersion.appendTo(row); let cellversionType = that.createTitleColumn(upgrade.versionType); cellversionType.appendTo(row); let cellApkUrl = that.createTitleColumn(upgrade.apkUrl); cellApkUrl.appendTo(row); let cellNote = that.createTitleColumn(upgrade.note); cellNote.appendTo(row); let cellforceUpgrade = that.createTitleColumn(upgrade.forceUpgradeText); cellforceUpgrade.appendTo(row); let cellIsSkip = that.createTitleColumn(upgrade.isSkipText); cellIsSkip.appendTo(row); let cellCreateTime = that.createTitleColumn(upgrade.createTime); cellCreateTime.appendTo(row); let cellBtn = that.createButtonColumn([{ "text": "编辑", "data": upgrade, "click": function (data) { that.update(data); } },{ "text": "删除", "data": upgrade, "click": function (data) { that.delete(data.id); } }]); cellBtn.appendTo(row); return row; } /** * 创建普通的文字列 * @param text * @returns {jQuery|HTMLElement} */ AppUpgrade.prototype.createTitleColumn = function (text) { let sb = new StringBuilder(); sb.append("<td data-label='Title'><div>").append(text).append("</div></td>"); return $(sb.toString()); }; /** * 创建按钮列 * @param user */ AppUpgrade.prototype.createButtonColumn = function (options) { let cell = $("<td></td>"); let btnContainter = $("<div class='btn-list flex-nowrap'></div>"); $.each(options, function (index, opt) { let button = $("<a href='#' class='btn btn-primary'>").append(opt.text).append("</a>"); button.unbind('click').bind('click', opt.data, function (e) { if(opt.click){ opt.click(e.data); } }); button.appendTo(btnContainter); }); btnContainter.appendTo(cell); return cell; }; /** * 创建 */ AppUpgrade.prototype.create = function () { $('#dlg_appUpgrade_title').text('新增版本信息'); $('#modal-appUpgrade').modal('show'); $('#form_save_appUpgrade').clearForm(); }; /** * 编辑 */ AppUpgrade.prototype.update = function (data){ $('#dlg_appUpgrade_title').text('编辑版本信息'); $('#form_save_appUpgrade').clearForm(); $('#modal-appUpgrade').modal('show'); $('#form_save_appUpgrade').loadForm(data); }; /** * 保存 */ AppUpgrade.prototype.save = function () { let that = this; let json = $('#form_save_appUpgrade').serializeJSONNoNull(); if(json.forceUpgrade){ json.forceUpgrade = '1'; }else{ json.forceUpgrade = '0'; } if(json.isSkip){ json.isSkip = '1'; }else{ json.isSkip = '0'; } let ly = layer.load(1, {shade: [0.1,'#000']}); let action = 'createAppUpgrade'; if(json.id && parseInt(json.id)>0){ action = "updateAppUpgrade"; } that.main.postData(action, JSON.stringify(json), function (result, res) { layer.close(ly); if (result) { if (res.code === '200') { $('#modal-appUpgrade').modal('hide'); layer.alert('保存成功!'); that.findList(that.pageIndex); }else{ layer.alert(res.message); } }else{ layer.alert(res); } }); }; /** * 删除 * @param id */ AppUpgrade.prototype.delete = function (id) { let that = this; let ly = layer.confirm('确定要注销码?', { btn: ['是','否'] //按钮 }, function(){ let array = new Array(); array.push(id); ly = layer.load(1, {shade: [0.1,'#000']}); that.main.postData('removeAppUpgrade', {'ids':array}, function (result, res) { layer.close(ly); if (result) { if (res.code === '200') { layer.alert('删除成功!'); that.findList(that.pageIndex); }else{ layer.alert(res.message); } }else{ layer.alert(res); } }); }, function(){ }); };
const emojiClasses = [ emojiReplacer.classNames['emoji'], emojiReplacer.classNames['translation'] ]; let menuShown = false; function showMenu(shouldShow) { const content = shouldShow ? 'show' : 'hide'; menuShown = shouldShow; browser.runtime.sendMessage({ 'type': 'context-menu', 'content': content }); } function isEmojiComponent(node) { return ( node && ( twitterDecoder.mightContainEmoji(node) || emojiClasses.some(className => { return node.classList.contains(className); }) ) ); } function hasTextContent(node) { return ( node && [...node.childNodes].some(childNode => { const isTextNode = childNode.nodeType === Node.TEXT_NODE; const isNonEmpty = childNode.textContent.trim(); return isTextNode && isNonEmpty; }) ); } document.addEventListener('mouseover', function(e) { if ((isEmojiComponent(e.target) || hasTextContent(e.target)) && !menuShown) { showMenu(true); } }); document.addEventListener('mouseout', function(e) { if ((isEmojiComponent(e.target) || hasTextContent(e.target)) && menuShown) { showMenu(false); } }); function handleMessage(message) { if (message['type'] === 'context-menu-set-setting') { const setting = message['content']['key']; const value = message['content']['value']; settingsInterface.set(setting, value); domManipulator.start(); } else if (message['type'] === 'context-menu-action') { if (message['content'] === 'reload') { orchestrator.scan(); } } } browser.runtime.onMessage.addListener(handleMessage);
// Preguntar nombre y apellido var names= prompt("¿cual es tu nombre y apellido?"); //Obteniendo primera inicial var firstInitial = names.slice(0,1); //Buscando segunda inicial var secondInitialPosition = names.indexOf(" "+ 1); //obteniendo segunda inicial var secondInitial = names.slice(secondInitialPosition, secondInitialPosition+1); //Mostrando document.write("Tus iniciales son "+ firstInitial; var last_name='Martinez';
// Бургер меню let menu = document.querySelector(".menu"); document.querySelector(".burger").onclick = () => { menu.classList.toggle("active"); }; window.onscroll = () => { menu.classList.remove("active"); }; $(function () { // Плавный скролл $(".menu a").on("click", function (event) { event.preventDefault(); let id = $(this).attr("href"), top = $(id).offset().top; $("body,html").animate({ scrollTop: top }, 1000); }); // Слайдер $(".banners__slider").slick({ centerMode: true, centerPadding: "20px", slidesToShow: 3, arrows: false, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: "40px", slidesToShow: 3, }, }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: "40px", slidesToShow: 1, }, }, ], }); });
define([ 'common/collections/single-timeseries' ], function (Collection) { describe('Single Timeseries collection', function () { var collection; beforeEach(function () { collection = new Collection([], { denominatorMatcher: 'foo', numeratorMatcher: 'bar', valueAttr: '_end' }); }); describe('parse', function () { it('maps valueAttr to "uniqueEvents"', function () { var input = [ { _end: 5 } ]; var output = collection.parse({ data: input }); expect(output[0]).toEqual({ _end: 5, uniqueEvents: 5 }); }); it('should add null if no end value', function () { var input = [ { _end: null } ]; var output = collection.parse({ data: input }); expect(output[0]).toEqual({ _end: null, uniqueEvents: null }); }); it('should add a default value if end is null and one is provided', function () { collection.options.defaultValue = 0; var input = [ { _end: null } ]; var output = collection.parse({ data: input }); expect(output[0]).toEqual({ _end: null, uniqueEvents: 0 }); }); }); }); });
/** * Created by lusiwei on 2016/9/26. */ 'use strict'; import React from 'react' import FilmCard from '../FilmCard' import TicketCard from '../TicketCard' import config from '../../config/base' import {connect} from 'react-redux' class Cart extends React.Component { render() { return ( <div className="content"> {this.props.orders.map((item, index) => { switch (item.type) { case config.order_type.film: return <FilmCard film={item.content} key={index} /> case config.order_type.ticket: return <TicketCard ticket={item.content} key={index} /> default: return <div key={index}>空</div> ; } })} </div> ) } } function mapStateToProps(state) { return { orders: state.orders } } export default connect(mapStateToProps)(Cart);
var path = require('path') var px2rem = require('postcss-px2rem') var postcss = px2rem({ remUnit: 40, remPrecision: 8 }) function resolve(dir) { return path.join(__dirname, dir) } module.exports = { chainWebpack: config => { config.resolve.alias .set('com*', resolve('./src/components')) .set('assets*', resolve('./src/assets')) }, css: { loaderOptions: { css: { modules: true, localIdentName: '[name]-[hash]', camelCase: 'only' }, postcss: { plugins: [ postcss ] } } } }
import { createSelector } from "reselect"; const selectSearchPanelHeader = (state) => state.searchPanelHeader; export const selectSearchPanelQueryValue = createSelector( [selectSearchPanelHeader], (searchPanelHeader) => searchPanelHeader.query ); export const selectSearchPanelHeaderItemsByQuery = createSelector( [selectSearchPanelHeader], (searchPanelHeader) => searchPanelHeader.itemsByQuery ); export const selectSearchPanelHeaderIsFetching = createSelector( [selectSearchPanelHeader], (searchPanelHeader) => searchPanelHeader.isFetching ); export const selectSearchPanelHeaderisLoaded = createSelector( [selectSearchPanelHeader], (searchPanelHeader) => !!searchPanelHeader.itemsByQuery );
import React from 'react' const Footer = () => { return ( <div> <p style={{textAlign:'center', marginTop:'10px'}}>Copyright 2021</p> </div> ) } export default Footer
// Dice roll function that takes in value of the dice selected from the drop down // and displays the number on the web page diceRoll = () => { var dieSize = document.getElementById("diceType").value; var roll; if (dieSize === "Select") { document.getElementById("demo").innerHTML = "Please select a die"; } else { roll = Math.floor((Math.random() * dieSize) + 1); var crit; if (roll === 20) { crit = '!!!!!!' } else { crit = '!' } document.getElementById("demo").innerHTML = "You rolled a: " + roll + crit; } return roll; }
import React, { Component } from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faUserCircle, faPhoneAlt, faEnvelope, faMapMarkerAlt, faBirthdayCake } from '@fortawesome/free-solid-svg-icons'; class SubInfo extends Component { render() { return ( <div className="d-flex m-2"> <FontAwesomeIcon className="mt-1" icon={this.props.logo} /> <div className="pl-3"> <p className="m-0">{this.props.name}</p> <p style={{ color: "#4288E4" }} className="m-0">{this.props.details}</p> </div> </div> ) } } export default SubInfo
import React from "react" import { ReactComponent as Home } from "../../images/home-icon.svg" import { ReactComponent as Inbox } from "../../images/inbox-icon.svg" import { ReactComponent as Explore } from "../../images/explore-icon.svg" import { ReactComponent as Notifications } from "../../images/notifications-icon.svg" import { ProfileIcon } from "../ProfileIcon/index" import image from "../../images/profile-icon.jpg" import "./index.css" export const Menu = () => { return ( <div className="menu"> <Home className="icon" /> <Inbox className="icon" /> <Explore className="icon" /> <Notifications className="icon" /> <ProfileIcon iconSize="small"image={image} storyBorder={true}/> </div> ) }
import { ContactsPlugin } from './contacts'; import { MyWalletsPlugin } from './my-wallets'; import { ReceiveFundsPlugin } from './receive-funds'; import { SendFundsPlugin } from './send-funds'; import { TransactionHistoryPlugin } from './transaction-history'; export const plugins = [ MyWalletsPlugin, TransactionHistoryPlugin, SendFundsPlugin, ReceiveFundsPlugin, ContactsPlugin, ];
var x=0, y=0; $( document ).ready(function() { $(".box").click(function(){ if ($(this).hasClass("red") && !$(this).hasClass("clicked")) { $(this).addClass("clicked"); $(this).css("background", "red"); x++; document.getElementById('scoreRed').innerHTML = x; }else if (!$(this).hasClass("clicked")) { $(this).addClass("clicked"); $(this).css("background", "green"); y++; document.getElementById('scoreGreen').innerHTML = y; } }); });
import router from 'express' const router = Router() router.length('/', (req, res, next) => { res.render('index', {title: 'Express'}) }) export { router }
function caps() { var x = document.getElementById("usr"); x.value = x.value.toUpperCase(); var alpha = /^[A-Za-z]+$/; if(x.value.match(alpha)) { document.getElementById("id1").innerHTML = ""; } else if(x.value ==="" || x.value === null) { document.getElementById("id1").innerHTML ="do not leave it empty!"; } else { document.getElementById("id1").innerHTML = "no numbers please!"; } } //for username function emp() { var x = document.getElementById("employer"); var alpha = /^[A-Za-z]+$/; if(x.value.match(alpha)) { document.getElementById("id6").innerHTML = ""; } else { document.getElementById("id6").innerHTML = "hey employer name can't be numeric!"; } } //for employer if present function myfne(id,name) { var x = document.getElementById(name); if(isNaN(x.value)) { document.getElementById(id).innerHTML="only numbers please!"; } else if(x.value ==="" || x.value === null) { document.getElementById(id).innerHTML ="do not leave it empty!"; } else if(x.value.length < 10) { document.getElementById(id).innerHTML="must be 10 numbers"; } else { document.getElementById(id).innerHTML=""; } } //for fne num ,landline mobile etc function myname(id,name) { var x = document.getElementById(name); var alpha = /^[A-Za-z]+$/; if(x.value.match(alpha)) { document.getElementById(id).innerHTML = ""; } else if(x.value ==="" || x.value === null) { document.getElementById(id).innerHTML ="do not leave it empty!"; } else { document.getElementById(id).innerHTML = "no numbers please!"; } } //for string function email(id,name) { var x = document.getElementById(name); var alpha= /^[a-z0-9_-]+@[a-z0-9._-]+\.[a-z]+$/i; if(x.value.match(alpha)) { document.getElementById(id).innerHTML = ""; } else if(x.value==="" || x.value === null) { document.getElementById(id),innerHTML="do not leave it empty!"; } else { document.getElementById(id).innerHTML="Please enter a valid email id"; } } //for emailid function myzipp(id,name) { var x = document.getElementById(name); if(isNaN(x.value)) { document.getElementById(id).innerHTML="only numbers please!"; } else if(x.value ==="" || x.value === null) { document.getElementById(id).innerHTML ="do not leave it empty!"; } else if(x.value.length < 7) { document.getElementById(id).innerHTML="must be 7 numbers"; } else { document.getElementById(id).innerHTML=""; } } //for fax function mystreet(id,name) { var x = document.getElementById(name); var alpha = /^[0-9A-Za-z]+$/; isempty(id,x); if(x.value.match(alpha)) { document.getElementById(id).innerHTML = ""; } else if(x.value ==="" || x.value === null) { document.getElementById(id).innerHTML ="do not leave it empty!"; } else { document.getElementById(id).innerHTML = "no special characters please!"; } } //mystreet function pwd() { var pwd = document.getElementById("password"); var retype = document.getElementById("retypepassword"); if(pwd.value != retype.value) { document.getElementById("id24").innerHTML="retyped password does not match"; } } //for retyped pwd function myfax(id,name) { var x = document.getElementById(name); if(isNaN(x.value)) { document.getElementById(id).innerHTML="only numbers please!"; } else if(x.value ==="" || x.value === null) { document.getElementById(id).innerHTML ="do not leave it empty!"; } else if(x.value.length < 5) { document.getElementById(id).innerHTML="must be 5 numbers"; } else { document.getElementById(id).innerHTML=""; } }
let gameSurvivor; let gameZombies; function drawSurvivor(survivor) { line(0, 0, survivor.x, survivor.y); } function drawZombie(zombie) { circle(zombie.x, zombie.y, 35); } function drawZombies(zombies) { zombies.forEach(zombie => drawZombie(zombie)); } // Pure functions function createSurvivor() { return p5.Vector.fromAngle(radians(45), 50); } function createZombie(distance = 75) { return p5.Vector.fromAngle(radians(-90), distance); } function moveZombie(zombie) { return p5.Vector.fromAngle(zombie.heading(), zombie.mag() - 1); } function moveZombies(zombies) { return zombies.map(zombie => moveZombie(zombie)); } // p5Js functions function setup() { createCanvas(400, 400); gameSurvivor = createSurvivor(); gameZombies = [createZombie(), createZombie(120)]; } function draw() { gameZombies = moveZombies(gameZombies); background(220); translate(width / 2, height / 2); drawSurvivor(gameSurvivor); drawZombies(gameZombies); }
/* <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.indigo-pink.min.css"> <script src="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" */
import React from 'react'; import './sign-in-out.style.scss'; import SingIn from '../../components/sign in/signin.comp'; import Signup from '../../components/sign-up/sign-up.comp' const Signiout= ()=>( <div className="sign-in-out"> <SingIn/> <Signup/> </div> ) export default Signiout;
var picIndex = 1//图片编号 var itemArr = []//每列高度 var loadImgSrc = 'http://jrgzuoye.applinzi.com/%E4%BD%9C%E4%B8%9A%E5%AE%89%E6%8E%92/jscode/JS9-jqueryajax/loading.gif' appendImg(makeImg(24))//打开浏览器加载18张图片并按照瀑布流规则放在页面中 //当滚到页面底部时,加载更多图片 $(window).on('scroll', function () { if ($(window).scrollTop() + $(window).height() == $(document).height()) { appendImg(makeImg(6)) } }) //当页面宽度发生改变时,改变页面布局 $(window).on('resize', function () { render(); }) function render() { var picWidth = $('#layout img').outerWidth(true)//获取图片高度 var colLength = parseInt($(window).width() / picWidth)//得到可以摆放的列数 var newHeightArr = []//各个列的高度 for (var i = 0; i < colLength; i++) { newHeightArr.push(0)//从0开始机选新列的高度 } $('#layout img').each((index, element) => {//遍历所有图片,并且执行一下函数 var minIndex = 0//最小数的下标 var minHeight = newHeightArr[0]//最小列的高度 for (var i = 0; i < newHeightArr.length; i++) {//找到最小高度的一列 if (newHeightArr[i] < minHeight) { minIndex = i minHeight = newHeightArr[i] } } $(element).animate({//动画效果 left: picWidth * minIndex,//距左偏移图片宽度*列数 top: minHeight//距上偏移最小列的高度 }); newHeightArr[minIndex] = $(element).outerHeight(true) + newHeightArr[minIndex]//将新曾图片高度加入该列的总高度中 }); itemArr = newHeightArr } //将图片插入页面 function appendImg($images) { var containerWidth = $('#layout').width()//容器宽度 let imgNum = 0; $(`<p class='loading'>正在下载<img src=${loadImgSrc}></p>`).appendTo($('body'))//插入等待提示 $images.on('load', function () {//当图片加载完成后 imgNum++ if (imgNum === $images.length) { for (let i = 0; i < $images.length; i++) { $images.eq(i).appendTo($('#layout')).css(`top`, -300)//将图片放在页面某处 $images.eq(i).appendTo($('#layout')).css(`left`, -300)//将图片放在页面某处 } var imgWidth = $('#layout img').width()//获取图片宽度,因为jquery不能获取还未在文档流中图片的宽高,所以需要将图片放入文档流中再获取图片宽高 var colLength = parseInt(containerWidth / imgWidth, 10) for (let key = 0; key < colLength; key++) {//初始化高度数组的数据,确定数组的长度 if (itemArr[key] === undefined) { itemArr[key] = 0 } } for (let i = 0; i < $images.length; i++) { var minValue = Math.min.apply(null, itemArr)//另一种获取最小值的方法 var minIndex = itemArr.indexOf(minValue)//获取最小值的下标 $images.eq(i).animate({ top: itemArr[minIndex], left: $images.eq(i).outerWidth(true) * minIndex, }) itemArr[minIndex] += $images.eq(i).outerHeight(true) $(".loading").remove()//图片全部加载完成后移除等待提示 } } }) } //生成一个200宽度,随机高度、随机颜色的图片的Jquery集合(默认三个) function makeImg(Num) { Num = Num || 3 var colorbox = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c', 'd', 'e', 'f'] var images = [] var imgSrc = `` for (let key = 0; key < Num; key++) {//随机颜色 imgHeight = parseInt(Math.random() * 200 + 200, 10)//随机高度 var color = '' for (let i = 0; i < 6; i++) { var c = parseInt(Math.random() * colorbox.length) color += colorbox[c] } imgSrc = `http://via.placeholder.com/200x${imgHeight}/${color}?text=${picIndex++}` var img = new Image() images.push(img) img.src = imgSrc } var $images = $(images) return $images; } //等待完善的随机图片 // function makeImg(Num,imgHeight,imgWidth){ // Num = Num||3 // imgWidth = imgWidth||200 // imgHeight = imgHeight||parseInt(Math.random()*200+200, 10)//随机高度 // var colorbox=[1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f'] // var images=[] // var imgSrc=`` // for(let key=0; key < Num; key++){//随机颜色 // var color='' // for(let i = 0; i < 6; i++){ // var c = parseInt(Math.random()*colorbox.length) // color += colorbox[c] // } // imgSrc = `http://via.placeholder.com/${imgWidth}x${imgHeight}/${color}` // var img = new Image() // images.push(img) // img.src = imgSrc // } // var $images = $(images) // return $images; // }
;(function(window) { var View = class View { constructor(setEventListeners) { this.cache = {} this.setEventListeners = setEventListeners } cacheDOM() { this.cache.results = document.querySelector('.gallery-results') this.cache.form = document.querySelector('.search') this.cache.input = document.querySelector('.search__field') this.cache.dropDown = document.querySelector('select') this.cache.overlay = document.querySelector('.overlay') this.cache.likes = document.querySelector('.likes__list') this.cache.clearLikes = document.querySelector('.clear-likes-btn') this.cache.loader = document.querySelector('.loader') this.setEventListeners() } addToNode(node) { node.insertAdjacentHTML('afterbegin', this.render()) this.cacheDOM() } addSearchResultsToView(images) { this.cache.results.innerHTML = '' images.forEach(image => { this.cache.results.insertAdjacentHTML( 'beforeend', this.renderImage(image) ) }) this.cache.allImages = [...document.querySelectorAll('.image-container')] this.lazyLoadImages() } renderImage({ url, id, liked }) { return ` <div class="image-container" data-id=${id}> <img src="../resources/images/Wix_logo.jpg" data-src="${url}" class="image preload"/> <div class='image-action'> <span class='like-image'> ${ liked ? `<i class="fas fa-heart fa-6x"></i>` : `<i class="far fa-heart fa-6x"></i>` } </span> <span class='view-image'> <i class="far fa-eye fa-6x"></i> </span> </div> </div> ` } clearResults() { this.cache.results.innerHTML = '' } showLoader() { this.cache.loader.style.visibility = 'visible' } hideLoader() { this.cache.loader.style.visibility = 'hidden' } focusInput() { this.cache.input.focus() } showNoResults() { const markup = `<div class='no-results'> <h1>No results found :(</h1> </div>` this.cache.results.insertAdjacentHTML('afterbegin', markup) } setLikes(images) { images.forEach(image => { this.addToLikes(image.url) }) } viewImage(image) { this.cache.overlay.innerHTML = '' this.cache.overlay.style.visibility = 'visible' this.cache.overlay.insertAdjacentHTML( 'afterbegin', `<img class="overlay-image" src=${image}/>` ) } closeImage() { this.cache.overlay.style.visibility = 'hidden' this.cache.overlay.innerHTML = '' } addToLikes(url, likeSpan) { const markup = ` <li> <img class='liked-image' src=${url}/> </li> ` this.cache.likes.insertAdjacentHTML('beforeend', markup) if (likeSpan) { likeSpan.innerHTML = `<i class="fas fa-heart fa-6x"></i>` } } removeFromLikes(likes, likeSpan) { this.cache.likes.innerHTML = '' likes.forEach(({ url }) => { this.addToLikes(url) }) if (likeSpan) { likeSpan.innerHTML = `<i class="far fa-heart fa-6x"></i>` } } clearLikes() { this.cache.likes.innerHTML = '' } lazyLoadImages() { let images = [...document.querySelectorAll('.image')] const interactSettings = { root: document.querySelector('.gallery-results'), rootMargin: '0px 0px 200px 0px' } function onIntersection(imageEntites) { imageEntites.forEach(image => { if (image.isIntersecting) { observer.unobserve(image.target) image.target.src = image.target.dataset.src image.target.onload = () => { image.target.classList.remove('preload') image.target.style.animation = 'fadeIn 1.5s' } } }) } let observer = new IntersectionObserver(onIntersection, interactSettings) images.forEach(image => observer.observe(image)) } render() { return ` <div class="container"> <!-- header --> <header class="header"> <img src="../resources/images/Wix_logo.jpg" alt="Logo" class="header__logo" /> <form class="search"> <input type="text" class="search__field" placeholder="What are you looking for?" /> <button class="btn search__btn"> <span class="search__icon"> <i class="fas fa-search fa-lg"></i> </span> </button> </form> <select class="select"> <option value="flickr" class='flickr' selected>Flickr</option> <option value="static" class='static'>Static</option> </select> <div class="likes"> <div class="likes__field"> <span class="likes__icon"> <i class="fas fa-heart fa-4x"></i> </span> </div> <div class="likes__panel"> <ul class="likes__list"> <!-- liked images --> </ul> <button class='clear-likes-btn'>Clear likes</button> </div> </div> </header> <!-- end of header --> <!-- results --> <section class="gallery-results"> </section> <!-- end of results --> <!-- Footer --> <div class="footer"> <h1 class="">Designed by Karolis</h1> </div> <!-- end of Footer --> <div class="overlay"></div> <div class="loader"> <img src='../resources/loader.svg'/> </div> </div> ` } } window.CLASSES.ViewClass = View })(window)
import { combineReducers } from 'redux'; import homeData from './homeReducer'; import mapData from './mapReducer'; const appReducer = combineReducers({ homeData:homeData, mapData:mapData }) const rootReducer = (state, action) => { if (action.type === 'USER_LOGGED_OUT') { state = undefined } return appReducer(state, action) } export default rootReducer;
import React from 'react'; import styled from 'styled-components'; import axios from 'axios'; import { useHistory } from 'react-router-dom'; const url = 'http://ec2-13-209-5-166.ap-northeast-2.compute.amazonaws.com:8000/api/vote?'; function CandidateVotes({ candidate, flipVoteFlag, rank, loginCookie }) { let history = useHistory(); function handleVoteButtonClick() { axios .get(url, { params: { id: candidate.id, }, headers: { authorization: `${loginCookie.loginCookie}`, }, }) .then(function (response) { alert(response.data); flipVoteFlag(); }) .catch(function (error) { if (error.response.status === 401) { alert('로그인 후 투표 가능합니다.'); history.push('/signin'); } else if (error.response.status === 404) alert('해당 후보는 존재하지 않습니다.'); else alert(error.response.data); }); } return ( <CandidateContainer> <CandidateRank>{rank}위</CandidateRank> <CandidateName>{candidate.name}</CandidateName> <CandidateVoteCounts> [{candidate.voteCount}]</CandidateVoteCounts> <VoteButton onClick={handleVoteButtonClick} r={194} g={147} b={216}> vote </VoteButton> </CandidateContainer> ); } export default CandidateVotes; export const CandidateContainer = styled.div` text-align: center; font-size: 19px; margin: 10px; margin-bottom: 15px; `; export const CandidateRank = styled.span` margin-right: 40px; `; export const CandidateName = styled.span` margin-right: 10px; `; export const CandidateVoteCounts = styled.span` margin-right: 10px; `; export const Button = styled.button` border-radius: 28px; display: inline-block; margin-right: 30px; font-size: 15px; width: 85px; height: 35px; text-decoration: none; background-color: rgba( ${(props) => props.r}, ${(props) => props.g}, ${(props) => props.b}, 0.7 ); &:hover { background-color: rgba( ${(props) => props.r}, ${(props) => props.g}, ${(props) => props.b}, 1 ); } `; const VoteButton = styled(Button)` border: #6a1b9a 1px solid; color: #6a1b9a; width: 50px; height: 23px; font-size: 12px; margin: auto; `;
$(document).ready(function() { $('#datatable').DataTable(); $('#scheduled').toggle(); $('#schedule').click(function(){ $('#scheduled').toggle(); }); $('#message').on('input keyup change click', function(){ var nochar = $(this).val().length; $('.messagecounter').html("No of Characters: "+nochar); var divider = 160; if(nochar>310){ divider = 155}else if(nochar>500){divider = 150} var pages = eval(Math.ceil(nochar/divider)); $('.pagecounter').html("No of Pages: "+pages); }); }); function addphoneNumber(phonenumber){ var currepients = $("#recipient").val(); var recipients; if(currepients!=""){ recipients = currepients+","+phonenumber; }else{ recipients = phonenumber; } $('#recipient').val(recipients); }
const orderName = document.getElementById('order_name'); const total = document.getElementById('_price'); const image = document.getElementById('images'); const orderInfo = document.querySelector('.order-info'); const person = document.getElementById('person'); const increaseDecValue = document.getElementById('increase_value'); const confirm_button = document.getElementById('confirm_button'); const customerName = document.getElementById('name'); const customerAddress = document.getElementById('address'); let plus = ''; let minus = ''; let dishName = ''; let dishPrice = 0; let total_price = 0; const buttonAction = (btn1, btn2)=>{ plus = btn1; minus = btn2; } function getInfo(){ const name = localStorage.getItem('Name'); const price = localStorage.getItem('Price'); dishName = name; dishPrice = price; if(name === 'Chicken Biriyani'){ image.innerHTML = '<img src="/image/biriyani.jpg" alt="chicken biriyani"/>'; }else if(name === 'Butter Chicken'){ image.innerHTML = '<img src="/image/butter chicken.jpg" alt="butter chicken"/>'; } else if(name === 'Chicken Curry'){ image.innerHTML = '<img src="/image/chicken curry.jpg" alt="curry">'; } else if(name === 'Special Burger'){ image.innerHTML = '<img src="/image/burger.jpg" alt="burger">'; } else if(name === 'Vegetable Shawrma'){ image.innerHTML = '<img src="/image/shawrma.jpg" alt="shawrma">'; } else if(name === 'Mango Milkshake'){ image.innerHTML = '<img src="/image/mango.jpg" alt="mango shake" />'; } else if(name === 'Strawberry Milkshake'){ image.innerHTML = '<img src="/image/strawberry.jpg" alt="milkshake" />'; } orderName.innerHTML = name; perPersonPrice = price; total.innerHTML = price; const plus = document.createElement('button'); plus.innerHTML = '<i class="fas fa-plus"></i>'; plus.className = 'plus_btn'; increaseDecValue.appendChild(plus); const minus = document.createElement('button'); minus.innerHTML = '<i class="fas fa-minus"></i>'; minus.className = 'minus_btn'; increaseDecValue.appendChild(minus); buttonAction(plus, minus); } getInfo(); plus.addEventListener('click', ()=>{ let total_person = ++person.value; let totalPrice = total_person * dishPrice; total_price = totalPrice; total.innerHTML = totalPrice; }) function decrease(){ if(person.value >0){ let currentValue = person.value--; if(currentValue >= 0){ console.log(currentValue); total_price = total_price - dishPrice; total.innerHTML = total_price; console.log(total_price); } } } minus.addEventListener('click', decrease); confirm_button.addEventListener('click', ()=>{ let name = customerName.value; let address = customerAddress.value; if(person.value > 0 && name.length != 0 && address.length != 0){ alert("Your order confirmed!"); }else if(name.length == 0 && address.length == 0){ alert('Please fill up the name & address field'); }else if(name.length == 0){ alert('Please fill up the name field'); }else if(address.length == 0){ alert('Please fill up the address field'); } else{ alert("Please set the number of order"); } })
const pagination = require('pagination'); let paginator; let m_rowsPerPage; module.exports = { create: (prelink, current, rowsPerPage, totalResult) => { m_rowsPerPage = rowsPerPage; paginator = new pagination.TemplatePaginator({ prelink: prelink, current: current, rowsPerPage: rowsPerPage, totalResult: totalResult, slashSeparator: true, // prelink시 slash 로 구분 지을지 여부 template: (result) => { var i, len, prelink; var html = '<nav><ul class="pagination">'; if(result.pageCount < 2) { html += '</ul>'; return html; } prelink = paginator.preparePreLink(result.prelink); if(result.previous) { html += '<li class="disabled"><a href="'+ prelink + result.previous +'" aria-label="Previous">' + '<span aria-hidden="true"> << </span></a></li>'; } if(result.range.length) { for( i = 0, len = result.range.length; i < len; i++) { if(result.range[i] === result.current) { html += '<li class="active"><a class="page-link" href="' + prelink + result.range[i] + '">' + result.range[i] + '</a></li>'; } else { html += '<li><a class="page-link" href="' + prelink + result.range[i] + '">' + result.range[i] + '</a></li>'; } } } if(result.next) { html += '<li><a aria-label="Next" href="' + prelink + result.next + '"><sapn aria-hidden="true"> >> </a></li>'; } html += '</ul></nav>'; return html; }}); }, getPaginationData: () => { let pageData = paginator.getPaginationData(); pageData.limitIndex = pageData.fromResult - 1; // mysql limit 작업용 param pageData.rowsPerPage = m_rowsPerPage; return pageData; }, render: () => { return paginator.render(); } }
/** * Router module * @param app:object, express app */ module.exports = (app) =>{ app.get('/',(req, res)=>{ res.send("<h1>This is minicube k8 cluster version of simple node app!</h1>"); }); app.get('/login',(req, res)=>{ res.send("So you want to login here?"); }); app.get('/logout',(req, res)=>{ res.send("Now you are logged out"); }); app.get('/home',(req, res)=>{ res.send("<h1>Welkom home my son!</h1>"); }); }
const path = require('path'); const fs = require('fs'); class Events { constructor() { this.cache = {}; this.cachePath = path.join(__dirname, 'cache'); this.cacheTXPath = path.join(this.cachePath, 'tx'); fs.exists(this.cachePath, (exists) => { if (!exists) { fs.mkdirSync(this.cachePath); fs.mkdirSync(this.cacheTXPath); } }); } add(socket) { this.socket = socket; socket.on('disconnect', data => { log.debug('CORE DISCONNECT - PLEASE MAKE SURE THE SUPPLIED SECRET KEY IS VALID'); process.exit(1); }); socket.on('client:connect', data => { log.debug('client:connect', data); }); socket.on('client:disconnect', data => { log.debug('client:disconnect', data); }); socket.on('provider:rx', rx => { rx = this.processLatency(rx, 'rx'); this.providerRx(rx); }); } providerRx(rx) { try { rx = this.verifyTransaction(rx); if (!rx) { log.error("EVENTS:PROVIDER:RX INVALID REQUEST", rx); return; } log.debug("RX IS ", rx); let lambda = rx.lambda; log.debug("LAMBDA IS ", lambda); if (this.cache[lambda]) { log.debug("SENDING TO CACHED LAMBDA " + lambda); //SEND REQUEST TO PROCESS try { this.cache[lambda].send({ action: 'rx', request: rx }); } catch (e) { this.spawnHandler(lambda, rx); } } else { log.debug("SPINNING UP LAMBDA " + lambda); this.spawnHandler(lambda, rx); } } catch (e) { log.error("EVENTS:PROVIDER:RX ", e); } } providerTx(tx) { try { tx = this.verifyTransaction(tx); if (!tx) { log.error("EVENTS:PROVIDER:TX INVALID RESPONSE (NO PID)", rx); return; } //GET THE FIRST CHUNK'S DATA let firstChunk = path.join(this.cacheTXPath, tx.pid + '.0.chunk'); fs.readFile(firstChunk, 'utf8', (err, data) => { if (err) { log.error("CHUNK @ " + firstChunk + " NOT FOUND. DROPPING"); return; } //CREATE THE PAYLOAD try { data = JSON.parse(data); } catch (e) { log.warn("COULD NOT PARSE CHUNK"); } let response = { error: tx.error, version: tx.version, pid: tx.pid, response: { chunkTotal: tx.response.chunkTotal, chunkId: 0, data: data }, latency: tx.latency } response = this.processLatency(response, 'tx'); this.socket.emit('provider:tx', response); }); } catch (e) { } } spawnHandler(name, rx) { let lambdaFile = path.join(__dirname, '../', 'lambdas', name + '.js'); fs.exists(lambdaFile, (exists) => { if (!exists) { log.error("LAMBDA FOR " + name + " (lambdas/" + name + ".js) NOT FOUND"); return; } try { log.debug("FORKING PROCESS FOR " + name + "@" + lambdaFile); let fork = require('child_process').fork; this.cache[name] = fork(lambdaFile); this.cache[name].send({ action: 'configure', release: release, domain: domain }); this.cache[name].send({ action: 'rx', request: rx }); //GET RESPONSE FORM PROCESS this.cache[name].on('message', msg => { log.debug("GOT RESPONSE FROM HANDLER ", msg); this.providerTx(msg); //CREATE THE PAYLOAD }); } catch (e) { log.error("COULD NOT SPAWN HANDLER", e.stack); } }) } verifyTransaction(obj) { return obj.pid ? obj : false } processLatency(obj, type) { try { if (obj) { if (type == 'rx') { obj.latency.providerReceiveAt = new Date().getTime(); } else { obj.latency.providerResponseAt = new Date().getTime(); } } } catch (e) { log.error("COULD NOT ADD LATENCY " + type + " TO ", obj); } return obj; } } module.exports = Events;
var app = new Vue({ el: '#app', data: { NT: 0, US: 30.475, JPY: 0.2645, CNY: 4.356, HKD: 3.781, dateTime: '2018/11/24-AM:10:48' }, computed: { japan: function() { return this.NT / this.JPY; }, usa: function(){ return this.NT / this.US; }, china:function(){ return this.NT / this.CNY; }, hk:function(){ return this.NT / this.HKD; } } });
import React from 'react'; import { connect } from 'react-redux'; import { Form, Input, Button, Row, Col } from 'antd'; import CustomBreadcrumb from '@/components/BreadCrumb'; import { updateProfile } from '../../store/reducers/user/actions'; import items from './items'; const { Item } = Form; const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 }, }; class User extends React.Component { handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { this.props.dispatch(updateProfile(values)); }); } render() { const { user } = this.props; const { getFieldDecorator } = this.props.form; return ( <> <CustomBreadcrumb arr={['Profile']} /> <div className="login"> <Form onSubmit={this.handleSubmit} className="login-form" style={{ width: 500 }} > { items.map(({ label, key }) => ( <Item key={key} {...formItemLayout} label={label} > { getFieldDecorator(key, { initialValue: user[key] })(<Input />) } </Item> )) } <Row> <Col span={24} style={{ textAlign: 'right' }}> <Button type="primary" htmlType="submit">Apply</Button> </Col> </Row> </Form> </div> </> ); } } const mapStateToProps = ({ user }) => ({ user }); export default Form.create()(connect(mapStateToProps)(User));
// Created by Vince Chang import React, { Component } from 'react'; import './App.css'; import Game from './Game'; class App extends Component { /* ========================================================================= * Function Name: render * Task: This function will render a Game component * * The purpose of the game is to allow users to click from the * numbers component that add up to the target number, until all numbers * have been used. If the user experiences a case where the remaining * numbers don't add up to the target number, then they are allowed the * ability to refresh their target number in hopes of having a combination * of two numbers that add up to the target number ========================================================================= */ render() { return ( <div className="App"> <Game /> </div> ); } } export default App;
kompair .service('sharedProperties', ['$state', SharedProp]); function SharedProp($state) { var oSharedObj = { bSingedIn: false, sSignedInUserId: null, oCompair: null, ChangeStateTo: function(sState) { $state.go(sState); } } return oSharedObj; }
var restify = require('restify'); var async = require('async'); function fd42 (opts) { var self = this; self.url = opts.url; self.user = opts.user; self.pass = opts.pass; self.subnet_name = opts.subnet_name; self.host = opts.host; self.client = restify.createJsonClient({ url: self.url }); self.client.basicAuth(self.user, self.pass); } fd42.prototype.init = function() { var self = this; self.get_subnet_details(self.subnet_name, function(err, subnet){ if(subnet.type != 2) { // type == DHCP throw new Error('Subnet is not set as DHCP'); } self.subnet = subnet.network + '/' + subnet.mask_bits; self.range_start = subnet.range_begin; self.range_end = subnet.range_end; self.routers = [ subnet.gateway ]; }); }; fd42.prototype.get_subnet_details = function(name, cb) { var self = this; self.client.get('/subnets', function(err, req, res, obj) { var subnet; obj.forEach(function(elem){ if(elem.name == name){ subnet = elem; } }); cb(err, subnet); }); }; fd42.prototype.get_lease = function(mac, cb) { var self = this; self.client.get({ path: '/macs/', query: [ { 'mac': mac } ] }, function(err, req, res, obj) { var macaddr = obj[0]; if(macaddr){ // ... } }); };
'use strict'; var fs = require('fs'); var assert = require('chai').assert; var tv4 = require('tv4'); var schemaFile = './vega-embed-schema.json'; var schema = JSON.parse(fs.readFileSync(schemaFile)); var res = './test/resources/'; function error_msg(desc, e) { return desc + ': ' + JSON.stringify(e, function(key, value) { return key === 'stack' ? undefined : value; }, 2); } describe('schema', function() { it('should validate airports spec', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-airports.json')); var v = tv4.validate(spec, schema); assert.ok(v, error_msg('Airports', tv4.error)); }); it('should validate force spec', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-force.json')); var v = tv4.validate(spec, schema); assert.ok(v, error_msg('Force', tv4.error)); }); it('should validate jobs spec', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-jobs.json')); var v = tv4.validate(spec, schema); assert.ok(v, error_msg('Jobs', tv4.error)); }); it('should validate world spec', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); var v = tv4.validate(spec, schema); assert.ok(v, error_msg('World', tv4.error)); }); it('should validate vega mode', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); spec.mode = 'vega'; var v = tv4.validate(spec, schema); assert.ok(v, error_msg('World', tv4.error)); }); it('should validate vega-lite spec', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-vl.json')); var v = tv4.validate(spec, schema); assert.ok(v, error_msg('World', tv4.error)); }); it('should validate vega-lite url', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-vl-url.json')); var v = tv4.validate(spec, schema); assert.ok(v, error_msg('World', tv4.error)); }); it('should invalidate unrecognized mode', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); spec.mode = 'foobar'; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate mising vega chart ref', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); delete spec.url; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate ill-formed url', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); spec.url = 1; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate ill-formed source', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-airports.json')); spec.source = 1; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate ill-formed vega spec', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-jobs.json')); spec.spec = 'foo'; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate unsupported property', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); spec.foo = 'bar'; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate extra checkbox property', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-force.json')); spec.parameters[4].foo = 'bar'; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate missing range min/max', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); delete spec.parameters[0].min; assert.notOk(tv4.validate(spec, schema)); spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); delete spec.parameters[0].max; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate extra range property', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-world.json')); spec.parameters[0].foo = 'bar'; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate missing select options', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-jobs.json')); spec.parameters[1].type = 'select'; delete spec.parameters[1].options; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate extra select property', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-jobs.json')); spec.parameters[1].type = 'select'; spec.parameters[1].foo = 'bar'; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate missing radio options', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-jobs.json')); spec.parameters[1].type = 'radio'; delete spec.parameters[1].options; assert.notOk(tv4.validate(spec, schema)); }); it('should invalidate extra radio property', function() { var spec = JSON.parse(fs.readFileSync(res + 'embed-jobs.json')); spec.parameters[1].type = 'radio'; spec.parameters[1].foo = 'bar'; assert.notOk(tv4.validate(spec, schema)); }); });
const bunyan = require('bunyan'); const path = require('path'); const fs = require('fs'); const config = require('../config'); const {URL} = require('url'); // hack, see below // const BUNYAN_TO_STACKDRIVER = { // 60: 'CRITICAL', // 50: 'ERROR', // 40: 'WARNING', // 30: 'INFO', // 20: 'DEBUG', // 10: 'DEBUG', // }; const streams = [ // Log to the console { stream: process.stdout } ]; // wire in stack driver if google cloud service account provided let projectId; if( config.google.serviceAccountExists ) { let {LoggingBunyan} = require('@google-cloud/logging-bunyan'); // grab project id from service account file let accountFile = require(config.google.serviceAccountFile); // create bunyan logger for stackdriver projectId = accountFile.project_id; let loggingBunyan = new LoggingBunyan({ projectId: accountFile.project_id, keyFilename: config.google.serviceAccountFile, resource : {type: 'project'} }); // hack fix for issue we need to file // they are not properly setting the severity level // let googleFormatEntry = loggingBunyan.formatEntry_; // loggingBunyan.formatEntry_ = function(record) { // record = googleFormatEntry.call(loggingBunyan, record); // if( !record.metadata.severity ) { // record.metadata.severity = BUNYAN_TO_STACKDRIVER[record.data.level]; // } // return record; // } // add new logger stream streams.push(loggingBunyan.stream()); } let host = 'unknown.host' try { host = new URL(config.server.url).host; } catch(e) {} let logger = bunyan.createLogger({ name: (process.env.FIN_LOGGER_NAME || global.LOGGER_NAME || 'fin-server-generic')+'-'+host, level: config.server.loglevel || 'info', streams: streams }); let info = { name: (process.env.FIN_LOGGER_NAME || global.LOGGER_NAME || 'fin-server-generic')+'-'+host, level: config.server.loglevel || 'info', stackdriver : { enabled : projectId ? true : false, file : config.google.serviceAccountFile } } if( projectId ) { info.stackdriver.projectId = projectId; } logger.info('logger initialized', info); module.exports = logger;
angular.module('emailController',['userServices']) .controller('emailCntrl',function ($routeParams,$timeout,$route,User) { var app = this; User.activateAccount($routeParams.token).then(function(data) { app.successMsg = false; app.errorMsg = false; if(data.data.success){ app.successMsg = data.data.message; $timeout(function () { $route.reload('/login') },3000); } else{ app.errorMsg = data.data.message; } }) }) .controller('resendCntrl', function(User,$timeout,$route,$location) { app=this; app.checkCredentials = function (loginData) { app.loader=true; app.successMsg = false; app.errorMsgNU = false; app.errorMsgWP = false; User.checkCredentials(app.loginData).then(function (data) { if(data.data.success){ // Custom function that sends activation link User.resendLink(app.loginData).then(function(data) { // Check if sending of link is successful if (data.data.success) { app.loader=false; app.successMsg = data.data.message; // If successful, grab message from JSON object } else { app.loader=false; app.errorMsg = data.data.message; // If not successful, grab message from JSON object } }); $timeout(function () { $route.reload('/login') },3000); } else{ if(data.data.message === "No user found"){ app.loader=false; // If not successful, grab message from JSON object app.errorMsgNU = data.data.message; } else if(data.data.message === "Wrong password"){ app.loader=false; // If not successful, grab message from JSON object app.errorMsgWP = data.data.message; } else{ app.loader=false; // If not successful, grab message from JSON object app.errorMsgNU = data.data.message; } } }); }; }) // Controller: passwordCtrl is used to send a password reset link to the user .controller('passwordCntrl', function(User,$timeout,$route) { app = this; // Function to send reset link to e-mail associated with username this.sendPassword = function(resetData) { app.errorMsg = false; // Clear errorMsg app.successMsg = false; // Clear errorMsg app.loader = true; // Start loading icon // Runs function to send reset link to e-mail associated with username User.sendPassword(this.resetData).then(function(data) { app.loader = false; // Stop loading icon // Check if reset link was sent if (data.data.success) { app.successMsg = data.data.message; // Grab success message from JSON object $timeout(function () { $route.reload('/login') },3000); } else { app.errorMsg = data.data.message; // Grab error message from JSON object } }); } }) .controller('passwordrstCntrl',function (User,$routeParams,$timeout,$location) { app = this; app.hide = true; app.successMsg = false; app.errorMsg = false; app.successMsgsp = false; app.errorMsgsp = false; app.loader = true; User.verifyLink($routeParams.token).then(function(data) { if(data.data.success){ app.successMsg = "Reset link verified, enter a new password"; app.username = data.data.user.userName; app.hide = false; } else{ app.errorMsg = data.data.message; $timeout(function () { $location.path('/login') },3000); } }); app.savePassword = function (userData) { this.userData.username = app.username; User.savePassword(this.userData).then(function(data) { if(data.data.success){ app.successMsgsp = data.data.message; app.hide = true; $timeout(function () { $location.path('/login') },3000); } else{ app.errorMsgsp = data.data.message; } }); } });
const body = document.body; const level = document.querySelectorAll('.menu-item'); const selectLevel = (item) => { level.forEach((item) => item.classList.remove("selected")); item.target.classList.add("selected"); }; level.forEach((item) => item.addEventListener("click", selectLevel)); const startButton = document.getElementById('start-button'); function getLevel() { const selectedLevel = document.querySelector(".selected"); const idSelectedLevel = selectedLevel.id; return idSelectedLevel; } function getNumbersOfCard() { const idSelectedLevel = getLevel(); let numberOfCards; switch (idSelectedLevel) { case "simple": numberOfCards = 3; break; case "middle": numberOfCards = 6; break; default: numberOfCards = 9; } return numberOfCards; } function clearField() { document.querySelector('.container').classList.add('invisible'); document.querySelector('.game-field').classList.add('game-field__wrapper'); } function createCard() { const card = document.createElement('div'); card.classList.add('card__wrap'); const cardFront = document.createElement('div'); const cardBack = document.createElement('div'); cardFront.classList.add('card__front'); cardBack.classList.add('card__back'); document.querySelector('.cards').append(card); card.append(cardBack); card.append(cardFront); card.addEventListener("click", card.classList.add("card_flipped")); } function startGame() { getLevel(); clearField(); const numberOfCards = getNumbersOfCard(); for (let i = 1; i <= numberOfCards; i++) { createCard(); } } const elements = document.querySelectorAll(".card__wrap"); for (let i = 0; i < elements.length; i++) { elements[i].onclick = function(){ console.log(elements[i]); elements[i].classList.add("card_flipped"); }; } // const cards = document.querySelectorAll('.card__wrap'); // cards.forEach( // (item) => { // // console.log(item); // item.addEventListener("click", item.classList.add("card_flipped")); // // onclick() => {item.classList.add("card_flipped")}; // } // ) // function game() { // // [...document.querySelectorAll('.card__wrap')].forEach( // // (item) => { // // // console.log(item); // // item.addEventListener("click", item.classList.add("card_flipped")); // // // onclick() => {item.classList.add("card_flipped")}; // // } // // ) // } startButton.addEventListener("click", startGame);
// eslint-disable-next-line no-restricted-imports import jQuery from 'jquery'; import { compare as compareVersions } from '../core/utils/version'; import errors from '../core/utils/error'; import useJQueryMethod from './jquery/use_jquery'; var useJQuery = useJQueryMethod(); if (useJQuery && compareVersions(jQuery.fn.jquery, [1, 10]) < 0) { throw errors.Error('E0012'); } import './jquery/renderer'; import './jquery/hooks'; import './jquery/deferred'; import './jquery/hold_ready'; import './jquery/events'; import './jquery/easing'; import './jquery/element_data'; import './jquery/element'; import './jquery/component_registrator'; import './jquery/ajax';
class FormScript { constructor(inStartVal, inVals, inClass, inSelector) { this.StartVals = inStartVal; this.inputvals = inVals; this.inputClass = inClass; this.selector = inSelector; this.ChangePasswordType = true; } StartVals; inputvals; inputClass; selector; ChangePasswordType; FeltFokus(feltIndex) { this.ValiderFelter(feltIndex); if(this.inputvals[feltIndex] === this.StartVals[feltIndex]) { if(this.selector[feltIndex].name === "kodeord" || this.selector[feltIndex].name === "loginkodeord") { this.selector[feltIndex].type = "password"; } this.selector[feltIndex].value = ""; } } StartKodeordStatus(kodeordIndex) { if(this.selector[kodeordIndex].value !== this.StartVals[kodeordIndex] && this.selector[kodeordIndex].type === "text") { this.selector[kodeordIndex].type = "password"; } } ValiderFelter(feltIndex) { for (var i = 0; i < this.inputvals.length; i++) { if(i !== feltIndex) { if(this.selector[i].value === "") { this.selector[i].value = this.StartVals[i]; } if(this.selector[i].value === "Kodeord" && this.selector[i].type === "password") { this.selector[i].type = "text"; } } } } PassivFeltKlik(feltIndex) { this.ChangePasswordType = false; this.ValiderFelter(feltIndex); } }
import React from 'react' import ReactDOM from 'react-dom'; import StarInfoWrapper from '../styles/StarInfo/StarInfoWrapper.js' import Stars from '../styles/StarInfo/Stars.js' import Reviews from '../styles/StarInfo/Reviews.js' const StarInfo = (props) => ( <StarInfoWrapper> {/* <Star /> Placeholder for Airbnb Star */} <Stars>{Number.parseFloat(props.starReviewTotal).toFixed(2)}</Stars> <Reviews> ({props.numberOfReviews} reviews)</Reviews> </StarInfoWrapper> ) export default StarInfo
import styled from 'styled-components'; import fibonacci_bg from '../images/fibonacci.png' ; export const FlexContainer = styled.section` display: flex; flex-direction: column; justify-content: center; align-items: center; `; export const AppBG = styled.div` position: fixed; top: 0; left: 0; height: 100vh; width: 100vw; opacity: 0.3; background-image: url(${fibonacci_bg}); background-position: center center; background-size: cover; background-repeat: no-repeat; z-index: -1; `; export const AppHeader = styled.header` width: 100%; height: 5rem; margin-top: 2rem; background-color: white; display: flex; justify-content: center; align-items: center; `; export const PageTitle = styled.h1` font-weight: 700; font-size: 2rem; `; export const SecondaryTitle = styled.h2` font-weight: 500; font-size: 1.5rem; padding: 1rem; `; export const FormElm = styled.form` display: flex; flex-direction: column; justify-content: center; align-items: center; `; export const InputElm = styled.input` display: block; margin: 0.5rem; padding: 0.5rem; border: none; `; export const SmallText = styled.small` font-size: 0.8rem; line-height: 2rem; `; export const ErrorText = styled.small` font-size: 0.8rem; line-height: 2rem; color: red; `;
var isSidebarOut = 0; var sidebarbusy = 0; var isTestBoxOut = 0; var sidebarForceReject = 0; var adminValidated = 0; var adminSidebarWidth = 250; var buttonWidth = 15; adminSidebarWidthWithButton = (adminSidebarWidth + buttonWidth) + "px"; function sideBarTurbolinksLoad(sideBarIsOut){ if (sideBarIsOut === 1) { $( "#pagewrapper" ).css({"marginLeft": adminSidebarWidthWithButton}); $( ".top" ).css({"width": '100%'}); $( ".top" ).css({"width": '-='+adminSidebarWidth}); $( "#footer" ).css({"marginLeft": adminSidebarWidthWithButton}); } else { $( "#pagewrapper" ).css({"marginLeft": "0px"}); $( ".top" ).css({"width": '100%'}); $( "#footer" ).css({"marginLeft": "0px"}); } } function sideBarToggle(delay){ sidebarbusy = 1; if (isSidebarOut === 0){ // create center div $( "#adminsidebar" ).html("<div id=\"admin-center\"></div>"); // slide in admin bar $( "#adminsidebar" ).velocity({left: "0px"}, 325, "easeOutQuart"); //USED TO BE 500, "spring" AND width: "200px" // fade in admin button color, fade out old icons and fade in new icon ("finish" stops current animation) $( "#admintogglebutton" ).velocity({left: adminSidebarWidth, backgroundColor: "#D35050"}, 325, "easeOutQuart"); //USED TO BE 500, "spring" AND width: "200px" $( "#admintoggleicon" ).velocity("finish"); $( "#admintoggleicon" ).velocity({opacity: "0"}, 325, "linear", function(){ $( "#admintoggleicon" ).removeAttr("class"); $( "#admintoggleicon" ).attr("class", "fa fa-times"); $( "#admintoggleicon" ).velocity({opacity: "1"}, 325, "linear"); }); // squeezes the rest of the page 200px to the right $( "#pagewrapper" ).velocity({marginLeft: adminSidebarWidthWithButton}, 325, "easeOutQuart"); $( ".top" ).css({"width": '100%'}); $( ".top" ).velocity({width: '-='+adminSidebarWidthWithButton}, 325, "easeOutQuart"); $( "#footer" ).velocity({marginLeft: adminSidebarWidthWithButton}, 325, "easeOutQuart"); // slides background slightly $( "#bg img" ).velocity("stop"); $( "#bg img" ).velocity({left: "3%"}, 625, "easeOutQuart"); isSidebarOut = 1; } else{ setTimeout(function(){ $( "#adminsidebar" ).velocity({left: "-"+adminSidebarWidth}, 325, "easeOutQuart", function(){ $("#adminsidebar").html(""); sidebarbusy = 0; }); $( "#admintogglebutton" ).velocity({left: "0px", backgroundColor: "#7C7C7C"}, 325, "easeOutQuart"); $( "#admintoggleicon" ).velocity("finish"); $( "#admintoggleicon" ).velocity({opacity: "0"}, 325, "linear", function(){ $( "#admintoggleicon" ).removeAttr("class"); $( "#admintoggleicon" ).attr("class", "fa fa-cog"); $( "#admintoggleicon" ).velocity({opacity: "1"}, 325, "linear"); }); $( "#pagewrapper" ).velocity({marginLeft: "0px"}, 325, "easeOutQuart"); $( ".top" ).velocity({width: '100%'}, 325, "easeOutQuart"); $( "#footer" ).velocity({marginLeft: "0px"}, 325, "easeOutQuart"); $( "#bg img" ).velocity("stop"); $( "#bg img" ).velocity({left: "0%"}, 625, "easeOutQuart"); isSidebarOut = 0; }, delay); } } function testBox(){ if (isTestBoxOut === 0){ $("#content").before("<div id=\"testbox\">" + "<p><h2>Testbox</h2></p>" + "<p><a href=\"#\" data-turbolinks=\"false\" onClick=\"showblockscreen('firstsignin', 'en', 1, 0, 0, 1, 0, 0); return false;\">test blockui</a></p>" + "<p><a href=\"#\" data-turbolinks=\"false\" onClick=\"showblockscreen('firstsignin', 'en', 1, 1, 1, 1, 1, 1); return false;\">test 2</a></p>" + "<p><a href=\"#\" data-turbolinks=\"false\" onClick=\"testGrowl(); return false;\">test growl</a></p>" + "<p><a href=\"#\" data-turbolinks=\"false\" onClick=\"testDrag(); return false;\">test drag</a></p>" + "<textbox id=\"seltest\"></textbox>" + "<p>Apply theme: <select id=\"themeselect\" class=\"inputbox\" style=\"margin-left:5px;\"><option value=\"0\"> </option><option value=\"1\">1</option><option value=\"2\">2</option><option value=\"3\">3</option></select></p>" + "</div>"); isTestBoxOut = 1; $('#seltest').selectize({ delimiter: ',', persist: false, create: function(input) { return { value: input, text: input }; }, maxItems: null, searchField: ['name'], options: [ {name: 'Hello'}, {name: 'Helllo'}, {name: 'Hell'} ], }); $( "#themeselect" ).change(function() { theme = $('#themeselect').val(); addTheme(theme); // if (theme == "0"){ // $("#themecss").remove(); // } // else{ // $("#themecss").remove(); // addTheme(theme); // } }); } else{ $("#testbox").remove(); isTestBoxOut = 0; } } var reload = 0; var debug = 0; function updateAdmin(page, getid) { adminNavigation(page,null,getid); } function adminAction(action, id, fromadminbar, page){ if (fromadminbar == 1) { NProgress.configure({ parent: '#adminsection' }); bararea = "admin"; } else { NProgress.configure({ parent: 'body' }); bararea = "normal"; } NProgress.start(); $.post("admin/adminfunctions.php", { 'action': action, 'id': id }, function(data) { if (debug) {console.log(data);} NProgress.done(); if (data.auth === false) { if (data.reason == "nouser") { barnotice.add("Your account doesn't exist.",bararea); } else if (data.reason == "notsignedin") { barnotice.add("You are not signed in.",bararea); } else if (data.reason == "notadmin") { barnotice.add("You are not an admin.",bararea); } else if (data.error == "servererror") { barnotice.add("Server Error",bararea); } } else { if (data.error) { if (data.error == "servererror") { barnotice.add("Server Error",bararea); } else if (data.error == "invalidaction") { barnotice.add("That is not a valid action.",bararea); } else if (data.error == "alreadybanned") { barnotice.add("User is already banned.",bararea); } else if (data.error == "alreadyunbanned") { barnotice.add("User is already unbanned.",bararea); } else if (data.error == "topicalreadyclosed") { barnotice.add("Topic is already closed.",bararea); } else if (data.error == "topicalreadyopen") { barnotice.add("Topic is already open.",bararea); } else if (data.error == "topic-alreadybinned") { barnotice.add("Topic is already in the bin.",bararea); } else if (data.error == "topic-notinbin") { barnotice.add("Topic is not in the bin.",bararea); } } else if (data.result == "success") { if (action == "banuser") { barnotice.add("User banned",bararea); if (page == "user") { $( ".subheader" ).css("text-decoration", "line-through"); $('#admin-banbutton').attr({onclick:"adminAction(\'unbanuser\',"+id+",1,currentpage); return false;"}); $('#admin-banbutton .adminitem').text('Unban'); } if (page == "userlist") { $('.banbutton.id'+id).html('<a class="colorbutton" href="#" onclick="adminAction(\'unbanuser\','+id+',0,currentpage); return false;">Unban</a>'); $( ".userlistname.id"+id ).css("text-decoration", "line-through"); } } if (action == "unbanuser") { barnotice.add("User unbanned",bararea); if (page == "user") { $( ".subheader" ).css("text-decoration", "none"); $('#admin-banbutton').attr({onclick:"adminAction(\'banuser\',"+id+",1,currentpage); return false;"}); $('#admin-banbutton .adminitem').text('Ban'); } if (page == "userlist") { $('.banbutton.id'+id).html('<a class="colorbutton" href="#" onclick="adminAction(\'banuser\','+id+',0,currentpage); return false;">Ban</a>'); $( ".userlistname.id"+id ).css("text-decoration", "none"); } } if (action == "closetopic") { barnotice.add("Topic closed.",bararea); $('#admin-topicclosed').attr({onclick:"adminAction(\'opentopic\',"+id+",1,currentpage); return false;"}); $('#admin-topicclosed .adminitem').html('<i class="fa fa-lock" style="margin-right:7px"></i>'); } if (action == "opentopic") { barnotice.add("Topic opened.",bararea); $('#admin-topicclosed').attr({onclick:"adminAction(\'closetopic\',"+id+",1,currentpage); return false;"}); $('#admin-topicclosed .adminitem').html('<i class="fa fa-unlock" style="margin-right:7px"></i>'); } if (data.serveraction == "topic-binned") { barnotice.add("Topic moved to bin.",bararea); $('#topic-'+id).hide(); } if (data.serveraction == "topic-restored") { barnotice.add("Topic restored from bin.",bararea); $('#topic-'+id).show(); } } } }); // end ajax call } function adminNavigation(navigation, page, getid) { if (isSidebarOut == 1) { if (sidebarbusy === 0){ NProgress.configure({ parent: '#adminsection' }); NProgress.start(); $.post( "admin/adminfunctions.php", { 'navigation': navigation, 'previouspage': previoussection, 'pageid': getid }, function( data ) { //JSON.parse( data ); if (debug) {console.log(data);} if (data.auth === false) { if (data.reason == "nouser" | data.reason == "notsignedin") { NProgress.done(); sideBarToggle(); } else if (data.reason == "notadmin" | sidebarForceReject == "1") { NProgress.done(); $('#adminsidebar').html("<div id=\"admin-redcross\">✖</div>"); sideBarToggle(625); } } else { NProgress.done(); adminValidated = 1; $('#adminsidebar').html( "<div id=\"adminsidebarcontainer\">" + "<div id=\"adminheader\">" + "<a id=\"adminheadertext\">" + data.title + "</a>" + "</div>"+ "<div id=\"adminsection\">" + "<div role=\"button\" id=\"adminbackbutton\" onClick=\"adminNavigation('back', currentpage, getid); return false;\"><i class='fa fa-angle-left' aria-hidden='true'></i></div>"+ "<a id=\"adminsectiontext\">" + data.section + "</a>" + "</div>"+ "<div id=\"adminbody\">" + "<div id=\"admincontent\">" + data.content + "</div>"+ "</div>"+ "</div>"+ "<div id=\"notice-bar-admin\"></div>" ); sidebarbusy = 0; } }); } } } function initAdmin(page, getid) { var desired_delay = 4000; var message_timer = false; if (sidebarbusy === 0){ if (isSidebarOut == 1) { sideBarToggle(); } else{ sideBarToggle(); NProgress.configure({ parent: '#adminsidebar' }); NProgress.start(); //AJAX $.post( "admin/adminfunctions.php", { 'action': 'initadmin', 'currentpage': page, 'pageid': getid }, function( data ) { //JSON.parse( data ); if (debug) {console.log(data);} if (data.auth === false) { if (data.reason == "nouser" | data.reason == "notsignedin") { NProgress.done(); sideBarToggle(); } else if (data.reason == "notadmin" | sidebarForceReject == "1") { NProgress.done(); $('#adminsidebar').html("<div id=\"admin-redcross\">✖</div>"); sideBarToggle(625); } } else { NProgress.done(); adminValidated = 1; $('#adminsidebar').html( "<div id=\"adminsidebarcontainer\">" + "<div id=\"adminheader\">" + "<a id=\"adminheadertext\">" + data.title + "</a>" + "</div>"+ "<div id=\"adminsection\">" + "<div role=\"button\" id=\"adminbackbutton\" onClick=\"adminNavigation('back', currentpage, getid); return false;\"><i class=\"fa fa-angle-left\" aria-hidden=\"true\"></i></div>"+ "<a id=\"adminsectiontext\">" + data.section + "</a>" + "</div>"+ "<div id=\"adminbody\">" + "<div id=\"admincontent\">" + data.content + "</div>"+ "</div>"+ "</div>"+ "<div id=\"notice-bar-admin\"></div>" ); sidebarbusy = 0; previoussection = data.page; } }); } } } function adminMobile() { showblockscreen("admin","en",1,1,0,0,0,0); $(".blockMsgContents").html("<h1>Admin</h1><p class='blockMsgContentspsmaller'>testing</p>"); } $( document ).ajaxError(function(event, jqxhr, settings, thrownError) { NProgress.done(); console.log("Error: " + thrownError); //$.jGrowl("Error: " + thrownError); if (isSidebarOut === 1){ $('#admin-center').append("<a style=\"white-space: pre-wrap;height:100px;\">There was a problem connecting.</a>"); sideBarToggle(625); } });
'use strict'; /** * @ngdoc service * @name seedApp.previewService * @description * # previewService * Service in the seedApp. */ angular.module('seedApp') .service('previewService', function ($mdDialog) { // AngularJS will instantiate a singleton by calling "new" on this function // This service is for opening an mdDialog that previews an actions intention // eg - 'this button should search for this tag on the main page' this.preview = function(ev, parent, text, header) { var headerText = header ? header : 'Action preview'; return $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector(parent))) .clickOutsideToClose(true) .title(headerText) .textContent(text) .ariaLabel('action preview dialog') .ok('Okay') .targetEvent(ev) ); }; });
import { PubSub } from 'apollo-server-express'; import { chatUsers as model } from '../../models/chat_users'; import { userApi as modelUser } from '../../models/user_api'; import { getTokenUser, addNewUser, updateUser } from './utils' const pubsub = new PubSub(); const CHAT_USER = 'CHAT_USER', CHAT_USERS_ONLINE = 'CHAT_USERS_ONLINE', USER_PROFILE = 'USER_PROFILE'; //GENERATE TOKEN export const loginUser = (email, password) => getTokenUser(email, password); //OBTIENE EL USUARIO DEL TOKEN VALIDADO export const userValid = async currentUserApi => { if (currentUserApi) { await usersOnline(); return new Promise((resolve, reject) => { modelUser.findOne({ email: currentUserApi.email }) .then(userBD => { const newUser = { name: userBD.name, lastname: userBD.lastname, email: userBD.email, imageUrl: userBD.imageUrl, roles: userBD.roles }; const currentUser = { name: currentUserApi.name, lastname: currentUserApi.lastname, email: currentUserApi.email, imageUrl: currentUserApi.imageUrl, roles: currentUserApi.roles }; newUser == currentUser ? resolve(currentUserApi) : resolve(newUser); }) }); } else { return currentUserApi; } }; //SOLO USUARIOS CON ROL DE ADMIN export const paginationUsers = (limit, offset, currentUserApi) => { if(currentUserApi){ const rolAdmon = currentUserApi.roles.map(rol => rol.name); if (rolAdmon.indexOf('rol_admon') >= 0 ){ return modelUser.find({}).limit(limit).skip(offset) .then(users => users) .catch(error => console.log('*** Error_MONGODB_totalUsers', error)); } } }; export const totalUsers = () => { return new Promise((resolve, reject) => { modelUser.countDocuments({}, (error, count) => { error ? reject(error) : resolve(count); }); }); }; //NUEVO USUARIO Y ROLES PARA INTERACTUAR CON LA API export const newUser = user => addNewUser(user); export const editUser = async user => { let objUser = [] await updateUser(user) .then(async (userDB) => { await usersOnline(true, false); await pubsub.publish(USER_PROFILE, { subUserProfile: userDB }); objUser = userDB; }) .catch(error => console.log('*** Error_MONGODB_updateUser',error)); return objUser; }; export const deleteUser = async email => { let delt = ''; await modelUser.deleteOne({ email }).then(async () => { await usersOnline(true,true); delt = 'delete user ok'; }); return delt; }; export const chatUsers = async () => { let objChat = []; await model.find({}).then(data => { objChat = data; return objChat; }) .catch(error => console.log('error_MONGODB_chatUsers',error)); await objChat.forEach(chat => { pubsub.publish(CHAT_USER, { subChatUsers: { new:false, user:chat.user, message:chat.message, date:chat.date } }); }); return objChat; }; export const newChatUser = (user, message) => { const date = new Date(); pubsub.publish(CHAT_USER, { subChatUsers: { new:true, user, message, date } }); return model.create({ user, message, date }).then(data => data).catch(error => error); }; export const usersOnline = async (update = false, deleted = false) => { let objUsersOn = []; await modelUser.find({ online: true }).then(async users => { await pubsub.publish(CHAT_USERS_ONLINE, { subUsersOnline: { update, deleted, user: users } }); objUsersOn = users; }) .catch(error => console.log('*** Error_MONGODB_usersOnline', error)); return objUsersOn; }; export const userOnlineOff = async email => { await modelUser.updateOne({ email }, { $set: { online: false } }) .then(() => {}) .catch(error => console.log('*** Error_MONGODB_userOnlineOff',error)); await usersOnline(true,false); return `user ${email} off`; }; //***SUBSCRIPTION ITERATORS***// export const subChatUsers = () => ({ subscribe: () => pubsub.asyncIterator(CHAT_USER) }); export const subUsersOnline = () => ({ subscribe: () => pubsub.asyncIterator(CHAT_USERS_ONLINE) }); export const subUserProfile = () => ({subscribe: () => pubsub.asyncIterator(USER_PROFILE)});
// let Animal = {}; // let Cat = Object.create(Animal); // let fluffy = Object.create(Cat); // console.log(fluffy instanceof Animal); // class Animal {} // class Cat extends Animal {} // let fluffy = new Cat(); // console.log(fluffy instanceof Object); // console.log(Object.getPrototypeOf(fluffy)); // function Animal() {} // function Cat() {} // Cat.prototype = new Animal(); // function makeCat() { // return {}; // } // let fluffy = makeCat(); // console.log(fluffy instanceof Animal); let Animal = {}; let Cat = Object.create(Animal); let fluffy = Object.create(Cat); console.log(fluffy instanceof Animal);
/** * 使用http模块接收客户端请求消息 * * 演示QueryString模块的使用 参考文档http://nodejs.cn/ * node interpreter: C:\Program Files (x86)\nodejs\node.exe * */ const http = require('http'); const url = require('url'); //创建一个Web服务器 —— 创建一个面包售货员 const server = http.createServer(); //让Web服务器能够处理客户端连接请求——岗前培训 server.on('request', function(request, response){ console.log('Node.js Web服务器接收到一个HTTP请求消息'); //console.log(arguments.length,arguments[0],arguments[1], arguments); console.log(`请求Request:${request}`); console.log(`请求Method:${request.method}`); console.log(`请求URL:${request.url}`) console.log('请求URL数据:') var obj = url.parse(request.url, true); console.log(obj); //query / pathname console.log(`请求头部:`); console.dir(request.headers); }); //练习:使用url模块解析出请求URL中的: // (1) 请求资源的名称 // (2) 查询字符串数据 //让Web服务器开始监听指定端口——开始上岗 server.listen(8888, function(){ console.log('Node.js Web服务器开始监听8888端口...') }) // 1.启动脚本; // 2.在本机地址栏输入:http://localhost:8888/ // 3.返回脚本查看;
var s = 'abb' for(let i of s){ console.log(i); } var s1 = ''; console.log(s.indexOf('b')); console.log(s.slice(1));
import React, { useState } from 'react'; import { Message } from "./message"; export function Checkbox(props) { return <div> <h3>Estado</h3> <div style={{ display: 'flex', fontSize: '1.4rem', width: 450, }}> <label htmlFor="check1"> <input onChange={(e) => { props.onChange(true) }} checked={props.good} id="check1" type="radio" value=":)" name="check1" /> :) </label> <label htmlFor="check2"> <input style={{ marginLeft: 20, }} onChange={(e) => { props.onChange(false) }} checked={!props.good} id="check2" type="radio" value=":(" name="check1" /> :( </label> </div> </div> }
const events = require('events'); var emitter = new events.EventEmitter; emitter.once('tick', () => { let timeStamp = Date.now(); emitter.on('tick', () => console.log((Date.now() - timeStamp) / 1000 + '"')); }) setInterval(() => emitter.emit('tick'), 1000)
import { createContext } from 'preact'; import { useContext, useMemo } from 'preact/hooks'; export { ClientRPC } from './client-rpc'; export { GradingService } from './grading'; export { VitalSourceService } from './vitalsource'; /** * Directory of available services. * * The directory is a map of service class to instance. The instances don't * have to be instances of the exact class, but they must have the same interface. * * @typedef {Map<Function, unknown>} ServiceMap */ /** * Context object used to make services available to components. * * A `Services.Provider` component must be rendered at the top of the tree * with a directory of available services. Components within the tree can access * the service instances using the `useService` hook. * * @example * const MyApp = (props) => { * const fooService = useService(FooService); * fooService.doSomething(); * ... * }; * * const services = new Map(); * services.set(FooService, new FooService(...)); * <Services.Provider value={services}> * <MyApp /> * </Services.Provider> * * @type {import('preact').Context<ServiceMap>} */ export const Services = createContext(new Map()); /** * Hook that looks up a service. * * There must be a `Services.Provider` component higher up the component tree * which provides the service. This hook throws if the service is not available. * * @template {new (...args: any) => any} Class * @param {Class} class_ - The service class. This is used as a key to look up the instance. * @return {InstanceType<Class>} - Registered instance which implements `class_`'s interface */ export function useService(class_) { const serviceMap = useContext(Services); const service = serviceMap.get(class_); if (!service) { throw new Error(`Service "${class_.name}" is not registered`); } return /** @type {InstanceType<Class>} */ (service); } /** * Utility that wraps a component that relies on services with a `Services.Provider`. * * This is mainly useful in tests for such components. In non-test environments, * there should generally be a `<Services.Provider>` near the root of the tree. * * The wrapped component accepts the same props as the original. * * @example * const WidgetWrapper = withServices(Widget, () => [[APIService, apiService]]); * render(<WidgetWrapper someProp={aValue}/>, container) * * @param {import('preact').FunctionComponent} Component * @param {() => [class_: Function, instance: any][]} getServices - * Callback that returns an array of `[ServiceClass, instance]` tuples, called * when the component is first rendered. */ export function withServices(Component, getServices) { /** @param {object} props */ const ComponentWrapper = props => { const services = useMemo(() => new Map(getServices()), []); return ( <Services.Provider value={services}> <Component {...props} /> </Services.Provider> ); }; return ComponentWrapper; }
//VARIABLES const apiKey = '5de7cfe50c166403acf5dd4f68334d90'; const searchInput = document.querySelector('#search'); const searchSubmit = document.querySelector('#submit'); const randomBtn = document.querySelector('#RandomMovie'); const resultHeading = document.querySelector('#result-heading'); const movieElm = document.querySelector('#movies'); const singleMovieElm = document.querySelector('#single-movie'); const modal = document.querySelector('#single-movie-modal'); const modalCloseBtn = document.querySelector('#ModalClose'); const navMenu = document.querySelector('.nav-icon'); //CLASSES const ui = new UI(); const movie = new Movie(); //EVENT LISTENERS window.addEventListener('DOMContentLoaded', getPage); searchSubmit.addEventListener('submit', searchMovie); movieElm.addEventListener('click', selectMovie); navMenu.addEventListener('click', triggerNavMenu); randomBtn.addEventListener('click', openRandomMovie); //FUNCTIONS function triggerNavMenu(){ if(document.getElementsByClassName('nav-list')[0].style.display === "" || document.getElementsByClassName('nav-list')[0].style.display === "none"){ document.getElementsByClassName('nav-list')[0].style.display = "flex" } else{ document.getElementsByClassName('nav-list')[0].style.display = "none" } } async function searchMovies(searchTerm){ const movieResponse = await fetch(`https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&query=${searchTerm}`); const movies = await movieResponse.json(); return movies } //search movie and fetch from API function searchMovie(e){ e.preventDefault(); //Clear single movie singleMovieElm.innerHTML = ''; //Get Search term const term = searchInput.value; //Check for emput input if(term.trim()){ searchMovies(term) .then(movies => { //Reduce size of area around search box ui.minimizeSearchArea(); //Check for movie results if(movies.total_results === 0){ //Show error in heading ui.updateResultHeading('error', term); } else{ //Update result heading ui.updateResultHeading('',term); //Create new movie for each response in movies movies.results.forEach(mov => { movie.getMoviePreview(mov); }); } }); //Clear UI ui.clearUI(); } else{ //TODO: Convert to an on page alert alert('Please enter a search term'); } } //Select Movie from Search function selectMovie(e){ //Check if user has clicked on a movie and pull the ID of the target let movieInfo; if(e.target.classList.contains('movie-info')){ movieInfo = e.target; } else if(e.target.parentElement.classList.contains('movie-info')){ movieInfo = e.target.parentElement; } else if(e.target.nextElementSibling && e.target.nextElementSibling.classList.contains('movie-info')){ movieInfo = e.target.nextElementSibling; } else{ movieInfo = false; } if(movieInfo){ const movieID = movieInfo.getAttribute('data-movieid'); movie.getMovieFull(movieID) .then(movie => { ui.openMovieModal(movie); }) } } function getPage(){ if(document.URL.includes("top-movies")){ getMovieLists('top_rated'); } else if(document.URL.includes("now-playing")){ getMovieLists('now_playing'); } else if(document.URL.includes("upcoming")){ getMovieLists('upcoming'); } } async function getMovieLists(listType){ const movieResponse = await fetch(`https://api.themoviedb.org/3/movie/${listType}?api_key=${apiKey}&language=en-US`); const movies = await movieResponse.json(); try{ //Add Event listener to movies movieElm.addEventListener('click', selectMovie); //Create new movie for each response in movies movies.results.forEach(mov => { movie.getMoviePreview(mov); }); } catch{ console.log('Could not find list'); } } async function openRandomMovie(){ //Get random ID between 1 and most recent movie ID in database const randomID = await movie.getRandomMovie(); try { const randomMovie = await movie.getMovieFull(randomID); ui.openMovieModal(randomMovie); } catch { //If movie of random ID cannot be found, retry the function openRandomMovie(); } } function comingSoon(){ alert('This feature is coming soon!'); }
/* eslint-disable flowtype/require-valid-file-annotation */ /* eslint-env detox/detox, jest */ import { Date } from 'core-js' import { launchAppWithPermissions } from '../utils.js' // FUNCTIONS // const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)) const genUsername = () => 'TU' + Date.now() const findByText = locator => element(by.text(locator)) // DATA const USERNAME = { tooShort: '12', invalidCharacters: "username'", taken: 'JS test 0', valid: genUsername() } const PASSWORD = { tooShort: 'yMvPLFupQ', lacksNumber: 'yMvPLFupQj', lacksUppercase: 'y768mv4plfupqjmu', lacksLowercase: 'Y768MV4PLFUPQjMU', mismatch: 'uMjQpuFLP4vM867y', valid: 'y768Mv4PLFupQjMu' } const loginscene = () => ({ createAccountButton: element(by.text('Create account')), getStartedButton: element(by.text('Get Started')), usernameInput: element(by.type('RCTUITextField')), nextButton: element(by.text('Next')), usernameTakenError: element(by.text('Username already exists')), passwordInput: element(by.type('RCTUITextField')).atIndex(0), confirmPasswordInput: element(by.type('RCTUITextField')).atIndex(1), passwordMismatchError: element(by.text('Does not match password')), pinInput: element(by.type('RCTUITextField')), confirmation1: element(by.type('RCTImageView')).atIndex(0), confirmation2: element(by.type('RCTImageView')).atIndex(1), confirmation3: element(by.type('RCTImageView')).atIndex(2), confirmation4: element(by.type('RCTImageView')).atIndex(3), confirmFinishButton: element(by.text('Confirm & Finish')), usernameTooShortError: element(by.text('Minimum 3 characters')), usernameInvalidCharactersError: element(by.text('Must only be ascii characters')), walletListScene: element(by.text('Slide wallets to show more options')) }) beforeEach(async () => { await launchAppWithPermissions() }) afterEach(async () => { // await navigateFromPinToLanding() }) describe('Edge GUI: ', () => { it('should be able to simply create an account', async () => { const loginScene = loginscene() // NAVIGATE TO CREATE ACCOUNT await waitFor(loginScene.createAccountButton).toBeVisible().withTimeout(5000) await expect(loginScene.createAccountButton).toExist() await loginScene.createAccountButton.tap() await expect(loginScene.getStartedButton).toBeVisible() // NAVIGATE TO CHOOSE USERNAME await loginScene.getStartedButton.tap() await expect(loginScene.usernameInput).toBeVisible() await expect(loginScene.nextButton).toBeVisible() // VALID USERNAME await loginScene.usernameInput.typeText(USERNAME.valid) await expect(loginScene.usernameTakenError).toBeNotVisible() // NAVIGATE TO CHOOSE PASSWORD await loginScene.nextButton.tap() await expect(loginScene.passwordInput).toBeVisible() await expect(loginScene.confirmPasswordInput).toBeVisible() await expect(loginScene.nextButton).toBeVisible() // VALID PASSWORD await loginScene.passwordInput.typeText(PASSWORD.valid) await loginScene.confirmPasswordInput.typeText(PASSWORD.valid) await expect(loginScene.passwordMismatchError).toNotExist() // NAVIGATE TO CHOOSE PIN await loginScene.nextButton.tap() await expect(loginScene.pinInput).toExist() await expect(loginScene.nextButton).toBeVisible() // VALID PIN await loginScene.pinInput.typeText('1234') // NAVIGATE TO ACCOUNT CONFIRMATION await loginScene.nextButton.tap() // WAIT FOR LOADING SCREEN await waitFor(findByText("Almost done! Let's write down your account information")).toBeVisible().withTimeout(5000) // NAVIGATE TO REVIEW await loginScene.nextButton.tap() // await waitFor(confirmation1).toBeVisible().withTimeout(5000) await expect(loginScene.confirmation1).toBeVisible() await expect(loginScene.confirmation2).toBeVisible() await expect(loginScene.confirmation3).toBeVisible() await expect(loginScene.confirmation4).toBeVisible() await expect(loginScene.confirmFinishButton).toBeNotVisible() // CONFIRM await loginScene.confirmation1.tap() await loginScene.confirmation2.tap() await loginScene.confirmation3.tap() await loginScene.confirmation4.tap() expect(loginScene.confirmFinishButton).toBeVisible() // NAVIGATE TO WALLET LIST await loginScene.confirmFinishButton.tap() // ASSERT DASHBOARD SHOWN await waitFor(findByText('Slide wallets to show more options')).toBeVisible().withTimeout(10000) await expect(findByText('Slide wallets to show more options')).toBeVisible() }) xit('should be able to fix invalid inputs & create account', async () => { const loginScene = loginscene() // NAVIGATE TO CREATE ACCOUNT await waitFor(loginScene.createAccountButton).toBeVisible().withTimeout(5000) await expect(loginScene.createAccountButton).toExist() await loginScene.createAccountButton.tap() await expect(loginScene.getStartedButton).toBeVisible() // NAVIGATE TO CHOOSE USERNAME await loginScene.getStartedButton.tap() await expect(loginScene.usernameInput).toBeVisible() await expect(loginScene.nextButton).toBeVisible() // TOO SHORT await loginScene.usernameInput.typeText(USERNAME.tooShort) await expect(loginScene.usernameTooShortError).toBeVisible() await loginScene.usernameInput.clearText() // INVALID CHARACTERS await loginScene.usernameInput.typeText(USERNAME.invalidCharacters) await expect(loginScene.usernameInvalidCharactersError).toBeVisible() await loginScene.usernameInput.clearText() // USERNAME TAKEN await loginScene.usernameInput.typeText(USERNAME.taken) await loginScene.nextButton.tap() await expect(loginScene.usernameTakenError).toBeVisible() await loginScene.usernameInput.clearText() // VALID USERNAME await loginScene.usernameInput.typeText(USERNAME.valid) await expect(loginScene.usernameTakenError).toBeNotVisible() // NAVIGATE TO CHOOSE PASSWORD await loginScene.nextButton.tap() await expect(loginScene.passwordInput).toBeVisible() await expect(loginScene.confirmPasswordInput).toBeVisible() await expect(loginScene.nextButton).toBeVisible() // PASSWORD MISMATCH(confirm password is fixed before password is fixed) await loginScene.confirmPasswordInput.typeText(PASSWORD.mismatch) await loginScene.passwordInput.typeText(PASSWORD.valid) await expect(loginScene.passwordMismatchError).toExist() await loginScene.passwordInput.clearText() await loginScene.confirmPasswordInput.clearText() // VALID PASSWORD await loginScene.passwordInput.typeText(PASSWORD.valid) await loginScene.confirmPasswordInput.typeText(PASSWORD.valid) await expect(loginScene.passwordMismatchError).toNotExist() // NAVIGATE TO CHOOSE PIN await loginScene.nextButton.tap() await expect(loginScene.pinInput).toExist() await expect(loginScene.nextButton).toBeVisible() // VALID PIN await loginScene.pinInput.typeText('1234') // NAVIGATE TO ACCOUNT CONFIRMATION await loginScene.nextButton.tap() // WAIT FOR LOADING SCREEN await waitFor(findByText("Almost done! Let's write down your account information")).toBeVisible().withTimeout(5000) // NAVIGATE TO REVIEW await loginScene.nextButton.tap() // await waitFor(confirmation1).toBeVisible().withTimeout(5000) await expect(loginScene.confirmation1).toBeVisible() await expect(loginScene.confirmation2).toBeVisible() await expect(loginScene.confirmation3).toBeVisible() await expect(loginScene.confirmation4).toBeVisible() await expect(loginScene.confirmFinishButton).toBeNotVisible() // CONFIRM await loginScene.confirmation1.tap() await loginScene.confirmation2.tap() await loginScene.confirmation3.tap() await loginScene.confirmation4.tap() expect(loginScene.confirmFinishButton).toBeVisible() // NAVIGATE TO WALLET LIST await loginScene.confirmFinishButton.tap() // ASSERT DASHBOARD SHOWN await waitFor(findByText('Slide wallets to show more options')).toBeVisible().withTimeout(10000) await expect(findByText('Slide wallets to show more options')).toBeVisible() }) })
//http://www.mapdevelopers.com/geocode_tool.php console.log(dbPokemons); var pokemons = JSON.parse(dbPokemons); console.log(pokemons); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 19, center: new google.maps.LatLng(-30.865341,-51.800741), mapTypeId: 'satellite' }); var iconBase = '../public/imgs/'; //inicializa objeto de janela de info dos marcadores var infowindow = new google.maps.InfoWindow(); //criar os marcadores for(i = 0; i < pokemons.length; i++){ var marker = new google.maps.Marker({ position: new google.maps.LatLng(pokemons[i].lati,pokemons[i].long), icon : iconBase + pokemons[i].img, map: map }); var conteudo = pokemons[i].info; //adiciona evento de clique aos marcadores google.maps.event.addListener(marker,'click', (function(marker,conteudo,infowindow){ return function() { infowindow.setContent(conteudo);//setando a string html para a janela do marcador infowindow.open(map,marker); }; })(marker,conteudo,infowindow)); } }
'use strict'; module.exports = [ './node_modules/normalize.css/normalize.css', './node_modules/slick-carousel/slick/slick.css', './node_modules/magnific-popup/dist/magnific-popup.css', './node_modules/lightgallery/dist/css/lightgallery.min.css', './node_modules/lightslider/dist/css/lightslider.min.css' ];
import React, { useState } from "react"; import { withRouter } from "react-router-dom"; //------------------------------------------------- Images --------------------------------------------------- import Quizs from "../ButtonBasesImages/Quizs.jpg"; import Assignments from "../ButtonBasesImages/Assignments.jpg"; import Excel from "../ButtonBasesImages/ExcelSheet.jpg"; import AssignmentDoctor from "../ButtonBasesImages/AssignmentDoctor.png"; import Grades from "../ButtonBasesImages/Grades.png"; import materials from "../ButtonBasesImages/Materials.jpg"; //---------------------------------------------------------------------------------------------------- //--------------------------------- What was used from material ui core ------------------------------------- import { Typography, ButtonBase, withStyles } from "@material-ui/core"; //----------------------------------------------------------------------------------------------------------- const CoursesNavigationButtons = ({ history, match, classes }) => { // ---------------------------- variables with it's states that we use it in this Page ------------------- const [accountType, setaccountType] = useState( JSON.parse(localStorage.getItem("Information")).AccountType ); //---------------------------------------------------------------------------------------------------- const images = [ { url: materials, title: "Open Materials", onClick: () => accountType == 2 ? history.push(`/courses/${match.params.courseId}/${match.params.coursename}/materials`) : history.push(`/courses/${match.params.courseId}/${match.params.coursename}/StudentMaterials`), }, { url: Quizs, title: accountType !== 2 ? "Online Quiz" : "Create Quiz", onClick: () => accountType == 2 ? history.push(`/quiz/${match.params.courseId}/${match.params.coursename}`) : history.push(`/quizstudent/${match.params.courseId}/${match.params.coursename}`), }, { url: accountType == 2 ? AssignmentDoctor : Assignments, title: accountType !== 2 ? "Upload assignment answers" : "Student Assignment Answers", onClick: () => accountType == 2 ? history.push(`/assignmentInstructor/${match.params.courseId}/${match.params.coursename}`) : history.push(`/assignmentstudent/${match.params.courseId}/${match.params.coursename}`), }, { url: accountType == 2 ? Excel : Grades, title: accountType == 2 ? "Student Grades" : "Grades", onClick: () => history.push(`/grades/${match.params.courseId}/${match.params.coursename}`) }, ]; return ( <React.Fragment> <div className={classes.root}> {images.map(({ title, url, onClick }) => ( <ButtonBase focusRipple key={title} className={classes.image} focusVisibleClassName={classes.focusVisible} onClick={onClick} style={{ width: "24%", height: "190px", marginLeft:"10px", }} > <span className={classes.imageSrc} style={{ backgroundImage: `url(${url})`, }} /> {/* <span className={classes.imageBackdrop} /> <span className={classes.imageButton}> <Typography component="span" variant="subtitle1" color="inherit" className={classes.imageTitle} style={{ fontSize: "20px", fontWeight: "bold" }} > {title} <span className={classes.imageMarked} /> </Typography> </span> */} </ButtonBase> ))} </div> <div className={classes.root}> {images.map(({ title, url, onClick }) => ( <ButtonBase focusRipple key={title} className={classes.image} focusVisibleClassName={classes.focusVisible} onClick={onClick} style={{ width: "24%", height: "120px", marginLeft:"10px", }} > <Typography component="span" variant="subtitle1" color="inherit" className={classes.imageTitle} style={{ fontSize: "25px", fontWeight: "bold" }} > {title} <span className={classes.imageMarked} /> </Typography> </ButtonBase> ))} </div> </React.Fragment> ); }; const styles = (theme) => ({ root: { display: "flex", flexWrap: "wrap", minWidth: 300, width: "100%", }, image: { position: "relative", height: 200, [theme.breakpoints.down("xs")]: { width: "100% !important", height: 100, }, "&:hover, &$focusVisible": { zIndex: 0, "& $imageBackdrop": { opacity: 0.15, }, "& $imageMarked": { opacity: 0, }, "& $imageTitle": { border: "4px solid black", color: "black", fontWeight: "bold", }, }, }, focusVisible: {}, imageButton: { position: "absolute", bottom: 20, display: "flex", color: theme.palette.common.white, fontWeight:"bold" }, imageSrc: { position: "absolute", left: 0, right: 0, top: 0, bottom: 0, backgroundSize: "cover", backgroundPosition: "center 40%", }, imageBackdrop: { position: "absolute", left: 0, right: 0, top: 0, bottom: 0, backgroundColor: theme.palette.common.black, opacity: 0.6, transition: theme.transitions.create("opacity"), }, imageTitle: { position: "relative", padding: "5px", }, imageMarked: { height: 3, width: 18, backgroundColor: theme.palette.common.white, position: "absolute", bottom: -2, left: "calc(50% - 9px)", transition: theme.transitions.create("opacity"), }, }); export default withStyles(styles)(withRouter(CoursesNavigationButtons));
'use strict' const Startup = use('App/Models/Startup') class HomeController { async render({ view }) { try { const allStartups = await Startup .query() .has('votes') .withCount('votes') .fetch() const startups = allStartups.toJSON() const sorted = startups.sort((a, b) => b['__meta__']['votes_count'] - a['__meta__']['votes_count']); return view.render('pages.home', { leaders: sorted.splice(0, 10) }) } catch (error) { console.log(error) } } } module.exports = HomeController
/** * The MIT License (MIT) * Copyright (c) 2016, Jeff Jenkins. */ const React = require('react'); import { Link } from 'react-router'; const SearchItem = React.createClass({ propTypes: { item: React.PropTypes.object.isRequired, onSelect: React.PropTypes.func.isRequired }, /** * @return {object} */ render: function() { const item = this.props.item; const overflow = {overflow: 'hidden', textOverflow: 'ellipsis', 'lineHeight':'3rem'}; var parser = document.createElement('a');// Stripping the protocol from the link for proper link structure parser.href = item.canonicalLink; const host = parser.host return <div className="article" > <h3 style={overflow} > <a onClick={this._onClick} to={"/"+item._id} href="javascript:void(0);" > {item.title} </a> </h3> <img className="favicon" src={item.favicon}/> &nbsp; <a href={item.canonicalLink} >{host}</a> <p style={overflow}>{item.description}</p> </div>; }, _onClick: function() { this.props.onSelect(this.props.item._id); } }); module.exports = SearchItem;
import '../../../../scripts/common/app' import Payment from '../../../../models/ecommerse/payment' import formItems from './form/form-items' import Order from '../../../../models/ecommerse/order' import View from '../../../../views/domain/create.vue' import Constant from '../../../../configs/constant' const create = async data => { // data.value = data.value.map(it => { return { name: it.name } }) // data.value = JSON.stringify(data.value) // return Spec.create(data) const orderPage = await Order.page(1, 1, [{ filterType: 'EQ', property: 'sn', value: data.sn }]) if (_.isEmpty(orderPage.content)) { this.$Message.error('未找到该订单编号') return } const order = orderPage.content[0] if (order.payStatus === Constant.PayStatus.Payed) { this.$Message.error('该订单已经支付!请勿重复付款!') return } data.orderId = order.id const result = await Payment.createQrcode(data) App.modal({ width: 400, title: '支付二维码', closable: false, render: h => { // h = this.$root.$createElement const style = { width: '100%' } const cardStyle = { width: '300px', height: '360px', display: 'table-cell', 'vertical-align': 'middle', 'text-align': 'center' } return <card style = {cardStyle}><img style = {style} src ={result}/></card> }, onOk: async(OrderTransform) => { await OrderTransform.submit() App.removeModal() } }) } new Vue({ el: '#app', render: h => { const v = h(View, { props: { domain: Payment, formItems, formProps: { labelWidth: 120 }, create }}) return App.target === 'dialog' ? v : <card>{v}</card> } })
'use strict'; (function() { class MainController { constructor($http, $scope, socket, chatService, $state, $rootScope, Auth) { var self = this; this.$http = $http; this.$state = $state; this.chatService = chatService; this.Auth = Auth; // Display Variables this.posts = this.posts || []; this.selectedPost = undefined; // Forum Variables this.forum = this.forum || {}; this.forum.commentInput = ''; // Map Settings this.map = this.map || {}; this.map.control = {}; this.map.status = { center: { latitude: 22, longitude: 0 }, zoom: 2, bounds: {} }; this.map.settings = { disableDefaultUI: true, styles: mapStyles, draggable: true, backgroundColor: '#fff', minZoom: 2, maxZoom: 9, streetViewControl: false, }; // Map Events var lastValidCenter = new google.maps.LatLng(this.map.status.center.latitude, this.map.status.center.longitude); this.map.events = { center_changed: function(theMap) { // Ensure that the user cannot pan out of bounds if (theMap.getBounds().getNorthEast().lat() < 85 && theMap.getBounds().getSouthWest().lat() > -85) { lastValidCenter = theMap.getCenter(); } else { theMap.panTo(new google.maps.LatLng(lastValidCenter.lat(), theMap.getCenter().lng())); } }, zoom_changed: function(theMap) { // Ensure that the user cannot zoom out and have out of bounds showing if (theMap.getBounds().getNorthEast().lat() > 85) { theMap.panTo(new google.maps.LatLng(theMap.getCenter().lat() - ( theMap.getBounds().getNorthEast().lat() - 85 ) * 10, theMap.getCenter().lng())); } else if (theMap.getBounds().getSouthWest().lat() < -85) { theMap.panTo(new google.maps.LatLng(theMap.getCenter().lat() - ( theMap.getBounds().getSouthWest().lat() + 85 ) * 10, theMap.getCenter().lng())); } else return; }, dragstart: function(theMap) { self.selectedPost = undefined; } }; // Map icon generator var iconGen = function(scale, path) { return { path: path, scale: scale, strokeWeight: 0, fillColor: 'rgb(255,255,255)', fillOpacity: 1, } }; this.map.icons = { politics: iconGen(0.2, fontawesome.markers.UNIVERSITY), culture: iconGen(0.2, fontawesome.markers.USERS), travel: iconGen(0.2, fontawesome.markers.PLANE), news: iconGen(0.2, fontawesome.markers.NEWSPAPER_O), user: iconGen(0.2, fontawesome.markers.MALE) }; // Marker Click this.map.markerEvents = { click: function(marker, event, postObj) { self.selectedPost = postObj; } } this.symbols = { politics: 'fa fa-university', culture: 'fa fa-users', travel: 'fa fa-plane', news: 'fa fa-newspaper-o', user: 'fa fa-male' }; var postGen = function(postObj) { postObj.icon = self.map.icons[postObj.category]; // Append icon postObj.symbolClass = self.symbols[postObj.category]; } $http.get('/api/posts').then(response => { this.posts = response.data; for (var i = self.posts.length - 1; i >= 0; i--) { postGen(self.posts[i]); }; }); $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ switch(toState.name) { case 'main.chat': self.selectedPost = undefined; if (!chatService.isChatServiceReady()) { self.chatService.init(self.map); } else { chatService.setChatVisible(true); } break; case 'main.forum': chatService.setChatVisible(false); break; } }); } submitComment() { if (this.forum.commentInput !== '' && this.selectedPost !== undefined) { this.$http.post('/api/posts/' + this.selectedPost._id + '/comment', {content: this.commentInput, author: Auth.getCurrentUser()._id}); this.commentInput = ''; } } // deleteThing(thing) { // this.$http.delete('/api/things/' + thing._id); // } } angular.module('oneWorldApp') .controller('MainController', MainController); })();
export const studentsList = (state = null, action) => { if (action.type === 'STUDENTs-LIST') { return action.payload } return state }
tour_bus_33_interval_name = ["高鐵嘉義站","故宮南院","高鐵嘉義站","南靖火車站","後壁火車站","白河轉運站","白河水庫","寶泉橋","關子嶺"]; tour_bus_33_interval_stop = [ ["高鐵嘉義站"], ["故宮南院"], ["高鐵嘉義站"], ["南靖火車站"], ["後壁火車站"], ["白河轉運站"], ["白河水庫"], ["寶泉橋"], ["關子嶺"] ]; tour_bus_33_fare = [ [26], [26,26], [33,26,26], [70,55,37,26], [90,74,57,26,26], [109,94,76,39,26,26], [128,113,95,58,39,26,26], [145,129,112,74,55,35,26,26], [148,132,115,77,58,38,26,26,26] ]; // format = [time at the start stop] or // [time, other] or // [time, start_stop, end_stop, other] tour_bus_33_main_stop_name = ["高鐵<br />嘉義站","故宮南院<br /><span style='color:red;'>(周一不停)</span>","高鐵<br />嘉義站","南靖<br />火車站","後壁<br />火車站","白河<br />轉運站","白河<br />水庫","寶泉橋","關子嶺"]; tour_bus_33_main_stop_time_consume = [0, 9, 18, 30, 36, 45, 55, 63, 66]; tour_bus_33_important_stop = [0, 5, 8]; // 高鐵嘉義站, 白河轉運站, 關子嶺 tour_bus_33_time_go = [["10:00"],["12:00"],["14:00"]]; tour_bus_33_time_return = [["11:30"],["13:30"],["15:30"]];
(() => { angular.module('kemia-app') .directive('chemHeader', chemHeader) chemHeader.$inject = [] function chemHeader() { return { restrict: 'E', templateUrl: 'frontend/src/chem-header/chem-header.html', controller: 'loginController', controllerAs: 'lc' } } })()
import React, { Component } from 'react'; import { easePolyOut } from 'd3-ease'; import Animate from 'react-move/Animate'; export default class Stripes extends Component { state = { stripes:[ { background: '#F58426', //background: '#98c5e9', left: 370, rotate:2, top: -230, delay: 100 }, { background: '#BEC0C2', //background: '#ffffff', left: 240, rotate: 2, top:-197, delay: 300 }, { background: '#006BB6', //background: '#98c5e9', left:98, rotate:2, top:-98, delay: 500 } ] } showStripes = () => { //Using parenthesis instead of brackets to return just the element return( this.state.stripes.map((stripe,i)=>( <Animate key = {i} show = {true} start = {{ background: 'ffffff', opacity:0, left: 0, rotate:0, top:0 }} enter = {{ background: [stripe.background], opacity:[1], left: [stripe.left], rotate:[stripe.rotate], top:[stripe.top], timing: {delay:stripe.delay, duration:400, ease:easePolyOut}, events:{ end(){ console.log("finished animating"); } } }} > {({ opacity,left,rotate,top,background})=>{ return( <div className = "stripe" style = {{ background, opacity, transform: `rotate(${rotate}0deg) translate(${left}px, ${top}px)`, left, top }} > </div> ); }} </Animate> )) ) } render() { return ( <div className = "featured_stripes"> {this.showStripes()} </div> ) } }
var _viewer = this; _viewer.tabHide("TS_KCGL_UPDATE"); //设置卡片只读 if(_viewer.opts.readOnly){ _viewer.readCard(); } _viewer.getBtn("stop").click(function() { if(_viewer.getItem("KC_STATE").getValue() != 6){ _viewer.getItem("KC_STATE").setValue(6); _viewer._saveForm(); } });
import Basket from "../../utils/basket"; describe("basket", () => { it("adds product to basket", () => { const b = new Basket(); expect(b.products()).toHaveLength(0); b.add({ name: "Produkt 1" }); expect(b.products()).toHaveLength(1); }); it("removes products from basket", () => { const b = new Basket(); expect(b.products()).toHaveLength(0); b.add({ name: "Produkt 1" }); expect(b.products()).toHaveLength(1); expect(b.hasProduct({ name: "Produkt 1" })).toBeTruthy(); b.remove({ name: "Produkt 1" }); expect(b.products()).toHaveLength(0); }); });
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const home =()=>import('../components/home'); const about=()=>import('../components/about'); const test=()=>import('../components/test'); const routes =[ { path: '/', redirect:'/home' }, { path: '/home', meta:{ title:"主页" }, component: home }, { path: '/about', meta:{ title:"关于" }, children:[ {path:'test',component:test,meta:{title:"测试"}} ], component: about } ] const router =new Router({ routes, mode: 'history' }) router.beforeEach((to,from,next)=>{ console.log(to); document.title=to.meta.title; next(); }) export default router;
var assert = require('assert'); var util = require('../util.js'); var DummyVersionGraph = require('../dummyVersionGraph.js'); var AppBase = require('../appBase.js'); var EvalEnv = require('../evalEnv.js'); var HashDB = require('../hashDB.js'); var DummyKVS = require('../keyvalue.js'); describe('AppBase', function(){ var graphDB = new DummyVersionGraph(); var evaluators = { comp: require('../composite.js'), inv: require('../inv.js'), atom: require('../atom.js'), dir: require('../dir.js'), counter: require('../counter.js'), jsMapper: require('../jsMapper.js'), }; var evalEnv = new EvalEnv(new HashDB(new DummyKVS()), new DummyKVS(), evaluators); var appBase = new AppBase(evalEnv, graphDB); beforeEach(function(done) { util.seq([ function(_) { graphDB.clear(_); }, ], done)(); }); var compPatch = {_type: 'comp', patches: [ {_type: 'create', _path: ['a'], evalType: 'atom', args: {val: 'foo'}}, {_type: 'create', _path: ['b'], evalType: 'atom', args: {val: 'bar'}}, {_type: 'create', _path: ['c'], evalType: 'atom', args: {val: 'baz'}}, {_type: 'set', _path: ['a'], from: 'foo', to: 'bat'}, ]}; describe('.trans(branch, patch, options, cb(err))', function(){ it('should apply the given patch on the tip of the given branch', function(done){ var compPatch = {_type: 'comp', patches: [ {_type: 'create', _path: ['a'], evalType: 'atom', args: {val: 'foo'}}, {_type: 'create', _path: ['b'], evalType: 'atom', args: {val: 'bar'}}, {_type: 'create', _path: ['c'], evalType: 'atom', args: {val: 'baz'}}, {_type: 'set', _path: ['a'], from: 'foo', to: 'bat'}, ]}; util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state')); }, function(_) { appBase.trans(this.state, compPatch, {}, _.to('state')); }, function(_) { evalEnv.query(this.state, {_type: 'get', _path: ['a']}, _.to('res')); }, function(_) { assert.equal(this.res, 'bat'); _(); }, ], done)(); }); it('should report conflicts', function(done){ util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state')); }, function(_) { appBase.trans(this.state, compPatch, {}, _.to('state')); }, function(_) { appBase.trans(this.state, {_type: 'set', _path: ['a'], from: 'foo', to: 'bar'}, {}, _.to('state', 'conf')); }, function(_) { assert(this.conf, 'Should conflict'); _(); }, function(_) { evalEnv.query(this.state, {_type: 'get', _path: ['a']}, _.to('res')); }, function(_) { assert.equal(this.res, 'bar'); _(); }, // The conflicting value ], done)(); }); it('should force the change if the strong option is used', function(done){ util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state')); }, function(_) { appBase.trans(this.state, compPatch, {}, _.to('state')); }, function(_) { appBase.trans(this.state, {_type: 'set', _path: ['a'], from: 'foo', to: 'bar'}, {strong: true}, _.to('state')); }, function(_) { evalEnv.query(this.state, {_type: 'get', _path: ['a']}, _.to('res')); }, function(_) { assert.equal(this.res, 'bar'); _(); }, ], done)(); }); it('should apply effect patches as part of the transition', function(done){ var mapper = fun2str({ map_set: function(patch) { emit({_type: 'create', _path: [patch.to], evalType: 'atom', args: {val: patch._at_path[0]}}); }, }); util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state')); }, function(_) { appBase.trans(this.state, compPatch, {}, _.to('state')); }, function(_) { evalEnv.init('jsMapper', mapper, _.to('mapper')); }, function(_) { appBase.trans(this.state, {_type: 'add_mapping', _path: ['a'], mapper: this.mapper}, {}, _.to('state')); }, function(_) { appBase.trans(this.state, {_type: 'set', _path: ['a'], from: 'bat', to: 'bar'}, {}, _.to('state')); }, function(_) { evalEnv.query(this.state, {_type: 'get', _path: ['bar']}, _.to('a')); }, function(_) { assert.equal(this.a, 'a'); _(); }, ], done)(); }); }); describe('.merge(dest, source, options, cb(err))', function(){ it('should apply the patches contributing to source to the tip of branch', function(done){ util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state1')); }, function(_) { appBase.trans(this.state1, compPatch, {}, _.to('state1')); }, function(_) { this.state2 = this.state1; _(); }, function(_) { appBase.trans(this.state1, {_type: 'set', _path: ['b'], from: 'bar', to: 'bar2'}, {}, _.to('state1')); }, function(_) { appBase.trans(this.state2, {_type: 'set', _path: ['c'], from: 'baz', to: 'baz2'}, {}, _.to('state2')); }, function(_) { appBase.merge(this.state1, this.state2, {}, _.to('state1')); }, function(_) { evalEnv.query(this.state1, {_type: 'get', _path: ['c']}, _.to('c')); }, function(_) { assert.equal(this.c, 'baz2'); _(); }, function(_) { evalEnv.query(this.state1, {_type: 'get', _path: ['b']}, _.to('b')); }, function(_) { assert.equal(this.b, 'bar2'); _(); }, ], done)(); }); it('should report conflicts if they occur', function(done){ util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state1')); }, function(_) { appBase.trans(this.state1, compPatch, {}, _.to('state1')); }, function(_) { this.state2 = this.state1; _(); }, function(_) { appBase.trans(this.state1, {_type: 'set', _path: ['b'], from: 'bar', to: 'bar2'}, {}, _.to('state1')); }, function(_) { appBase.trans(this.state2, {_type: 'set', _path: ['b'], from: 'bar', to: 'bar3'}, {}, _.to('state2')); }, function(_) { appBase.merge(this.state1, this.state2, {}, _.to('state1', 'conf')); }, function(_) { assert(this.conf, 'A conflict must be reported'); _(); }, function(_) { evalEnv.query(this.state1, {_type: 'get', _path: ['b']}, _.to('b')); }, function(_) { assert.equal(this.b, 'bar3'); _(); }, // Should take the merged value ], done)(); }); it('should accept a "weak" option, by which it would apply only non-conflicting changes', function(done){ util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state1')); }, function(_) { appBase.trans(this.state1, compPatch, {}, _.to('state1')); }, function(_) { this.state2 = this.state1; _(); }, function(_) { appBase.trans(this.state1, {_type: 'set', _path: ['b'], from: 'bar', to: 'bar2'}, {}, _.to('state1')); }, // Conflicting change function(_) { appBase.trans(this.state2, {_type: 'set', _path: ['b'], from: 'bar', to: 'bar3'}, {}, _.to('state2')); }, // Unconflicting change function(_) { appBase.trans(this.state2, {_type: 'set', _path: ['c'], from: 'baz', to: 'baz3'}, {}, _.to('state2')); }, function(_) { appBase.merge(this.state1, this.state2, {weak: true}, _.to('state1', 'conf')); }, function(_) { assert(!this.conf, 'A conflict should not be reported'); _(); }, function(_) { evalEnv.query(this.state1, {_type: 'get', _path: ['c']}, _.to('c')); }, function(_) { assert.equal(this.c, 'baz3'); _(); }, function(_) { evalEnv.query(this.state1, {_type: 'get', _path: ['b']}, _.to('b')); }, function(_) { assert.equal(this.b, 'bar2'); _(); }, // The value on the destination branch ], done)(); }); it('should apply a back-merge correctly', function(done){ util.seq([ function(_) { evalEnv.init('dir', {}, _.to('state1')); }, function(_) { appBase.trans(this.state1, compPatch, {}, _.to('state1')); }, function(_) { this.state2 = this.state1; _(); }, function(_) { appBase.trans(this.state1, {_type: 'set', _path: ['b'], from: 'bar', to: 'bar2'}, {}, _.to('state1')); }, function(_) { appBase.trans(this.state2, {_type: 'set', _path: ['c'], from: 'baz', to: 'baz2'}, {}, _.to('state2')); }, function(_) { appBase.merge(this.state1, this.state2, {}, _.to('state1')); }, function(_) { appBase.merge(this.state2, this.state1, {}, _.to('state2')); }, // merge back // Check that br1 got the data from br2 function(_) { evalEnv.query(this.state1, {_type: 'get', _path: ['c']}, _.to('c')); }, function(_) { assert.equal(this.c, 'baz2'); _(); }, // Check that br2 got the data from br1 function(_) { evalEnv.query(this.state2, {_type: 'get', _path: ['b']}, _.to('b')); }, function(_) { assert.equal(this.b, 'bar2'); _(); }, ], done)(); }); }); function fun2str(obj) { var ret = {}; for(var key in obj) { if(typeof obj[key] == 'function') { ret[key] = obj[key].toString(); } else { ret[key] = obj[key]; } } return ret; } });
const { save } = require("../../modules/exports"); module.exports.run = async (bot, message, args) => { const memory = require("../../memory/"+message.guild.id+".json"); if (memory.tables[args[0]] == undefined) { return message.reply("Either the table you have referenced doesn't exist, or you have misspelled its name!") }; if (isNaN(args[1]) || parseInt(args[0]) <= 0) { return message.reply("You did not provide a valid entry number!"); }; let tableid = args[0]; let entrynumber = args[1] - 1; let table = memory.tables[tableid]; let entry = table.entries[entrynumber]; let content = entry.content; if (!message.member.hasPermission("MANAGE_MESSAGES") && message.author.username !== table.creator && message.author.username !== entry.creator && message.author.id !== "272554505944432650") { return message.reply("You do not have the necessary permissions. Only a server mod, the creator of the table, or the creator of the entry can perform this command."); }; args.splice(0, 2); let newcontent = args.join(" "); let stringsplit = newcontent.split("^"); for (let i = 0; i < stringsplit.length; i++) { if (i%2 !== 0) { if (memory.tables[stringsplit[i]] == undefined) { return message.reply("The table '"+stringsplit[i]+"' you are referencing between ^^'s doesn't exist, or you have misspelled its name."); }; }; }; table.entries[entrynumber].content = newcontent; save("./memory/"+message.guild.id+".json", memory); message.reply("Entry replaced from table: "+table.id+" Entry: "+content+" by "+entry.creator+". New Content: "+newcontent); } module.exports.config = { name: "replace", description: "Replace a specific entry from a table with new text. syntax: .replace [tableid] [entry number] [new text]", usage: ".replace", accessableby: "Members", aliases: ['re'] }
const Person = require('./Person') const UnyPerson = require('./Uniperson') const Guardian =require('./Guardian') const Student =require('./Student') const Employee = require('./Employee') const Teacher = require('./Teacher') const Stuff = require('./Stuff') module.exports={ Person, UnyPerson, Guardian, Student, Employee, Teacher, Stuff }
var mongoose = require("mongoose"); var importGoodSchema = mongoose.Schema({ manufactureId: {type: String, required: '{PATH} is required!'}, userId: {type: String, required: '{PATH} is required!'}, dayImport: {type: String, required: '{PATH} is required!'}, numberBill: {type: String, required: '{PATH} is required!'}, totalCost: {type: Number, required: '{PATH} is required!'}, note: {type: String}, dateCreate: {type: Date}, dateModify: {type: Date} }); var ImportGood = mongoose.model("ImportGood", importGoodSchema);
const axios = require('axios'); const axiosInstance = axios.create({ }); class BackendMockClient{ constructor(){ this.baseUrl = 'http://localhost:8080/client/' ; } async updateAuthSessionWithRoles(auth, roles){ return await axiosInstance.post(`${this.baseUrl}session/user/roles`,{ auth: auth, roles: roles }) } async updateAuthSessionWithRoleAssignments(auth, roleAssignments) { return await axiosInstance.post(`${this.baseUrl}session/user/roleAssignments`, { auth: auth, roleAssignments: roleAssignments }) } async setUserApiData(auth, apiMethod, response) { return await axiosInstance.post(`${this.baseUrl}session/userApiData`, { auth: auth, apiMethod: apiMethod, apiResponse: response }) } async getSessionRolesAndRoleAssignments(auth){ return await axiosInstance.post(`${this.baseUrl}session/getUserRolesAndRoleAssignments`, { auth: auth }) } } module.exports = new BackendMockClient();
import { graphql } from 'react-apollo' import gql from 'graphql-tag' import imageFragment from '../fragments/image' const editImage = gql` mutation editImage($id: ID!, $title: String, $description: String) { editImage(id: $id, title: $title, description: $description) { ...ImageFragment } } ${imageFragment} ` const mutationConfig = { props: ({ mutate, ownProps: { categoryId } }) => ({ editImage: image => { console.log('edit Image called') mutate({ variables: { ...image } }) } }) } export default graphql(editImage, mutationConfig)
// Lo creo sin $ para evitar sobreescribir los preparados por angular eventsApp.factory('eventData', function($resource) { var resource = $resource('/data/event/:id', {id:'@id'}, {"getAll": {method: "GET", isArray: true, params: {something: "foo"}}}); return { getEvent: function() { // return $http({method: 'GET',url: 'data/event/5'}) //Call to the resource method instead. Assumes RESTful service //URL de formato, obejto que especifica valores y id es cambiado por id que se pide. return resource.get({id:5}); }, save: function(event){ event.id = 333; //Falta que los eventos cambien con respecto al ultimo id return resource.save(event); }, getAllEvents: function() { return resource.query(); } //tambien hay funciones de query, remove y delete }; });
import React, { Component } from 'react'; import axios from 'axios'; class EduOrgAppCreate extends Component { getStyleEduOrg1 = () => { return { Color : '#f4f4f4', //backgroundColor : '#003366' } } ss = () =>{ return{ //textAlign:'left', // backgroundColor: "808080", float:'center', background: '#d3d3d3' } } btnStyle= () => { return{ background:'#333', padding: '5px', margin: '10px', align: 'center', float: 'center', textAlign: 'center', borderRadius: '10px', color:'#fff', width: '130px', height: '50px' } } state={ userName: '', name: '', password: '', email: '', // masterClasses:'', // courses: '', // workshops: '', // trainers: '', // educators: '', // trainingPrograms: '', // description: '', // contract: '', // expirationDate: '' } addEduOrg=(userName,name,password,email) =>{//,masterClasses,courses,workshops,trainers,educators,trainingPrograms,description,contract,expirationDate)=>{ axios.post("http://localhost:5000/api/educationalOrganizations/",{ userName:userName, name:name, password:password, email:email, // masterClasses:masterClasses, // courses:courses, // workshops:workshops, // trainers:trainers, // educators:educators, // trainingPrograms:trainingPrograms, // description:description, // contract:contract, // expirationDate:expirationDate } ).then(res => this.setState({EduOrgAppCreate:[...this.state.EduOrgAppCreate,res.data]})) .catch(e=>"error") alert('Educatioinal Organization created successfully!!') } onSubmit=(e)=>{ e.preventDefault(); if(!this.state.userName||(this.state.userName.length<3)||!this.state.name||!this.state.password||(this.state.password.length<8)||!this.state.email) alert('validations not satisfied,try again!') else this.addEduOrg(this.state.userName,this.state.name,this.state.password,this.state.email); //,this.state.masterClasses,this.state.courses,this.state.workshops,this.state.trainers, //this.state.educators,this.state.trainingPrograms,this.state.description, //this.state.contract,this.state.expirationDate); } onChange=(e)=>this.setState({[e.target.name]:e.target.value}); render() { return ( <div > <h1 style = {this.ss()}>Educatioinal Organization Application </h1> <form style = {this.ss()}onSubmit={this.onSubmit}> <h4 style = {this.getStyleEduOrg1()}> User Name: <input name="userName" type="text" value={this.state.userName} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Name: {' '} <input name="name" type="text" value={this.state.name} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Password: <input name="password" type="text" value={this.state.password} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Email: <input name="email" type="email" value={this.state.email} onChange={this.onChange} /> </h4> <br /> <br /> {/* <h4 style = {this.getStyleEduOrg1()}> Master Classes: <input name="masterClasses" type="array" value={this.state.masterClasses} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Courses: <input name="courses" type="array" value={this.state.courses} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Workshops: <input name="workshops" type="array" value={this.state.workshops} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Trainers: <input name="trainers" type="array" value={this.state.trainers} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Educators: <input name="educators" type="array" value={this.state.educators} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Training Programs: <input name="trainingPrograms" type="array" value={this.state.trainingPrograms} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Description: <input name="description" type="text" value={this.state.description} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Contract: <input name="contract" type="boolean" value={this.state.contract} onChange={this.onChange} /> </h4> <br /> <br /> <h4 style = {this.getStyleEduOrg1()}> Expiration Date: <input name="expirationDate" type="date" value={this.state.expirationDate} onChange={this.onChange} /> </h4> <br /> <br /> */} {/* <button onClick={this.addjob.bind(this)} style={btnStyle}> Submit</button> */} <input style = {this.btnStyle()} type="submit" value="Submit" //className="btn" // style={{flex: '1'}} /> </form> </div> ); } } export default EduOrgAppCreate;
var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); var najax = require('najax'); var url_ajax = "datos.php"; app.listen(80); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.on('connection', function (socket) { socket.on('cliente_opcion', function (data) { console.log(data); if(data["value_client"] == "lista_clientes" ) { najax({ url:'http://localhost:8080/cordova/datos.php', type:'POST', data: ({ opcion : "buscar", coordenadas : ""}), success: function(html){ console.log(html); socket.emit('servidor_respuesta', { value_server: html }); } }); } if(data["value_client"] == "preferencia_cliente" ) { socket.emit('servidor_respuesta', { value_server: 'funciono2' }); } if(data["value_client"] == "maps_cliente" ) { socket.emit('servidor_respuesta', { value_server: 'funciono3' }); } }); });
const express = require('express') const router = express.Router() const{ getclasses, getclass, postclass, putclass, deleteclass }= require('./controller') router.route('/').get(getclasses).post(postclass) router.route('/:id').get(getclass).put(putclass).delete(deleteclass) module.exports = router
angular.module('app', ['ngRoute'] ); angular .module('app') .controller('main', ['$scope', '$route', '$routeParams', '$location', function($scope, $route, $routeParams, $location){ $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; $scope.limit = 10 $scope.hello = "hello" console.log($routeParams, $scope.activeGame) }])
const createDivisor = require("./helper.js").createDivisor; // Long-processing time block function function greatestCommonDivisor(a, b) { let lowest = Math.min(a, b), greatest = Math.max(a, b), aDivisor = null, bDivisor = null, commonDivisor = null; for(i = lowest; i > 0; i--) { aDivisor = createDivisor(lowest, i); if(aDivisor.isDivisor) { bDivisor = createDivisor(greatest, i); if(bDivisor.isDivisor) { commonDivisor = i; break; } } } return commonDivisor; } module.exports = { greatestCommonDivisor: greatestCommonDivisor, }
let rightSideList = document.createElement('ul'); rightSide.appendChild(rightSideList); rightSideList.classList.add('right-side__list'); for(let i=0; i<Friends.List.length; i++){ let rightSideListItem = document.createElement('li'); rightSideList.appendChild(rightSideListItem); rightSideListItem.classList.add('right-side__list__item'); let listItemContent = document.createElement('div'); rightSideListItem.appendChild(listItemContent); listItemContent.classList.add('right-side__list__item__content'); let listItemPicture = document.createElement('div'); listItemContent.appendChild(listItemPicture); listItemPicture.classList.add('right-side__list__item__picture'); let ListItemName = document.createElement('div'); listItemContent.appendChild(ListItemName); ListItemName.classList.add('right-side__list__item__name') let ListItemNameText = document.createTextNode(Friends.List[i].name); ListItemName.appendChild(ListItemNameText); if(Friends.List[i].isOnline == true){ let listItemCircle = document.createElement('div'); listItemContent.appendChild(listItemCircle); listItemCircle.classList.add('right-side__list__item__circle') } } let rightSideSerchBar = document.createElement('li'); rightSideList.appendChild(rightSideSerchBar); rightSideSerchBar.classList.add('right-side__search'); rightSideSerchBar.classList.add('right-side__list__item'); let searchBarIcons = document.createElement('div'); rightSideSerchBar.appendChild(searchBarIcons); searchBarIcons.classList.add('right-side__search__icons'); let searchBarIcon = document.createElement('i'); searchBarIcons.appendChild(searchBarIcon); searchBarIcon.setAttribute('class','fa fa-search'); let searchBarInput = document.createElement('input'); rightSideSerchBar.appendChild(searchBarInput); searchBarInput.setAttribute('type','search'); searchBarInput.setAttribute('placeholder','search'); let searchBarIconRight = document.createElement('div'); rightSideSerchBar.appendChild(searchBarIconRight); searchBarIconRight.classList.add('right-side__search__icons2'); let searchBarIconClassArr = ['fa fa-users right','fas fa-pencil-alt right','fas fa-cog right']; for(let j=0; j<3; j++){ let icons = document.createElement('i'); searchBarIconRight.appendChild(icons); icons.setAttribute('class',searchBarIconClassArr[j]); }
import { sortBy } from 'lodash'; /** * The order to use when deciding which platform to display first. */ const platformOrder = { usage: 1, react: 2, scss: 3, ios: 4, android: 5, }; const getPlatformByPathname = pathname => { const splitPathname = pathname.split('/'); // If input is `/components/button/react/`, this gets the word `react`. return splitPathname[splitPathname.length - 2]; }; const getURL = platforms => { // Sort the available platforms by `platformOrder`. const sorted = sortBy( platforms, platform => platformOrder[getPlatformByPathname(platform.node.path)], ); return sorted[0].node.path; }; /** * Removes platform from the URL for URLs ending with or without a slash. * * Turns `/components/button/react` and `/components/button/react/` into * `/components/button`. */ const removeLastDirectoryOfURL = url => { const urlWithoutTrailingSlash = url.endsWith('/') ? url.substring(0, url.length - 1) : url; const urlArr = urlWithoutTrailingSlash.split('/'); urlArr.pop(); return urlArr.join('/'); }; const getComponentsLinkProps = (platforms, pathname) => { const to = getURL(platforms); return { to, isActive: pathname ? removeLastDirectoryOfURL(to) === removeLastDirectoryOfURL(pathname) : false, }; }; export default getComponentsLinkProps;
//Set Environments var mongoose = require('mongoose'); var Schema = mongoose.Schema; //Create my Model Schema var uploadSchema = new Schema({ name: String, service_type: Number, ip: String, link: String, created_at: Date }); mongoose.model('upload', uploadSchema, 'uploads'); //Define my schema to a Model and set Collection
import { Conditions } from "../../common"; var mapping_codes = { 'clear-day': Conditions.ClearSky, 'clear-night': Conditions.ClearSky, 'partly-cloudy-day': Conditions.FewClouds, 'partly-cloudy-night': Conditions.FewClouds, 'cloudy': Conditions.BrokenClouds, 'rain': Conditions.Rain, 'thunderstorm': Conditions.Thunderstorm, 'snow': Conditions.Snow, 'sleet': Conditions.Snow, 'fog': Conditions.Mist }; export function fetchWeather(apiKey, latitude, longitude) { return new Promise(function (resolve, reject) { var url = 'https://api.darksky.net/forecast/' + apiKey + '/' + latitude + ',' + longitude + '?exclude=minutely,hourly,alerts,flags&units=si'; console.log(url); fetch(encodeURI(url)) .then(function (response) { return response.json(); }) .then(function (data) { if (data.currently === undefined) { reject(data); return; } var conditionCode = mapping_codes[data.currently.icon]; if (conditionCode === undefined) conditionCode = Conditions.Unknown; var temp = data.currently.temperature; var weather = { temperatureC: temp, temperatureF: (temp * 9 / 5 + 32), location: "", description: data.currently.summary, isDay: data.currently.time > data.daily.data[0].sunriseTime && data.currently.time < data.daily.data[0].sunsetTime, conditionCode: conditionCode, realConditionCode: data.currently.icon, sunrise: data.daily.data[0].sunriseTime * 1000, sunset: data.daily.data[0].sunsetTime * 1000, timestamp: Date.now() }; // retreiving location name from Open Street Map var url = 'https://nominatim.openstreetmap.org/reverse?lat=' + latitude + '&lon=' + longitude + '&format=json&accept-language=en-US'; fetch(url) .then(function (response) { return response.json(); }) .then(function (data) { if (data.address.hamlet != undefined) weather.location = data.address.hamlet; else if (data.address.village != undefined) weather.location = data.address.village; else if (data.address.town != undefined) weather.location = data.address.town; else if (data.address.city != undefined) weather.location = data.address.city; // Send the weather data to the device resolve(weather); }) .catch(function () { resolve(weather); // if location name not found - sending weather without location }); }) .catch(function (e) { return reject(e.message); }); }); }
import constantRouterComponents from './constantRouterComponents' import Main from "_c/main"; import exampleMenuData from "./exampleMenuData"; /** * 动态生成菜单 * @param permissionList * @returns Router */ export const generatorDynamicRouter = (permissionList) => { let menuData = [], pageNode = { path: '/page', name: 'page', meta: { hideInMenu: true, notCache: true }, component: 'Main', children: [] } listToMenuTree(permissionList, menuData, pageNode, '0', [], true) if (pageNode.children.length > 0) { menuData.push(pageNode) } const dynamicRouter = generator(menuData) return dynamicRouter } /* 生成 vue-router 层级路由表 */ const generator = (menuData) => { for (let item of menuData) { if (item.component) { const target = constantRouterComponents[item.component] if (target) { if (typeof target.component == 'string') { // 解决路由name与组件name不一致导致的keeplive不生效的问题 item.component = (resolve) => require([`@/view/${target.component}`], data => { data.default.name = item.name; resolve(data); }) } else { item.component = target.component } if (target.url) { item.path = target.url } else if (item.uri && item.uri.startsWith("/")) { item.path = item.uri } if (target.alias) { item.alias = target.alias } if (target.frameUrl) { item.meta.frameUrl = target.frameUrl } if (target.notCache) { item.meta.notCache = target.notCache } if (target.hideInMenu) { item.meta.hideInMenu = target.hideInMenu } if (target.hideInBread) { item.meta.hideInBread = target.hideInBread } } else { console.error(`找不到组件定义:${item.component}`) item.component = (resolve) => require([`@/view/exception/dev.vue`], data => { data.default.name = '开发中'; resolve(data); }) } if (item.path == null) { item.path = '' } if (item.children && item.children.length > 0) { generator(item.children) } } } return menuData } /** * 数组转树形结构 */ const listToMenuTree = (list, menuTree, pageNode, parentId, crumbs, root) => { list.forEach(item => { // 判断是否为父级菜单 if (item.pid === parentId) { if (item.type === 1 || item.type === 2) { let node = { meta: { title: item.label, icon: item.icon, crumbs: [...crumbs], activeName: item.name, tag:item.tag }, type: item.type, pid: item.pid, component: item.name, name: item.name, uri: item.uri, children: [] } node.meta.crumbs.push({ icon: item.icon, name: item.name, title: item.label, type: item.type, tag:item.tag }) if(item.type ===1){ if (root) { node.component = "Main" } else { node.component = "parentView" } } // 迭代 list, 找到当前菜单相符合的所有子菜单 listToMenuTree(list, node.children, pageNode, item.permissionId, node.meta.crumbs, false) // 删掉不存在 children 值的属性 if (node.children.length <= 0) { delete node.children } // 加入到树中 menuTree.push(node) } if (item.type === 4) { let child = { meta: { title: item.label, hideInMenu: true, crumbs: [...crumbs], type: item.type, tag:item.tag }, type: item.type, pid: item.pid, component: item.name, name: item.name, uri: item.uri } child.meta.crumbs.push({ icon: item.icon, name: item.name, title: item.label, type: item.type, tag:item.tag }) pageNode.children.push(child) } } }) } const addExtendMenu = (menuData) => { let menu = []; if (process.env.NODE_ENV === 'development') { menu = menu.concat(exampleMenuData) } menu = menu.concat(menuData) return menu } export default generatorDynamicRouter
import React from 'react'; import Logo from '../../assets/images/logo.png'; import { MdClose, MdDehaze } from "react-icons/md"; import { Link } from 'react-router-dom'; import './index.css'; function getData() { return JSON.parse( localStorage.getItem("dadosUsuario") ) || null; } function handleMenuShow () { let menu = document.getElementById("menu"); menu.setAttribute("class", "show"); } function handleMenuHidden () { let menu = document.getElementById("menu"); menu.removeAttribute("class"); } function handleLogout () { localStorage.removeItem("dadosUsuario"); } function Header() { const dadosUsuario = getData(); return ( <div> <header className="header"> <img src={Logo} className="header--logo" alt="logo do sistema"/> <div id="buttonMenu" onClick={ () => { handleMenuShow()} } > <MdDehaze /> </div> </header> <div id="menu"> <div id="buttonCloseMenu" onClick={ () => { handleMenuHidden() } } > <MdClose /> </div> <div className="menu--image-profile"> <img src={dadosUsuario.foto} className="image-profile--user" alt="imagem do usuario" /> <p>{dadosUsuario.nome}</p> </div> <div className="menu--navbar"> <ul> <li> <Link tabIndex="-1" to="/">Inicio</Link> </li> <li> <Link tabIndex="-1" to="/perfil">Perfil</Link> </li> <li> <Link tabIndex="-1" to="/login" onClick={handleLogout} >Sair</Link> </li> </ul> </div> </div> </div> ); } export default Header;
import React from 'react' import {Link} from 'react-router-dom' import {auth} from './firebase' import {withRouter} from 'react-router-dom' const navBar = ({history}) => { const cerrarSesion = () =>{ auth.signOut().then(()=>{ history.push("/") }) } return ( <div> <nav className ="navbar navbar-expand-lg navbar-dark bg-primary" > <Link className ="navbar-brand" to="/">Emanuel</Link> <button className ="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span className ="navbar-toggler-icon"></span> </button> <div className ="collapse navbar-collapse" id="navbarNavAltMarkup"> <div className ="navbar-nav"> {auth.currentUser && <Link className ="nav-item nav-link float-right" to="/Admin">Admin <span className ="sr-only">(current)</span></Link>} {auth.currentUser ? (<button className ="btn btn-dark float-right" onClick = {()=> cerrarSesion()}>Salir</button>): (<Link className ="nav-item nav-link float-right" to="/login">Login</Link>) } </div> </div> </nav> </div> ) } export default withRouter(navBar)
import { StyleSheet } from 'react-native' const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'stretch' }, content: { flex: 1, justifyContent: 'flex-start', alignItems: 'center', paddingTop: 50 }, imgTrip: { width: 200, height: 200 }, imgLOGO: { height: 50, width: '100%', marginBottom: 30 }, btnBottom: { backgroundColor: '#FFF', justifyContent: 'center', alignItems: 'center', padding: 15 }, stepEmpty: { backgroundColor: '#FFF', alignItems: 'center', padding: 10, justifyContent: 'center', }, stepEmptyText: { fontSize: 18, color: '#000', width: '50%', textAlign: 'center', marginTop: 10, }, imgPin: { height: 90 }, btnArrow: { padding: 15, width: 100, justifyContent: 'center', alignItems: 'center' } }) export default styles
var React = require('react'); var AdminStore = require('../../../stores/AdminStore'); var AdminActions = require('../../../actions/adminActions'); var Link = require('react-router').Link; var dateFormat = require('dateformat'); var Requests = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, getInitialState: function() { return this._getState(); }, componentWillMount: function() { this.props.checkPermission(this.props.permissions.Approver); if(this.state.requestStates.length === 0 ) { AdminActions.getRequestStates('/api/requeststates'); } AdminStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { AdminStore.removeChangeListener(this._onChange); }, _onChange: function() { this.setState( this._getState() ) }, _getState: function() { return { users: AdminStore.getUsers(), requests: AdminStore.getNewRequests(), requestStates: AdminStore.getRequestStates() } }, _setRequest: function(request) { return function() { AdminActions.setRequest(request); } }, render: function() { var that = this; return ( <div className="container-fluid admin-content"> <div className="row"> <div className="col-xs-12 col-sm-4"> <h3 className="underline">Pending Requests</h3> {this.state.requests.length > 0 ? <ul className="requests-list"> {this.state.requests.map(function(request, index){ var link = '/requests/' + request.id; return ( <li className="requests-list-item" key={index}> <Link onClick={that._setRequest(request)} activeClassName="active" to={link}> <p className="request-item-user">{request.userName}</p> <p className="request-item-date">{dateFormat(request.date, "dddd, mmmm dS, yyyy, h:MM TT")}</p> <p className="request-item-name">{request.type} - {request.name}</p> </Link> </li> ) })} </ul> : <p>No new Requests!</p> } </div> <div className="col-xs-12 col-sm-8"> {this.props.children && React.cloneElement(this.props.children, { requestStates: this.state.requestStates, permissions: this.props.permissions, checkPermission: this.props.checkPermission})} </div> </div> </div> ) } }); module.exports = Requests;
define([ 'extensions/mixins/safesync', 'backbone' ], function (SafeSync, Backbone) { describe('SafeSync', function () { describe('sync', function () { beforeEach(function () { spyOn(Backbone, 'ajax'); SafeSync.trigger = jasmine.createSpy(); }); it('escapes HTML characters in received response', function () { var response = null; SafeSync.sync('get', new Backbone.Model(), { url: '//testurl', success: function (resp) { response = resp; } }); var success = Backbone.ajax.argsForCall[0][0].success; success({'someProperty': '<b>html content</b>'}); expect(response.someProperty).toBe('&lt;b&gt;html content&lt;/b&gt;'); }); it('sends a "loading" event', function () { SafeSync.sync('get', new Backbone.Model(), { url: '//testurl', success: function () {} }); // ensure "loading" state is reset for next test var success = Backbone.ajax.argsForCall[0][0].success; success({'someProperty': '<b>html content</b>'}); expect(SafeSync.trigger).toHaveBeenCalledWith('loading'); }); it('sets the "loading" property while a request is active and resets on success', function () { expect(SafeSync.loading).toBeFalsy(); var response = null; SafeSync.sync('get', new Backbone.Model(), { url: '//testurl', success: function (resp) { response = resp; } }); expect(SafeSync.loading).toBeTruthy(); var success = Backbone.ajax.argsForCall[0][0].success; success({'someProperty': '<b>html content</b>'}); expect(SafeSync.loading).toBeFalsy(); }); it('sets the "loading" property while a request is active and resets on error', function () { expect(SafeSync.loading).toBeFalsy(); var errorArgs = {}; SafeSync.sync('get', new Backbone.Model(), { url: '//testurl', error: function (args) { expect(errorArgs).toBe(args); } }); expect(SafeSync.loading).toBeTruthy(); var error = Backbone.ajax.argsForCall[0][0].error; error(errorArgs); expect(SafeSync.loading).toBeFalsy(); }); }); }); });
import React, { Component, createRef } from 'react'; import propTypes from 'prop-types'; import createVisualization from './create-visualization'; import './visualizer.scss'; class VisualizerComponent extends Component { constructor(props) { super(props); this.containerElement = createRef(); } render() { return <div className="visualizer" ref={this.containerElement} />; } componentDidMount() { const visualization = createVisualization(this.containerElement.current); if (this.props.isPlaying) { visualization.start(); } this.setState({ visualization, }); } componentWillUnmount() { this.state.visualization.stop(); } componentDidUpdate(previousProps) { if (previousProps.isPlaying && !this.props.isPlaying) { this.state.visualization.stop(); } else if (!previousProps.isPlaying && this.props.isPlaying) { this.state.visualization.start(); } } } VisualizerComponent.propTypes = { isPlaying: propTypes.bool.isRequired, }; export default VisualizerComponent;
import React, { useRef } from 'react'; import './style/add.css'; export const Add = (props)=>{ const {addNewBook} = props; const formData = useRef(); const onSubmitForm = async(e)=>{ e.preventDefault(); await addNewBook(formData.current) } return( <div className="add-main"> <div className="add-back"> <a style={{textDecoration:'none'}} href="/home"><div><h2>🠔</h2></div></a> </div> <h1>Add a new book</h1> <form ref={formData} onSubmit={(e)=> onSubmitForm(e)}> <input placeholder="name" name="name" required /> <input placeholder="genre" name="genre" required /> <input placeholder="author" name="author" required /> <input placeholder="publisher" name="publisher" required /> <input placeholder="cover" name="cover" required /> <input placeholder="pages" type="number" name="pages" required /> <input placeholder="language" name="language" required /> <input placeholder="price: $25.50 > 2550" type="number" name="price" required /> <input placeholder="year" type="number" name="year" required /> <button type="submit">Add</button> </form> </div> ); }
module.exports = function(router) { require('./users')(router); require('./devices')(router); require('./user')(router); };
$(document).ready(function () { var str=" ( 23 + 32 - sin ( 20 + 3 ) ) " var str1=str.split(" ") var str2=str1.split('(') alert(str) alert(str1) alert(str2) });
'use strict'; const File = require('./file'); const Path = require('path'); const SASS = require('node-sass'); /** * Render an SCSS stylesheet */ class Style { /** * Create an Express handler function to serve stylesheets * @return {Function} */ static serve() { return function(req, res, next) { // Normalize .. traversal, strip leading / const path = Path.resolve('/' + req.path).slice(1); const dirname = Path.dirname(path); const basename = Path.basename(path, '.css'); Log.info(`SCSS: Serve ${path} for ${req.originalUrl}`); new Style(Path.join(dirname, basename)).render() .then((stylesheet) => res.type('text/css').send(stylesheet.css)) .catch((err) => next(err)); }; } /** * Render stylesheets into a static site directory * @return {Function} */ static static() { return function(writer) { return File.resources('styles', '.scss') .then((files) => Promise.all(files.map((style) => { return new Style(style).render() .then((stylesheet) => writer.file(style, stylesheet.css, '.css')); }))); }; } /** * Add an include directory from a module * @param {String} name The mount-point for the included directory when resolving paths * @param {String} path The target module name and subpath to its SCSS source. Note that * the module must already be installed in the node_modules directory. */ static use(name, path) { this.includes.set(name, Path.resolve(__dirname, '../node_modules', path)); } /** * Resolve an include path to a file on disk. * * Resolution logic: * - If the path begins with the name of a configured source module, it will * be resolved to a subpath of that module. e.g. `bootstrap/bootstrap-grid` will resolve * to `node_modules/bootstrap/scss/bootstrap-grid.scss`, assuming that `bootstrap/scss` * as mounted as `bootstrap` * - If a parent path is provided, the parent's module will be used and the * path will be resolved relative to the directory name of the parent within * its module. * * The return value is an Object with keys * - `path`: the absolute file-system path to the target file * - `module.name`: the mount-name of the module the file was resolved to * - `module.path`: the file-system path of the module the file was resolved to * - 'file': the relative path, including its module-name prefix, of the target file * * @param {String} path * @param {String} parent * @return {Object} */ static resolve(path, parent) { Log.debug(`SCSS: Resolve module ${path}` + (parent ? `, imported by ${parent}` : '')); const nodes = path.split(Path.sep); const name = nodes.shift(); const resource = nodes.join(Path.sep); // The path maps to a configured SCSS module if (this.includes.has(name)) { const prefix = this.includes.get(name); Log.debug(`SCSS: Using module ${name} (${prefix}) for ${path}`); return { path: Path.join(prefix, resource), module: {name, path: prefix}, file: path, parent }; } // If there's no parent parameter, fail. if (!parent) { throw new Error(`Cannot resolve ${path} to an SCSS module`); } // Fall back to an internal reference relative to the parent const resolved = this.resolve(parent); // Inject an _ into internal file names const file = Path.join(Path.dirname(path), '_' + Path.basename(path)); Log.debug(`SCSS: Using module ${resolved.module.name} (${resolved.module.path}) for ${file}`); return { path: Path.resolve(resolved.module.path, file), module: resolved.module, file: Path.join(resolved.module.name, file) }; } /** * A custom importer for node-scss that is aware of node_modules and uses the caching * file loader * @param {String} path * @param {String} parent * @param {Function} done */ static importer(path, parent, done) { const resolved = this.resolve(path, parent); File.read(resolved.path, 'scss').then((file) => done({ contents: file.content.toString('utf8'), file: resolved.file }), (err) => done(err)); } /** * @constructor * @param {String} name */ constructor(name) { this.name = name; } /** * Render the SCSS stylesheet * @return {Promise} */ render() { return File.resource('styles', this.name, 'scss') .then((file) => new Promise((resolve, reject) => SASS.render({ data: file.content.toString('utf8'), file: file.path, importer: Style.importer.bind(Style) }, (err, result) => err ? reject(err) : resolve(result)))); } } Style.includes = new Map(); module.exports = Style;
import React from "react"; const Appointment = props => { return ( <div> <table className="table table-striped" style={{ marginTop: 20 }}> <thead> <tr> <th>Appointment Date</th> <th>Doctor</th> <th>Type</th> <th>Status</th> <th>Created By</th> </tr> </thead> <tbody> {props.appointment.map(function(obj, i) { return ( <tr key={i}> <td>{(obj.aptDate).substring(0, 10)}</td> <td>{obj.doctor.name}</td> <td>{obj.type}</td> <td>{obj.status}</td> <td>{obj.createdBy.name}</td> </tr> ); })} </tbody> </table> </div> ); }; export default Appointment;
import React from 'react'; import {connect} from 'react-redux'; class Selector extends React.Component { render() { return ( <div className=""> <ul className="list-group"> { this.props.list.map((item) => { if (this.props.selected.id == item.id) { return <a href="#" key={item.id} className="list-group-item list-group-item-action active"> {item.first_name} {item.last_name}</a> } else { return <a href="#" key={item.id} onClick={() => { this.props.selectPerson(item); }} className="list-group-item list-group-item-action"> {item.first_name} {item.last_name}</a> } }) } </ul> </div> ) } } const mapStateToProps = (state) => { let selectedPerson = state.peopleReducer.selected || {}; let people = state.peopleReducer.people || []; console.log(`People are ${people}`); return { list: people, selected: selectedPerson, } }; const mapDispatchToProps = (dispatch) => { return { selectPerson: (person) => { dispatch({type: "SET_SELECTED", selected: person}); } } }; export default connect(mapStateToProps, mapDispatchToProps)(Selector);
import Vue from 'vue' import VueRouter from 'vue-router' import store from '../store' import user from './user' import admin from './admin' import category from './category' import product from './product' import tag from './tag' import search from './search' const home = () => import('../pages/home.vue') const notFound = () => import('../pages/notFound.vue') Vue.use(VueRouter) const router = new VueRouter({ mode: 'history', linkActiveClass: 'active', routes: [ { path: '/', component: home }, { path: '/page/:page', component: home }, ...user, ...admin, ...category, ...product, ...tag, ...search, { path: '*', component: notFound } ], scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition } return { x: 0, y: 0 } } }) router.beforeEach(async (to, from, next) => { await store.dispatch({ type: 'getUser' }) let data = store.state.user.data let logedIn = false let user = {} if (data) { logedIn = data.ok user = data.user } if (to.matched.some(record => record.meta.requiresLogin)) { if (!logedIn) { next({ path: '/' }) } else { next() } } else if (to.matched.some(record => record.meta.requiresAdmin)) { if (logedIn && user.isAdmin) { next() } else { next({ path: '/' }) } } else { next() } }) export default router
'use strict' const { maybeRequire } = require('../../util') class NativeCpuProfiler { constructor (options = {}) { this.type = 'wall' this._pprof = maybeRequire('pprof') this._samplingInterval = options.samplingInterval || 10 * 1000 } start () { // pprof otherwise crashes in worker threads if (!process._startProfilerIdleNotifier) { process._startProfilerIdleNotifier = () => {} } this._record() } profile () { const profile = this._stop() this._record() return profile } stop () { this._stop() } _record () { this._stop = this._pprof.time.start(this._samplingInterval) } } module.exports = { NativeCpuProfiler }
(function () { 'use strict'; var uptime = { 'el': document.getElementById('uptime') }; uptime.controller = function () { var ctrl = this; ctrl.data = {}; uptime.el.addEventListener('uptime', function (event) { var body = event.detail; body.hosts.forEach(function (host) { host.active = host.active ? 'aktiv' : 'inaktiv'; }); ctrl.data = body; m.render(uptime.el, uptime.view(ctrl)); }); }; uptime.view = function (c) { if (Object.keys(c.data).length === 0) { return m('p', 'Waiting for data'); } var rows = c.data.hosts.map(function (host) { return m('tr', [ m('td.label', host.label), m('td.active', host.active) ]); }); return [ m('p.fade', 'Enheter'), m('table', rows), m('p', {'class': 'fade updated-at'}, 'Sist oppdatert: ' + c.data.updatedAt) ]; }; if (uptime.el !== null) { m.module(uptime.el, uptime); } })();