text
stringlengths
7
3.69M
const express = require('express'); const app = express(); const mysql = require('mysql'); const cors = require('cors'); app.use(cors()); app.use(express.json()); const db = mysql.createConnection({ host: 'localhost', database:'reactnode', user: 'root', password: '' }); // Employees api app.post('/create',(req,res) => { const name = req.body.name const age = req.body.age const country = req.body.country const position = req.body.position const wage = req.body.wage db.query("INSERT INTO employees (name,age,country,position,wage) VALUES (?,?,?,?,?)", [name,age,country,position,wage], (err,result) => { if(err){ console.log(err); }else{ res.send("Record Successfully Added"); } }); }); app.get('/employees',(req,res)=>{ db.query("SELECT * FROM employees", (err,result) => { if(err){ console.log(err); }else{ res.send(result); } }); }); app.put('/update',(req,res) => { const id = req.body.id; const name = req.body.name; const age = req.body.age; const country = req.body.country; const position = req.body.position; const wage = req.body.wage; db.query("UPDATE employees SET name=?,age=?,country=?,position=?,wage=? WHERE id=?", [name,age,country,position,wage,id], (err,result) =>{ if(err){ console.log(err); }else{ res.send("Record Successfully Updated"); } }); }); app.delete('/delete/:id',(req,res)=>{ const id = req.params.id; db.query("DELETE FROM employees WHERE id=?",id, (err,result)=>{ if(err){ console.log(err); }else{ res.send("Record Successfully Deleted"); } }); }); // END Employees api app.listen(3001,function(){ console.log("works, server is running. check localhost:3001"); });
import React from 'react' import { shallow, mount } from 'enzyme' import { expect } from 'chai' import Panel from '../../components/Panel' describe('<Panel />', () => { it('renders without throwing an error', () => { expect(() => shallow(<Panel />)).to.not.throw() }) it('defaults to <div />', () => { expect(shallow(<Panel />).find('div')).to.have.length(1) }) it('renders specified tag', () => { expect(shallow(<Panel tag="section" />).find('section')).to.have.length(1) }) it('renders children', () => { const child = <h1>Title</h1> expect( shallow(<Panel>{child}</Panel>).contains(child) ).to.equal(true) }) it('sets inset spacing', () => { expect( shallow(<Panel inset="xs" />).hasClass('panel-inset-xs') ).to.equal(true) }) it('can fit elements', () => { expect( shallow(<Panel fit />).hasClass('panel-fit') ).to.equal(true) }) it('sets below spacing', () => { expect( shallow(<Panel below="xs" />).hasClass('panel-below-xs') ).to.equal(true) }) it('sets between spacing', () => { expect( shallow(<Panel between="xs" />).hasClass('panel-between-xs') ).to.equal(true) }) it('sets inline-between spacing', () => { expect( shallow(<Panel between="xs" inline />).hasClass('panel-between-inline-xs') ).to.equal(true) }) it('allows using row and column flex directions', () => { expect( shallow(<Panel row />).props().style ).to.have.property('flexDirection', 'row') expect( shallow(<Panel column />).props().style ).to.have.property('flexDirection', 'column') }) it('sets `justify-content` style', () => { const value = 'center' expect( shallow(<Panel justify={value} />).props().style ).to.have.property('justifyContent', value) }) it('sets `align-items` style', () => { const value = 'center' expect( shallow(<Panel align={value} />).props().style ).to.have.property('alignItems', value) }) it('sets `flex-wrap` style', () => { expect( shallow(<Panel wrap />).props().style ).to.have.property('flexWrap', 'wrap') }) })
import React, {Component} from 'react'; import Header from '../Header/Header'; import './Landing.css'; import Footer from '../Footer/Footer'; import SadDog from '../../../sad_dog.jpg'; import SadDog2 from '../../../sad_dog_2.webp'; class Landing extends Component { render(){ return( <div> <Header /> <div className='home-page'> <div className='dog-facts'> <img src={SadDog} alt='' className='dog-images'/> </div> <div className='dog-facts'> Only 1 dog out of 10 will find a permanent home. Approximately 3.9 million dogs end up in a shelter every year. </div> {/* <div className='dog-facts'> This app is designed to give you an interest in dogs and finding a dog that is just right for you. To help motivate you to adopt a dog into your home and family. </div> */} <div className='dog-facts'> <img src={SadDog2} alt='' className='dog-images'/> </div> </div> <Footer /> </div> ) } } export default Landing;
// a constant is a variable that should be read-only after initial value is set const express = require('express'); const router = express.Router(); // bring in controller const updateCtrl = require('../controllers/update.controller'); // update specific, by id router.put('/update/:id', updateCtrl.updateOneById); module.exports = router;
var input = document.getElementById("input"), leftIn = document.getElementById("left-in"), leftOut = document.getElementById("left-out"), rightIn = document.getElementById("right-in"), rightOut = document.getElementById("right-out"), queue = document.getElementById("queue"), query_button = document.getElementById("query-button"); query_input = document.getElementById("query-input"); query_button.addEventListener("click", match); leftIn.addEventListener("click",leftSideIn); leftOut.addEventListener("click",leftSideOut); rightIn.addEventListener("click",rightSideIn); rightOut.addEventListener("click",rightSideOut); queue.addEventListener("click",function(e){ var node = e.target; //Array.prototype == []??? var index = Array.prototype.indexOf.call(node.parentNode.children, node); remove(index); }); var container = new Array(); var inputArray = []; function highLight(index) { var cursor = queue.children[index]; cursor.style.backgroundColor = "red"; } function match() { for(var z in container) { queue.children[z].style.backgroundColor = "green"; } for(var i = 0, j = queue.children.length; i < j; i++) { if (queue.children[i].innerHTML.search(query_input.value) != -1) { highLight(i); } } } function divideInput() { if(validate()) { var templeInput = input.value.replace(/[,,。.;;、/s]/g,'|'); inputArray = templeInput.split('|'); return true; } return false; } function remove(index) { container.splice(index,1); render(); } function validate() { //非数字的正则表达式不能检测出空格 if(input.value=="" || /[^0-9,,。.;;、/s]/g.test(input.value)){ alert("请输入数字"); return false; } return true; } function render() { var content = "",height = ""; for(var i=0, j = container.length; i < j; i++) { content += '<div class="bar" style="background-color:#2288;' + 'margin:10px;width: 100px;height: 100px;">' +container[i] + '</div>'; } queue.innerHTML = content; } function leftSideIn() { if(divideInput()) { //这里value是字符串 for (var i = 0, j = inputArray.length; i < j; i++) { container.unshift(inputArray[i]); } render(); } } function leftSideOut() { container.shift(); render(); } function rightSideIn() { if(divideInput()) { //这里value是字符串 for (var i = 0, j = inputArray.length; i < j; i++) { container.push(inputArray[i]); } render(); } } function rightSideOut() { container.pop(); render(); }
class Quiz { constructor(){} start(){ question = new Question() question.display(); } play(){ question.hide() background("yellow") textSize(30) text("result of the quiz:",340,50) Contestant.getPlayerInfo() if(allContestants!=undefined){ var displayAnswer = 230 textSize(20) text("Contestants who Answer correctly are in green",130,230) for(var plr in allContestants){ var correctAnswer = "2" if(correctAnswer == allContestants[plr].answer){ fill("green") } else{ fill("red") } displayAnswer+=30 textSize(20) text(allContestants[plr].name+":"+allContestants[plr].answer,250,displayAnswer) } } } }
var ss = ss || {}; ss.Config = { init: function() { this._setSize(); Crafty.init(this.screenSize, this.screenSize); Crafty.background('black'); }, // initialize a proportionally sized game _setSize: function() { var width = window.innerWidth, height = window.innerHeight; this.screenSize = height < width ? height : width; this.playerSize = this.screenSize * .1; this.laserSize = this.playerSize * .2; this.playerLaserSpeed = this.screenSize * .02; this.playerSpeed = this.screenSize * .02; this.enemySize = this.playerSize * .7; this.enemySpeed = this.screenSize * .005; this.enemyLaserSize = this.enemySize * .2; } };
/* * Reset the bubblePlot to default option * @param * @return */ chart.bubblePlots.reset = function () { chart.bubblePlots.change(defaultOptions) };
import React, { useState, useEffect } from 'react' import { View, Image } from 'react-native' import { Layout, Text, Tab, TabBar, TopNavigation, TopNavigationAction, Icon, ViewPager } from '@ui-kitten/components' import { showMessage } from 'react-native-flash-message' import { useNavigation } from '@react-navigation/native' import { LoadingPlaceholder } from '~/components' import { About, Badge, Stats, Evolutions } from './elements' import { tryAwait } from '~/utils' import { typeColors } from '~/helpers' import styled from 'styled-components' import api from '~/api' import pokebadge from '../../assets/images/pokebadge.png' const PokeNavigation = styled(TopNavigation)` background: ${(props) => (props.bg ? props.bg : 'white')}; ` const PokeBackground = styled(View)` background: ${(props) => (props.bg ? props.bg : 'white')}; height: 250px; padding: 8px; position: relative; ` const PokeImage = styled(Image)` height: 100%; width: 100%; ` const BadgeImageSmall = styled(Image)` height: 100px; width: 100px; position: absolute; left: -32px; top: 0; opacity: 0.5; z-index: 0; ` const BadgeImage = styled(Image)` height: 200px; width: 200px; position: absolute; right: 0; bottom: 0; opacity: 0.5; ` const PokeTypeRow = styled(View)` flex-direction: row; justify-content: flex-start; align-items: center; flex-wrap: wrap; flex-grow: 1; width: 100%; position: absolute; bottom: 8px; right: 8px; left: 8px; ` const PokeType = styled(Text)` font-size: 10px; padding-top: 8px; padding-left: 8px; padding-right: 8px; background: ${(props) => (props.bg ? props.bg : 'white')}; color: white; ` export default ({ route: { params: { id, name, type, num, prev_evolution, next_evolution, weaknesses, height, weight, egg } }}) => { const { goBack } = useNavigation() const [ loading, setLoading ] = useState(true) const [ selectedIndex, setSelectedIndex ] = useState(0) const [ details, setDetails ] = useState({}) useEffect(() => { tryAwait({ promise: api.pokemons.pokemonDetails(id), onResponse: ({ data }) => setDetails(data), onError: () => { showMessage({ message: 'Erro', description: 'Error while fetching pokemon data.', type: 'danger' }) }, onLoad: _loading => setLoading(_loading) }) }, []) return ( <Layout style={{ flex: 1 }} level="4"> <PokeNavigation bg={typeColors[type[0]]} alignment="center" title={name} subtitle={`#${num}`} accessoryLeft={() => ( <TopNavigationAction style={{ padding: 8, paddingRight: 48, zIndex: 1 }} icon={props => <Icon name="arrow-back-outline" {...props} />} onPress={goBack} /> )} /> <PokeBackground bg={typeColors[type[0]]}> <BadgeImageSmall style={{ resizeMode: 'contain' }} source={pokebadge} /> <BadgeImage style={{ resizeMode: 'contain' }} source={pokebadge} /> <PokeImage style={{ resizeMode: 'contain' }} source={{ uri: `https://raw.githubusercontent.com/fanzeyi/pokemon.json/master/images/${num}.png`}} /> <PokeTypeRow> {type && type.map((t, i) => ( <PokeType style={{ marginRight: i + 1 == type.length ? 0 : 8, borderColor: 'white', borderWidth: 1 }} bg={typeColors[t]} key={i} > {t} </PokeType> ))} </PokeTypeRow> </PokeBackground> <TabBar selectedIndex={selectedIndex} onSelect={index => setSelectedIndex(index)}> <Tab title='About'/> <Tab title='Stats'/> <Tab title='Evolutions'/> </TabBar> <ViewPager style={{ flex: 1 }} selectedIndex={selectedIndex} onSelect={index => setSelectedIndex(index)} > <Layout level="1" style={{ flex: 1 }}> {loading ? ( <LoadingPlaceholder /> ) : ( <About {...details} weaknesses={weaknesses} height={height} weight={weight} egg={egg} /> )} </Layout> <Layout level="1" style={{ flex: 1 }}> {loading ? ( <LoadingPlaceholder /> ) : ( <Stats {...details} /> )} </Layout> <Layout level="1" style={{ flex: 1 }}> <Evolutions id={id} num={num} name={name} prev_evolution={prev_evolution} next_evolution={next_evolution} /> </Layout> </ViewPager> <Badge /> </Layout> ) }
'use strict'; angular .module('sbAdminApp') .controller('doctorListController', function ($scope, $mdDialog, $filter, ConsultaService, consultas) { var scheduled = _.map(consultas, function (c) { return c.pacientes; }); var flatten = _.flatten(scheduled); function findConsult(id) { return _.find(consultas, function (c) { return c.id === id; }); } function mapEvents(scheduled) { return scheduled.map(function (s) { var turno = new Date(s.turno); var consult = findConsult(s.consultaId); var interval = consult.fecha_fin - consult.fecha_inicio; var end_date = new Date(turno.getTime() + interval); return { id: s.id, title: [s.persona.nombre, s.persona.apellido].join(' '), start: s.turno, end: end_date }; }); } function showDetail(date) { $mdDialog.show({ controller: function ($mdDialog) { var vm = this; vm.data = {}; vm.save = function () { ConsultaService .completeDayPart(date.id, vm.data) .then(function () { $mdDialog.hide('save'); _.remove($scope.events, function (e) { return e.id === date.id }); }) .catch(function (err) { console.log(err); }) }; vm.cancel = function () { $mdDialog.hide('cancel'); } }, controllerAs: 'ctrl', resolve: {}, templateUrl: 'views/modals/diagnostic.html', parent: angular.element(document.body), clickOutsideToClose: true }); } $scope.eventSource = { className: 'gcal-event', currentTimezone: 'America/Chicago' }; $scope.events = mapEvents(flatten); $scope.uiConfig = { calendar: { height: 450, editable: false, header: { left: 'month basicWeek basicDay agendaWeek agendaDay', center: 'title', right: 'today prev,next' }, dayClick: $scope.alertEventOnClick, eventDrop: $scope.alertOnDrop, eventResize: $scope.alertOnResize, eventClick: showDetail } }; $scope.eventSources = [$scope.events, $scope.eventSource]; });
var api = require("../api.js"); var app = getApp(); Page({ data: { share: false, animation: {}, toastShow: false, type: 1, isLike: false, collegeInfo: "", scrollH: 0, chooseSubjectType: 1 }, onShareAppMessage: function onShareAppMessage(res) { var that = this; if (res.from === "button") {} return { title: "我已生成[新高考选科]的报告", imageUrl: "http://wmei-appfile.cn-bj.ufileos.com/share_xk.png", path: "/packages/chooseSubjects/collegeResult/collegeResult?code=" + that.code + "&uCode=" + that.uCode + "&provinceId=" + that.provinceId + "&year=" + that.year + "&share=true" }; }, goCollegeDetail: function goCollegeDetail() { wx.navigateTo({ url: "/packages/findUniversity/collegeDetail/collegeDetail?numId=" + this.code }); }, onLoad: function onLoad(options) { var code = options.code, uCode = options.uCode; this.code = options.code; this.uCode = options.uCode; if (options && options.share) { this.provinceId = options.provinceId; this.year = options.year; this.setData({ chooseSubjectType: options.type, share: true }); } else { this.provinceId = app.globalData.chooseSubject.provinceId; this.year = app.globalData.chooseSubject.year; this.setData({ chooseSubjectType: app.globalData.chooseSubject.provinceType }); } this.getCollegeResult(code, uCode); this.getScrollH(); }, // 计算dom高度 getScrollH: function getScrollH() { var that = this; var item = wx.createSelectorQuery(); item.select("#nav").boundingClientRect(); item.exec(function(res) { that.setData({ scrollH: app.globalData.systemInfo.screenHeight - res[0].height - app.globalData.navigationCustomCapsuleHeight - app.globalData.navigationCustomStatusHeight }); }); }, //获取大学选考科目查询结果/专业匹配率 getCollegeResult: function getCollegeResult(code, uCode) { var that = this; api.getCollegeResult("ChooseSubject/Colleges/Get", "POST", { uCode: uCode, collegeId: code, provinceId: that.provinceId, year: that.year }).then(function(res) { that.setData({ collegeInfo: res.result }); }); }, like: function like() { this.setData({ isLike: !this.data.isLike }); }, //弹出抽屉 showToast: function showToast(e) { var type = e.currentTarget.dataset.type; this.setData({ type: type }); var anim = wx.createAnimation({ duration: 200, timingFunction: "linear", delay: 0 }); anim.translateY(521).step(); this.setData({ animationData: anim.export(), toastShow: true }); setTimeout(function() { anim.translateY(0).step(); this.setData({ animationData: anim.export() }); }.bind(this), 200); }, hideToast: function hideToast() { var anim = wx.createAnimation({ duration: 200, timingFunction: "linear", delay: 0 }); anim.translateY(521).step(); this.setData({ animationData: anim.export() }); setTimeout(function() { anim.translateY(0).step(); this.setData({ animationData: anim.export(), toastShow: false }); }.bind(this), 200); } });
'use strict' const { Telegraf } = require('telegraf') const Aria2 = require('aria2') const commands = require('./core/commands') // Init aria2c daemon require('./core/aria').init() const bot = new Telegraf(process.env.BOT_TOKEN) const aria2 = new Aria2() const username = process.env.BOT_USERNAME bot.context = { aria: aria2 } const pattern = /^\/([a-zA-Z]+)(@.*bot)?(?: |$)(.*)/i bot.hears(pattern, (ctx) => { if (ctx.match[2] !== username || !ctx.match[2]) { let command = ctx.match[1] if (command in commands) { commands[command].execute(ctx) } } }) bot.launch() // Enable graceful stop process.once('SIGINT', () => bot.stop('SIGINT')) process.once('SIGTERM', () => bot.stop('SIGTERM'))
import React, { Component } from 'react'; import {Heading, Header, AppWrapper, Dashboard, HouseCupHero, HouseCupFeatures, TeamsOrIndividuals, ArticleCards, FinalThingsToClick, JoinTogether, Modal, Footer} from '../../components'; import {Helmet} from "react-helmet"; export default class Home extends Component { render() { return ( <AppWrapper> <Helmet> <title>Join Together</title> </Helmet> <HouseCupHero /> <JoinTogether /> <HouseCupFeatures /> <TeamsOrIndividuals /> <ArticleCards /> <FinalThingsToClick /> </AppWrapper> ); } }
const express = require('express'); const hbs = require('express-handlebars'); const logger = require('./util/logger'); const home = require('./controllers/home'); const catalog = require('./controllers/catalog'); const init = require('./util/storage'); async function start(){ const app = express(); app.engine('.hbs', hbs({ extname: '.hbs' })) app.set('view engine', '.hbs'); app.use(logger); app.use('/static', express.static('static')); app.use(express.urlencoded({ extended: true })); app.use(await init()); app.get('/', home); app.use('/catalog', catalog); app.listen(3000, () => console.log('Server listening on port 3000')); } start();
import React, { useState, useEffect } from 'react' import { MainSt, AddArticleSt } from '../elements/Main-styled' import { AdminPanelSt } from './adminPanel-styled' import { get, edit, create, removeArt, checkToken } from '../../static/functions' import AdmPanelsCard from './admPanelCard' import EditArticle from './modal/editArticle' import { PropTypes } from 'prop-types' const AdminPanel = () => { const [articles, setArticles] = useState([]) const [editMode, setEditMode] = useState(false) const [activeArticleId, setActiveArticleId] = useState('') const [activeArticle, setActiveArticle] = useState(undefined) const [type, setType] = useState('') const [res, setRes] = useState(null) const [user, setUser] = useState(null) const [dspArticles, setDspArticles] = useState('all') const [articlesForDisplay, setArticlesForDisplay] = useState([]) const [isSorted, setIsSorted] = useState(false) useEffect(() => { if (typeof window !== 'undefined') { const token = localStorage.getItem('token') const tempUser = JSON.parse(localStorage.getItem('user')) setUser(tempUser) checkToken(token, res => { setRes(res) if (res.status === 200 && tempUser.isAdmin) { get( 'articles', '', (res) => { setArticles(res) } ) } else { history.pushState(null, null, '/') window.location.reload() } }) } }, []) useEffect(() => { if (articles.length > 0) { const temp = articles.sort((a, b) => { return a.editDate > b.editDate ? -1 : a.editDate < b.editDate ? 1 : 0 }) setArticles(temp) setIsSorted(true) } if (articles.length > 0 && isSorted) { let temp if (dspArticles === 'all') { temp = articles } else if (dspArticles === 'notModerated') { temp = articles.filter(e => e.isChecked === false) } setArticlesForDisplay(temp) } }, [articles, dspArticles, isSorted]) const createNewArticle = () => { setEditMode(true) } const activeEditMode = (id) => { setActiveArticleId(id) setType('Update') setEditMode(true) setActiveArticle(articles.filter(e => e._id === id)) } const disableEditMode = () => { setActiveArticle(undefined) setEditMode(false) setActiveArticleId(undefined) } const newArticleData = (data) => { edit(data, 'articles', activeArticleId, () => { setActiveArticle(undefined) setEditMode(false) setActiveArticleId(undefined) get( 'articles', '', (res) => { setArticles(res) } ) }) } const deleteArticle = (id) => { if (typeof window !== 'undefined') { const token = localStorage.getItem('token') checkToken(token, res => setRes(res)) } if (res.status) { removeArt('articles', id, () => { get( 'articles', '', (res) => { setArticles(res) } ) }) } else { history.pushState(null, '/') } } const createArticle = (data) => { if (res.status) { create(data, 'articles', () => { setActiveArticle(undefined) setEditMode(false) setActiveArticleId(undefined) get( 'articles', '', (res) => { setArticles(res) } ) }) } } const setEditedArticleData = (data) => { if (type === 'Create') { createArticle(data) } else { newArticleData(data) } } return ( <MainSt> <div className='tools'> <div className='displayArticles'> <span> Display articles: </span> <select onChange={ e => { setDspArticles(e.currentTarget.value) }} > <option value='all'> All </option> <option value='notModerated'> Not moderated </option> </select> </div> <AddArticle setType={setType} createNewArticle={createNewArticle} /> </div> {editMode && <EditArticle user={user} disableEditMode={disableEditMode} type={type} setEditedArticleData={setEditedArticleData} article={activeArticle && activeArticle[0]} />} {/* all Articles */} {/* Articles not moderated */} {articlesForDisplay.length > 0 ? <AdminPanelSt> {articlesForDisplay.map((e) => <AdmPanelsCard deleteArticle={deleteArticle} activeEditMode={activeEditMode} key={e._id} {...e} /> )} </AdminPanelSt> : dspArticles === 'notModerated' ? <span className='artLoadingStatus'>There are no articles for moderation</span> : <span className='artLoadingStatus'>loading</span> } </MainSt> ) } const AddArticle = (props) => { return ( <AddArticleSt> <span onClick={ () => { props.createNewArticle(); props.setType('Create') }}>Add article</span> </AddArticleSt> ) } AddArticle.propTypes = { createNewArticle: PropTypes.func, setType: PropTypes.func } export default AdminPanel
import React from "react"; import { Card } from "react-bootstrap"; import { Link } from "react-router-dom"; class ProfileCard extends React.Component { render() { return ( <Card className="border-0 my-3"> <Card.Img src={`${process.env.PUBLIC_URL}/img/profiles/${this.props.profile.img}`} /> <Card.Body> <Card.Title className="pri-font font-weight-bold"> {this.props.profile.name} </Card.Title> <Card.Text className="sec-font"> {this.props.profile.title} </Card.Text> <Link className="btn btn-outline-dark sec-font" to={`/about/${this.props.profile.link}`} > Learn more </Link> </Card.Body> </Card> ); } } export default ProfileCard;
const path = require('path') const resolve = dir => path.join(__dirname, dir); const PUBLIC_PATH = process.env.NODE_ENV === 'production' ? '/venus' : '/' module.exports = { devServer: { proxy: 'http://localhost:8761', //代理 port: 8888 }, lintOnSave: false, publicPath: PUBLIC_PATH, chainWebpack: config => { config.resolve.alias .set('@', resolve('src')) .set('@c', resolve('src/components')) .set('@v', resolve('src/views')) }, // 打包时不生成.map文件 productionSourceMap: false }
"use strict"; var async = require.main.require('async'); var meta = require.main.require('./src/meta'); var privileges = require.main.require('./src/privileges'); var posts = require.main.require('./src/posts'); var topics = require.main.require('./src/topics'); var plugins = require.main.require('./src/plugins'); var server = require.main.require('./src/socket.io'); var Sockets = module.exports; Sockets.push = function(socket, pid, callback) { var postData; async.waterfall([ function (next) { privileges.posts.can('topics:read', pid, socket.uid, next); }, function (canRead, next) { if (!canRead) { return next(new Error('[[error:no-privileges]]')); } posts.getPostFields(pid, ['content', 'tid', 'uid', 'handle'], next); }, function (_postData, next) { postData = _postData; if (!postData && !postData.content) { return next(new Error('[[error:invalid-pid]]')); } async.parallel({ topic: function(next) { topics.getTopicDataByPid(pid, next); }, tags: function(next) { topics.getTopicTags(postData.tid, next); }, isMain: function(next) { posts.isMain(pid, next); } }, next) }, function (results, next) { if (!results.topic) { return next(new Error('[[error:no-topic]]')); } plugins.fireHook('filter:composer.push', { pid: pid, uid: postData.uid, handle: parseInt(meta.config.allowGuestHandles, 10) ? postData.handle : undefined, body: postData.content, title: results.topic.title, thumb: results.topic.thumb, tags: results.tags, isMain: results.isMain }, next); }, ], callback); }; Sockets.editCheck = function(socket, pid, callback) { posts.isMain(pid, function(err, isMain) { callback(err, { titleEditable: isMain }); }); }; Sockets.renderPreview = function(socket, content, callback) { plugins.fireHook('filter:parse.raw', content, callback); }; Sockets.renderHelp = function(socket, data, callback) { var helpText = meta.config['composer:customHelpText'] || ''; if (meta.config['composer:showHelpTab'] === '0') { return callback(new Error('help-hidden')); } plugins.fireHook('filter:parse.raw', helpText, function(err, helpText) { if (!meta.config['composer:allowPluginHelp'] || meta.config['composer:allowPluginHelp'] === '1') { plugins.fireHook('filter:composer.help', helpText, callback); } else { callback(null, helpText); } }); }; Sockets.getFormattingOptions = function(socket, data, callback) { module.parent.exports.getFormattingOptions(callback); };
angular.module("cart", []) .controller("CartCtrl", function( $scope, $rootScope, $ionicPopup, $ionicHistory, $ionicSideMenuDelegate, $state, sharedCartService, openHours, empresa ) { $scope.cart = sharedCartService.cart; $scope.promos = sharedCartService.cartPromo; $scope.total = sharedCartService.total_amount; $scope.vacio = !(sharedCartService.total_qty > 0); $scope.llevaAderezo = sharedCartService.qtyAderezo > 0; $scope.parametros = {}; $scope.aderezos = {}; $scope.item = { aclaracion: sharedCartService.aclaraciones, aderezos: sharedCartService.aderezos, }; $scope.descuento = sharedCartService.calcularDescuento(); empresa.getParametros().success(function(response) { $scope.parametros = response.data; }); empresa.getHorarios().success(function(response) { $scope.days = response.data; var respuesta = openHours.isOpen($scope.days); $rootScope.open = respuesta.valor; $scope.message = respuesta.message; }); empresa.getAderezos().success(function(response) { $scope.aderezos = response.data; }); // plus quantity $scope.addAclaracion = function(item) { var myPopup2 = $ionicPopup.show({ templateUrl: "templates/popup-aclaracion.html", title: "Aclaracion", scope: $scope, buttons: [ { text: "Cancelar" }, { text: "<b>Aceptar</b>", type: "button-assertive", onTap: function(e) { return item.aclaracion; }, }, ], }); myPopup2.then(function(res) { item.aclaracion = res; sharedCartService.aclaraciones = item.aclaracion; }); }; $scope.selAderezos = function(item) { if ($scope.aderezos.length > 0) { var myPopup = $ionicPopup.show({ templateUrl: "templates/popup-aderezos.html", title: "Elija sus Aderezos", scope: $scope, buttons: [ { text: "Cancelar" }, { text: "<b>Guardar</b>", type: "button-assertive", onTap: function(e) { var texAde = ""; angular.forEach($scope.aderezos, function(aderezo) { if (aderezo.selected) { texAde += aderezo.ade_nombre + " "; } }); return texAde; }, }, ], }); myPopup.then(function(res) { if (res) { item.aderezos = res; sharedCartService.aderezos = item.aderezos; } else { item.aderezos = "Sin Aderezos"; sharedCartService.aderezos = item.aderezos; } }); } // An elaborate, custom popup }; // remove item from cart $scope.removeProd = function(index) { sharedCartService.cart.drop(index); $scope.total = sharedCartService.total_amount; $scope.cart = sharedCartService.cart; }; $scope.removePro = function(index) { sharedCartService.cartPromo.drop(index); $scope.total = sharedCartService.total_amount; $scope.promos = sharedCartService.cartPromo; }; $scope.checkOut = function() { $scope.total = sharedCartService.total_amount; if (!($rootScope.open && $scope.parametros.par_habilitado == 1)) { var alertPopup = $ionicPopup.alert({ title: "Atencion", template: "Por el momento no podemos recibir Pedidos por este Medio", }); alertPopup.then(function(res) { $state.go("home", {}, {}); }); } else { if ($scope.total >= $scope.parametros.par_pedidoMinimo) { if (sharedCartService.cartMitad.isEmpty()) { if ($scope.parametros.par_pagoHabilitado < 1) { $state.go("checkout", { 'DisablePago': true }, {}); } else $state.go("checkout", { 'DisablePago': false }, {}); } else { var alertPopup = $ionicPopup.alert({ title: "Atencion", template: "Falta Pedir Otra Media Pizza " + sharedCartService.cartMitad[0].variedad, }); } } else { var alertPopup = $ionicPopup.alert({ title: "Atencion", template: "Debe completar el Pedido Minimo", }); } } }; $scope.pedirComida = function() { $ionicHistory.nextViewOptions({ historyRoot: true, }); $ionicSideMenuDelegate.canDragContent(true); // Sets up the sideMenu dragable $state.go("home", {}, { location: "replace" }); }; });
function beautifulDays(i, j, k) { let count = 0; for (let x = i; x <= j; x++) { if (isBeautifulDay(x, k)) { count++; } } return count; } function isBeautifulDay(x, k) { return differenceOfReverse(x) % k === 0; } function differenceOfReverse(x) { let reversedX = parseInt( x .toString() .split('') .reverse() .join('') ); return Math.abs(x - reversedX); }
import Controller from './controller.js'; import '../../static/style.css'; const startGame = () => new Controller(); startGame(); export default startGame;
app.directive('range',function () { return { restrict: 'A', scope: true, link: function (scope, element, attrs) { scope.$slider = element.find('.b-filters__range-slider'); scope.$rangeFrom = element.find('.b-filters__range-input--from'); scope.$rangeTo = element.find('.b-filters__range-input--to'); var range = scope.$eval(attrs.range); scope.rangeValueFrom = range.rangeValueFrom; scope.rangeValueTo = range.rangeValueTo; scope.rangeValueStart = range.rangeValueStart; scope.rangeValueEnd = range.rangeValueEnd; scope.$slider.noUiSlider({ start: [ scope.rangeValueStart, scope.rangeValueEnd ], connect: true, range: { 'min': [ scope.rangeValueFrom ], 'max': [ scope.rangeValueTo ] }, serialization: { lower: [ $$.Link({ target: scope.$rangeFrom, format: { decimals: 0 } }) ], upper: [ $$.Link({ target: scope.$rangeTo, format: { decimals: 0 } }) ] } // behaviour: 'drag-tap', }); } }; });
const express=require("express"); const app=express(); const mongoose=require("mongoose"); const bodyParser=require("body-parser"); app.use(express.static("public")); app.set("view engine", "ejs"); app.use(bodyParser.urlencoded({extended: true})); mongoose.connect("mongodb://localhost:27017/erpDB",{ useNewUrlParser: true, useUnifiedTopology: true}); const facultySchema=new mongoose.Schema({ facultyID:String, password:String, name:String, emailID:String, education:String, subject:String, // image:String, }); const faculty=mongoose.model("faculty",facultySchema); module.exports = faculty;
(function() { var generateProxyTests = function(useComputed) { var moduleName = useComputed ? 'ProxyComputed' : 'ProxyDependentObservable'; module(moduleName); var func = function() { var result; result = useComputed ? ko.computed.apply(null, arguments) : ko.dependentObservable.apply(null, arguments); return result; }; testStart[moduleName] = function() { test = { evaluationCount: 0, writeEvaluationCount: 0 }; test.create = function(createOptions) { var obj = { a: "b" }; var mapping = { a: { create: function(options) { createOptions = createOptions || {}; var mapped = ko.mapping.fromJS(options.data, mapping); var DOdata = function() { test.evaluationCount++; return "test"; }; if (createOptions.useReadCallback) { mapped.DO = func({ read: DOdata, deferEvaluation: !!createOptions.deferEvaluation }, mapped); } else if (createOptions.useWriteCallback) { mapped.DO = func({ read: DOdata, write: function(value) { test.written = value; test.writeEvaluationCount++; }, deferEvaluation: !!createOptions.deferEvaluation }, mapped); } else { mapped.DO = func(DOdata, mapped, { deferEvaluation: !!createOptions.deferEvaluation }); } return mapped; } } }; return ko.mapping.fromJS(obj, mapping); }; }; test('ko.mapping.fromJS should handle interdependent dependent observables in objects', function() { var obj = { a: { a1: "a1" }, b: { b1: "b1" } } var dependencyInvocations = []; var result = ko.mapping.fromJS(obj, { a: { create: function(options) { return { a1: ko.observable(options.data.a1), observeB: func(function() { dependencyInvocations.push("a"); return options.parent.b.b1(); }) } } }, b: { create: function(options) { return { b1: ko.observable(options.data.b1), observeA: func(function() { dependencyInvocations.push("b"); return options.parent.a.a1(); }) } }, } }); equal("b1", result.a.observeB()); equal("a1", result.b.observeA()); }); test('ko.mapping.fromJS should handle interdependent dependent observables with read/write callbacks in objects', function() { var obj = { a: { a1: "a1" }, b: { b1: "b1" } } var dependencyInvocations = []; var result = ko.mapping.fromJS(obj, { a: { create: function(options) { return { a1: ko.observable(options.data.a1), observeB: func({ read: function() { dependencyInvocations.push("a"); return options.parent.b.b1(); }, write: function(value) { options.parent.b.b1(value); } }) } } }, b: { create: function(options) { return { b1: ko.observable(options.data.b1), observeA: func({ read: function() { dependencyInvocations.push("b"); return options.parent.a.a1(); }, write: function(value) { options.parent.a.a1(value); } }) } }, } }); equal(result.a.observeB(), "b1"); equal(result.b.observeA(), "a1"); result.a.observeB("b2"); result.b.observeA("a2"); equal(result.a.observeB(), "b2"); equal(result.b.observeA(), "a2"); }); test('ko.mapping.fromJS should handle dependent observables in arrays', function() { var obj = { items: [ { id: "a" }, { id: "b" } ] } var dependencyInvocations = 0; var result = ko.mapping.fromJS(obj, { "items": { create: function(options) { return { id: ko.observable(options.data.id), observeParent: func(function() { dependencyInvocations++; return options.parent.items().length; }) } } } }); equal(result.items()[0].observeParent(), 2); equal(result.items()[1].observeParent(), 2); }); test('nested calls to mapping should not revert proxyDependentObservable multiple times', function() { var vmjs = { "inner1": { "inner2": { } } } var vm = undefined; var mapping = { "inner1": { "create": function(options) { //use the same mapping object to map inner2 var that = ko.mapping.fromJS(options.data, mapping); that.DOprop = func(function() { // if the DO is evaluated straight away, this will return undefined return vm; }); return that; } }, "inner2": { "create": function(options) { var that = ko.mapping.fromJS(options.data); return that; } } }; var vm = ko.mapping.fromJS(vmjs, mapping); equal(vm.inner1.DOprop(), vm); }); test('dependentObservables with a write callback are passed through', function() { var mapped = test.create({ useWriteCallback: true }); equal(mapped.a.DO.hasWriteFunction, true); mapped.a.DO("hello"); equal(test.written, "hello"); equal(test.writeEvaluationCount, 1); }); test('dependentObservables without a write callback do not get a write callback', function() { var mapped = test.create({ useWriteCallback: false }); equal(mapped.a.DO.hasWriteFunction, false); }); asyncTest('undeferred dependentObservables that are NOT used immediately SHOULD be auto-evaluated after mapping', function() { var mapped = test.create(); window.setTimeout(function() { start(); equal(test.evaluationCount, 1); }, 0); }); asyncTest('undeferred dependentObservables that ARE used immediately should NOT be auto-evaluated after mapping', function() { var mapped = test.create(); equal(ko.utils.unwrapObservable(mapped.a.DO), "test"); window.setTimeout(function() { start(); equal(test.evaluationCount, 1); }, 0); }); asyncTest('deferred dependentObservables should NOT be auto-evaluated after mapping', function() { var mapped = test.create({ deferEvaluation: true }); window.setTimeout(function() { start(); equal(test.evaluationCount, 0); }, 0); }); asyncTest('undeferred dependentObservables with read callback that are NOT used immediately SHOULD be auto-evaluated after mapping', function() { var mapped = test.create({ useReadCallback: true }); window.setTimeout(function() { start(); equal(test.evaluationCount, 1); }, 0); }); asyncTest('undeferred dependentObservables with read callback that ARE used immediately should NOT be auto-evaluated after mapping', function() { var mapped = test.create({ useReadCallback: true }); equal(ko.utils.unwrapObservable(mapped.a.DO), "test"); window.setTimeout(function() { start(); equal(test.evaluationCount, 1); }, 0); }); asyncTest('deferred dependentObservables with read callback should NOT be auto-evaluated after mapping', function() { var mapped = test.create({ deferEvaluation: true, useReadCallback: true }); window.setTimeout(function() { start(); equal(test.evaluationCount, 0); }, 0); }); test('can subscribe to proxy dependentObservable', function() { var mapped = test.create({ deferEvaluation: true, useReadCallback: true }); mapped.a.DO.subscribe(function() { }); }); test('can subscribe to nested proxy dependentObservable', function() { var obj = { a: { b: null } }; var DOsubscribedVal; var mapping = { a: { create: function(options) { var mappedB = ko.mapping.fromJS(options.data, { create: function(options) { var DOval; var m = {}; m.myValue = ko.observable("myValue"); m.DO = func({ read: function() { return DOval; }, write: function(val) { DOval = val; } }); m.readOnlyDO = func(function() { return m.myValue(); }); return m; } }); mappedB.DO.subscribe(function(val) { DOsubscribedVal = val; }); return mappedB; } } }; var mapped = ko.mapping.fromJS(obj, mapping); mapped.a.DO("bob"); equal(ko.utils.unwrapObservable(mapped.a.readOnlyDO), "myValue"); equal(ko.utils.unwrapObservable(mapped.a.DO), "bob"); equal(DOsubscribedVal, "bob"); }); asyncTest('dependentObservable dependencies trigger subscribers', function() { var obj = { inner: { dependency: 1 } }; var inner = function(data) { var _this = this; ko.mapping.fromJS(data, {}, _this); _this.DO = func(function() { _this.dependency(); }); _this.evaluationCount = 0; _this.DO.subscribe(function() { _this.evaluationCount++; }); }; var mapping = { inner: { create: function(options) { return new inner(options.data); } } }; var mapped = ko.mapping.fromJS(obj, mapping); var i = mapped.inner; equal(i.evaluationCount, 0); window.setTimeout(function() { start(); // after the timeout, the DO is already evaluated once by the mapping plugin, causing the subscription to update equal(i.evaluationCount, 1); // change the dependency i.dependency(2); // should also have re-evaluated equal(i.evaluationCount, 2); }); }); test('dependentObservable.fn extensions are not missing during mapping', function() { var obj = { x: 1 }; var model = function(data) { var _this = this; ko.mapping.fromJS(data, {}, _this); _this.DO = func(_this.x); }; var mapping = { create: function(options) { return new model(options.data); } }; ko.dependentObservable.fn.myExtension = true; var mapped = ko.mapping.fromJS(obj, mapping); equal(mapped.DO.myExtension, true) }); test('Dont wrap dependent observables if already marked as deferEvaluation', function() { var obj = { x: 1 }; var model = function(data) { var _this = this; ko.mapping.fromJS(data, {}, _this); _this.DO1 = func(_this.x, null, {deferEvaluation: true}); _this.DO2 = func({read: _this.x, deferEvaluation: true}); _this.DO3 = func(_this.x); }; var mapping = { create: function(options) { return new model(options.data); } }; var mapped = ko.mapping.fromJS(obj, mapping); equal(mapped.DO1._wrapper, undefined); equal(mapped.DO2._wrapper, undefined); equal(mapped.DO3._wrapper, true); }); test('ko.mapping.updateViewModel should allow for the avoidance of adding an item to its parent observableArray', function() { var obj = { items: [ { id: "a" }, { id: "b" } ] } var dependencyInvocations = 0; var result = ko.mapping.fromJS(obj, { "items": { create: function(options) { if (options.data.id == "b") return options.data; else return options.skip; } } }); equal(result.items().length, 1); equal(result.items()[0].id, "b"); }); //unit test for updating existing arrays (e.g. first item is retained, second item is skipped and the third item gets added)? test('ko.mapping.updateViewModel skipping an item should retain all other items', function() { var obj = { items: [ { id: "a" }, { id: "b" }, { id: "c" } ] } var dependencyInvocations = 0; var result = ko.mapping.fromJS(obj, { "items": { create: function(options) { debugger; if (options.data.id == "b") return options.skip; else return options.data; } } }); equal(result.items().length, 2); equal(result.items()[0].id, "a"); equal(result.items()[1].id, "c"); }); }; generateProxyTests(false); generateProxyTests(true); })();
$(() => { // prompt层 layer.prompt({ title: '请输入昵称', offset: ['200px', '400px'], skin: 'layui-layer-lan', // success:function(layero,index){ // $(".layui-layer-input").on('keydown',function(e){ // if(e.which === 13){ // name=$('.layui-layer-input').val(); // layer.close(index); // } // }); // }, }, (value, index) => { layer.close(index); const name = value; if ($.trim(name).length > 0) { $('#m').focus(); // 聊天开始 const socket = io(); // 定义一个私聊公聊的变量吧 socket.emit('user connection', name); $('button').click(() => { // 非空验证 if ($('#m').val().length > 0) { socket.emit('chat message', $('#m').val()); $('#m').val(''); } // return 去掉的话,页面会刷新 return false; }); // 头像点击事件 ,直接开始私聊 $('body').on('click', '#messages .avatar', function () { const id = $(this).attr('data-id'); socket.emit('whisper-1', id); }); // 接收到服务器的消息,被请求的客户端有个confirm // second是to的窗口 socket.on('whisper-2', msg => { layer.confirm(`有个叫 ${msg.user.name} 的人想和你私聊,是否同意?`, { skin: 'layui-layer-lan', }, i => { layer.close(i); // 同意,先发送同意消息,然后打开一个聊天的layer socket.emit('whisper-3', { to: msg.to, from: msg.from, }); // 打开一个私聊窗口,里面只有from和to两个人 layer.open({ type: 1, area: ['500px', '600px'], title: `与 ${msg.user.name} 的私聊窗口`, move: false, skin: 'layui-layer-lan', // 加上边框 shift: 2, content: `<ul id="si"> <li class="users-in-out">你们的私聊已经开始</li> </ul> <form class="s"><input id="s" autocomplete="off" /> <button>发送</button></form>`, success: () => { $('.s button').click(() => { if ($('#s').val().length > 0) { socket.emit('whisper-5', { to: msg.to, from: msg.from, chatMsg: $('#s').val(), }); $('#s').val(''); } return false; }); }, // 如果to方关闭 end: () => { socket.emit('whisper-8', { to: msg.to, from: msg.from, }); }, }); }); }); // forth是from的窗口 socket.on('whisper-4', msg => { // 打开一个私聊窗口,里面只有from和to两个人 layer.open({ type: 1, area: ['500px', '600px'], title: `与 ${msg.user.name} 的私聊窗口`, move: false, skin: 'layui-layer-lan', // 加上边框 shift: 2, content: `<ul id="si"> <li class="users-in-out">你们的私聊已经开始</li> </ul><form class="s"> <input id="s" autocomplete="off" /> <button>发送</button></form>`, success: () => { $('.s button').click(() => { if ($('#s').val().length > 0) { socket.emit('whisper-7', { to: msg.to, from: msg.from, chatMsg: $('#s').val(), }); $('#s').val(''); } return false; }); }, // 如果from方关闭 end: () => { socket.emit('whisper-10', { to: msg.to, from: msg.from, }); }, }); }); // sixth是接收到服务器的消息,然后展现在私聊框的,不管有自己的还是别人的 socket.on('whisper-6', msg => { $('#si').append( `<li> <div class="avatar" data-id="${msg.user.id}"> <img src="imgs/${msg.user.avatar}.jpg" alt="头像" /> <p class="name">${msg.user.name}<p> </div> <div class="chat"> <span class="tan"></span> <p>${msg.msg}</p> </div> </li>`); $('.layui-layer-content').animate({ scrollTop: $(document).height() }, 400); }); // ninth是当有一方关闭窗口时,另一方接收到的消息 socket.on('whisper-9', msg => { $('#si').append($('<li class="users-in-out">').text(`${msg.user.name} 已经退出了私聊`)); $('.layui-layer-content').animate({ scrollTop: $(document).height() }, 400); }); // 开始公开聊天 socket.on('chat message', msg => { $('#messages').append( `<li> <div class="avatar" data-id="${msg.user.id}"> <img src="imgs/${msg.user.avatar}.jpg" alt="头像" /> <p class="name">${msg.user.name}<p> </div> <div class="chat"> <p class="time">${msg.createdAt}</p>${msg.msg} </div> </li>`); $('html, body, #message').animate({ scrollTop: $(document).height() }, 400); }); socket.on('hi', msg => { $('#messages').append($('<li class="users-in-out">').text(msg)); $('html, body, #message').animate({ scrollTop: $(document).height() }, 400); }); } }); });
angular.module('entraide').directive('animStar', function(){ return { restrict: 'AE', templateUrl: 'client/app/common/directives/anim-star/anim-star.ng.html', scope: { currentRating: '=', maxRating : '=', callback: '&', callbackArguments: '=' }, compile: function(element, attrs) { return function link(scope, elt) { scope.currentRating = scope.currentRating ? scope.currentRating : 0; scope.maxRating = scope.maxRating ? scope.maxRating : 5; var callback = function(rating){ scope.callback()(rating, scope.callbackArguments); }; rating(elt.find('#anim-star-container')[0], scope.currentRating, scope.maxRating, callback); }; } }; });
context('miscellaneous.spec', () => { it('Write to file', () => { cy.writeFile('cypress/fixtures/data.json', { name: 'Eliza', email1: 'eliza@example.com' }) .then((user) => { expect(user.name).to.equal('Eliza') }) }) })
/** * LINKURIOUS CONFIDENTIAL * Copyright Linkurious SAS 2012 - 2018 * * - Created on 2016-11-25. */ 'use strict'; // external libs const Promise = require('bluebird'); const jwt = require('jsonwebtoken'); const _ = require('lodash'); // locals const AbstractOAuth2 = require('./abstractoauth2'); const LkRequest = require('./../../../../lib/LkRequest'); // services const LKE = require('./../../../index'); const Utils = LKE.getUtils(); const Errors = LKE.getErrors(); class OpenIDConnect extends AbstractOAuth2 { /** * @param {{userinfoURL?: string, scope?: string, groupClaim?: string}} oidcConf */ constructor(oidcConf) { super(); oidcConf = _.defaults(oidcConf, {}); const userDefinedScope = Utils.hasValue(oidcConf.scope) ? oidcConf.scope.split(' ') : []; this._scope = _.union(['openid', 'profile', 'email'], userDefinedScope).join(' '); this._userinfoURL = oidcConf.userinfoURL; this._groupClaim = oidcConf.groupClaim; if (Utils.hasValue(this._groupClaim) && Utils.noValue(this._userinfoURL)) { throw Errors.business( 'invalid_parameter', 'access.oauth2.openidconnect.groupClaim is set ' + 'but access.oauth2.openidconnect.userinfoURL is missing.' ); } if (Utils.hasValue(this._userinfoURL)) { this._request = new LkRequest({baseUrl: this._userinfoURL, json: true}); } } /** * The OAuth2 scope. * * @returns {string} scope */ getScope() { return this._scope; } /** * Retrieve username and email of the user by parsing the ID token inside response. * * @param {{access_token: string, id_token: string}} response * @returns {Bluebird<ExternalUserProfile>} */ getProfileData(response) { const decodedIDToken = jwt.decode(response.id_token); // no need to validate the ID token, since it's taken directly from the provider (hopefully) via secure HTTP const email = decodedIDToken.email; const username = decodedIDToken.name || decodedIDToken.email; if (Utils.hasValue(this._groupClaim)) { return this._request.get('', { headers: { Authorization: 'Bearer ' + response.access_token } }).then(r => { const externalGroupIds = r.body[this._groupClaim] || []; return { username: username, email: email, externalGroupIds: externalGroupIds }; }); } else { return Promise.resolve({username: username, email: email}); } } } module.exports = OpenIDConnect;
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Crypto Test Harness - AES (c) Chris Veness 2014-2018 */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ import Aes from '../aes.js'; import AesCtr from '../aes-ctr.js'; // import chai from 'chai'; // BDD/TDD assertion library - uncomment for Node.js tests chai.should(); // just for this test suite! String.prototype.toBytes = function() { return this.replace(/ /g, '').match(/(..?)/g).map(b => parseInt('0x'+b)); }; String.prototype.toWords = function() { return this.split(/ /).map(w => w.match(/(..?)/g).map(b => parseInt('0x'+b))); }; Array.prototype.toByteStr = function() { return this.map(b => b.toString(16).padStart(2, '0')).join(' '); }; Array.prototype.toWordStr = function() { return this.map(w => w.map(b => b.toString(16).padStart(2, '0')).join('')).join(' '); }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* AES - test vectors: csrc.nist.gov/publications/fips/fips197/fips-197.pdf appendices A, C */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ describe('nist fips 197 §a key expansion', function() { this.slow(2); // 2 ms const key128 = '2b 7e 15 16 28 ae d2 a6 ab f7 15 88 09 cf 4f 3c'; const schedule128 = '2b7e1516 28aed2a6 abf71588 09cf4f3c'; // 1st 4 words const key192 = '8e 73 b0 f7 da 0e 64 52 c8 10 f3 2b 80 90 79 e5 62 f8 ea d2 52 2c 6b 7b'; const schedule192 = '8e73b0f7 da0e6452 c810f32b 809079e5 62f8ead2 522c6b7b'; // 1st 6 words const key256 = '60 3d eb 10 15 ca 71 be 2b 73 ae f0 85 7d 77 81 1f 35 2c 07 3b 61 08 d7 2d 98 10 a3 09 14 df f4'; const schedule256 = '603deb10 15ca71be 2b73aef0 857d7781 1f352c07 3b6108d7 2d9810a3 0914dff4'; // 1st 8 words it('Aes-128-bit key expansion test vector', function() { Aes.keyExpansion(key128.toBytes()).slice(0, 4).should.deep.equal(schedule128.toWords()); }); it('Aes-192-bit key expansion test vector', function() { Aes.keyExpansion(key192.toBytes()).slice(0, 6).should.deep.equal(schedule192.toWords()); }); it('Aes-256-bit key expansion test vector', function() { Aes.keyExpansion(key256.toBytes()).slice(0, 8).should.deep.equal(schedule256.toWords()); }); }); describe('nist fips 197 §c aes vectors', function() { this.slow(2); // 2 ms const plaintext = '00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff'; const key128 = '00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f'; const cipher128 = '69 c4 e0 d8 6a 7b 04 30 d8 cd b7 80 70 b4 c5 5a'; const key192 = '00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17'; const cipher192 = 'dd a9 7c a4 86 4c df e0 6e af 70 a0 ec 0d 71 91'; const key256 = '00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f'; const cipher256 = '8e a2 b7 ca 51 67 45 bf ea fc 49 90 4b 49 60 89'; it('Aes-128-bit cipher test vector', function() { Aes.cipher(plaintext.toBytes(), Aes.keyExpansion(key128.toBytes())).should.deep.equal(cipher128.toBytes()); }); it('Aes-192-bit cipher test vector', function() { Aes.cipher(plaintext.toBytes(), Aes.keyExpansion(key192.toBytes())).should.deep.equal(cipher192.toBytes()); }); it('Aes-256-bit cipher test vector', function() { Aes.cipher(plaintext.toBytes(), Aes.keyExpansion(key256.toBytes())).should.deep.equal(cipher256.toBytes()); }); }); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* NIST AES-CTR - test vectors: csrc.nist.gov/publications/detail/sp/800-38a/final */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ describe('nist sp 800-38a aes-ctr example vectors', function() { this.slow(4); // 4 ms const counter = 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'; const plaintext = '6bc1bee22e409f96e93d7e117393172a'+ 'ae2d8a571e03ac9c9eb76fac45af8e51'+ '30c81c46a35ce411e5fbc1191a0a52ef'+ 'f69f2445df4f9b17ad2b417be66c3710'; it('verifies CTR-AES128.Encrypt §F.5.1, CTR-AES128.Decrypt §F.5.2', function() { const key128 = '2b7e151628aed2a6abf7158809cf4f3c'; const ciphertext128 = '874d6191b620e3261bef6864990db6ce'+ '9806f66b7970fdff8617187bb9fffdff'+ '5ae4df3edbd5d35e5b4f09020db03eab'+ '1e031dda2fbe03d1792170a0f3009cee'; AesCtr.nistEncryption(plaintext.toBytes(), key128.toBytes(), counter.toBytes()).should.deep.equal(ciphertext128.toBytes()); AesCtr.nistDecryption(ciphertext128.toBytes(), key128.toBytes(), counter.toBytes()).should.deep.equal(plaintext.toBytes()); }); it('verifies CTR-AES192.Encrypt §F.5.3, CTR-AES192.Decrypt §F.5.4', function() { const key192 = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'; const ciphertext192 = '1abc932417521ca24f2b0459fe7e6e0b'+ '090339ec0aa6faefd5ccc2c6f4ce8e94'+ '1e36b26bd1ebc670d1bd1d665620abf7'+ '4f78a7f6d29809585a97daec58c6b050'; AesCtr.nistEncryption(plaintext.toBytes(), key192.toBytes(), counter.toBytes()).should.deep.equal(ciphertext192.toBytes()); AesCtr.nistDecryption(ciphertext192.toBytes(), key192.toBytes(), counter.toBytes()).should.deep.equal(plaintext.toBytes()); }); it('verifies CTR-AES256.Encrypt §F.5.5, CTR-AES256.Decrypt §F.5.6', function() { const key256 = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'; const ciphertext256 = '601ec313775789a5b7a7f504bbf3d228'+ 'f443e3ca4d62b59aca84e990cacaf5c5'+ '2b0930daa23de94ce87017ba2d84988d'+ 'dfc9c58db67aada613c2dd08457941a6'; AesCtr.nistEncryption(plaintext.toBytes(), key256.toBytes(), counter.toBytes()).should.deep.equal(ciphertext256.toBytes()); AesCtr.nistDecryption(ciphertext256.toBytes(), key256.toBytes(), counter.toBytes()).should.deep.equal(plaintext.toBytes()); }); }); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Aes CTR: test Unicode text & password (ciphertext will be different on each invocation) */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ describe('aes.ctr', function() { this.timeout(10e3); // 10 sec describe('unicode plaintext/password', function() { this.slow(4); // 4 ms const origtext = 'My big secret סוד קצת بت سرية ความลับบิต 位的秘密'; const password = 'pāšşŵōřđ'; it('en/decrypts ciphertext to match original (unicode) text @ 128', function() { const ciphertext128 = AesCtr.encrypt(origtext, password, 128); const decrypttext128 = AesCtr.decrypt(ciphertext128, password, 128); decrypttext128.should.equal(origtext); }); it('en/decrypts ciphertext to match original (unicode) text @ 192', function() { const ciphertext192 = AesCtr.encrypt(origtext, password, 192); const decrypttext192 = AesCtr.decrypt(ciphertext192, password, 192); decrypttext192.should.equal(origtext); }); it('en/decrypts ciphertext to match original (unicode) text @ 256', function() { const ciphertext256 = AesCtr.encrypt(origtext, password, 256); const decrypttext256 = AesCtr.decrypt(ciphertext256, password, 256); decrypttext256.should.equal(origtext); }); }); describe('various lengths of plaintext', function() { this.slow(8); // 8 ms const password = Date().toString(); const plaintext1 = '0'; it('en/decrypts string of 1 @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1, password, 128), password, 128).should.equal(plaintext1); }); it('en/decrypts string of 1 @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1, password, 192), password, 192).should.equal(plaintext1); }); it('en/decrypts string of 1 @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1, password, 256), password, 256).should.equal(plaintext1); }); const plaintext10 = '0123456789'; it('en/decrypts string of 10 @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext10, password, 128), password, 128).should.equal(plaintext10); }); it('en/decrypts string of 10 @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext10, password, 192), password, 192).should.equal(plaintext10); }); it('en/decrypts string of 10 @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext10, password, 256), password, 256).should.equal(plaintext10); }); const plaintext100 = plaintext10.repeat(10); it('en/decrypts string of 100 @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext100, password, 128), password, 128).should.equal(plaintext100); }); it('en/decrypts string of 100 @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext100, password, 192), password, 192).should.equal(plaintext100); }); it('en/decrypts string of 100 @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext100, password, 256), password, 256).should.equal(plaintext100); }); const plaintext1k = plaintext100.repeat(10); it('en/decrypts string of 1k @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1k, password, 128), password, 128).should.equal(plaintext1k); }); it('en/decrypts string of 1k @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1k, password, 192), password, 192).should.equal(plaintext1k); }); it('en/decrypts string of 1k @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1k, password, 256), password, 256).should.equal(plaintext1k); }); const plaintext10k = plaintext1k.repeat(10); it('en/decrypts string of 10k @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext10k, password, 128), password, 128).should.equal(plaintext10k); }); it('en/decrypts string of 10k @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext10k, password, 192), password, 192).should.equal(plaintext10k); }); it('en/decrypts string of 10k @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext10k, password, 256), password, 256).should.equal(plaintext10k); }); const plaintext100k = plaintext10k.repeat(10); it('en/decrypts string of 100k @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext100k, password, 128), password, 128).should.equal(plaintext100k); }); it('en/decrypts string of 100k @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext100k, password, 192), password, 192).should.equal(plaintext100k); }); it('en/decrypts string of 100k @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext100k, password, 256), password, 256).should.equal(plaintext100k); }); const plaintext1M = plaintext100k.repeat(10); it('en/decrypts string of 1M @ 128', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1M, password, 128), password, 128).should.equal(plaintext1M); }); it('en/decrypts string of 1M @ 192', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1M, password, 192), password, 192).should.equal(plaintext1M); }); it('en/decrypts string of 1M @ 256', function() { AesCtr.decrypt(AesCtr.encrypt(plaintext1M, password, 256), password, 256).should.equal(plaintext1M); }); }); }); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
(function (window) { var speakWord = "Good Bye"; byeSpeaker = {}; // Created an object byeSpeaker.speak = function (name) { // Attached the speak method and linked it with the given function. console.log(speakWord + " " + name); // print Good Bye + space + name content of the function`s input. } window.byeSpeaker = bySpeaker; // Exposed the byeSpeaker object to the global scope. })(window)
import { variant } from './db/variant'; import { columns } from './db/columns' export { variant, columns };
"use strict"; module.exports = { "appurl": "https://www.way2automation.com/angularjs-protractor/banking/#/login", "customers": { "firstname": "Manas", "lastname": "Panigrahi", "postalcode": "12345" }, "customers2": { "firstname": "Abhai", "lastname": "Kumar", "postalcode": "345678" }, "customers3": { "firstname": "Vamsi", "lastname": "Dhar", "postalcode": "456789" } };
import styled from 'styled-components'; import { tokens } from '@sparkpost/design-tokens'; import { Box } from '../Box'; import { focusOutline } from '../../styles/helpers'; const inputHeight = '2.5rem'; export const StyledInputWrapper = styled(Box)` display: flex; flex-wrap: wrap; background: ${props => (props.isDisabled ? tokens.color_gray_200 : tokens.color_white)}; border: ${props => props.hasError ? `${tokens.borderWidth_100} solid ${tokens.color_red_700}` : `${tokens.borderWidth_100} solid ${tokens.color_gray_400}`}; border-radius: ${tokens.borderRadius_100}; min-height: ${inputHeight}; ${focusOutline({ modifier: '&:focus-within' })} `; export const StyledInput = styled('input')` display: inline-block; flex: 1; background: none; border: none; outline: none; padding-left: ${tokens.spacing_300}; padding-right: ${tokens.spacing_300}; line-height: calc(${inputHeight} - 2px); height: calc(${inputHeight} - 2px); font-weight: ${tokens.fontWeight_normal}; color: ${tokens.color_gray_900}; &:disabled { cursor: not-allowed; } `;
'use strict'; angular.module('Users', []).controller('UserController', function($scope, UserService){ $scope.initialize = function(){ UserService.getUserInformation().then(function(response){ $scope.user = response.data; }); }; }).factory('UserService', function($http){ return { getUserInformation: function(){ return $http.get('/users'); } } });
import React, { Component } from 'react'; import SideBar from './sideBar'; import Post from './post'; import PostList from './postList'; import Homepage from './homepage.js'; class ContentArea extends Component { constructor(props) { super(props); this.state = { postData: false }; } renderContent = () => { //debugger; if (this.props.postData) { return ( <Post onPostSelect={this.props.onPostSelect} postListData={this.props.postListData} postData={this.props.postData} /> ) } return ( <div> <Homepage onMenuSelect={this.props.onMenuSelect} /> <div className='latest-articles-container'> <PostList onPostSelect={this.props.onPostSelect} postListData={this.props.postListData} /> </div> </div> ) } render() { return ( <div className='col-md-12' id='content-area'> {this.renderContent()} </div> ); } } export default ContentArea;
/****************** * CONFIG SECTION * * configure confidential data in config.json * an example is in config.json.dist ******************/ var config = require("./config.json"); /** * Here you can add depencencies, which will be concatenated to the main.min.js, * css or html file respectively * Only add dependencies from node_modules or lib folder * everything else is read automatically */ config.jsDeps = [ //javascript dependencies 'node_modules/webcomponents.js/webcomponents-lite.min.js', 'node_modules/promise-polyfill/promise.min.js', 'node_modules/yapl/index.js', 'src/js/lib/whenAll.jQuery.js', ]; config.cssDeps = [ //css dependencies 'node_modules/select2/dist/css/select2.min.css', ]; config.expaDeps = [ //html dependencies 'src/lib/webcomponents-polyfill.html', 'src/lib/columnView.html', 'src/lib/sortableTable.html', ]; config.opDeps = [ //html dependencies 'src/lib/webcomponents-polyfill.html', ]; /****************** * GULP Section ******************/ var gulp = require('gulp'), ts = require('gulp-typescript'), uglify = require('gulp-uglify'), jsPrettify = require('gulp-js-prettify'), y = require('yapl'), cssPrettify = require('gulp-cssbeautify'), concat = require('gulp-concat'), file = require('gulp-file'), diff = require('gulp-diff'), sourcemaps = require('gulp-sourcemaps'), readdir = require('recursive-readdir'), path = require('path'), sftp = require('gulp-sftp'), childProcess = require('child_process'), fs = require('fs'), expa = require('node-gis-wrapper')(config.expa.user, config.expa.password); function errorlog(err) { console.log(err); this.emit('end'); } // files will be ignored based on this filter function ignoreFunc(file, stats) { // `file` is the absolute path to the file, and `stats` is an `fs.Stats` // object returned from `fs.lstat()`. return (stats.isDirectory() && path.basename(file) == "lib") //ignore files in config dir, include them specifically depending on environment || (stats.isDirectory() && path.basename(file) == "config") // ignore files not ending in js/html || (stats.isFile() && !path.extname(file).match("ts|js|html")); } // Scripts Task gulp.task('scripts', function(){ var def = y(); //copy init script gulp.src('./src/js/timInit.js') .pipe(ts({ noImplicitAny: true, target: 'ES5', allowJs: true, out: 'timInit.js' })) .pipe(uglify()) .pipe(gulp.dest('bin')); //ignore timInit.js, tim.js as they need to be in a specific order //ignoreFunc ignores lib files readdir('src/js', ['timInit.js', 'tim.js', ignoreFunc], function (err, files) { // files is an array of filename files = config.jsDeps.concat('src/js/tim.js', 'src/js/config/dev.js').concat(files); //concat and copy all other scripts according to config above var t = gulp.src(files) .pipe(sourcemaps.init()) .pipe(ts({ noImplicitAny: true, target: 'ES5', allowJs: true, out: 'main.min.js' })) .pipe(uglify()) .pipe(sourcemaps.write('bin')) .pipe(gulp.dest('bin')); def.resolve(t); }); return def; }); gulp.task('scripts-prod', function(){ //copy init script gulp.src('./src/js/timInit.js') .pipe(gulp.dest('bin')); //ignore timInit.js, tim.js as they need to be in a specific order //ignoreFunc ignores lib files readdir('src/js', ['timInit.js', 'tim.js', ignoreFunc], function (err, files) { // files is an array of filename files = config.jsDeps.concat(['src/js/tim.js', 'src/js/config/prod.js']).concat(files); //concat and copy all other scripts according to config above gulp.src(files) .pipe(sourcemaps.init()) .pipe(ts({ noImplicitAny: true, allowJs: true, target: 'ES5', out: 'main.min.js' })) .pipe(uglify()) .pipe(sourcemaps.write('bin')) .pipe(gulp.dest('bin')); }); }); //html task: concatenate html gulp.task('html', function(){ // build html for experience portal readdir('src/expa', [ignoreFunc], function (err, files) { if(typeof files == 'undefined') files = []; files = config.expaDeps.concat(files.reverse()); gulp.src(files) .pipe(concat('expa.html')) .on('error', errorlog) .pipe(gulp.dest('bin')); }); //build html for opportunities portal readdir('src/op', [ignoreFunc], function (err, files) { if(typeof files == 'undefined') files = []; files = config.expaDeps.concat(files.reverse()); gulp.src(files) .pipe(concat('op.html')) .on('error', errorlog) .pipe(gulp.dest('bin')); }); }); gulp.task('html-prod', function(){ readdir('src/expa', [ //ignore these files for live version 'test.html', 'src/html/bookmarklets/*.html', 'src/expa/analytics/analytics-SnS.html', 'src/expa/analytics/addSnS.html', ignoreFunc], function (err, files) { if(typeof files == 'undefined') files = []; files = config.expaDeps.concat(files.reverse()); gulp.src(files) .pipe(concat('expa.html')) .on('error', errorlog) .pipe(gulp.dest('bin')); }); //build html for opportunities portal readdir('src/op', [ //ignore these files for live version 'test.html', 'src/op/profile-applications-agb.html', ignoreFunc], function (err, files) { if(typeof files == 'undefined') files = []; files = config.expaDeps.concat(files.reverse()); gulp.src(files) .pipe(concat('op.html')) .on('error', errorlog) .pipe(gulp.dest('bin')); }); }); //css task: concatenate css gulp.task('css', function(){ readdir('src/css', [ignoreFunc], function (err, files) { files = config.cssDeps.concat(files); gulp.src(files) .pipe(concat('style.css')) .on('error', errorlog) .pipe(gulp.dest('bin')); }); }); // Watch Task gulp.task('watch', function(){ gulp.watch('src/js/**/*.js', ['scripts']); gulp.watch('src/css/**/*.css', ['css']); gulp.watch('src/op/**/*.html', ['html']); gulp.watch('src/expa/**/*.html', ['html']); }); //build and deploy to server gulp.task('deploy-expa', ['css', 'html-prod', 'scripts-prod'], function(){ return gulp.src(['bin/style.css', 'bin/expa.html', 'bin/main.min.js']) .pipe(sftp({ host: config.server.host, user: config.server.user, remotePath: config.server.livePath, agent: process.env.SSH_AUTH_SOCK, agentForward: true })); }); //build and deploy to server gulp.task('deploy-op', ['css', 'html-prod', 'scripts-prod'], function(){ return gulp.src(['bin/style.css', 'bin/op.html', 'bin/main.min.js']) .pipe(sftp({ host: config.server.host, user: config.server.user, remotePath: config.server.livePath, agent: process.env.SSH_AUTH_SOCK, agentForward: true })); }); gulp.task('docs', function(){ //only generate docs if tim-docs is accessible fs.access('../tim-docs', fs.F_OK, function(err) { if (!err) { childProcess.exec('node_modules/.bin/jsdoc -c jsdoc.json', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); }); } else { console.log("did not generate docs. no access to tim-docs directory"); } }); }); gulp.task('check-expa', function(){ var saveScript = function(name){ if(name.indexOf('.css') > 0) { return function(content){ console.log(`Write ${name}`); file(name, content, { src: true }) .pipe(cssPrettify()) .pipe(gulp.dest('test/expa_src')); }; } else { return function(content){ console.log(`Write ${name}`); file(name, content, { src: true }) .pipe(jsPrettify({collapseWhitespace: true})) .pipe(gulp.dest('test/expa_src')); }; } }; expa.get('http://experience.aiesec.org/').then(function(body) { var matches = []; body.replace(/(?:src|href)=\"((?:scripts|styles)\/(?:vendor|app)-\w*\.(?:js|css))\"/gi, (m, capture) => { matches.push(capture); }); for(var i in matches){ var name = matches[i].split('/').pop(); console.log(`Get ${name}`); expa.get('https://experience.aiesec.org/' + matches[i]).then(saveScript(name)).catch(console.log); } }, console.log); }); gulp.task('mockserver', function(){ var mock; var projectDir = __dirname.split('/').pop(); //if in vagrant call server directly if(__dirname.match('^/var/www/*')){ mock = childProcess.execFile('node', ['test/db.js'], { "cwd": __dirname }); setTimeout(console.log.bind(null, ' Type e + enter to exit'), 2000); // if gulp locally run, enter vagrant via ssh and run server } else { mock = childProcess.exec('vagrant ssh -c "node /var/www/' + projectDir + '/test/server.js"'); } process.stdin.resume(); process.stdin.setEncoding('utf8'); mock.stdout.pipe(process.stdout); mock.stderr.pipe(process.stderr); process.stdin.on('data', function (chunk) { mock.stdin.write(chunk); if (chunk.trim().toLowerCase() === 'e') { mock.kill(); process.exit(0); } }); }); // Default Task gulp.task('default', ['scripts', 'css', 'html', 'watch']); gulp.task('deploy', ['deploy-expa']);
export default { apiUrl: 'http://192.168.1.100:8000', loginMethod: 'post', loginRequest: '/oauth/token', getUserMethod: 'get', getUserRequest: '/api/user', registerMethod: 'post', registerRequest: '/api/register', }
const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const mysqlConnection = require('../database.js'); //let token = req.headers.authorization.split(" ")[1]; //var decoded = jwt.verify(token, process.env.JWT_KEY); //console.log(decoded.role) // get role /* // sucess return res.status(201).json({ message: "??????" }); // sucess return res.status(200).json(??); //objet //error return res.status(401).json({ message: "??????" }); mysqlConnection.query({ sql: 'SELECT * FROM users WHERE `email` = ? or email = ?', timeout: 10000, // 10s values: [var1,var2] }, (err, rows, fields) => { if (!err) { res.status(201).json(rows); } else { return res.status(401).json({ error: "error" }); } }); */ exports.addBrand = (req, res) =>{ let token = req.headers.authorization.split(" ")[1]; var decoded = jwt.verify(token, process.env.JWT_KEY); let name = req.body.name let description = req.body.description let image = req.body.image if(decoded.role == 'Customer'){ return res.status(401).json({ error: "you do not have the permission to execute this action, your information has been loged in our system" //TODO: create a log }); }else{ mysqlConnection.query({ sql: 'INSERT INTO brand VALUES (NULL, ?, ?, ?)', timeout: 10000, // 10s values: [name,description,image] }, (err, rows, fields) => { if (!err) { return res.status(201).json({ message: "Inserted suceefully" }); } else { return res.status(401).json({ error: "somthing is wrong, please contact support", info: err.sqlMessage }); } }); } }; exports.updateBrand = (req, res) => { let token = req.headers.authorization.split(" ")[1]; var decoded = jwt.verify(token, process.env.JWT_KEY); let name = req.body.name let description = req.body.description let image = req.body.image let idBrand = req.params.idBrand if(decoded.role == 'Customer'){ return res.status(401).json({ error: "you do not have the permission to execute this action, your information has been loged in our system" //TODO: create a log }); }else{ mysqlConnection.query({ sql: 'UPDATE brand SET name = ? ,description = ? ,image = ? WHERE idBrand = ?', timeout: 10000, // 10s values: [name,description,image,idBrand] }, (err, rows, fields) => { if (!err) { return res.status(201).json({ message: "Updated suceefully" }); } else { return res.status(401).json({ error: "somthing is wrong, please contact support", info: err.sqlMessage }); } }); } }; exports.deleteBrand = (req, res) => { let token = req.headers.authorization.split(" ")[1]; var decoded = jwt.verify(token, process.env.JWT_KEY); let idBrand = req.params.idBrand if(decoded.role == 'Customer'){ return res.status(401).json({ error: "you do not have the permission to execute this action, your information has been loged in our system" //TODO: create a log }); }else{ mysqlConnection.query({ sql: 'DELETE FROM brand WHERE idBrand = ?', timeout: 10000, // 10s values: [idBrand] }, (err, rows, fields) => { if (!err) { return res.status(201).json({ message: "Deleted sucessfully" }); } else { return res.status(401).json({ error: "somthing is wrong, pelase contact support", info : err.sqlMessage }); } }); } }; exports.getBrand = (req, res) => { let token = req.headers.authorization.split(" ")[1]; var decoded = jwt.verify(token, process.env.JWT_KEY); let idBrand = req.params.idBrand if(decoded.role == 'Customer'){ return res.status(401).json({ error: "you do not have the permission to execute this action, your information has been loged in our system" //TODO: create a log }); }else{ mysqlConnection.query({ sql: 'SELECT * FROM brand WHERE idBrand = ?', timeout: 10000, // 10s values: [idBrand] }, (err, rows, fields) => { if (!err) { return res.status(201).json(rows[0]); } else { return res.status(401).json({ error: "somthing is wrong, pelase contact support", info : err.sqlMessage }); } }); } };
const Color = require('./Color'); //http://there4.io/2012/05/02/google-chart-color-list/ const PALETTE_HEX = [ '3366CC', 'DC3912', 'FF9900', '109618', '990099', '3B3EAC', '0099C6', 'DD4477', '66AA00', 'B82E2E', '316395', '994499', '22AA99', 'AAAA11', '6633CC', 'E67300', '8B0707', '329262', '5574A6', '3B3EAC' ]; let paletteRGB = []; PALETTE_HEX.forEach(function(hex) { paletteRGB = paletteRGB.concat(Color.hexToRgb(hex)); }); const Theme = { palette: paletteRGB }; module.exports = Theme;
'use strict'; const Transaction = { DEPOSIT: 'deposit', WITHDRAW: 'withdraw', }; /* * Каждая транзакция это объект со свойствами: id, type и amount */ const account = { balance: 0, transactions: [ { id: 'id-1', type: 'deposit', amount: 10 }, { id: 'id-2', type: 'deposit', amount: 20 }, { id: 'id-3', type: 'deposit', amount: 30 }, { id: 'id-4', type: 'withdraw', amount: 20 }, { id: 'id-4', type: 'withdraw', amount: 10 }, ], /* * Метод отвечающий за добавление суммы к балансу * Создает объект транзакции и вызывает addTransaction */ deposit(amount) { this.balance += amount; //===== Вариант добавления суммы по типу транзакции (если они уже записаны в объект)=====// // for (const transaction of this.transactions) { // if (transaction.type === 'deposit') { // this.balance += transaction.amount; // } // } return this.balance; }, /* * Метод отвечающий за снятие суммы с баланса. * Создает объект транзакции и вызывает addTransaction * * Если amount больше чем текущий баланс, выводи сообщение * о том, что снятие такой суммы не возможно, недостаточно средств. */ withdraw(amount) { if (amount <= this.balance) { this.balance -= amount; } else { console.log('На Ващем счету недостаточно средств для проведения операции'); } return this.balance; }, /* * Метод добавляющий транзацию в свойство transactions * Принимает объект трназкции */ addTransaction(transaction) { this.transactions.push(transaction); }, /* * Метод возвращает текущий баланс */ getBalance() { return this.balance; }, /* * Метод ищет и возвращает объект транзации по id */ getTransactionDetails(id) { for (let i = 0; i < this.transactions.length; i += 1) { const transaction = this.transactions[i]; if (transaction.id === id) { return transaction; } } }, /* * Метод возвращает количество средств * определенного типа транзакции из всей истории транзакций */ getTransactionTotal(type) { let total = 0; for (const transaction of this.transactions) { if (transaction.type === type) { total += transaction.amount; } } return total; }, }; console.log(account.deposit(100)); account.addTransaction({ id: 'id-4', type: 'deposit', amount: 100 }); console.log(account.transactions); console.log(account.withdraw(60)); console.log(account.getBalance()); console.log(account.getTransactionTotal('deposit')); console.log(account.getTransactionDetails('id-4'));
import * as ACTIONS from './actions'; import cookie from '@/utils/cookie'; const name = cookie.getCookie('name'); const sig = cookie.getCookie('sig'); const user = (state = { name, sig }, action = {}) => { const { type, ...data } = action; switch (type) { case ACTIONS.LOGIN: return { ...state, ...data }; case ACTIONS.GET_CURRENT: return { ...state, ...data }; case ACTIONS.GET_USERS: return { ...state, users: action.users }; case ACTIONS.GET_TEAMS: return { ...state, ...data }; case ACTIONS.LOGOUT: return {}; default: return state; } }; export default user;
describe("parser functions", function() { const _ = require("underscore"); const crypto = require("crypto"); describe("parseLinks", function() { var parseLinks = require("../lib/parser").parseLinks; var testStory = require("./support/test_story"); it("should exist", function() { expect(parseLinks).toBeDefined(); expect(_.isFunction(parseLinks)).toBe(true); }); it("should parse the links within a passage (regardless of format)", function() { var testPassage = _.findWhere(testStory.passages, {"name": "My First Room"}); var text = parseLinks(testPassage, testStory); expect(testPassage.links.length).toEqual(3); expect(_.findWhere(testPassage.links, {"passageId": 2})).toBeDefined(); expect(_.findWhere(testPassage.links, {"passageId": 3})).toBeDefined(); expect(_.findWhere(testPassage.links, {"passageId": 4})).toBeDefined(); // test template replacement var ctx = { "links": {} }; _.each(testPassage.links, function(link, index){ ctx.links[link.id] = "$link" + index + "$"; }); var textTemplate = _.template(text); var result = textTemplate(ctx); expect(result.indexOf("$link0$")).toBeGreaterThan(-1); expect(result.indexOf("$link1$")).toBeGreaterThan(-1); expect(result.indexOf("$link2$")).toBeGreaterThan(-1); }); it("should accept a custom linkFormat function", function() { var testPassage = _.findWhere(testStory.passages, {"name": "My First Room"}); var linkFormatRunTimes = 0; var linkFormat = function(link) { linkFormatRunTimes++; return "$" + link.id + "$"; }; var result = parseLinks(testPassage, testStory, linkFormat); expect(result.indexOf("$1c161af31e61e31bedd6297f978ca31e84532676$")).toBeGreaterThan(-1); expect(result.indexOf("$8e4fe77c1b2b892e60fee08abcb102ddf232b2fb$")).toBeGreaterThan(-1); expect(result.indexOf("$5505e0b3cd81669f1f03b1687c6768787d23db3e$")).toBeGreaterThan(-1); expect(linkFormatRunTimes).toEqual(3); }); it("should accept a custom linkFormat template string", function() { var testPassage = _.findWhere(testStory.passages, {"name": "My First Room"}); var linkFormat = "$<%= id %>$"; var result = parseLinks(testPassage, testStory, linkFormat); expect(result.indexOf("$1c161af31e61e31bedd6297f978ca31e84532676$")).toBeGreaterThan(-1); expect(result.indexOf("$8e4fe77c1b2b892e60fee08abcb102ddf232b2fb$")).toBeGreaterThan(-1); expect(result.indexOf("$5505e0b3cd81669f1f03b1687c6768787d23db3e$")).toBeGreaterThan(-1); }); }); describe("removeComments", function() { var removeComments = require("../lib/parser").removeComments; it("should remove all /* */ style comments", function() { var testPassage = { text: "/* this is my comment! blah blah blah */nada" }; expect(removeComments(testPassage)).toEqual("nada"); }); }); describe("getLinkId", function() { var getLinkId = require("../lib/parser").getLinkId; it("should return the sha1 hash of the given string", function() { var testStr = "my test string"; var hash = crypto.createHash('sha1'); hash.update(testStr); var hashResult = hash.digest('hex'); expect(getLinkId(testStr)).toEqual(hashResult); }); }); describe("handleCustomTags", function() { var handleCustomTags = require("../lib/parser").handleCustomTags; it("should exist", function() { expect(handleCustomTags).toBeDefined(); expect(_.isFunction(handleCustomTags)).toBe(true); }); it("should be able to swap out all given custom tags in the passage text", function() { var passage = { text: "<options>This is my list.<ul><li>yay</li></ul><custom>Hello</custom></options>" }; var customTags = [ { name: "options", swap: "<div></div>" }, { name: "custom", swap: "<span></span>" } ]; handleCustomTags(passage, customTags); expect(passage.text).toEqual("<div>This is my list.<ul><li>yay</li></ul><span>Hello</span></div>"); }); }); describe("handleTransforms", function() { var handleTransforms = require("../lib/parser").handleTransforms; it("should exist", function() { expect(handleTransforms).toBeDefined(); expect(_.isFunction(handleTransforms)).toBe(true); }); it("should apply a given function to the given passage and story", function() { var passage = { text: "this is pre-transform" }; handleTransforms(passage, {}, (p) => { p.text = "this is post-transform"; }); expect(passage.text).toEqual("this is post-transform"); }); it("should also be able to apply an array of functions", function() { var passage = { text: "I am noodle" }; var transforms = [ (p) => { p.text += " pasta"; }, (p) => { p.text += " lumbago"; }, (p) => { p.text += " shortening!"; } ]; handleTransforms(passage, {}, transforms); expect(passage.text).toEqual("I am noodle pasta lumbago shortening!"); }); }); });
import React from 'react' import * as S from './styles' import { routes } from '../../Routes' import { userLogin } from '../../services/user' import { login } from '../../services/auth' const Home = ({ history }) => { const [loading, setLoading] = React.useState(false) const [error, setError] = React.useState(false) const handleSubmit = async data => { setLoading(true) try { const resp = await userLogin(data) setLoading(false) login(resp.data.token) history.push(routes.dashboard) } catch (error) { setError(true) } } return ( <S.Wrapper> <S.Form onSubmit={handleSubmit}> <S.Title>Login</S.Title> <S.Text>Please sign-in to continue</S.Text> <S.Input name="email" placeholder="Email" disabled={loading} /> <S.Input name="password" type="password" placeholder="Password" disabled={loading} /> {error && <S.Error>Email or Password is wrong!</S.Error>} <S.ButtonWrapper> <S.Link to={routes.auth.passwordReset}>Forget password?</S.Link> <S.Button type="submit" disabled={loading}> Sign in </S.Button> </S.ButtonWrapper> <S.Divider /> <S.Text> Doesn't have an account?{' '} <S.Link to={routes.auth.signup}>Create an account</S.Link> </S.Text> </S.Form> </S.Wrapper> ) } export default Home
import cn from 'classnames'; import s from './style.module.css' import { Link } from 'react-router-dom'; const MENU = [ { title: 'HOME', to: 'home', }, { title: 'GAME', to: 'game', } , { title: 'ABOUT', to: 'about', }, { title: 'CONTACT', to: 'contact', }, ] const Menu = ({state, onClickButton}) => { const handleCloseMenu = () => { onClickButton && onClickButton(); } return ( <div className={cn(s.menuContainer, {[s.active]: state, [s.deactive]: !state})}> <div className={s.overlay} /> <div className={s.menuItems}> <ul> { MENU.map(({title, to}, index) => ( <li key={index} onClick={handleCloseMenu}> <Link to={to}> {title} </Link> </li> )) } </ul> </div> </div> ); }; export default Menu;
var SerialPort = require('serialport'); var Readline = SerialPort.parsers.Readline; var port = new SerialPort('COM3', { baudRate: 9600, dataBits: 8 }); var Readline = SerialPort.parsers.Readline; var parser = new Readline(); var buffer = ''; port.on('open', function() { console.log('Serial Port Opened'); port.on('data', function(data) { buffer += data; var answers = buffer.split(/\r?\n/); buffer = answers.pop(); if (answers.length > 0) { console.log(answers[0]); } }); }); port.on('error', function(e) { });
import axios from 'axios'; import store from '@/store'; import { Message, Loading } from 'element-ui'; import { getToken, getRefreshToken, saveToken, saveRefreshToken, saveTokenExpire, delToken, deleteRefreshToken, delUUID, delTokenExpire, delLoginInfo, delLoginUserId, getTokenExpire } from '@/cache'; let loading = null; // 判断加载中的状态 let prom = null; // 一个Promise对象,用作yield的返回值 let isRefresh = false; // 用于判断刷新token接口调用是否结束 const hostName = location.host; // 获取当前地址域名 const CancelToken = axios.CancelToken; // 给接口添加取消 let cancelArr = []; // 存储被取消的接口,等待刷新token后重新请求 let pending = []; // 当前正在请求中的接口,用于去重 let newToken = null; // 最新的token const service = axios.create({ // 设置超时时间 timeout: 15000, baseURL: process.env.VUE_APP_BASE_URL || '/' }); service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // 请求前拦截 service.interceptors.request.use( config => { const pendingIdx = pending.findIndex(ele => ele.url === config.url && ele.method === config.method); if(pendingIdx > -1) { return Promise.reject('接口请求重复'); }; pending.push(config); // 如果请求中没有取消,则添加 if(!config.cancelToken) { config.cancelToken = new CancelToken(function executor(c) { // 设置 cancel token config.cancel = c; }); } // 在请求先展示加载框,uploadVideo/appvideo接口除外 if (config.url.indexOf('uploadVideo/appvideo') === -1) { loading = Loading.service({ text: '正在加载中......', background: 'rgba(0,0,0,0.2)' }); } // 配置post和get对应的传参 if (config.data) { String(config.method).toLocaleUpperCase() === 'GET' && (config.params = config.data); } const token = getToken(); const isLogin = config.url.indexOf('/javaapi/appmember/assistantLogin') > -1; if (token && !isLogin) { config.headers['Authorization'] = 'Bearer ' + token; // 后台接口定义传入的token前加Beare加空格 } // 如果正在调用刷新token接口,则后续接口请求 let p = new Promise((resolve) => { // 判断token是否即将过期,排除登录接口 if (token && tokenExpire() && !isLogin) { console.log('token即将过期'); if (isRefresh) { console.log('正在等待刷新token'); let idx = cancelArr.findIndex(ele => ele.url === config.url && ele.method === config.method); idx === -1 && cancelArr.push(config); config.cancel('终止请求'); resolve(prom); return; } isRefresh = true; prom = new Promise((resolve) => { getReToken().then(res => { isRefresh = false; let data = res.data; config.headers['Authorization'] = 'Bearer ' + data.access_token; newToken = data.access_token; saveToken(data.access_token); saveRefreshToken(data.refresh_token); saveTokenExpire(data.expires_in * 1000 + (new Date()).getTime()); let userInfo = { headImg: data.headImage, nickName: data.nickName, userName: data.userName, userId: data.userId, coach: data.coach }; store.dispatch('setUser', JSON.stringify(userInfo)); resolve('success'); }).catch(err => { console.log('刷新token接口出错了'); console.log(err); // 请求响应后关闭加载框 delToken(); deleteRefreshToken(); delUUID(); delTokenExpire(); delLoginInfo(); delLoginUserId(); loading && loading.close(); window.location.href = 'http://' + hostName + '/#/login'; }); }).then(() => { console.log('重新请求失败的接口', config); removePending(config); return service(config); }); return prom; } resolve('success'); }).then(() => { return config; }); return p; }, error => { return Promise.reject(error); } ); // 请求响应拦截 service.interceptors.response.use( response => { // 请求响应后关闭加载框 loading && loading.close(); let code = response.data.code; // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据 if (code === 200) { // 如果有被取消的接口,则重新请求 if(cancelArr.length) { cancelArr.forEach(ele => { let newConfig = ele; newConfig.cancelToken = null; newConfig.cancel = null; newConfig.headers.Authorization = 'Bearer ' + newToken; return service(newConfig).then(res => res).catch(err => { loading && loading.close(); return err; }) }); cancelArr = []; } removePending(response.config); return Promise.resolve(response.data); } // 否则的话抛出错误 switch (code) { case 400: Message({ showClose: true, message: response.data, type: 'error' }); break; case 404: Message({ showClose: true, message: '网络请求不存在', type: 'error' }); break; default: Message({ message: response.data.msg, type: 'error' }); } return Promise.resolve(response.data); }, error => { // 请求响应后关闭加载框 loading && loading.close(); if(error.message === '终止请求' || error === '接口请求重复') { return Promise.reject(error); } else if (!error.response) { // 断网 或者 请求超时 状态 // 请求超时状态 if (error.message.includes('timeout')) { // console.log('超时了'); Message.error('请求超时,请检查网络是否连接正常'); } else { // 可以展示断网组件 Message.error('请求失败,请检查网络是否已连接'); } return; } return Promise.reject(error); } ); function removePending(config) { let hasEndIdx = pending.findIndex(ele => ele.url === config.url && ele.method === config.method); hasEndIdx > -1 && pending.splice(hasEndIdx, 1); } // 获取refreshTokenS function getReToken() { let refreshToken = getRefreshToken(); // refresh_token使用vuex存在本地的localstorage // qs的使用主要是因为该接口需要表单提交的方式传数据 return axios.get(`/javaapi/appmember/refreshToken/${refreshToken}`, { refreshToken: refreshToken }); } // 判断是否快过期 function tokenExpire() { let tokenExpire = getTokenExpire(); let nowTime = new Date().getTime(); return tokenExpire - nowTime < 1000 * 300; } export default service;
import React, {Fragment} from 'react'; import {BrowserRouter as Router, Route} from 'react-router-dom'; import './App.css'; import ArtistNews from './components/ArtistNews' import ArtistNewsPage from './components/ArtistNewsPage' import Contact from './components/contact/Contact' function App() { return ( <div> <Router> <Fragment> <Route exact path="/reactheadlesstest/" component={ArtistNews} /> <Route exact path="/reactheadlesstest/artistnews/:id" component={ArtistNewsPage} /> </Fragment> </Router> <Contact /> </div> ); } export default App;
module.exports = require('./RunTimeErrorWrapper.jsx');
$(document).ready(function () { if ($('#page-auth').length) { $('#select-user-status-pics .status-item').click(function () { $('#select-user-status-pics .status-item').removeClass('-selected'); $(this).addClass('-selected'); $('#select-user-status-pics input[type=hidden]').val($(this).data('value')) }); } });
import axios from 'axios' const BASE_URL = "https://api-staging.tt.ge" const PUBLIC_BUCKET_URL = "https://s3.eu-central-1.amazonaws.com/public.tt.ge" const is_Empty_Comp_url = company_url ? company_url : "/images/logos/redberry.png" const Company_URL = `${PUBLIC_BUCKET_URL}${is_Empty_Comp_url}` const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNlYXJjaC1jaGFsbGVuZ2VAdHQuZ2UiLCJzdWIiOiJlOGE3N2E4OS00MzM2LTQyYzYtOWZiYS1hZDY4ODU2YzkzMmEiLCJpYXQiOjE2MTA4NzQzNTgsImV4cCI6MTYxMzQ2NjM1OH0.CEa_eMgGrkzlULWt76D8-E-QzH45tlM99c7_IVk4dd0" export function apiForJobs() { return axios.get(`${BASE_URL}/search/jobs?take=7`,{ headers: { 'Authorization': `Bearer ${token}` } }) } export function apiForJobsUsingQuery(query, skip, take, field) { const URL = field === "null" ? `${BASE_URL}/search/jobs?query=${query}&skip=${skip}&take=${take}` : `${BASE_URL}/search/jobs?fieldId=${field}&query=${query}&skip=${skip}&take=${take}` return axios.get(URL,{ headers: { 'Authorization': `Bearer ${token}` } }) } export function apiForJobsUsingFields(field) { const URL_2 = field === "null" ? `${BASE_URL}/search/jobs?take=7` : `${BASE_URL}/search/jobs?fieldId=${field}&take=7` return axios.get(URL_2,{ headers: { 'Authorization': `Bearer ${token}` } }) }
// Author: Jasser Dhaouadi // Student ID: 610099 // Homework: maze var gameOver = false; // track the user if he/she hits the wall while moving the mouse window.onload = function() { $('#start')[0].onclick = startMazeGameOnClick; $('#end')[0].onmouseover = EndMazeGame; var boundaries = $('#maze .boundary'); for (var i = 0; i < boundaries.length; i++) { boundaries[i].onmouseover = overBoundary; } }; function overBoundary() { gameOver = true; var boundaries = $('#maze .boundary'); for (var i = 0; i < boundaries.length; i++) { boundaries[i] = $(boundaries[i]); boundaries[i].addClass("youlose"); } } function startMazeGameOnClick() { $( "#status" ).text( 'Click the "S" to begin.' ); gameOver = false; var boundaries = $("#maze .boundary"); for (var i = 0; i < boundaries.length; i++) { boundaries[i] = $(boundaries[i]); boundaries[i].removeClass("youlose"); } } function EndMazeGame() { if(gameOver) { alert("Sorry, you lost. :["); $( "#status" ).text( "You lose" ); } else { alert("You win! :]"); $( "#status" ).text( "You win" ); } }
modules.define( 'super-input', [ 'inherit', 'input' ], function ( provide, inherit, Input ) { var SuperInput = inherit(Input, { __constructor: function (params) { this.__base.apply(this, arguments); }, // Переопределили метод класса Input focus: function () { console.log('Переопределил метод focus!'); // Вызвали базовый метод this.__base(); } }); provide(SuperInput); });
"use strict"; const modFs = require("fs"); const modZip = require("./zip.js"); /* Returns the chain of virtual file systems used in the given path. */ function vfsChain(path) { var chain = ["fs"]; var parts = path.split("/"); parts.slice(0, parts.length - 1).forEach(function (p) { var lcpath = p.toLowerCase(); var type = ""; if (lcpath.endsWith(".zip")) { type = "zip"; } else if (lcpath.endsWith(".tgz")) { type = "tgz"; } if (type !== "" && type !== chain[chain.length - 1]) { chain.push(type); } }); return chain; } /* Returns the last (innermost) virtual file system in the given path. */ function lastVfs(path) { var chain = vfsChain(path); return chain[chain.length - 1]; } /* Splits the given path up into the path leading to the innermost filesystem and the innermost path. */ function splitPath(path) { var parts = path.split("/"); var idx = -1; for (var i = parts.length - 2; i >= 0; --i) { var lcpath = parts[i].toLowerCase(); if (lcpath.endsWith(".zip") || lcpath.endsWith(".tgz")) { idx = i; break; } } if (idx != -1) { var outerPath = parts.slice(0, idx + 1).join("/"); var innerPath = parts.slice(idx + 1).join("/"); //console.log("vfs.splitPath: " + path + " -> " + outerPath + "#" + innerPath); return [outerPath, innerPath]; } else { return ["", ""]; } }; exports.close = function (fd, callback) { //console.log("vfs.close"); if (fd.isZip) { modZip.close(fd, callback); } else { modFs.close(fd, callback); } }; exports.createReadStream = function (path, callback) { //console.log("vfs.createReadStream"); switch (lastVfs(path)) { case "zip": var parts = splitPath(path); modZip.createReadStream(parts[0], parts[1], function (size, stream) { callback(stream); }); break; default: try { callback(modFs.createReadStream(path)); } catch (err) { console.log(err); callback(null); } break; } }; exports.createReadStreamRanged = function (path, from, to, callback) { //console.log("vfs.createReadStream"); switch (lastVfs(path)) { case "zip": var parts = splitPath(path); modZip.createReadStreamRanged(parts[0], parts[1], from, to, function (size, stream) { callback(stream); }); break; default: callback(modFs.createReadStream(path, { start: from, end: to})); break; } }; exports.createWriteStream = function (path, callback) { //console.log("vfs.createWriteStream"); try { callback(modFs.createWriteStream(path)); } catch (err) { console.log(err); callback(null); } }; exports.createWriteStreamFd = function (fd, callback) { //console.log("vfs.createWriteStreamFd"); try { callback(modFs.createWriteStream("", { "fd": fd })); } catch (err) { console.log(err); callback(null); } }; exports.fstat = function (fd, callback) { modFs.fstat(fd, callback); }; exports.mkdir = function (path, callback) { modFs.mkdir(path, callback); }; exports.open = function (path, mode, callback) { //console.log("vfs.open"); switch (lastVfs(path)) { case "zip": var parts = splitPath(path); modZip.open(parts[0], parts[1], mode, callback); break; default: modFs.open(path, mode, callback); break; } }; exports.read = function (fd, buffer, offset, length, position, callback) { //console.log("vfs.read"); if (fd.isZip) { modZip.readFile(fd.file, buffer, offset, length, position, callback); } else { modFs.read(fd, buffer, offset, length, position, callback); } }; exports.readdir = function (path, callback) { //console.log("vfs.readdir"); if (! path.endsWith("/")) { path += "/"; } switch (lastVfs(path)) { case "zip": var parts = splitPath(path); modZip.readZip(parts[0], parts[1], callback); break; default: modFs.readdir(path, callback); break; } }; exports.readFile = function (path, callback) { //console.log("vfs.readFile"); switch (lastVfs(path)) { case "zip": var parts = splitPath(path); modZip.createReadStream(parts[0], parts[1], function (size, stream) { callback(null, stream.read()); }); break; default: modFs.readFile(path, callback); break; } }; exports.rename = function (path, newPath, callback) { modFs.rename(path, newPath, callback); }; exports.rmdir = function (path, callback) { modFs.rmdir(path, callback); }; exports.stat = function (path, callback) { //console.log("vfs.stat"); switch (lastVfs(path)) { case "zip": var parts = splitPath(path); modZip.stat(parts[0], parts[1], callback); break; default: modFs.stat(path, callback); break; } }; exports.unlink = function (path, callback) { modFs.unlink(path, callback); }; exports.writeFile = function (path, data, callback) { modFs.writeFile(path, data, callback); };
import React from "react" //import { Link } from "gatsby" import { graphql } from "gatsby" import Img from "gatsby-image" import SvgIcon from '@material-ui/core/SvgIcon'; import Layout from "../components/layout" import SEO from "../components/seo" import { Helmet } from "react-helmet" import { InView } from 'react-intersection-observer'; import { useIntl,Link, FormattedMessage } from "gatsby-plugin-intl" import ArrowRight from "../components/Icons/ArrowR" import Button from "../components/Button" import Officecounter from "../components/Officecounter" import Subscribe from "../components/Subscribe" import Pacjencicarousel from "../components/Pacjencicarousel" import UslugiSection from "../components/UslugiSection" import surgery from "../images/surgery-tools.svg" import control from "../images/control.svg" import rtg from "../images/rtg.svg" import profilactic from "../images/profilactic.svg" import vaccine from "../images/vaccine.svg" import bandage from "../images/bandage.svg" import calendar from "../images/calendar.svg" import location from "../images/location.svg" import time from "../images/time.svg" import clinic from "../images/clinic.svg" import "../components/slider.css" const IndexPage = props => { const pacjenci = props.data.pacjenci.frontmatter.list; const services = props.data.services.edges[0].node.frontmatter.services; return( <Layout> <SEO title="Home" /> <section id="welcome"> <div className="container"> <div className="welcome-content"> <InView triggerOnce delay={7000}> {({ inView, ref, entry }) => ( <h1 className={inView? "inview": ""} ref={ref}>AnimalVet</h1> )} </InView> <p><FormattedMessage id="main_subtitle"/></p> <Link to="/kontakt#kontakt-form"><Button color="#fff" background="#F24C3D"> <FormattedMessage id="appointment" /></Button></Link> </div> <div className="welcome-img"> <Img fluid={props.data.imgOne.childImageSharp.fluid} /> </div> <div className="welcome-opening"> <div className="desctop"><img src={clinic} alt="klinika" />Jesteśmy otwarci!</div> <div className="address"><Link style={{display:"block"}} to={"/kontakt#kontakt"}><img src={location} alt="Lokacja"/>Zasieki 4B</Link></div> <div className="days"><Link style={{display:"block"}} to={"/kontakt#kontakt"}><img src={calendar} alt="Kalendarz"/>Pn - Pt</Link></div> <div className="hours"><Link style={{display:"block"}} to={"/kontakt#kontakt"}><img src={time} alt="Czas"/>10:00 - 16:00</Link></div> </div> </div> </section> <section id="uslugi"> <div className="container"> <div className="uslugi-header border-b"> <h2>Popularne usługi</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> <UslugiSection services={services} isHomepage={true} /> </div> </section> <section id="office"> <div className="container"> <div className="row"> <div className="office-container col-8"> <div className="office-title"><h3>O nas</h3></div> <div className="office-text"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <Officecounter /> </div> <div className="office-img col-4"> <Img fluid={props.data.imgOffice.childImageSharp.fluid} /> </div> </div> </div> </section> <section id="clients"> <div className="container "> <div className="row"> <div className="col-4 client-titles"> <h2>Zaufali nam</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> <Link activeClass="active" to="pacjenci"><Button color="#fff" background="#F24C3D">Nasi pacjenci</Button></Link> </div> <div className="col-8 slider"> <Pacjencicarousel pacjenci={pacjenci} /> {/* <div className="clients-list slides"> {pacjenci.map((item, index)=>( <div className="clients-item" id={`item_${index}`}> <div className="slide-nav"> <a className="slide-prev" href={index> 0 ? `#item_${index-1}` : ""} > { index > 0 ? <Slidearrow style={{ color: '#000', fontSize: "25px", transform: "scaleX(-1)" }}/> : <Slidearrow style={{ color: '#BCBCBC', fontSize: "25px", transform: "scaleX(-1)" }}/> } </a> <div className="slide-counter">{index+1} / {pacjenci.length}</div> <a className="slide-next" href={index<(pacjenci.length-1)?`#item_${index+1}`:""}> {index<(pacjenci.length-1) ? <Slidearrow style={{ color: "#000", fontSize: "25px" }}/> : <Slidearrow style={{ color: "#BCBCBC", fontSize: "25px" }}/> } </a> </div> <div className="clients-text"> <p><b>{item.title}</b></p> <p><q>{item.description}</q></p> </div> <div className="clients-img"> <Img fluid={item.featuredImage.childImageSharp.fluid} placeholderStyle={{"backgroundColor": "#d5f1ff" }} /> </div> </div> ))} </div> */} </div> </div> </div> </section> <Subscribe image={props.data.dog.childImageSharp.fluid}/> </Layout> )} export default IndexPage function Slidearrow(props) { return ( <SvgIcon {...props} viewBox="0 0 16 8"> <path d="M15.3536 4.35355C15.5488 4.15829 15.5488 3.84171 15.3536 3.64645L12.1716 0.464466C11.9763 0.269204 11.6597 0.269204 11.4645 0.464466C11.2692 0.659728 11.2692 0.976311 11.4645 1.17157L14.2929 4L11.4645 6.82843C11.2692 7.02369 11.2692 7.34027 11.4645 7.53553C11.6597 7.7308 11.9763 7.7308 12.1716 7.53553L15.3536 4.35355ZM0 4.5L15 4.5V3.5L0 3.5L0 4.5Z" /> </SvgIcon> ); } export const pageQuery = graphql` query { imgOne : file(relativePath: {eq: "doghome2.png"}) { childImageSharp { fluid{ ...GatsbyImageSharpFluid_withWebp_noBase64 } } }, imgOffice : file(relativePath: {eq: "office.png"}){ childImageSharp { fluid{ ...GatsbyImageSharpFluid_withWebp_noBase64 } } }, bengal : file(relativePath: {eq: "bengal.jpg"}){ childImageSharp { fluid{ ...GatsbyImageSharpFluid_withWebp_noBase64 } } }, dog : file(relativePath: {eq: "dog.png"}) { childImageSharp { fluid{ ...GatsbyImageSharpFluid_withWebp_noBase64 } } } pacjenci : markdownRemark(frontmatter: {templateKey: {eq: "pacjenci"}}) { frontmatter { list { description title featuredImage { childImageSharp { fluid(maxWidth: 360) { ...GatsbyImageSharpFluid_withWebp_noBase64 } } } } } }, services : allMarkdownRemark(filter: {frontmatter: {templateKey: {eq: "uslugi"}}}) { edges { node { frontmatter { services { description image text title } } } } } } `
class Node { constructor(data) { this.data = data; this.next = null; } } class LinkedList { constructor() { this.head = null; this.size = 0; } add(data) { // create new Node const newNode = new Node(data); //if head is null set head to new Node; if(this.head == null) { this.head = newNode; this.size++; return; } // Add to the end of the list since head is not null // Create a pointer that points at the beginning of the list let pointer = this.head; while(pointer.next !== null) { pointer = pointer.next; } pointer.next = newNode; this.size++; } palindrome() { let slow = this.head; let fast = this.head; while(fast != null) { fast = fast.next.next; slow = slow.next } let stack = []; let mid = slow console.log(mid) while(slow != null) { //slow is already halfway stack.push(slow) slow = slow.next; } fast = this.head; while(fast !== mid) { let value = stack.pop(); if(fast.data != value.data) { return false; } fast = fast.next; } return true; } print() { let pointer = this.head; let counter = 0; while(pointer !== null) { console.log(`${counter} : ${pointer.data}`) pointer = pointer.next; counter++; } } } let list = new LinkedList(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(2); list.add(1); list.print(); console.log(list.palindrome());
var WsItemFactory = function() { this.createView = function(model) { Object.extend(model, { type : undefined, p : -1, i : -1, x : 0, y : 0, w : 0, h : 0, bg : 'transparent', color : '#000000', borderColor : 'transparent', borderWidth : 0, opacity : 1, zIndex : 0, action : '', anchor : '', config : {} }); var view = new Kinetic.Group(); view.setAttr('model', model); view.setSize({ width : model.w, height : model.h }); view.setPosition({ x : model.x, y : model.y }); return view; }; this.render = function(view) { var model = view.getAttr('model'); if (view.getWidth() !== model.w || view.getHeight() !== model.h) { view.setSize({ width : model.w, height : model.h }); } var bg = new Kinetic.Rect({ name : 'bg', width : view.getWidth(), height : view.getHeight(), fill : model.bg, stroke : model.borderColor, strokeWidth : model.borderWidth }); view.add(bg); bg.moveToBottom(); view.setOpacity(model.opacity); if (typeof view.getParent() !== 'undefined') { view.setZIndex(model.zIndex); } }; this.clearView = function(view) { view.removeChildren(); }; this.createProperties = function(onChange) { var properties = {}; PropertiesBuilder(properties) .addNumberProperty('p', 'Page') .addNumberProperty('i', 'Index') .addNumberProperty('x', 'X', onChange, 0, 10000, 1) .addNumberProperty('y', 'Y', onChange, 0, 10000, 1) .addNumberProperty('w', 'Width', onChange, 0, 10000, 1) .addNumberProperty('h', 'Height', onChange, 0, 10000, 1) .addColorProperty('bg', 'Bg Color', onChange) .addColorProperty('color', 'Color', onChange) .addNumberProperty('opacity', 'Opacity', onChange, 0, 1, 0.1) .addNumberProperty('zIndex', 'ZIndex', onChange, -127, 127, 1) .addStringProperty('action', 'Action', onChange) .addStringProperty('anchor', 'Anchor', onChange); return properties; }; this.createEditor = function(model, onChange) { return null; }; }; WsItemFactory.cache = {}; WsItemFactory.forType = function(type) { if (!type) { throw 'WsItemFactory: Failed to create WsItemFactory. Cause:\n' + 'Item type "' + type + '" is not specified'; } var factory = WsItemFactory.cache[type]; if (typeof factory === 'object') { return factory; } var constructor = window[type[0].toUpperCase() + type.substring(1) + 'WsItemFactory']; if (!constructor) { throw 'WsItemFactory: Failed to create WsItemFactory. Cause:\n' + 'Unknown item type "' + type + '"'; } factory = new constructor(); WsItemFactory.cache[type] = factory; return factory; };
import React, {Component} from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import Paper from 'material-ui/Paper'; import Avatar from 'material-ui/Avatar'; import {List, ListItem} from 'material-ui/List'; import FileCloudUpload from 'material-ui/svg-icons/file/cloud-upload'; import FileUpload from 'material-ui/svg-icons/file/file-upload'; import Files from 'react-files'; import axios from 'axios'; import Snackbar from 'material-ui/Snackbar'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import FileCreateNewFolder from 'material-ui/svg-icons/file/create-new-folder'; import { Row, Col } from 'react-flexbox-grid'; import {StatusInformation} from './StatusInformation'; import PropTypes from 'prop-types'; /** * This component is used to upload FAERS data zip files and show status information about the last analysis ran. */ class UploadFAERS extends Component { constructor(props) { super(props) this.state = { uploadDialog: false, uploadFiles: [], prevFiles: [], uploadSnackbar: false, uploadSnackbarMessage: '', currentlyRunning: props.status.status === 'inprogress' }; this.openUploadDialog = this.openUploadDialog.bind(this); this.closeUploadDialog = this.closeUploadDialog.bind(this); this.beginMARAS = this.beginMARAS.bind(this); this.onFilesChange = this.onFilesChange.bind(this); this.createRemoveFileHandler = this.createRemoveFileHandler.bind(this); } /* * When new props are received, check whether they are undefined before * updating the state. */ componentWillReceiveProps(nextProps) { if(nextProps.status.status !== undefined) { if(nextProps.status.status === 'inprogress') { this.setState({currentlyRunning: true}); } else { this.setState({currentlyRunning: false}); } } } /* * Called when the iconbutton is clicked to open the upload dialog. */ openUploadDialog(){ this.props.getStatus(); this.setState({uploadDialog: true}); }; /* * Called when the the upload dialog is closed. */ closeUploadDialog(){ this.setState({uploadDialog: false, uploadFiles: []}); }; /* * Begin the MARAS analysis using whatever data files have been added. */ beginMARAS(){ const files = this.state.uploadFiles; if(this.state.uploadFiles.length > 0) { // start MARAS process on current files var formData = new FormData(); files.forEach((f) => { formData.append('file', f); }); axios.post('/csv/reports', formData).then( (response) => { this.setState({ uploadSnackbar: true, uploadSnackbarMessage: (response.data.success) ? "File(s) uploaded, your visualization will be updated when analysis is completed" : "Error uploading files", }); }, (error) => {console.log(error);} ); this.closeUploadDialog(); } else{ this.setState({ uploadSnackbar: true, uploadSnackbarMessage: "Add one or more file(s) to begin analysis", }); } }; /* * Callback for when a file is added. Checks for new files added, removes duplicates, and adds * the resulting files to the list of files to be uploaded. * * @param files List of all files added */ onFilesChange(files){ var newFiles = []; //find any new files that have been added for(var i = files.length-1; i > files.length-1-(files.length - this.state.prevFiles.length); i--) { newFiles.push(files[i]); } var filesWithoutDuplicates = this.state.uploadFiles; var found = false; //check to see if each new file is a duplicate, otherwise add it to the list of files to upload newFiles.forEach((newFile) => { filesWithoutDuplicates.forEach((addedFile) => { if(newFile.name === addedFile.name) { found = true; } }); if(!found) { filesWithoutDuplicates.push(newFile); } }); this.setState({ uploadFiles: filesWithoutDuplicates, prevFiles: files, }); }; /* * Callback on error adding a file. * * @param error The error being thrown * @param file The file causing the error */ onFilesError(error, file){ console.log(error.message); }; /* * Creates a function when a file is added to the list that can be used to remove that file from the * list of files to be uploaded. * * @param file The file to be removed */ createRemoveFileHandler(file){ return function() { var files = this.state.uploadFiles; for(var i=0; i < files.length; i++) { if(files[i].name === file) { files.splice(i, 1); break; } } this.setState({ uploadFiles: files, }); }.bind(this); } /* * Render this component. */ render() { return ( <div> <IconButton tooltip="Upload FAERS data" iconStyle={{ color: 'white' }} tooltipPosition='bottom-left' onClick={this.openUploadDialog}> <FileUpload /> </IconButton> <Snackbar open={this.state.uploadSnackbar} message={this.state.uploadSnackbarMessage} autoHideDuration={4000} style={{zIndex: 1400}} onRequestClose={() => {this.setState({uploadSnackbar: false})}}/> <Dialog title="Upload FAERS data" contentStyle={{width: "80%", maxWidth: "none"}} actions={[ <FlatButton label="Cancel" primary={false} onClick={this.closeUploadDialog} />, <FlatButton label="Upload" primary={true} onClick={this.beginMARAS} disabled={this.state.currentlyRunning} /> ]} modal={false} open={this.state.uploadDialog} onRequestClose={this.closeUploadDialog} autoScrollBodyContent={true}> { (this.state.currentlyRunning) ? ( <div style={{textAlign: 'center'}}> Analysis is currently in progress. Please wait for analysis to complete before uploading any more files. </div> ) : ( <Row> <Col md={8}> <Files className='files-dropzone' onChange={this.onFilesChange} onError={this.onFilesError} accepts={['application/x-zip-compressed']} multiple maxFileSize={1000000000} minFileSize={0} clickable > <Paper zDepth={1} style={{height: 114, lineHeight: '38px', textAlign: 'center'}}> <div> Drop files here or click to upload (File format must be .zip)<br/> Zip files can be downloaded from&nbsp; <a target="_blank" onClick={(event) => {event=event || window.event; event.stopPropagation();}} href="https://www.fda.gov/Drugs/GuidanceComplianceRegulatoryInformation/Surveillance/AdverseDrugEffects/ucm082193.htm"> this link </a>. <br/> Note: Please upload the ASCII version. </div> </Paper> </Files> <List> <ListItem primaryText={'Example:'} disabled={true}/> <ListItem leftAvatar={<Avatar icon={<FileCreateNewFolder/>}/>} rightIconButton={<IconButton onClick={() => {}}><NavigationClose/></IconButton>} primaryText={'faers_ascii_2013q1.zip'} disabled={true} /> <ListItem primaryText={'Files to Upload:'} disabled={true}/> { (this.state.uploadFiles.length == 0) ? ( <ListItem primaryText={'No files have been added.'} disabled={true}/> ) : (this.state.uploadFiles.map((file) => ( <ListItem key={file.name} leftAvatar={<Avatar icon={<FileCreateNewFolder/>}/>} rightIconButton={<IconButton onClick={this.createRemoveFileHandler(file.name)}><NavigationClose/></IconButton>} primaryText={file.name} /> ))) } </List> </Col> <Col md={4}> <StatusInformation status={this.props.status} /> </Col> </Row> ) } </Dialog> </div> ); } } UploadFAERS.propTypes = { /** * The status of the last analysis ran. */ status: PropTypes.object.isRequired, /** * A function that can be called to get the updated analysis status. */ getStatus: PropTypes.func.isRequired, }; export default UploadFAERS;
({ // get course plan info getCourseSection: function (component, event, helper) { let courseSectionRecId = component.get("v.courseSectionRecId"); let assignedRegion = component.get("v.userRegion"); let iltId = component.get("v.iltClassId"); if(courseSectionRecId && assignedRegion ){ helper.callServer( component, "c.getCoursePlanSection", function (theCoursePlanSection) { if (theCoursePlanSection) { component.set("v.courseSectionWrapper", theCoursePlanSection); let courseId = theCoursePlanSection.courseSection.redwing__Training_Plan__c; //setting up data for course section items (Non ILT items) if (theCoursePlanSection.courseSectionWrappers) { let courseSectionItems = []; for (var i = 0; i < theCoursePlanSection.courseSectionWrappers.length; i++) { courseSectionItems.push({ sectionItem: theCoursePlanSection.courseSectionWrappers[i], region: component.get("v.userRegion"), course: courseId }) } component.set("v.courseSectionItems", courseSectionItems); } if (theCoursePlanSection.ILTClasses) { let iltItems = []; for (var i = 0; i < theCoursePlanSection.ILTClasses.length; i++) { iltItems.push({ ILTClass: theCoursePlanSection.ILTClasses[i], region: component.get("v.userRegion"), course: courseId }) } //console.log(JSON.stringify(iltItems)); component.set("v.ILTItems", iltItems); } } else { component.set("v.courseSectionItems", null); component.set("v.ILTItems", null); } }, { coursePlanSectionId: courseSectionRecId, region: assignedRegion, iltClassId:iltId } ); } } })
'use strict'; const Module = require('../../../utils/Module'); class CoreEvents extends Module { constructor(BetterTwitchApp) { super('core.events'); this.BetterTwitchApp = BetterTwitchApp; this.localStore = {}; this.init(); } init() { if(this.__initialized) return; $(document).bind('DOMSubtreeModified', (e) => { this.BetterTwitchApp.emit('BetterTwitchApp:Update.DOM', e, e.target); }); setInterval(() => { let parts = location.pathname.split('/'); if(this.localStore['Twitch:PageURL'] !== location.pathname) { this.localStore['Twitch:PageURL'] = location.pathname; this.BetterTwitchApp.emit('BetterTwitchApp:Update.PageURL', parts[1], parts, location.pathname); } if(this.localStore['Twitch:ChannelCode'] !== parts[2]) { this.localStore['Twitch:ChannelCode'] = parts[2]; if(parts[1].match('channel')) this.BetterTwitchApp.emit('BetterTwitchApp:Channel', parts[2]); if(parts[1].match('friends')) this.BetterTwitchApp.emit('BetterTwitchApp:Whispers', parts[2]); } }, 250); this.__initialized = true; } } module.exports = CoreEvents;
var input = [ { x: 3, y: 4 }, { x: 12, y: 5 }, { x: 8, y: 15 } ]; var result = input.map(function(factors){ var c = Math.sqrt(Math.pow(factors.x, 2) + Math.pow(factors.y, 2)) return c }) console.log(result[0] === 5);//z^2 = 5 console.log(result[1] === 13);//z^2 = 13 console.log(result[2] === 17);//z^2 = 17
const mongoose = require('mongoose'); const db = process.env.MONGODB_URI || 'mongodb+srv://aayush:aayush123@cluster0.myfvg.mongodb.net/urlshortner?retryWrites=true&w=majority'; const connectDB = async () => { try { await mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('mongoose connected'); } catch (error) { console.log(error); process.exit(1); } }; module.exports = connectDB;
import React from 'react' export default function List (props){ return( <div> <img src={props.gif.images.original.url} alt=''/> </div> ) }
function create(){ var password = $("#password").val(); $("#password").empty(); var username = $("#username").val(); $("#username").empty(); var name = $("#name").val(); $("#name").empty(); var fullname = $("#fullname").val(); $("#fullname").empty(); var cuser = JSON.stringify({ "password" : password, "username" : username, "name": name, "fullname":fullname, }); console.log(cuser) $.ajax({ url: '/users', type: 'POST', contentType: 'application/json', data : cuser, dataType:'json', success: function(){ window.location="/static/html/login.html" } }); }
import { eventBus } from '../../../services/event-bus.js' export default { props: [], template: ` <section > <textarea class="note-title text-area-input" v-model="note.info.title" @change="reportVal" name="note-input" cols="50" :rows="textRowsTitle" placeholder="Title" ></textarea> <textarea class="text-area-input" v-model="note.info.txt" @change="reportVal" name="note-input" cols="50" :rows="textRows" placeholder="write your note here" ></textarea> </section> `, data() { return { note: { id: null, type: 'noteTxt', isPinned: false, info: { title: '', txt: '', todos: [], imgUrl: '', videoUrl: '' }, categories: ['notes'], bgc: '#ffff88' } } }, methods: { reportVal() { this.$emit('setVal', this.note) }, cleanInput() { this.note.info.title = '' this.note.info.txt = '' }, }, computed: { textRows() { const text = this.note.info.txt let numberOfLineBreaks = (text.match(/\n/g) || []).length let characterCount = text.length + numberOfLineBreaks return numberOfLineBreaks + characterCount / 50 + 2 }, textRowsTitle() { const text = this.note.info.title let numberOfLineBreaks = (text.match(/\n/g) || []).length let characterCount = text.length + numberOfLineBreaks return numberOfLineBreaks + characterCount / 37 + 1 }, }, created() {; eventBus.$on('cleanInput', this.cleanInput) }, }
/*jslint node:true, unparam:true */ /*global describe, it*/ "use strict"; var rb = require('../index'), assert = require('assert'), nock = require('nock'); nock('http://localhost:8080').get('/getJson123').reply(200, '{"key":"123"}'); nock('http://localhost:8080').get('/getJson321').reply(200, '{"key":"321"}'); nock('http://localhost:8080').get('/getStatus500').reply(500); describe('io test', function () { it('should return json 123', function (done) { rb.io({ uri: 'http://localhost:8080/getJson123' }, function (e, resp) { assert.equal(resp, '{"key":"123"}'); done(); }); }); it('should return json 123 in cache', function (done) { rb.io({ uri: 'http://localhost:8080/getJson123' }, function (e, resp) { assert.equal(resp, '{"key":"123"}'); done(); }); }); it('should return json 321', function (done) { rb.io({ uri: 'http://localhost:8080/getJson321' }, function (e, resp) { assert.equal(resp, '{"key":"321"}'); done(); }); }); it('should return uri undefined', function (done) { rb.io({}, function (e, resp) { assert.equal(e.message, 'no uri in args.'); done(); }); }); it('should return uri error', function (done) { rb.io({ uri: 'thth' }, function (e, resp) { assert.equal(e instanceof Error, true); done(); }); }); it('should return 500 error', function (done) { rb.io({ uri: 'http://localhost:8080/getStatus500' }, function (e, resp) { assert.equal(e instanceof Error, true); assert.equal(e.message, 500); done(); }); }); });
var _ = require('lodash'); var stats = require('stats-analysis/stats') var utils = require('./../../utils'); var ColorDetector = require('./../color-detector'); var colors = require('./../../colors'); var Guitar = function(neckHand, pickHand) { this.neckHandDetector = new ColorDetector(colors[neckHand] || neckHand); this.pickHandDetector = new ColorDetector(colors[pickHand] || pickHand); this.configuiring = 50; this.neckHandPoints = []; this.pickHandPoints = []; this.pickHandAbove = true; }; Guitar.prototype.setInstrument = function(inst) { this.inst = new inst(); }; Guitar.prototype.removeOutliers = function() { var self = this; var pickHandDistances = this.pickHandPoints.map(function(hand) { return utils.dist(hand, [self.pickHandsMeanX, self.pickHandsMeanY]); }); var neckHandDistances = this.neckHandPoints.map(function(hand) { return utils.dist(hand, [self.nickHandsMeanX, self.nickHandsMeanY]); }); var i = 0; this.pickHandPoints = _.filter(this.pickHandPoints, function() { return stats.isOutlier(pickHandDistances[i++], pickHandDistances, 3.5); }); var i = 0; this.neckHandPoints = _.filter(this.neckHandPoints, function() { return stats.isOutlier(neckHandDistances[i++], neckHandDistances, 3.5); }); }; Guitar.prototype.calculateMeans = function() { var self = this; this.pickHandsMeanX = 0; this.pickHandsMeanY = 0; this.pickHandPoints.forEach(function(hand) { self.pickHandsMeanX += hand[0]; self.pickHandsMeanY += hand[1]; }); this.pickHandsMeanX /= this.pickHandPoints.length; this.pickHandsMeanY /= this.pickHandPoints.length; this.neckHandsMeanX = 0; this.neckHandsMeanY = 0; this.neckHandPoints.forEach(function(hand) { self.neckHandsMeanX += hand[0]; self.neckHandsMeanY += hand[1]; }); this.neckHandsMeanX /= this.neckHandPoints.length; this.neckHandsMeanY /= this.neckHandPoints.length; }; Guitar.prototype.configure = function(img) { var neckHands = this.neckHandDetector.detect(img); var pickHands = this.pickHandDetector.detect(img); if (pickHands[0]) { for (var i in pickHands) { var pickHand = pickHands[i]; img.ellipse(pickHand[0], pickHand[1], 5, 5, [0, 255, 0], 2); this.pickHandPoints.push(pickHand); } } if (neckHands[0]) { for (var i in neckHands) { var neckHand = neckHands[i]; img.ellipse(neckHand[0], neckHand[1], 5, 5, [0, 0, 255], 2); this.neckHandPoints.push(neckHand); } } return img; }; Guitar.prototype.getNeckHand = function(img) { var neckHands = this.neckHandDetector.detect(img); var min = 999999; var besst = undefined; for (var i in neckHands) { var neckHand = neckHands[i]; var dist = utils.dist(neckHand, this.bestNeckHand || [this.neckHandsMeanX, this.neckHandsMeanY]); if (dist < min) { min = dist; this.bestNeckHand = best = neckHand; } } return this.bestNeckHand; }; Guitar.prototype.getPickHand = function(img) { var pickHands = this.pickHandDetector.detect(img); var min = 999999; var best = undefined; for (var i in pickHands) { var pickHand = pickHands[i]; var dist = utils.dist(pickHand, [this.pickHandsMeanX, this.pickHandsMeanY]); if (dist < min) { min = dist; best = pickHand; } } return min < 200 ? best : undefined; }; // detect guitar like movements and play notes w/ inst // returns an image to be displayed in the window var notes = ['C', 'D', 'E', 'F', 'G', 'A', 'B', 'C2']; Guitar.prototype.process = function(img) { if (this.configuiring > 0) { this.configuiring--; return this.configure(img); } else if (this.configuiring !== false) { this.calculateMeans(); this.removeOutliers(); this.configuiring = false; } else { var neckHand = this.getNeckHand(img); var pickHand = this.getPickHand(img); img.line([this.pickHandsMeanX, this.pickHandsMeanY], [this.neckHandsMeanX, this.neckHandsMeanY]); img.line([this.pickHandsMeanX, this.pickHandsMeanY], neckHand, [255, 0, 0], 4); img.ellipse(this.pickHandsMeanX, this.pickHandsMeanY, 200, 200, [0, 255, 0], 2); img.ellipse(this.neckHandsMeanX, this.neckHandsMeanY, 5, 5, [0, 0, 255], 2); for (var i = 112; i < 1000; i += 112) { img.ellipse(this.pickHandsMeanX, this.pickHandsMeanY, i, i, [200, 0, 100], 2); } if (pickHand) { img.ellipse(pickHand[0], pickHand[1], 5, 5, [0, 0, 255], 8); var aboveOrBelow = this.pickHandsMeanY - pickHand[1]; var above = aboveOrBelow < 0; if (this.pickHandAbove != above) { this.pickHandAbove = above; var dist = utils.dist(neckHand, [this.pickHandsMeanX, this.pickHandsMeanY]); // var octave = Math.floor(dist / 90); // var note = Math.floor(Math.floor(dist % 90) / 7.5); var note = 8 - Math.floor(dist / 112); this.inst.play(notes[note] || 'B', 2); } } } return img; }; module.exports = Guitar;
"use strict"; function renderOutput(output) { let output_element = document.getElementById("output"); output_element.innerHTML += "<div>" + output + "</div>" } function days_hours(data) { let separate = data.split(": "); let day = separate[0]; let times = separate[1]; if (times === "closed") { renderOutput("On " + day + " the library is " + times); } else { renderOutput("On " + day + " the hours are " + times); } } function dailyHours(hours) { hours.forEach(days_hours); } dailyHours(hours);
BasicGame.InstructionsMenu = function (game) { this.menuMusic; this.menuItems; }; BasicGame.InstructionsMenu.prototype = { init: function(menuMusic) { // start the menu music as ealy as possible this.menuMusic = menuMusic; }, create: function () { console.log("Instructions menu"); this.menuItems = this.game.add.group(); // set the backgrounds this.farBackground = this.game.add.sprite(0, 0, 'far-background'); this.nearBackground = this.game.add.sprite(0,0, 'near-background'); // holder for the buttons this.title = this.game.add.sprite((this.game.width/2) - 272, 30, 'ui', 'instructionsPanel.png'); this.menuItems.add(this.title); // add action buttons this.mainMenuButton = this.game.add.button(this.game.width/2, 600, 'ui', this.menuClick, this, 'mainMenu.png', 'mainMenu.png', 'mainMenu.png'); this.mainMenuButton.anchor.setTo(0.5, 0.5); this.menuItems.add(this.mainMenuButton); // bring buttons / holder to the front this.game.world.bringToTop(this.menuItems); }, update: function () { // Do some nice funky main menu effect here }, resize: function (width, height) { // If the game container is resized this function will be called automatically. // You can use it to align sprites that should be fixed in place and other responsive display things. }, menuClick: function(){ // basic fade into the game this.state.start('MainMenu', false, false, this.menuMusic); } };
var users = require('./users'), when = require('when'), Boom = require('boom'), validator = require('validator'), utils = require('./utils'), _ = require('lodash'); /** * Index file comprising the core functionality. Exports user core and * additional core helper functions */ module.exports = { /** * @returns user core functions */ users: users, /** * Check if provided authentication token exists in database */ isAuthorized: function(object) { if (_.isEmpty(object.auth_token)) { throw new Boom.badRequest('Authorization required'); } users.findByAuthToken(object.auth_token).then(function(user) { return when.resolve(user); }).catch(function(error) { return when.reject(new Boom.unauthorized('Authorization required')); }); } };
const promise1 = first(); const promise2 = promise1.then((option) => { return second(option); }); promise2.then(console.log);
import React from 'react' import { Provider } from 'react-redux' import { cleanup, render, fireEvent } from '@testing-library/react-native' import Register from './Register' import configureStore from 'redux-mock-store' import * as action from '../../redux/actions/fairHandActionCreators' jest.mock('../../redux/actions/fairHandActionCreators') const mockStore = configureStore() jest.spyOn(action, 'userRegister').mockReturnValue({ type: '' }) describe('Given a component Login', () => { let store let component let goBack let navigate beforeEach(() => { store = mockStore({ userReducer: { user: [] } }) goBack = jest.fn() navigate = jest.fn() component = (<Provider store={store}><Register navigation={{ goBack, navigate }}/></Provider>) }) afterEach(() => cleanup()) it('It should match the snapshot', () => { render(component) expect(component).toMatchSnapshot() }) describe('When pressing a goBack button', () => { it('It should call navigation.goBack()', () => { const { getByTestId } = render(component) fireEvent.press(getByTestId('go-back')) expect(goBack).toHaveBeenCalled() }) }) describe('When changing the input of the name field to Pablo', () => { it('It should change the value name to Pablo', () => { const { getByPlaceholderText } = render(component) const newNameValue = 'Pablo' const inputName = getByPlaceholderText('Name') fireEvent.changeText(inputName, newNameValue) expect(inputName.props.value).toBe(newNameValue) }) }) describe('When changing the input of the email to pablo@gmail.com', () => { it('It should change the value email to pablo@gmail.com', () => { const { getByPlaceholderText } = render(component) const newEmailValue = 'pablo@gmail.com' const inputEmail = getByPlaceholderText('Email') fireEvent.changeText(inputEmail, newEmailValue) expect(inputEmail.props.value).toBe(newEmailValue) }) }) describe('When changing the input of the password to a1234567', () => { it('It should change the value password to a1234567', () => { const { getByPlaceholderText } = render(component) const newPasswordValue = 'a1234567' const inputPassword = getByPlaceholderText('Password') fireEvent.changeText(inputPassword, newPasswordValue) expect(inputPassword.props.value).toBe(newPasswordValue) }) }) describe('When changing the input of the repeate password to a1234567', () => { it('It should change the value repeated password to a1234567', () => { const { getByPlaceholderText } = render(component) const newRepeatPasswordValue = 'a1234567' const inputRepeatPassword = getByPlaceholderText('Repeat password') fireEvent.changeText(inputRepeatPassword, newRepeatPasswordValue) expect(inputRepeatPassword.props.value).toBe(newRepeatPasswordValue) }) }) describe('When pressing on SUBMIT with an invalid email', () => { it('It should call the alert with \'Please add a valid email\' ', () => { const { getByTestId, getByPlaceholderText } = render(component) global.alert = jest.fn() const newNameValue = 'Pablo' const inputName = getByPlaceholderText('Name') fireEvent.changeText(inputName, newNameValue) const newEmailValue = 'pablomail.com' const inputEmail = getByPlaceholderText('Email') fireEvent.changeText(inputEmail, newEmailValue) const newPasswordValue = 'a1234567' const inputPassword = getByPlaceholderText('Password') fireEvent.changeText(inputPassword, newPasswordValue) const newRepeatPasswordValue = 'a1234567' const inputRepeatPassword = getByPlaceholderText('Repeat password') fireEvent.changeText(inputRepeatPassword, newRepeatPasswordValue) fireEvent.press(getByTestId('valid-input')) expect(global.alert).toHaveBeenCalledWith('Please add a valid email') }) }) describe('When pressing on SUBMIT with an invalid password', () => { it('It should call the alert with \'Please add a valid password! Minimum of 8 characters and at least one letter\' ', () => { const { getByTestId, getByPlaceholderText } = render(component) global.alert = jest.fn() const newNameValue = 'Pablo' const inputName = getByPlaceholderText('Name') fireEvent.changeText(inputName, newNameValue) const newEmailValue = 'pablo@gmail.com' const inputEmail = getByPlaceholderText('Email') fireEvent.changeText(inputEmail, newEmailValue) const newPasswordValue = '34567' const inputPassword = getByPlaceholderText('Password') fireEvent.changeText(inputPassword, newPasswordValue) const newRepeatPasswordValue = 'a1234567' const inputRepeatPassword = getByPlaceholderText('Repeat password') fireEvent.changeText(inputRepeatPassword, newRepeatPasswordValue) fireEvent.press(getByTestId('valid-input')) expect(global.alert).toHaveBeenCalledWith('Please add a valid password! Minimum of 8 characters and at least one letter') }) }) describe('When pressing on SUBMIT with valid inputs', () => { it('It should call the alert with \'Thank you for joining Fairhand!\' ', () => { const { getByTestId, getByPlaceholderText } = render(component) global.alert = jest.fn() const newNameValue = 'Pablo' const inputName = getByPlaceholderText('Name') fireEvent.changeText(inputName, newNameValue) const newEmailValue = 'pablo@gmail.com' const inputEmail = getByPlaceholderText('Email') fireEvent.changeText(inputEmail, newEmailValue) const newPasswordValue = 'a1234567' const inputPassword = getByPlaceholderText('Password') fireEvent.changeText(inputPassword, newPasswordValue) const newRepeatPasswordValue = 'a1234567' const inputRepeatPassword = getByPlaceholderText('Repeat password') fireEvent.changeText(inputRepeatPassword, newRepeatPasswordValue) fireEvent.press(getByTestId('valid-input')) expect(global.alert).toHaveBeenCalledWith('Thank you for joining Fairhand!') }) it('It should call navigation.navigate', () => { component = ( <Provider store={mockStore({ userReducer: { user: { email: 'pablo@gmail.com' } } })}><Register navigation={{ goBack, navigate }}/></Provider>) render(component) expect(navigate).toHaveBeenCalledWith('TabNavigator') }) }) })
import React from 'react'; import styled from 'styled-components'; import PokemonListContainer from '../containers/PokemonListContainer'; import PokemonDetailsContainer from '../containers/PokemonDetailsContainer'; import SquadCard from '../components/SquadCard'; // import propTypes from 'prop-types'; const Logo = styled.img` display: block; margin: 0 auto; max-width: 200px; `; const Container = styled.div` max-width: 980px; margin: 0 auto; display: flex; flex-direction: column; `; const LogoRow = styled.div` display: flex; flex-direction: row; margin-bottom: 60px; `; const Row = styled.div` display: flex; flex-direction: row; > .row__title { text-align: center; flex: 1; } `; const SelectColumn = styled.div` flex: 1; `; const DetailColumn = styled.div` flex: 4; `; const CardColumn = styled.div` flex: 1; max-width: 16%; margin: 5px; `; class MainView extends React.Component { state = { selectedPokemon: {}, selectedPokemonMove: null, savedPokemon: [], } handlePokemonSelection = (pokemon) => { if(pokemon.id !== this.state.selectedPokemon.id) { this.handlePokemonResetStats(); this.setState({ selectedPokemon: pokemon, }) } } handlePokemonMoveAdd = (moves) => { if (!this.state.selectedPokemonMove || this.state.selectedPokemonMove.length < 4) { this.setState({ selectedPokemonMove: [ ...moves, ] }) } } handlePokemonMoveRemove = (moves) => { this.setState({ selectedPokemonMove: moves, }) } handlePokemonResetStats = () => { this.setState({ selectedPokemonMove: null, }) } handlePokemonSave = (pokemonDetails) => { if(this.state.savedPokemon.length > 5) { return; } let selectedMoves = this.state.selectedPokemonMove; if(selectedMoves === null) { selectedMoves = pokemonDetails.abilities; } this.setState({ savedPokemon: [ ...this.state.savedPokemon, { ...pokemonDetails, moves: selectedMoves, } ] }, () => console.log(this.state)); } render() { return ( <Container> <LogoRow> <Logo src="https://vignette.wikia.nocookie.net/logopedia/images/2/2b/Pokemon_2D_logo.svg/revision/latest/scale-to-width-down/639?cb=20170115063554" /> </LogoRow> <Row> <SelectColumn> <PokemonListContainer onClickItem={this.handlePokemonSelection} /> </SelectColumn> <DetailColumn> <PokemonDetailsContainer selectedPokemon={this.state.selectedPokemon} onSavePokemon={this.handlePokemonSave} selectedMoves={this.state.selectedPokemonMove} onSelectMove={this.handlePokemonMoveAdd} onRemoveMove={this.handlePokemonMoveRemove} /> </DetailColumn> </Row> <Row> <div className="row__title">SELECTED SQUAD</div> </Row> <Row> { this.state.savedPokemon.map(pokemon => ( <CardColumn key={`${pokemon.id}-${Math.random()}`}> <SquadCard pokemon={pokemon} /> </CardColumn> )) } </Row> </Container> ); } }; export default MainView;
export const FETCH_ANY = 'FETCH_ANY'; export const FETCH_ONLY = 'FETCH_ONLY'; export const CREATE_AD = 'CREATE_AD'; import axios from 'axios'; import {get} from 'jquery'; export function fetchAny(tags, categorys) { // api call let url = ('/api/findPostsWithAny/' + tags + '/' + categorys) const request = axios.get(url) return { type: FETCH_ANY, payload: request } } export function fetchOnly(tags, categorys) { // api call console.log(tags, categorys) let url = ('/api/findPostsWithOnly/' + tags + '/' + categorys) const request = axios.get(url) return { type: FETCH_ONLY, payload: request } } export function createAd(ad) { // api call let url = ('/api/createPost/') axios.post(url, { category: ad.category, title: ad.title, description: ad.description, images: [ad.image], email: ad.email, tags: ad.tags }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); return { type: CREATE_AD, payload: null } }
import Ember from 'ember'; import Promise from './promise'; export default Promise.extend({ _validators : null, init : function() { this._validators=Ember.A(); }, push : function(validator) { this._validators.push(validator); }, _validate : function(context) { var validator=this; context.result._valCountIncrease(); var promises=Ember.A(); promises.pushObjects(this._validators.invoke('_validate',context)); return Ember.RSVP.all(promises,validator.constructor.toString()+" All validations for "+context.path).then(function(values) { return context.result; },function(e) { return e; },validator.constructor.toString()+" Validations resolved").finally(function(){ context.result._valCountDecrease(); }); }, _observe : function(observer) { this._super(observer); var parent=this; this._validators.forEach(function(validator) { validator._observe(observer); }); } });
import React from 'react'; const Loading = props => { return ( <div className="d-flex align-items-center"> <strong>Loading...</strong> </div> ); }; export default Loading;
/** * Created by Asus on 3/30/2017. */ import React, {Component} from 'react'; import '../resource/bootstrap/css/bootstrap.min.css'; import '../resource/font-awesome/css/font-awesome.min.css'; import $ from 'jquery'; import "./main.css" import "../resource/main.css" import {Link} from 'react-router'; import {Error, Success} from '../Notify' // Import Notyf using CommonJS require var Notyf = require('notyf'); import 'notyf/dist/notyf.min.css'; // Create an instance of Notyf var notyf = new Notyf({ delay: 5000, }); class Register extends Component { constructor(props) { super(props); this.state = { name: '', email: '', password: '', success: false, confirmPassword: '', error: false } this._handleChange = this._handleChange.bind(this); this.fetchRegister = this.fetchRegister.bind(this); this.validateInput = this.validateInput.bind(this); this.resetForm = this.resetForm.bind(this); } resetForm() { let reset = document.getElementsByClassName('form-control'); for (var i = 0; i < reset.length; i++) { reset[i].value = ""; } } validateInput() { if (!this.state.name.trim().match(/^[a-zA-Z0-9_]{2,30}$/)) { notyf.alert("Username can't contain special character except '_' character"); return false; } if (this.state.password.trim() !== this.state.confirmPassword.trim()) { notyf.alert("Password and Confirm Password is not match"); return false; } else if (!this.state.password.trim().match(/^[0-9a-zA-Z@]{6,}$/)) { notyf.alert("The length of password must be 6 character at least and not contain special character"); return false; } else { this.setState({error: false}); return true; } } fetchRegister(event) { event.preventDefault(); let valid = this.validateInput(); if (valid) { $.ajax({ url: 'http://990614f2.ngrok.io/register', method: 'POST', // headers: { "Access-Control-Allow-Origin": "*" }, data: { name: this.state.name, email: this.state.email, password: this.state.password }, success: function (data) { this.setState({success: 'success'}); this.resetForm(); }.bind(this), error: function (err) { notyf.alert('Email existed. Please try another'); this.setState({ // error: 'Email existed. Please try another', success: false }); }.bind(this) }); } } _handleChange(event, attribute) { let newState = this.state; newState[attribute] = event.target.value; this.setState(newState); } render() { return ( <div className="overlay"> <div className="register-box"> <div className="popup-form-title"> <h1>Register</h1> </div> {this.state.error ? <Error error={this.state.error}/> : null} {this.state.success ? <Success/> : null} <div> <form onSubmit={(event) => this.fetchRegister(event)}> <div className="input-group"> <div className="input-group-addon"> <i className="fa fa-envelope" aria-hidden="true"/> </div> <input type="email" className="form-control" name="txtEmail" placeholder="Email" required onChange={(event) => this._handleChange(event, 'email')}/> </div> <div className="input-group"> <div className="input-group-addon"> <i className="fa fa-user" aria-hidden="true"/> </div> <input type="text" className="form-control" name="txtUsername" placeholder="Name" required onChange={(event) => this._handleChange(event, 'name')}/> </div> <div className="input-group"> <div className="input-group-addon"> <i className="fa fa-key" aria-hidden="true"/> </div> <input type="password" className="form-control" name="txtPassword" placeholder="Password" required onChange={(event) => this._handleChange(event, 'password')} /> </div> <div className="input-group"> <div className="input-group-addon"> <i className="fa fa-key" aria-hidden="true"/> </div> <input type="password" className="form-control" name="txtConfirmPassword" placeholder="Confirm Password" required onChange={(event) => this._handleChange(event, 'confirmPassword')}/> </div> <div className="input-group"> <input className="btn btn-success btn-block" id="btnRegister" type="submit" value="Register"/> </div> <div id="login-link" className="text-center"><Link to='/sign_in'>Login with existed account</Link></div> </form> </div> </div> </div> ); } } export default Register;
var http = require('http'); var https = require('https'); var _ = require('underscore'); var Crawler = require('../../crawler').Crawler; describe('Crawler._request method', function () { 'use strict'; var crawler; var mockRequest; var mockResponse; var noResponse; var COMMON_MEDIA_EXCLUDES = [ '3gp', 'aif', 'asf', 'asx', 'avi', 'flv', 'iff', 'm3u', 'm4a', 'm4p', 'm4v', 'mov', 'mp3', 'mp4', 'mpa', 'mpg', 'mpeg', 'ogg', 'ra', 'raw', 'rm', 'swf', 'vob', 'wav', 'wma', 'wmv' ]; beforeEach(function () { crawler = new Crawler(); noResponse = false; mockRequest = { abort: jasmine.createSpy('request.abort'), end: jasmine.createSpy('request.end'), on: jasmine.createSpy('request.on') }; mockResponse = { headers: {}, statusCode: 200, on: jasmine.createSpy('response.on') }; spyOn(http, 'request').andCallFake(function (params, callback) { setTimeout(function () { if (noResponse === false) { callback(mockResponse); } }, 10); return mockRequest; }); spyOn(https, 'request').andCallFake(function (params, callback) { setTimeout(function () { if (noResponse === false) { callback(mockResponse); } }, 10); return mockRequest; }); }); it('performs an HTTP request', function (done) { crawler._request({ url: 'http://www.google.com/' }, function () { expect(http.request).toHaveBeenCalledWith({ protocol: 'http:', host: 'www.google.com', port: null, path: '/', method: 'GET', rejectUnauthorized: false, headers: { 'Accept': jasmine.any(String), 'Accept-Encoding': jasmine.any(String), 'Accept-Language': jasmine.any(String), 'cookie': jasmine.any(String), 'User-Agent': jasmine.any(String), 'PageSpeed': 'off' } }, jasmine.any(Function)); expect(mockRequest.end).toHaveBeenCalled(); done(); }); }); it('performs an HTTPS request', function (done) { crawler._request({ url: 'https://www.google.com/' }, function () { expect(https.request).toHaveBeenCalledWith({ protocol: 'https:', host: 'www.google.com', port: null, path: '/', method: 'GET', rejectUnauthorized: false, headers: { 'Accept': jasmine.any(String), 'Accept-Encoding': jasmine.any(String), 'Accept-Language': jasmine.any(String), 'cookie': jasmine.any(String), 'User-Agent': jasmine.any(String), 'PageSpeed': 'off' } }, jasmine.any(Function)); expect(mockRequest.end).toHaveBeenCalled(); done(); }); }); it('times out after specified timeout', function (done) { crawler._request({ url: 'https://www.google.com/', timeout: 1 }, function (error, response, body) { expect(mockRequest.abort).toHaveBeenCalled(); expect(error).toEqual({ message: 'Request timed out.', code: 'ETIMEDOUT' }); expect(body.toString()).toBe(''); done(); }); }); it('executes callback on error with no response', function (done) { noResponse = true; mockRequest.on.andCallFake(function (event, callback) { callback(new Error('some error')); }); crawler._request({ url: 'https://www.google.com/' }, function (error, response, body) { expect(error.message).toBe('some error'); expect(response).toBe(undefined); expect(body.toString()).toBe(''); done(); }); }); it('executes callback with response even when error occurs', function (done) { mockRequest.on.andCallFake(function (event, callback) { callback(new Error('some error')); }); crawler._request({ url: 'https://www.google.com/' }, function (error, response) { expect(error.message).toBe('some error'); expect(response).toBe(mockResponse); done(); }); }); it('follows redirects', function (done) { mockResponse.statusCode = 301; mockResponse.headers.location = 'http://www.google.com/some-other-page'; crawler._request({ url: 'http://www.google.com/' }, function () { expect(http.request.calls.length).toBe(2); expect(mockRequest.abort.calls.length).toBe(2); expect(http.request).toHaveBeenCalledWith({ protocol: 'http:', host: 'www.google.com', port: null, path: '/some-other-page', method: 'GET', rejectUnauthorized: false, headers: { 'Accept': jasmine.any(String), 'Accept-Encoding': jasmine.any(String), 'Accept-Language': jasmine.any(String), 'cookie': jasmine.any(String), 'User-Agent': jasmine.any(String), 'PageSpeed': 'off' } }, jasmine.any(Function)); done(); }); setTimeout(function () { mockResponse.statusCode = 200; mockResponse.headers.location = null; }, 10); }); it('follows redirects relative to the url of the current redirect (when domains change)', function (done) { mockResponse.statusCode = 301; mockResponse.headers.location = 'http://www.bing.com/some-other-page'; crawler._request({ url: 'http://www.google.com/' }, function () { expect(http.request.calls[2].args[0].host).toBe('www.bing.com'); expect(http.request.calls[2].args[0].path).toBe('/another-page'); done(); }); setTimeout(function () { mockResponse.statusCode = 301; mockResponse.headers.location = '/another-page'; }, 10); setTimeout(function () { mockResponse.statusCode = 200; mockResponse.headers.location = null; }, 50); }); it('aborts request when running against non-text files', function (done) { mockResponse.headers['content-type'] = 'application/pdf'; crawler._request({ url: 'https://www.google.com/file.html' }, function () { expect(mockRequest.abort).toHaveBeenCalled(); done(); }); }); it('aborts request when running against an external page', function (done) { mockResponse.headers['content-type'] = 'text/html'; crawler._request({ url: 'http://www.google.com/', isExternal: true }, function (error, response, body) { expect(mockRequest.abort).toHaveBeenCalled(); expect(body.toString()).toBe(''); done(); }); }); _.each(COMMON_MEDIA_EXCLUDES, function (type) { it('aborts request when running against "' + type + '" files', function (done) { crawler._request({ url: 'http://domain.com/file.' + type }, function () { expect(mockRequest.abort).toHaveBeenCalled(); done(); }); }); }); it('returns a body on status code 200 requests', function (done) { mockResponse.headers['content-type'] = 'text/html'; mockResponse.on.andCallFake(function (event, callback) { callback(new Buffer('some body')); }); crawler._request({ url: 'https://www.google.com/' }, function (error, response, body) { expect(mockRequest.abort).not.toHaveBeenCalled(); expect(error).toBe(null); expect(response).toBe(mockResponse); expect(body).toBe('some body'); done(); }); }); });
import React, { useState, useEffect } from 'react' import AuthenticationContext from './AuthenticationContext' import useApi from '../../hooks/useApi' // import { useHistory } from 'react-router' const storedToken = window.localStorage.getItem('token') const AuthenticationWrapper = ({ children }) => { const { api } = useApi() const [token, setToken] = useState(storedToken) useEffect(() => { window.localStorage.setItem('token', token) api.setToken(token) }, [token, api]) const authenticate = async ({ username, password }) => { const res = await api.post('/auth/token/', { username, password }) if (res.status === 200 && res.data.token) { setToken(res.data.token) console.log(res.data.token) console.log(res) return true } console.log('Errored viado') setToken(null) return false } const register = async ({ username, email, password, passwordConfirmation }) => { const res = await api.post('/auth/register/', { username, email, password }) if (res.status === 201 && res.data.created_id) { await authenticate({ username, password }) return true } return false } const logout = () => { setToken(null) } return ( <AuthenticationContext.Provider value={{ authenticate, register, logout, token: api.token }} > {children} </AuthenticationContext.Provider> ) } export default AuthenticationWrapper
// https://www.hackerrank.com/challenges/dynamic-array/problem function dynamicArray(n, queries) { let lastAns = 0; let seqList = Array(n).fill(null); let results = []; // console.log(queries, seqList); queries.forEach(v => { const [type, x, y] = v; const index = (x ^ lastAns) % n; if (type === 1) { if (seqList[index] === null) { let myList = []; myList.push(y); seqList[index] = myList; } else { seqList[index].push(y); } } else { lastAns = seqList[index][y % seqList[index].length]; results.push(lastAns); } }); return results; } function main() { const n = 2; input = `1 0 5 1 1 7 1 0 3 2 1 0 2 1 1`; queries = input.split("\n").map(v => v.split(" ").map(Number)); console.log(dynamicArray(2, queries).join("\n") + "\n"); } main();
const bcrypt = require("bcryptjs"); module.exports = function(sequelize, DataTypes) { let User = sequelize.define("User", { username: { type: DataTypes.STRING, allowNull: false, unique: true, validate: { min: 6, notNull: { msg: "Please enter a username" } } }, email: { type: DataTypes.STRING, allowNull: false, validate: { isEmail: true, // msg: "This field must be a valid email.", // notNull: { // msg: "Email is required." // } } }, password: { type: DataTypes.STRING, allowNull: false, validate: { min: 8, // msg: "Password requires at least 8 characters.", // notNull: { // msg: "A password is required." // } } } }); User.addHook("beforeCreate", function(user) { user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null); }); User.prototype.validPassword = function(password) { return bcrypt.compareSync(password, this.password); }; return User; }
import styled from 'styled-components'; export const Container = styled.div` width:100%; margin: 80px auto; display: flex; flex-direction:column; `;
#! /usr/bin/env node const Koa = require('koa'); const app = new Koa(); const comander = require('commander'); const {exec} = require('child_process'); const fs = require('fs'); const rootPath = process.cwd(); const inquirer = require('inquirer'); const static = require('koa-static'); const path = require('path'); comander.version(require('../package.json').version); comander.option("-p, --port <port>",'请输入端口号'); comander.parse(process.argv); const PORT = comander.port || 8000; app.use(static(rootPath)); //static 处理文件 app.use(async (ctx,next)=>{ //文件夹 ///day1 let url = decodeURI(ctx.request.url); let data = fs.readdirSync(path.join(rootPath,url)); ctx.body = `<ul> ${ data.map(item=>`<li><a href="${path.join(url,item)}">${item}</a></li>`).join('') } </ul>` }) app.listen(PORT,()=>{ console.log(`Running at http://localhost:${PORT}`); //自动打开浏览器(进程) exec(`start http://localhost:${PORT}`); });
// Dependencies import React, { Component } from 'react' import PropTypes from 'prop-types' // App components import EpisodeComponent from './Episode' import Breadcrumbs from '../Breadcrumbs/Breadcrumbs' /** * The Episode List component presents a list of episodes for a given TV watchlist * item, split by seasons. * @type {Object} */ export default class EpisodeList extends Component { constructor(props) { super(props) this.state = { episodes: props.episodes, seasons: this.getSeasons(), // Determine how many seasons the item has. } } /** * Compile a list of seasons. * @return {Array} The collection of seasons from the available episodes. */ getSeasons() { const { episodes } = this.props const seasons = [] for (let i = 0; i < episodes.length; i += 1) { if (!seasons.includes(episodes[i].seasonNumber)) { seasons.push(episodes[i].seasonNumber) } } return seasons } /** * Render each of the episodes for a given season. * @param {Number} season The season for which episodes should be rendered. * @return {Object} The rendered episodes. */ renderEpisodes(season) { const episodes = this.state.episodes.filter(episode => episode.seasonNumber === season) return episodes.map(episode => ( <EpisodeComponent key={episode.id} {...episode} /> )) } /** * Render the available seasons and all episodes for each. * @return {Object} The rendered seasons. */ renderSeasons() { return this.state.seasons.map(season => ( <li key={season} className="c-episodelist-season"> <h2 id={`Season${season}`}>Season {season}</h2> <ol className="u-unstyled-list"> {this.renderEpisodes(season)} </ol> </li> )) } /** * Render the component. * @return {Object} The rendered component. */ render() { const seasonList = this.state.seasons.map(season => `Season ${season}`) return ( <div className="o-container c-episodelist"> <Breadcrumbs itemName="Season" list={seasonList} /> <ol className="u-unstyled-list"> {this.renderSeasons()} </ol> </div> ) } } /** * Define the property types. * @type {Object} */ EpisodeList.propTypes = { episodes: PropTypes.array, } /** * Set the default values for each property. * @type {Object} */ EpisodeList.defaultProps = { episodes: [], }
var gulp = require('gulp'); var sync = require('browser-sync'); var rename = require('gulp-rename'); var csso = require('gulp-csso'); var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); //for browser reloading gulp.task('default',function(){ sync({ server:{ baseDir: './' } }) gulp.watch('./*.html',sync.reload); gulp.watch('./*.css',['compressed-css']); gulp.watch('./*.js',['compressed-js']); }) //for compressed css gulp.task('compressed-css',function(){ return gulp.src('./*.css') .pipe(csso()) .pipe(rename({suffix: 'min'})) .pipe(gulp.dest('./minified')) }) //for compressed js gulp.task('compressed-js',function(){ return gulp.src('./*.js') .pipe(uglify()) .pipe(rename({suffix: 'min'})) .pipe(gulp.dest('./minified')) })
import { NavLink } from "react-router-dom"; const Leftnav = () => { return ( <div className="left-nav"> {/* Logo */} <div className="logo"> <NavLink to="/"> <img src="https://cdn.discordapp.com/attachments/641570546198249472/705386480234922054/dragon-1578289_960_720.webp" alt="logo" /> </NavLink> </div> </div> ); }; export default Leftnav;
import React, { Component } from "react"; import "./News.css"; import axios from "axios"; import SecNavbar from "../SecNavbar"; class News extends Component { constructor(props) { super(props); this.state = { articles: [], date: "" }; this.getDate = this.getDate.bind(this); this.getContent = this.getContent.bind(this); } componentDidMount() { axios .get( `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=5a86604b83ed474991ed1221830dd50b` ) .then(res => { const articles = res.data; this.setState({ articles: articles.articles }); }); } getContent() { let content = []; for (let i = 0; i < 6; i++) { let article = this.state.articles.length !== 0 ? this.state.articles[i] : "TOPIC "; content.push( <a href={article.url} style={{ marginBottom: "100px" }}> <div className="item"> <img className="news-image" alt="news-content-left" src={article.urlToImage} /> <div className="topic">{article.title}</div> <div className="news-author"> <b>By: </b> <em>{article.author}</em> </div> <div className="news-author"> <b>Published: </b> <em>{this.state.date}</em> </div> <div className="news-text">{article.description}</div> </div> </a> ); } return content; } getDate() { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); if (dd < 10) { dd = "0" + dd; } if (mm < 10) { mm = "0" + mm; } today = mm + "/" + dd + "/" + yyyy; this.setState({ date: today }); } render() { if (this.state.date === "") this.getDate(); let content = this.getContent(); const topbg = { backgroundImage: "url('../assets/newsbg.jpg')" }; return [ <SecNavbar />, <div className="news"> <div className="news-top" style={topbg}> <div className="news-top-first-title">TechCrunch</div> <div className="news-top-second-title">NEWSLETTER</div> </div> <div className="news-date"> <p>Date: {this.state.date}</p> </div> <div className="news-content">{content}</div> </div>, <div className="thanks">Powered by 'News API'.</div> ]; } } export default News;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './containers/App'; import Footer from './pages/footer' import 'normalize.css' import './index.css'; ReactDOM.render(<App />,document.getElementById('root'));
jQuery(document).ready(function($){ var toggleMinus = jQuery('#minus').attr('src'); var togglePlus = jQuery('#plus').attr('src'); var firstTd = jQuery('.site404LogRow td:first-child'); firstTd.prepend('<img src="' + togglePlus + '" alt="expand this section" />'); //hide the detail rows jQuery('.site404LogDetailRow').hide(); jQuery('img', firstTd).addClass('clickable').click(function() { var toggleSrc = jQuery(this).attr('src'); if ( toggleSrc == togglePlus ) { jQuery(this).attr('src', toggleMinus).parent().parent().next('.site404LogDetailRow').toggle(); } else { jQuery(this).attr('src', togglePlus).parent().parent().next('.site404LogDetailRow').toggle(); } }) ; });
/** * Created by Liujie on 2016/10/19. * 时间 初始化 */ (function (win, doc, $) { function timeInit() { } //其他格式 转换为 "2016/01/02" timeInit.prototype.initStr = function (time) { if (time == 0 || !time) { return ""; } //debugger time = new Date(time).toLocaleDateString();//转换为 YYYY/MM/DD return time; }; //其他格式 转换为 "2016/01/02 10:12:23" timeInit.prototype.initString = function (time) { if (time == 0 || !time) { return ""; } //debugger time = new Date(time);//转换为 时间戳 //获取完整的年份(4位,1970-????) var year = time.getFullYear();//获取当前月份(0-11,0代表1月) var month = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : (time.getMonth() + 1); var day = time.getDate() < 10 ? "0" + time.getDate() : time.getDate(); //获取当前日(1-31) var hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours(); var minute = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes(); var second = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds(); var timeList = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second; return time; }; /* 倒计时 (秒) * 传入参数: * 当前时间 currentTime * 结束时间 endTIme * 倒计时执行时的方法 succFunc * 倒计时执行结束方法 endFunc * 传出参数: * 60 (秒) */ timeInit.prototype.timeDownToSS = function (currentTime, endTime, succFunc, endFunc) { if (!currentTime || !endTime) { throw "时间参数错误" } var intDiff = (endTime - currentTime) / 1000; function timeDown() { if (intDiff >= 0) { var second = Math.floor(intDiff % 60); succFunc(second);// var timeOut = setTimeout(function () { if (intDiff > 0) { intDiff -= 1; timeDown(); } else { clearTimeout(timeOut); endFunc(); } }, 1000); } else { endFunc(); } } timeDown(); }; /* 倒计时 (时分秒) 单个倒计时 * 传入参数: * 当前时间 currentTime * 结束时间 endTIme * 倒计时执行时的方法 succFunc * 倒计时执行结束方法 endFunc * 传出参数: * 11:12:03 (时分秒) */ timeInit.prototype.timeDownToHHMMSS = function (currentTime, endTime, succFunc, endFunc) { if (!currentTime || !endTime) { throw "时间参数错误" } currentTime = currentTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" endTime = endTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" currentTime = new Date(currentTime).getTime(); endTime = new Date(endTime).getTime(); var intDiff = (endTime - currentTime) / 1000; //console.info(intDiff); function timeDown() { if (intDiff >= 0) { var second = Math.floor(intDiff % 60); var minute = Math.floor((intDiff / 60) % 60); var hour = Math.floor((intDiff / 3600)); hour = hour < 10 ? "0" + hour : hour; minute = minute < 10 ? "0" + minute : minute; second = second < 10 ? "0" + second : second; var count_down = hour + ":" + minute + ":" + second; succFunc(count_down);// var timeOut = setTimeout(function () { if (intDiff > 0) { intDiff -= 1; timeDown(); } else { clearTimeout(timeOut); endFunc(); } }, 1000); } else { endFunc(); } } timeDown(); }; //倒计时(多个) (时分秒) timeInit.prototype.timeDownToHHMMSSEach = function (currentTime, endTime, self, endFunc) { if (!currentTime || !endTime) { throw "时间参数错误" } currentTime = currentTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" endTime = endTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" currentTime = new Date(currentTime).getTime(); endTime = new Date(endTime).getTime(); var intDiff = (endTime - currentTime) / 1000; function timeDown() { if (intDiff >= 0) { var second = Math.floor(intDiff % 60); var minute = Math.floor((intDiff / 60) % 60); var hour = Math.floor((intDiff / 3600) % 24); hour = hour < 10 ? "0" + hour : hour; minute = minute < 10 ? "0" + minute : minute; second = second < 10 ? "0" + second : second; var count_down = hour + ":" + minute + ":" + second; $(self).html(count_down);// var timeOut = setTimeout(function () { if (intDiff > 0) { intDiff -= 1; timeDown(); } else { clearTimeout(timeOut); endFunc(self); } }, 1000); } else { endFunc(self); } } timeDown(); }; //倒计时 (分秒毫秒) timeInit.prototype.timeDownToMMSSMS = function (currentTime, endTime, succFunc, endFunc) { if (!currentTime || !endTime) { throw "时间参数错误" } currentTime = currentTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" endTime = endTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" currentTime = new Date(currentTime).getTime(); endTime = new Date(endTime).getTime(); var intDiff = endTime - currentTime; console.info(intDiff); function timeDown() { if (intDiff >= 0) { var ms = Math.floor(intDiff % 1000 / 10); var second = Math.floor(intDiff / 1000 % 60); var minute = Math.floor((intDiff / 1000 / 60) % 60); minute = minute < 10 ? "0" + minute : minute; second = second < 10 ? "0" + second : second; ms = ms < 10 ? "0" + ms : ms; var count_down = minute + ":" + second + ":" + ms; succFunc(count_down);// var timeOut = setTimeout(function () { if (intDiff > 0) { intDiff -= 20; timeDown(); } else { clearTimeout(timeOut); endFunc(); } }, 20); } else { endFunc(); } } timeDown(); }; //倒计时(多个) (分秒毫秒) timeInit.prototype.timeDownToMMSSMSEach = function (currentTime, endTime, self, endFunc) { if (!currentTime || !endTime) { throw "时间参数错误" } currentTime = currentTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" endTime = endTime.replace(/-/g, "/");//safari 不支持"2016-05-01",只支持"2016/05/01" currentTime = new Date(currentTime).getTime(); endTime = new Date(endTime).getTime(); var intDiff = endTime - currentTime; //console.info(intDiff); function timeDown() { if (intDiff >= 0) { var ms = Math.floor(intDiff % 1000 / 10); var second = Math.floor(intDiff / 1000 % 60); var minute = Math.floor((intDiff / 1000 / 60) % 60); minute = minute < 10 ? "0" + minute : minute; second = second < 10 ? "0" + second : second; ms = ms < 10 ? "0" + ms : ms; var count_down = minute + ":" + second + ":" + ms; $(self).html(count_down);//赋值 var timeOut = setTimeout(function () { if (intDiff > 0) { intDiff -= 20; timeDown(); } else { clearTimeout(timeOut); endFunc(self); } }, 20); } else { endFunc(self); } } timeDown(); }; win.timeInit_J = timeInit; })(window, document, $);
angular.module('StripePaymentCtrl', []).controller('StripePaymentController', function($scope, $http, authentication) { $scope.currentUser = authentication.currentUser(); $scope.errorMessage = ""; $scope.successMessage = ""; $scope.dob_date; $scope.card = {}; //card info $scope.bank = {}; //bank info $scope.address = {}; //adderss info $scope.dob = {}; //Date of birth $scope.ssn = ""; //SSN $scope.terms_accepted = false; //User must accept terms before creating stripe account var update = false; //not used //not used $scope.init = function(account_id){ if(account_id){ update = true; }else{ update = false; } console.log(update); } //Helper function to remove modal var removeModalBackdrop = function(){ $('#stripe-modal').modal('toggle'); $(".modal-backdrop").hide(); $('body').removeClass('modal-open'); } var formatDob = function(){ //use with date input (not user right now) if($scope.dob_date){ $scope.dob.month = $scope.dob_date.getMonth() + 1; $scope.dob.day = $scope.dob_date.getDate(); $scope.dob.year = $scope.dob_date.getFullYear(); } } $scope.submitForm = function(){ //format account info // formatDob(); var first_name = $scope.currentUser.name.split(" ")[0]; var last_name = $scope.currentUser.name.split(" ")[1]; var info = { payout_type: $scope.payout_type, email: $scope.currentUser.email, address: $scope.address, dob: $scope.dob, first_name: first_name, last_name: last_name, bank: $scope.bank } if($scope.ssn){ info.ssn = $scope.ssn; } //Create new stripe account $http.post('/api/stripe-account', info).success(function(account_data){ console.log(account_data); console.log("account created"); //Update profile (save account id in profile) $http.put('/api/profiles/' + $scope.currentUser.id, {stripe_account_id: account_data.body.id}) .success(function(data) { console.log(data); $scope.errorMessage = ""; $scope.successMessage = "Your information has been recieved and your account is now ready for payouts!"; $('#checkoutForm')[0].reset(); $scope.profile.stripe_account_id = account_data.body.id; }) .error(function(data, status, headers, config) { console.log('profile not found'); console.log(data); $scope.errorMessage = "Your information has been recieved, but there was an error updating your profile. Please contact will@middoffcampus.com to resolve this issue."; $scope.successMessage = ""; }); }).error(function(data, status, headers, config){ console.log(data); console.log("account error"); $scope.errorMessage = data.msg.message; $scope.successMessage = ""; $scope.bank = {}; }); } });
define([], function() { return Backbone.Router.extend({ initialize: function(options) { this.collection = options.collection; }, routes: { "(:projects)" : "updateProjects" }, updateProjects: function(projects) { if(!projects) { this.navigate("Utsuro", {trigger: true}); return false; } // Update collection with right projects. _.forEach(projects.split("-vs-"), function(name) { name = name.replace(/\+/g, " "); this.collection.every(function(project) { if(project.is(name)) { project.set("selected", true); return false; } return true; }); }, this); }, updateUrl: function() { // Update url with correct projects. var uri = _.map(this.collection.where({selected: true}), function(project) { return project.getShortName().replace(/ /g, "+"); }).join("-vs-"); this.navigate(uri); } }); });
import React from 'react'; import { View, Dimensions } from 'react-native'; import { Divider } from 'react-native-elements'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { ImagePicker } from 'expo'; import { Container } from '../../../../components/container'; import { Actions } from '../../actions'; import { DocumentationButtonContainer, DocumentationContainer, DocumentationSubtitleText, DocumentationTitleText, NextButtonText, NextButtonTouchable } from '../../styles'; import { DocumentationImage } from '../../components/documentation-image'; import { Button } from '../../../../components/button'; import { GaleriaButtonContainer } from './styles'; class Picture extends React.Component { static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state; return { title: '', headerRight: ( <NextButtonTouchable disabled={params.disabled} onPress={() => navigation.navigate('Vehicle')} > <NextButtonText disabled={params.disabled}>Siguiente</NextButtonText> </NextButtonTouchable> ), headerStyle: { backgroundColor: '#fff', elevation: 0, borderBottomWidth: 0 } }; }; constructor(props) { super(props); this.state = { picture: undefined, loadingImage: false }; } componentDidMount() { const { navigation } = this.props; navigation.setParams({ disabled: true }); } takePicture = async () => { const { actions, navigation } = this.props; this.setState({ loadingImage: true }); const photo = await ImagePicker.launchCameraAsync({ allowsEditing: false, aspect: [4, 3], quality: 0.5, mediaTypes: 'Images' }); if (!photo.cancelled) { this.setState({ picture: photo.uri }); actions.setCarrierProfileImage(photo); navigation.setParams({ disabled: false }); this.setState({ loadingImage: false }); } }; loadFromCameraRoll = async () => { const { actions, navigation } = this.props; this.setState({ loadingImage: true }); const photo = await ImagePicker.launchImageLibraryAsync({ allowsEditing: false, aspect: [4, 3], quality: 0.5, mediaTypes: 'Images' }); if (!photo.cancelled) { this.setState({ picture: photo.uri }); actions.setCarrierProfileImage(photo); navigation.setParams({ disabled: false }); this.setState({ loadingImage: false }); } }; render() { const { picture, loadingImage } = this.state; return ( <Container> <DocumentationTitleText>Agregá una foto de perfil</DocumentationTitleText> <DocumentationContainer> <DocumentationImage loading={loadingImage} source={ picture === undefined ? require('../../../../assets/images/profile.png') : { uri: picture } } /> <DocumentationSubtitleText> La foto de perfil debera ser de tu cara, tomada de frente, con una buena iluminacion, fondo claro y que sea lo mas actual posible. No uses fotos antiguas </DocumentationSubtitleText> </DocumentationContainer> <DocumentationButtonContainer> <View> <Divider style={{ backgroundColor: 'gray', marginVertical: 10, opacity: 0.2 }} /> <Button width={Dimensions.get('window').width - 30} color="#665EFF" radius onPress={this.takePicture} title="CAMARA" /> <GaleriaButtonContainer> <Button width={Dimensions.get('window').width - 30} color="#959DAD" radius onPress={this.loadFromCameraRoll} title="GALERIA" /> </GaleriaButtonContainer> </View> </DocumentationButtonContainer> </Container> ); } } function mapStateToProps(state) { return { reducer: state.carrierDocumentationReducer }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ ...Actions }, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(Picture);
var Catalogo = function() { this.articulos = {}; }; Catalogo.prototype.cargarCatalogo = function () { var url = 'https://demo8983883.mockable.io/productos/camisetas/hoy'; var promesaDatos = $.get(url); promesaDatos.done(function (datos) { console.table(datos); }); var promesaCatalogo = promesaDatos.then(function(datos) { for (var i=0; i < datos.length; i++) { var datosActual = datos[i]; var articuloActual = new Articulo( datosActual.modelo, datosActual.precio, datosActual.imagen, datosActual.colores); this.articulos[articuloActual.nombre] = articuloActual; } return this /* catálogo */; }.bind(this)); return promesaCatalogo; };
(function() { 'use strict'; angular.module( 'app.config', [ 'ui.router', 'angular-loading-bar', 'ui.bootstrap' ] ) .constant('BASE_URL', 'http://localhost/php-crud/'); })();
/** * 已审核的文章 * 审核人自己看的,当前已审核的文章 流程进入管理员决定是否发布 状态为:待发布6 * @class AfterAuditingDocManagePanel * @extends Disco.Ext.CrudPanel */ AfterAuditingDocManagePanel = Ext.extend(Disco.Ext.CrudPanel, { gridSelModel: 'checkbox', id: "afterAuditingDocManagePanel", baseUrl: "newsDoc.java", autoLoadGridData: true, autoScroll: false, totalPhoto: 0, pageSize: 20, showAdd: false, showRemove: false, showEdit: false, showView: false, defaultsActions: { create: 'save', list: 'getAfterAuditing', view: 'view', update: 'update', remove: 'remove' }, gridViewConfig: { forceFit: true, enableRowBody: true, showPreview: true }, topicRender: function(value, p, record) { return String.format('{1}<b><a style="color:green" href="news.java?cmd=show&id={0}" target="_blank">&nbsp查看</a></b><br/>', record.id, value) }, stateRender: function(v) { if (v == 6) { return "审核通过待发表"; } else { return "未知状态"; } }, toggleDetails: function(btn, pressed) { var view = this.grid.getView(); view.showPreview = pressed; view.refresh(); }, createWin: function() { return this.initWin(900, 600, "文章管理"); }, storeMapping: ["id", "title", "keywords", "createDate", "author", "source", "putDate", "dir", "toBranch", "branchDir", "state", "branchState", { name: "branchDirId", mapping: "branchDir" }, { name: "dirId", mapping: "dir" }], initComponent: function() { this.cm = new Ext.grid.ColumnModel([{ header: "主题", dataIndex: 'title', width: 200, renderer: this.topicRender }, { header: "栏目", sortable: true, width: 70, dataIndex: "dir", renderer: this.objectRender("name") }, { width: 70, sortable: true, header: "发布到分行", dataIndex: "toBranch", renderer: this.booleanRender }, { width: 70, sortable: true, header: "分行栏目", dataIndex: "branchDir", renderer: this.objectRender("name") }, { header: "作者", sortable: true, width: 50, dataIndex: "author" }, { header: "撰稿日期", sortable: true, width: 90, dataIndex: "createDate", renderer: this.dateRender() }, { width: 60, sortable: true, header: "流程状态", dataIndex: "state", renderer: this.stateRender }]); AfterAuditingDocManagePanel.superclass.initComponent.call(this); } });
// const { Message, Client, MessageEmbed } = require("discord.js"); // const fetch = require("node-fetch"); // module.exports = { // name: "roast", // description: "returns a roast", // /** // * // * @param {Client} client // * @param {Message} message // * @param {String[]} args // */ // run: async (client, message, args) => { // try { // let user = message.mentions.users.first(); // //console.log(user); // //console.log(client.config.owners[0]); // if (!args[0]) { // let roastArg = new MessageEmbed() // .setColor("#A348A6") // .setDescription("mention someone"); // return message.reply({ // embeds: [roastArg], // allowedMentions: { repliedUser: false }, // }); // } // if (user.id === client.config.owners[0]) { // let roastAnnan = new MessageEmbed() // .setColor("#A348A6") // .setDescription("How dare you roast annan!!!!!!!"); // return message.reply({ // embeds: [roastAnnan], // allowedMentions: { repliedUser: false }, // }); // } // if (user.id === message.author.id) { // let roastMention = new MessageEmbed() // .setColor("#A348A6") // .setDescription("You can not roast yourself"); // return message.reply({ // embeds: [roastMention], // allowedMentions: { repliedUser: false }, // }); // } // if (message.mentions.users.size < 1) { // let roastArg = new MessageEmbed() // .setColor("#A348A6") // .setDescription("You must mention someone to roast them."); // return message.reply({ // embeds: [roastArg], // allowedMentions: { repliedUser: false }, // }); // } // let body = await fetch( // "https://evilinsult.com/generate_insult.php?lang=en&type=json" // ); // let roast = await body.json(); // let roastEmbed = new MessageEmbed() // .setColor("#cce1f2") // .setDescription(user.username + ", " + roast.insult); // await message.reply({ // embeds: [roastEmbed], // allowedMentions: { repliedUser: false }, // }); // } catch (err) { // console.log(err); // } // }, // }; const { Command } = require("discord-akairo"); const { CreateEmbed } = require("../../Utility/CreateEmbed"); const { MessageEmbed } = require("discord.js"); const fetch = require("node-fetch"); module.exports = class RoastCommand extends Command { constructor() { super("roast", { aliases: ["roast"], description: { content: "returns a roast", usage: "roast", example: ["roast"], }, category: "fun", cooldown: 3000, args: [ { id: "person", type: "user", match: "rest", }, ], }); } /** * * @param {import('discord.js').Message} msg * @returns */ async exec(msg, { person }) { try { //console.log(person); let user = msg.mentions.users.first(); //console.log(user); //console.log(client.config.owners[0]); if (!person) { let embed = CreateEmbed("info", "mention someone."); return msg.reply({ embeds: [embed], allowedMentions: { repliedUser: false }, }); } else if (user.id === this.client.config.owners[0]) { let embed = CreateEmbed("info", "How dare you roast annan!!!!!!!"); return msg.reply({ embeds: [embed], allowedMentions: { repliedUser: false }, }); } else if (user.id === msg.author.id) { let embed = CreateEmbed("info", "You can not roast yourself"); return msg.reply({ embeds: [embed], allowedMentions: { repliedUser: false }, }); } else if (msg.mentions.users.size < 1) { let embed = CreateEmbed( "info", "You must mention someone to roast them." ); return msg.reply({ embeds: [embed], allowedMentions: { repliedUser: false }, }); } else { let body = await fetch( "https://evilinsult.com/generate_insult.php?lang=en&type=json" ); let roast = await body.json(); let embed = CreateEmbed( "info", ` \`${user.username}\`, ${roast.insult}` ); await msg.reply({ embeds: [embed], allowedMentions: { repliedUser: false }, }); } } catch (e) { this.client.logger.error(e.message); msg.channel.send(CreateEmbed("warn", "⛔ | An error occured")); } } };
Partials.prototype.header = function() { var self = this; self.header.__constructor = function() { self.header.resize(); Utils.resize.watch(self.header.resize); }; self.header.resize = function() {}; self.header.__constructor(); };
//---名片卡上medal define(function(requrie,exports){ function slide(container){ if(!(this instanceof slide)){ return new slide(container); } this.container = container; this.ITEM_SIZE = container.find(".items").length>0 && container.find(".items").find("img").length; this.PAGE_SIZE = 10; this.ITEM_WIDTH = 28; this.TOTAL_PAGE = Math.ceil(this.ITEM_SIZE / this.PAGE_SIZE); this.CUR_LEFT = 0; this.CUR_PAGE = 1; this.isWaiting = false; this.toLastPage = false; this.dir = "left"; } slide.prototype.move = function(){ if(this.isWaiting) return; var self = this, container = this.container, medal_container = container.find(".medals"), modal_items = medal_container.find(".items"), container_width = parseInt(medal_container.css("width")), page_total = Math.ceil(medal_container.find("img").length / this.PAGE_SIZE), left_btn = container.find(".left"), right_btn = container.find(".right"); var isLeft = (this.dir==="left"), delta; if((isLeft && this.CUR_PAGE == this.TOTAL_PAGE && this.toLastPage) || (!isLeft && this.CUR_PAGE == this.TOTAL_PAGE - 1 && !this.toLastPage)){ delta = (this.ITEM_SIZE % this.PAGE_SIZE)*this.ITEM_WIDTH; }else{ delta = this.PAGE_SIZE * this.ITEM_WIDTH; } modal_items.animate({ "left" : (isLeft ? self.CUR_LEFT += delta : self.CUR_LEFT -= delta) + "px" },500,function(){ isLeft ? self.CUR_PAGE -= 1 : self.CUR_PAGE += 1; if(self.CUR_PAGE == self.TOTAL_PAGE)self.toLastPage = true; if(self.CUR_PAGE == 1)self.toLastPage = false; if(self.CUR_PAGE == 1) { left_btn.css("visibility","hidden"); right_btn.css("visibility",""); }else if(self.CUR_PAGE == page_total) { right_btn.css("visibility","hidden"); left_btn.css("visibility",""); }else{ left_btn.css("visibility",""); right_btn.css("visibility",""); } self.isWaiting = false; }); this.isWaiting = true; } slide.prototype.left = function(){ this.dir = "left"; this.move(); } slide.prototype.right = function(){ this.dir = "right"; this.move(); } return slide; });
import server from './server'; import { HOST, PORT } from './settings.js' //TODO: Clusterize server.listen(PORT, HOST, () => { console.log("H2PAAS are running on %s:%s", HOST, PORT) })
import React from "react"; import ReactDOM from "react-dom"; import { Route } from "react-router-dom"; import { BrowserRouter as Router } from "react-router-dom"; import Nav from "./Nav"; import Home from "./components/Home"; import Clients from "./components/Clients"; import Invoices from "./components/Invoices"; import "./styles.css"; function App() { return ( <div className="App"> <header className="App-header"> <Nav /> <Route path="/" exact component={Home} /> <Route path="/clients" component={Clients} /> <Route path="/invoices" component={Invoices} /> </header> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render( <Router> <App /> </Router>, rootElement );