text
stringlengths
7
3.69M
const express = require('express'); const { getArchives, getArchive, createArchive, updateArchive, deleteArchive} = require('../controllers/archives'); const router = express.Router(); const { protect, authorize } = require('../middleware/auth'); router .route('/') .get(getArchives) .post(protect,authorize('admin', 'tu'), createArchive); router .route('/:id') .get(getArchive) .put(protect, authorize('admin', 'tu'),updateArchive) .delete(protect,authorize('admin', 'tu'), deleteArchive); module.exports = router;
(function () { "use strict"; angular.module("vcas").controller("RemoveAllDevicePairsModalCtrl", RemoveAllDevicePairsModalCtrl); /* @ngInject */ function RemoveAllDevicePairsModalCtrl(device, $modalInstance, DeviceMgmtService, AlertsService) { var vm = this, action, verify, prop, type; vm.dismissModal = dismissModal; vm.closeModal = closeModal; vm.confirmRemoval = confirmRemoval; initialize(); function initialize() { if (DeviceMgmtService.isSetTopBox(device)) { action = DeviceMgmtService.removeSTBDevicePairing; verify = DeviceMgmtService.getSTBPairing; prop = "smartCardDeviceList"; type = "Set-top Box"; } else { action = DeviceMgmtService.removeSmartCardDevicePairing; verify = DeviceMgmtService.getSmartCardPairing; prop = "stbDeviceList"; type = "Smart Card"; } } function dismissModal() { $modalInstance.dismiss(); } function closeModal() { $modalInstance.close(); } function confirmRemoval() { action(device).then(function () { verify(device).then(function (response) { var devices = (response[prop] || {}).devices; devices = _.compact(angular.isArray(devices) ? devices : [devices]); if (!devices.length) { AlertsService.addSuccess("Device pairs removed successfully for " + type + " " + device.smsDeviceId); vm.closeModal(); return; } AlertsService.addErrors("Some pairs weren't removed for " + type + " " + device.smsDeviceId); }); }); } } }());
import React, { Component } from 'react'; import Layout from '../../components/Layout'; import axios from 'axios'; class TradeInfo extends Component { constructor(props) { super(props); this.state = { cardTradeInfo: [] } } async componentDidMount() { const { hash } = this.props; try { const tradeInfo = await axios.get(`/card-trade-info?hash=${hash}`); if (tradeInfo) { const { content } = tradeInfo.data; this.setState({ cardTradeInfo: content.length > 0 ? content.map(a => { return (<li className="item-content"> <div> <div> 판매자 : {a.sourceProducerName} </div> <div> 구매자 :{a.destProducerName} </div> <div> 거래일 : {this.convertDate(a.tradeTime)} </div> 품목 : {a.item && a.item.map(b => { const itemName = this.getItemType(b.itemTypeId); return <div> {b.itemTypeId === 21 && <img src={`https://imas.gamedbs.jp/cg/image_sp/card/xs/${b.cardHash}.jpg`} />} <div>{`${itemName}: ${b.itemTypeId !== 21 ? b.volume : b.cardName}`}</div> </div> })} </div> </li>); }) : [] }) } else { this.setState({ cardTradeInfo: [] }) } } catch (error) { this.setState({ cardTradeInfo: [] }) } } convertDate = (val) => { const firstSplit = val.split("T"); const seconedSplit = firstSplit[1].split("+"); const yyyyMMdd = firstSplit[0].split("-"); const hhMMss = seconedSplit[0].split(":"); return (`${yyyyMMdd[0]}년 ${yyyyMMdd[1]}월 ${yyyyMMdd[2]}일 ${hhMMss[0]}시 ${hhMMss[1]}분 ${hhMMss[2]}초`) } getItemType = (val) => { const itemType = { 1: `스태미너 드링크`, 2: `에너지 드링크`, 3: `옷장 열쇠`, 11: `매니`, 21: `카드` } return itemType[val]; } render() { const { cardTradeInfo } = this.state return ( <Layout> <ul className="item-body">{cardTradeInfo}</ul> </Layout> ) } } TradeInfo.getInitialProps = ({ query }) => { return query; } export default TradeInfo;
import {DECREMENT, INCREMENT} from "./mutations_types"; export default { [INCREMENT](state){ state.counter++ }, [DECREMENT](state){ state.counter-- }, updateInfo(state,age) { state.vitamin.age=age; } }
const express = require('express'); const User = require('../../models/user'); const router = express.Router(); /** * @swagger * /loginUser: * post: * tags: * - Users * name: Login * summary: Logs in a user * consumes: * - application/json * parameters: * - name: body * in: body * schema: * $ref: '#/definitions/User' * type: object * properties: * username: * type: string * password: * type: string * format: password * required: * - username * - password * responses: * 200: * description: User found and logged in successfully * 401: * description: Bad username, not found in db * 403: * description: Username and password don't match */ router.post('/loginUser', (req, res, next) => { res.json({ message: 'HI', User }); }); module.exports = router;
import * as Count from '../constants'; import { createSelector } from 'reselect'; /* ******************************************************************** ******************************************************************** *** reducers *** ******************************************************************** ******************************************************************** */ // reducer handlers const decrementCount = (state, action) => { return state - action.payload; } const incrementCount = (state, action) => { return state + action.payload; } // lookup table const lookup = { [Count.increment]: incrementCount, [Count.decrement]: decrementCount }; // reducer lookup export const counterReducer = (state = 0, action) => lookup[action.type] ? lookup[action.type](state, action) : state; /* ******************************************************************** ******************************************************************** *** selectors *** ******************************************************************** ******************************************************************** */ const getCountValue = state => state.counter; export const getCurrentCount = createSelector( [getCountValue], count => { return count; } ); /* ******************************************************************** ******************************************************************** *** action creators *** ******************************************************************** ******************************************************************** */ export const increment = payload => { return { type: Count.increment, payload }; }; export const decrement = payload => { return { type: Count.decrement, payload }; }; export const delay = (payload) => { return dispatch => { dispatch(showLoading()); setTimeout(() => { dispatch(increment(payload)); }, 2000); }; }; export const showLoading = () => { return { type: Count.loading }; };
/** * 平台 * 比如詹密团 */ module.exports = function (Schema) { const GroupSchema = new Schema({ originId: { type: String, comment: '原始id' }, name: { type: String, comment: '小程序名字' }, qrcode: { type: String, comment: '小程序二维码' }, logo: { type: String, ref: '小程序logo' } }); return ['Group', GroupSchema]; };
const Bank = function(){ this.accounts = [250, 250, 500, 500, 500; this.total 0; } var Bank = function () { this.accounts = [250, 250, 500, 500, 500]; this.total = 0; } }
import React, { Component } from 'react' import { Table } from 'react-bootstrap' import SweetAlert from 'sweetalert2-react'; import './style.css' class StarwarsMember extends Component { constructor(props) { super(props); this.state = { show: false, key: 0 }; } render() { return ( <div style={{padding: "25px 50px"}}> <div className="flex-row"> <h2>{this.props.title}</h2> <h4 style={{verticalAlign : "bottom"}}>See all</h4> </div> <Table bordered hover> <thead> <tr> <th style={{width: "10%"}}>#</th> <th>Name</th> <th>Gender</th> <th>Height</th> <th>Home World</th> </tr> </thead> <tbody> { this.props.starwars.length ? this.props.starwars.map((data, nomor) => { return ( <tr key={nomor} onClick={()=> this.setState({show: true, key: nomor})}> <td>{nomor + 1}</td> <td>{data.name}</td> <td>{data.gender}</td> <td>{data.height}</td> <td>{data.homeworld}</td> </tr>) }) : ( <tr> <td colSpan="5">Loading...</td> </tr> ) } </tbody> </Table> <SweetAlert show={this.state.show} title="You clicked" text={JSON.stringify(this.props.starwars[this.state.key])} onConfirm={() => this.setState({ show: false })} /> </div> ); } } export default StarwarsMember;
import styled from 'styled-components' export const TextboxOpaque = styled.div` max-width: 70%; text-align: center; line-height: 1.125; background-color: ${(props) => props.theme.colors.textboxOpaque.background}; color: ${(props) => props.theme.colors.light}; margin: ${(props) => props.theme.spacings.medium}; padding: ${(props) => props.theme.spacings.medium}; border-radius: ${props => props.theme.borders.card}; &:not(button) { text-shadow: ${(props) => props.theme.shadows.text}; } @media ${(props) => props.theme.breakpoints.touch} { padding: ${(props) => props.theme.spacings.small}; } `
// xTestRoom1/events.js //$ PackConfig { "sprites" : [ "textures/star.png", "textures/waterdroplet.png", "textures/waterdroplets.png", "textures/smoke.png" ] } //$! var Event = require("tpp-event"); var Sign = require("tpp-sign"); var Warp = require("tpp-warp"); var CameraTrigger = require("tpp-cameratrigger"); var ParticleEvent = require("tpp-particle"); add(new CameraTrigger({ id: "CAMERA_toEast", locations: [9, 1, 1, 8], eCameraId: "toEast", wCameraId: "0", })); add(new CameraTrigger({ id: "CAMERA_toWest", locations: [24, 1, 1, 8], wCameraId: "toWest", eCameraId: "0", })); add(new CameraTrigger({ id: "CAMERA_toNorth", locations: [1, 16, 8, 1], nCameraId: "toNorth", sCameraId: "0", })); add(new CameraTrigger({ id: "CAMERA_toSouth", locations: [1, 9, 8, 1], sCameraId: "toSouth", nCameraId: "0", })); add(new ParticleEvent({ id: "PARTICLE_Test", location: [25, 17], sprite: "star.png", opacityTween: ParticleEvent.makeTween( [9, 10], [1, 0] ), particlesPerSecond: 1, particleDeathAge: 10, newParticle: function(p) { p.position.set(0, 0, 0); p.velocity.set(0, 0.5, 0); p.opacityTween = this.opacityTween; }, })); add(new ParticleEvent({ id: "PARTICLE_Test2", location: [37, 21], boundingSize: 5, killingFloor: -0.6, running: true, sprite: "waterdroplets.png", type: 0, _ring: 0, colorLTween: ParticleEvent.makeTween( [0, 1], [.6, .8] ), sizeTween: ParticleEvent.makeTween( [0, 1], [0.2, 0.5] ), particlesPerSecond: 400, particleDeathAge: 1.8, newParticle: function(p, rnd) { switch (this.type) { case 0: { p.position.set( rnd(0, 0.1), rnd(0, 0.3), rnd(0, 0.1) ); p.acceleration.set(0, -10, 0); var vx = rnd(0, 1), vy = rnd(0, 1); var vn = Math.sqrt(vx*vx + vy*vy); var vl = 1.6; p.velocity.set(vx*vl/vn, rnd(8, 0.5), vy*vl/vn ); } break; case 1: { var NUM_STREAMS = 16; var RADIUS_ADJ = 3.5; var VEL_ADJ = 0.6; this._ring = (this._ring+1) % NUM_STREAMS; var x = Math.sin((2*Math.PI) * (this._ring/NUM_STREAMS)) * RADIUS_ADJ; var y = Math.cos((2*Math.PI) * (this._ring/NUM_STREAMS)) * RADIUS_ADJ; p.position.set( rnd(x, 0.1), rnd(0, 0.1), rnd(y, 0.1) ); p.acceleration.set(0, -10, 0); p.velocity.set(rnd(-x*VEL_ADJ, 0.2), rnd(8, 0.5), rnd(-y*VEL_ADJ, 0.2) ); } break; case 2: { p.position.set( rnd(0, 0.3), rnd(0, 0.3), rnd(0, 0.1) ); p.acceleration.set(0, -10, 0); var angle = rnd(0, -Math.PI * 0.75) var vx = Math.sin(angle) * 5; var vy = Math.cos(angle) * 9; p.velocity.set(vx, vy, rnd(0, 0.5) ); } break; } p.size = rnd(0.4, 0.05); p.sizeTween = this.sizeTween; p.angle = Math.random() * 360; p.angleVelocity = (Math.random() - 0.5) * 15; p.color.setHSL(0.60, 1.0, rnd(0.8, 0.05)); p.colorLTween = this.colorLTween; p.opacity = 0.8; }, })); add(new ParticleEvent({ id: "PARTICLE_CampFireTest", location: [29, 12], sprite: "smoke.png", sizeTween: ParticleEvent.makeTween( [0, 0.3, 1.2], [0.2, 1.2, 0.01] ), opacityTween: ParticleEvent.makeTween( [0.9, 1.5], [1, .5] ), colorHTween: ParticleEvent.makeTween( [0.5, 1], [.02, .05] ), colorLTween: ParticleEvent.makeTween( [0.5, 1], [.5, 0] ), blendStyle : THREE.AdditiveBlending, particlesPerSecond: 60, particleDeathAge: 1.5, newParticle: function(p, rnd) { p.position.set( rnd(0, 0.3), rnd(-0.2, 0.2), rnd(0, 0.3) ); p.velocity.set(rnd(0, 0.6), 1.2, rnd(0, 0.6) ); p.sizeTween = this.sizeTween; p.angle = Math.random() * 360; p.angleVelocity = (Math.random() - 0.5) * 15; p.color.setHSL(0.02, 1.0, 0.5); p.colorHTween = this.colorHTween; p.colorLTween = this.colorLTween; p.opacityTween = this.opacityTween; }, }));
import React from "react"; import NotificationAlert from "react-notification-alert"; export default class Alertas extends React.Component { //Metodo constructor constructor(props) { super(props); this.state = { visible: true }; } notificationAlert = React.createRef(); notify(place, color,message) { var options = {}; options = { place: place, message:message, type: color, icon: "nc-icon nc-bell-55", autoDismiss: 7 }; this.notificationAlert.current.notificationAlert(options); } render() { return ( <div> <NotificationAlert ref={this.notificationAlert} /> </div> ); } }
import React from 'react'; import {Image} from 'react-native'; import globalStyles from '../../assets/styles/styles'; import styles from './styles'; import {useQuery} from '@apollo/react-hooks'; import {gql} from 'apollo-boost'; import Conduct from '../../components/Conduct'; import Paragraph from '../../components/Paragraph'; import Section from '../../components/Section'; import Heading from '../../components/Heading'; import {ScrollView} from 'react-native-gesture-handler'; import Spinner from '../../components/Spinner'; const AlL_CONDUCTS = gql` { allConducts { id title description order } } `; const About = () => { const {loading, error, data} = useQuery(AlL_CONDUCTS); return loading ? ( <Spinner /> ) : error ? ( <Paragraph>something went wrong.</Paragraph> ) : ( <ScrollView> <Section style={globalStyles.container}> <Section style={styles.logoContainer}> <Image source={require('../../assets/r10_logo.png')} /> </Section> <Section style={globalStyles.content}> <Paragraph> R10 is a conference that focuses on just about any topic related to dev. </Paragraph> <Heading>Date & Venue</Heading> <Paragraph> The R10 conference will take place on Tuesday, June 27, 2020 in Vancouver, BC. </Paragraph> </Section> <Section style={globalStyles.content}> <Heading>Code of Conduct</Heading> <ScrollView> {data.allConducts.map(data => ( <Conduct key={data.id} title={data.title} description={data.description} /> ))} </ScrollView> </Section> <Section style={styles.footer}> <Paragraph>© RED Academy 2020</Paragraph> </Section> </Section> </ScrollView> ); }; export default About;
export * from './base' export * from './utils' export * from './decorators'
import React from 'react'; import './Consultancy.css'; function Consultancy() { return ( <div className="consultancy-div"> <div className="title-div"> <h2 className="consultancy-title">Consultancy</h2> </div> <div className="rows-setup"> <img className="consultancy-card-image" src={require('../../assets/consultancy/Design_Sprints.jpg')} alt="Design Sprint" /> <div className="consultancy-title-text"> <p className="consultancy-card-title">Design sprints</p> <p className="consultancy-card-description"> Answer critical business and product questions by compressing months of endless interactions into 2, 3 or 4 days of focused work by a small critical team. Instead of waiting for a launch to observe the results, shortcut that learning process by quickly building and validating a smart prototype with real customers. </p> </div> </div> <div className="rows-setup"> <img className="consultancy-card-image show-small" src={require('../../assets/consultancy/Innovation_Programmes.jpg')} alt="Innovation Programmes" /> <div className="consultancy-title-text"> <p className="consultancy-card-title">Innovation programmes</p> <p className="consultancy-card-description"> Entrepreneurs and established business or policy players need each other to solve problems and build amazing new ways to increase the value to their customers and advance business or policy goals. We organize acceleration or open innovation programmes with processes tailored to match the goals of the promoters and the entrepreneurs. </p> </div> <img className="consultancy-card-image show-large" src={require('../../assets/consultancy/Innovation_Programmes.jpg')} alt="Innovation Programmes" /> </div> <div className="rows-setup"> <img className="consultancy-card-image" src={require('../../assets/consultancy/Startup_Coaching.jpg')} alt="Startup Coaching" /> <div className="consultancy-title-text"> <p className="consultancy-card-title"> Coaching for startups and product people </p> <p className="consultancy-card-description"> We are entrepreneurs and have been working with or within corporations for several years and know what it takes to help entrepreneurs navigate the harsh waters of building a new thing. We give support covering the basics of the critical aspects of a business model, product solution-problem fit and product development.. Needless to say, we are able to dive into the nitty gritty of product design. </p> </div> </div> <div className="rows-setup"> <img className="consultancy-card-image show-small" src={require('../../assets/consultancy/Product_Management.jpg')} alt="Product Management" /> <div className="consultancy-title-text"> <p className="consultancy-card-title">Product management</p> <p className="consultancy-card-description"> When your organization is developing a web or mobile product or service and it doesn’t have the specialized talent for managing the complex interactions between all the stakeholders, gathering and defining the specifications, run user behaviour and UX tests, create the product vision, roadmap, write the user stories and prepare the PRD (Product Requirements Document) to align the development team with the stakeholders and clear define the delivery dates per agile sprint. Otherwise, you’re likely on the road to something more costly, at lower quality and way over the deadline you expected to deliver the product. That’s why you need a product manager to set the pace and guarantee a proper alignment between everyone. </p> </div> <img className="consultancy-card-image show-large" src={require('../../assets/consultancy/Product_Management.jpg')} alt="Product Management" /> </div> <div className="rows-setup"> <img className="consultancy-card-image" src={require('../../assets/consultancy/Future_Studies.jpg')} alt="Future Studies" /> <div className="consultancy-title-text"> <p className="consultancy-card-title">Future studies</p> <p className="consultancy-card-description"> Companies that thrive in the long-run are companies that strategically prepare for plausible scenarios. We employ prospective study methods to help companies or functional areas define future scenarios on the markets where they operate, enabling them to identify areas for innovation, take strategic decisions on their positioning and communicate about innovation challenges. </p> </div> </div> </div> ); } export default Consultancy;
'use strict'; /** * logic * @param {} [] * @return {} [] */ export default class extends think.logic.base { /** * 权限验证 */ async checkAuth() { let value = await this.session('userInfo'); return think.isEmpty(value); } /** * 登录 */ loginAction(){ this.allowMethods = 'post'; } /** * 注册 */ async registerAction() { let auth = await this.checkAuth(); if(auth) return this.fail('没有权限!'); this.allowMethods = 'post'; this.rules = { account: "required", password: "required" } } /** * 检查是否登录 */ async checkLoginAction() { let auth = await this.checkAuth(); if(auth) return this.fail('没有权限!'); } }
Server = { allow: { owner: { insert: (userId, doc) => (userId && doc.owner === userId) || (Meteor.user() && Meteor.user().isAdmin), update: (userId, doc) => doc.owner === userId || (Meteor.user() && Meteor.user().isAdmin), remove: (userId, doc) => doc.owner === userId || (Meteor.user() && Meteor.user().isAdmin), fetch: [ 'owner' ] }, admin: { insert: () => (Meteor.user() && Meteor.user().isAdmin), update: () => (Meteor.user() && Meteor.user().isAdmin), remove: () => (Meteor.user() && Meteor.user().isAdmin) } } };
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); import cache from "./modules/cache" import headerStore from "./modules/headerStore" import session from "./modules/session" import userInfoDialog from "./modules/userInfoDialog" import readingDetailsDialog from "./modules/readingDetailsDialog" import groupSettingDrawer from "./modules/groupSettingDrawer" import officeGroupSettingDrawer from "./modules/officeGroupSettingDrawer" import createGroupUserDialog from "./modules/createGroupUserDialog" import joinUsersGroupDialoge from "./modules/joinUsersGroupDialoge" import forwardDialoge from "./modules/forwardDialoge" import createOfficeGroupDialog from "./modules/createOfficeGroupDialog" const store = new Vuex.Store({ modules: { cache, headerStore, session, userInfoDialog, readingDetailsDialog, groupSettingDrawer, createGroupUserDialog, officeGroupSettingDrawer, joinUsersGroupDialoge, forwardDialoge, createOfficeGroupDialog } }); export default store;
function noDupes(str) { var output = { noDupes: "", extras: "" } } noDupes("Declan Kottmeier")
'use strict'; //Echarts function initEnterFace($container,doc_model){ doc_model || ( doc_model={innerHTML:""} ); function setContent(innerHTMLstr){ that.$doc.find(".content").html( innerHTMLstr ); } function start_move(e){ window.addEventListener("mousemove",move_enterface,false); window.addEventListener("mouseup",end_move,false); that.mouse={x:e.clientX,y:e.clientY}; // set_active(that); } function end_move(e){ var top=that.doc.offsetTop; var left=that.doc.offsetLeft that.doc.style.left=(that.doc.offsetLeft+that.position.x)+"px"; that.doc.style.top=(that.doc.offsetTop+that.position.y)+"px"; if(that.position.y+top<0){ that.doc.style.top=0; } if(that.position.x+left+that.doc.offsetWidth-30<0){ that.doc.style.left=0; } if(that.position.x+left+30>window.innerWidth){ that.doc.style.left=window.innerWidth-that.doc.offsetWidth + "px"; } if(that.position.y+top>window.innerHeight){ that.doc.style.top=window.innerHeight-that.doc.offsetHeight + "px"; } that.position.x=0;that.position.y=0; that.doc.style.transform=""; window.removeEventListener("mousemove",move_enterface,false); } function move_enterface(e){ e.preventDefault(); that.position.x += e.clientX-that.mouse.x; that.position.y += e.clientY-that.mouse.y; that.doc.style.transform="translate("+ that.position.x +"px, "+ that.position.y +"px )"; // if(is_show){ // that.style.left=left+"px"; // } that.mouse.x=e.clientX; that.mouse.y=e.clientY; } function create_enterface(){ that.doc=document.createElement('div'); that.doc.className="enterface"; that.$doc = $(that.doc); that.$doc.hide(); that.$doc.html(doc_model.innerHTML); $container.append(that.doc); that.$doc.on("mousedown",".windowtop",start_move); that.$doc.on("click",".closebutton",close_enterface); Arg.$content=that.$doc.find(".content"); Arg.$topmessage=that.$doc.find(".topmessage"); } function show_enterface(){ that.doc.style.left=window.innerWidth/10 +"px"; that.doc.style.top=window.innerHeight/20 +"px"; that.position.x=0;that.position.y=0; that.$doc.show(); $container.show(); $("#background").fadeIn(500); } function close_enterface(){ that.$doc.hide(); $container.hide(); $("#background").fadeOut(500); } var Arg={ show:show_enterface, close:close_enterface, setContent:setContent, } var that={ doc:null, mouse:{ x:0, y:0, }, position:{ x:0,y:0 } }; create_enterface(); return Arg; } //jenkins //按钮样式,文字, toggle 标签 //Vue.js //function initface(model){ // var Arg={}; // // return Arg; //} //(function ($){ // if($===undefined){ // throw new Error("need $ from jquery !! "); // } // function close_enterface(e){ // that=$(e.target||e.srcElement).closest('.enterface')[0]; // $(that).css({ // "visibility":"hidden", // "display":"none", // }); // if(!is_showed){ // doc.style.background="rgba(0,0,0,0)"; // setTimeout(function (){doc.style.visibility="hidden";},500); // } // else{ // that.tobeshowall=false; // } // window.removeEventListener("mouseup",end_move,false); // } // function start_move(e){ // that=$(e.target||e.srcElement).closest('.enterface')[0]; // window.addEventListener("mousemove",move_enterface,false); // window.addEventListener("mouseup",end_move,false); // that.mouse={x:'',y:''}; // that.mouse.x=e.clientX; // that.mouse.y=e.clientY; // set_active(that); // } // function end_move(e){ // if(that.offsetTop<0){ // that.style.top=0+"px"; // } // if(that.offsetLeft+that.offsetWidth-30<0){ // that.style.left=0+"px"; // } // if(that.offsetLeft>window.screen.availWidth){ // that.style.left=window.screen.availWidth-that.offsetWidth+"px"; // } // if(that.offsetTop>window.screen.availHeight){ // that.style.left=window.screen.availHeight-that.offsetHeight+"px"; // } // window.removeEventListener("mousemove",move_enterface,false); // } // function move_enterface(e){ // e.preventDefault(); // var top=that.offsetTop; // var left=that.offsetLeft; // that.style.position="absolute"; // $(that).css({ // "left":left+(e.clientX-that.mouse.x)+"px", // "top":top+(e.clientY-that.mouse.y-martop)+"px" // }); //// if(is_show){ //// that.style.left=left+"px"; //// } // that.mouse.x=e.clientX; // that.mouse.y=e.clientY; // } // function add_enterface(e,par){ // if(e){//有事件触发的 // var $line=$(e.target||e.srcElement).closest('.item'); // if(active_line!==$line&&active_line!==undefined){ // active_line.css("background","#fff") // } // active_line=$line; // var ip=$line.find('.span-2').html(); // var usr=$line.find('.span-3').html(); // var pwd=$line.find('.span-4').html(); // } // // if(!par){//打开新的窗口 // var iframe_url="180.209.64.38:4999/telnet"; // if(ip.slice(-3)==':80'){ // iframe_url="http://"+ip.slice(0,-3)+":80"; // $line.css({ // "background":"#daf9f7" // }) // window.open(iframe_url,"_blank",'width=1000px,height=400px,top=500px,left=0'); // window.open("./keys.html","_blank","width=400px,heigt=400px,top=300px,left=100px") // return ; // } // else{ // var str="http://"+iframe_url; // ip=""+ip; // str+="?ip="+encodeURI(ip.slice(0,-3))+"&usr="+encodeURI(usr)+"&pwd="+encodeURI(pwd); // window.open(str); // // alert(str) // return ; // } // } // switch(par){ // case 1://本地多iframe加载; // if(is_showed){ // hide_all(); // } // var sdoc=window //只加载一次; // // var sdoc=(e.target||e.srcElement).parentElement; // if(sdoc.index===undefined){ // sdoc.index=the_i; // var enterface=$(".enterface").eq(0).clone(); // enterface.removeAttr('id'); // var iframe=document.createElement("iframe"); // iframe.setAttribute( // "class","controlframe" // ); // iframe.src=iframe_url; // enterface.find(".framewrap").eq(0).append($(iframe)); // enterface=the_webshells[the_i++]=enterface.get(0); // doc.appendChild(enterface); // }else{ // enterface=the_webshells[sdoc.index]; // } // // $(enterface).find('.closebutton')[0].onclick=close_enterface; // $(enterface).find('.windowtop')[0].onmousedown=start_move; // return enterface; // case 2: // //显示某一div; // var sdoc=document.getElementsByClassName("active")[0]; // var divhtml='<div class="center">' // +'<h4>ip失败与成功比</h4><hr />' // +'<div id="scan_pie" style="width:600px;height:400px ;margin: 50px 100px;"> </div>' // +'<h4>ip中国分布图</h4><hr />' // +'<div id="scan_map" style="width:100%;height: 550px; margin: 20px 0;"></div>' // +'</div>'; // var message; // switch(sdoc.dataset.target[0]){ // case 's':message='ip扫描结果的分析';break; // case 'h':message='ip历史记录的分析';break; // } // var diviframe=document.createElement("div"); // diviframe.setAttribute( // "class","controlframe" // ); // function createEnterface(sdoc){ // if(sdoc.index===undefined){ // sdoc.index=the_i; // var enterface=$(".enterface").eq(0).clone(); // enterface.removeAttr('id'); // if(divhtml) diviframe.innerHTML=divhtml; // // alert(message); // var top=enterface.find(".topmessage").eq(0); // var framewrap=enterface.find(".framewrap").eq(0).append($(diviframe)); // enterface=the_webshells[the_i++]=enterface.get(0); // doc.appendChild(enterface); // }else{ // enterface=the_webshells[sdoc.index]; // } // $(enterface).find('.closebutton')[0].onclick=close_enterface; // $(enterface).find('.windowtop')[0].onmousedown=start_move; // return { // doc:enterface, // top:top, // framewrap:framewrap // }; // } // var enter=createEnterface(sdoc); // return enter.doc; // } // } // function show_enterface(e,par){ // var enterface=add_enterface(e,par); // if(!enterface){ // return ; // } // set_active(enterface); // //Jquery 只是简单的应用;对于闭包函数回绑定多个; // // // //由于iframe的事件的冒泡阻止--->只能点头; //// str+='id:'+thedata[2].innerHTML+'&nbsp;&nbsp;usr:'+thedata[3].innerHTML+'&nbsp;&nbsp;pwd:'+thedata[4].innerHTML; // $(enterface).css({ // "visibility":"visible", // "display":"block", // "position":"relative", // "top":0, // "left":0, // "margin-top":martop+"px" // }); //// document.getElementById("showinfo").innerHTML=str; // $(doc).css({ // "visibility":"visible", // "opacity":'1', // "display":"flex", // "background":"rgba(0,0,0,0.5)" // }); // } // function show_all(e){ // $(doc).css({ // "visibility":"visible", // "position":"relative", // "opacity":'1', // "display":"flex", // "background":"rgba(0,0,0,0.5)" // }); // var topi=30; // var righti=30; // $(doc).find('.enterface').filter(function (){ // if(this.id==="enterface_model")return false; // if(is_refresh) return true; // if(this.tobeshowall===false){ // return false; // } // else return true; // }).css({ // "display":"block", // "position":"relative", // "visibility":"visible", // "margin-top":martop+"px" // }); // /*map(function (){ // if(is_showed){ // this.style.right="auto" // return this; // } // $(this).css({ // "top":topi+"px", // "right":righti+"px", // "left":"auto" // }); // topi+=45; // righti+=45; // return this; // })*/ // $(doc).find("#enterface_model").css("display","none"); // is_refresh=false; // is_showed=true; // } // function hide_all(){ // doc.style.display="none" // doc.style.position="fixed"; // $(doc).find('.enterface').css({ // "display":"none", // "position":"absolute", // "visibility":"hidden" // }); // is_showed=false; // } // function set_active(tdoc){ // if(active_face===tdoc)return ; // if(active_face){ // active_face.style.zIndex="3"; // } // tdoc.style.zIndex="4"; // active_face=tdoc; // } // // var that; // var martop=0;//间隔; // var the_webshells=[]; // var the_i=0; // var is_showed=false; // var is_refresh=false; // var active_face; // var doc=document.getElementsByClassName("enterbackground")[0]; // var active_line;//当前活动行; //})($); // //$('.scan-page').on('click','.controlbutton_yes',show_enterface); //$('.scan-page').on('click','.controlbutton_add',add_enterface); //$('#fenxi').on('click',function (){ // show_enterface('',2);//弹窗的形式打开分析图表; // startScan[].Arg=startdraw(); //// alert(startdraw.times); //}); //$('#control').on('click',show_all); //$('#control').on('dblclick',function (){ // is_refresh=true; // show_all(); //});
import React from 'react' export default class Sendedform extends React.Component { render() { return ( <React.Fragment> <div className='form-sended'> <p className='form-sended-text'>Спасибо за запись{`${this.props.user && ', '}` + this.props.user}, вскоре я с вами свяжусь</p> <p className='form-sended-text'>Подписывайтесь на меня в Instagram</p> <div className='form-sended-wrap-link'> <a href='https://www.instagram.com/stilist_73/' className='form-sended-link'>stilist_73</a> </div> <div className='form-sended-wrap-link'> <a href='https://www.instagram.com/daryusha006/' className='form-sended-link'>daryusha006</a> </div> </div> </React.Fragment> ) } }
import React from "react"; import { Link } from "react-router-dom"; function NavBar(props) { if (props) { console.log("PROPS", props); } return ( <div className=" Bar"> <Link to="/" className="navButton"> {/* <button className="navButton">Home</button> */} Home </Link> <Link to="/about" className="navButton"> {/* <button className="navButton">About</button> */} About </Link> <Link to="/mypoems" className="navButton"> {/* <button className="navButton">Poems</button> */} Poems </Link> <Link to="/contact" className="navButton"> {/* <button className="navButton">Tech</button> */} Contact </Link> </div> ); } export default NavBar;
angular.module('jobzz') .controller('EmployerProfileEmployeeCtrl', ['$scope', '$http', 'employerProfileService', 'userProfilePictureService', 'dateToStringService', function ($scope, $http, employerProfileService, userProfilePictureService, dateToStringService) { $scope.responses = {}; (function () { $scope.employer = employerProfileService.getEmployer(); $scope.employer.profilePicture = userProfilePictureService.employerProfilePicture($scope.employer.profilePicture); var req = { method: 'GET', dataType: 'json', url: '/employee/employer/' + $scope.employer.employerId, headers: { 'Content-Type': 'application/json; charset=utf-8' } }; $http(req).then(function (response) { $scope.responses = response.data; $scope.responses.forEach(function (response) { response.review.date = dateToStringService.dateToString(new Date(response.review.date)); }); }); })(); }]);
OC.L10N.register( "lib", { "Username" : "Nama pengguna", "Password" : "Kata laluan", "__language_name__" : "_nama_bahasa_", "Apps" : "Aplikasi", "General" : "Umum", "Search" : "Cari", "Settings" : "Tetapan", "Users" : "Pengguna", "Authentication error" : "Ralat pengesahan" }, "nplurals=1; plural=0;");
const color = require('../') console.log(`${color('red')} red ${color.RESET}`)
import React, { Component } from 'react'; import { Link, Route } from 'react-router-dom'; import Spinner from '../components/Spinner/Spinner'; import TMDbApi from '../services/TMDb-api'; import routes from '../routes'; import Cast from '../pages/Cast'; import Reviews from '../pages/Reviews'; import styles from '../components/Navigation/Navigation.module.css'; export default class MovieDetailsPage extends Component { state = { showMovie: null, loading: false, error: null, }; componentDidMount() { this.setState({ loading: true }); TMDbApi.fetchShowMovieDetails(this.props.match.params.movieId) .then(showMovie => this.setState({ showMovie })) .catch(error => this.setState({ error })) .finally(() => this.setState({ loading: false })); } handleGoBack = () => { const { state } = this.props.location; if (state && state.from) { return this.props.history.push(state.from); } this.props.history.push(routes.moviesPage); }; render() { return ( <div> <button className="Button" onClick={this.handleGoBack} type="button"> Go back </button> {this.state.loading && <Spinner />} {this.state.showMovie && ( <div className="details"> {this.state.showMovie.backdrop_path ? ( <img src={`https://image.tmdb.org/t/p/w500${this.state.showMovie.backdrop_path}`} alt={this.state.showMovie.title} /> ) : ( <img src={`https://memepedia.ru/wp-content/uploads/2017/04/61092-YzljOWQ3ZWQ2YQ.gif`} alt="not found" /> )} <div className="details-info"> <h3> {this.state.showMovie.title ? `${ this.state.showMovie.title } (${this.state.showMovie.release_date.substr(0, 4)})` : `${this.state.showMovie.status_message}`} </h3> <span> User Score: {this.state.showMovie.vote_average ? Math.round((this.state.showMovie.vote_average / 10) * 100) : 0} % </span> <p> <span> <b>Overviev</b> </span> <br /> {this.state.showMovie.overview ? this.state.showMovie.overview : 'No Overviev'} </p> <p> <span> <b>Genres</b> </span> <br /> {this.state.showMovie.genres ? this.state.showMovie.genres.map(genres => ( <span>{genres.name} </span> )) : 'No Genres'} </p> </div> </div> )} <h3>Additional information</h3> <div className={styles.navigation}> <ul> <li> <Link to={`${this.props.match.url}/cast`}>Cast</Link> </li> <li> <Link to={`${this.props.match.url}/reviews`}>Reviews</Link> </li> </ul> </div> <hr /> <Route path={`${this.props.match.path}/cast`} component={Cast} /> <Route path={`${this.props.match.path}/reviews`} component={Reviews} /> </div> ); } }
const express = require('express') const exphbs = require('express-handlebars') const app = express() const path = require('path') app.set('port',process.env.PORT || 4501) app.use(express.json()) app.engine('handlebars', exphbs({ defaultLayout:'layout' }) ) app.set('view engine','handlebars') app.use(express.static(path.join(__dirname,"public"))) app.use(require('./routes/usuarios')) app.use(require('./routes/data')) //app.use(require('./routes/bancos')) app.listen(app.get('port'),()=>{ console.log('Server on port',app.get('port')) })
//React import React from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; //Apollo import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink, } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; // Components import User from './components/pages/User'; import Header from './components/Header'; import Home from './components/pages/Home'; import Login from './components/pages/Login'; import SignUp from './components/pages/Signup'; //Chakra Components and Hooks import { ChakraProvider, theme, Grid } from '@chakra-ui/react'; // Construct our main GraphQL API endpoint const httpLink = createHttpLink({ uri: '/graphql', }); // Construct request middleware that will attach the JWT token to every request as an `authorization` header const authLink = setContext((_, { headers }) => { // get the authentication token from local storage if it exists const token = localStorage.getItem('id_token'); // return the headers to the context so httpLink can read them return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '', }, }; }); const client = new ApolloClient({ // Set up our client to execute the `authLink` middleware prior to making the request to our GraphQL API link: authLink.concat(httpLink), cache: new InMemoryCache(), }); function App() { return ( <ApolloProvider client={client}> <Router> <ChakraProvider theme={theme}> <Grid minH="100vh"> <Header /> {/* <ColorModeSwitcher /> */} {/* <ColorModeSwitcher justifySelf="flex-end" /> */} <Route exact path="/"> <Home /> </Route> <Route exact path="/login/"> <Login /> </Route> <Route exact path="/signup/"> <SignUp /> </Route> <Route exact path="/me"> <User /> </Route> <Route path="/profile/:username"> <User /> </Route> </Grid> </ChakraProvider> </Router> </ApolloProvider> ); } export default App;
const express = require('express'); const app = express(); app.get('/', (req,res,next) => { res.sendFile(__dirname + "/client/JogoDaVelha.html"); }); app.use('/client',express.static(__dirname + "/client")); module.exports = app;
function loadingStart(tipsContent, errorTips, iconUrl) { var isSupportTouch = window.supportTouch; $("#loadingSection .body div").unbind(isSupportTouch ? "touchend" : "click"); if (tipsContent) { $("#loadingSection .body p").html(tipsContent); if (errorTips === true) { if (iconUrl) { $("#loadingSection .body img")[0].src = iconUrl; } else { $("#loadingSection .body img")[0].src = ""; } $("#loadingSection .body img")[0].className = ""; $("#loadingSection .body div").css("display", ""); $("#loadingSection .body div").one(isSupportTouch ? "touchend" : "click", cropStop); } else { $("#loadingSection .body div").css("display", "none"); $("#loadingSection .body img")[0].src = ""; $("#loadingSection .body img")[0].className = "animate"; } } else { $("#loadingSection .body div").css("display", "none"); $("#loadingSection .body img")[0].src = ""; $("#loadingSection .body img")[0].className = "animate"; $("#loadingSection .body p").text("加载中请稍候"); } $("#loadingSection").css("display", ""); } function loadingStop() { $("#loadingSection").css("display", "none"); } var canvasDom; var canvasCtx; var cropGesture = null; function cropChoose(evt) { // if (window.isInWechat) { // var wxHeadImgUrl = pageGetCookie("ttpt-wxheadimgurl"); // if (wxHeadImgUrl) { // loadingStart(""); // $.get("api/getHeadIcon.php?url="+encodeURIComponent(wxHeadImgUrl), function(data, status, xhr){ // if (status == "success" && data.length > 0) { // var photoImg = new Image(); // photoImg.onload = function(){ // loadingStop(); // cropLoaded(this); // } // photoImg.src = "data:image/jpeg;base64,"+data; // } else { // loadingStop(); // cropStart(); // } // }); // } else { // var wxState = pageGetParam("state"); // if (wxState) { // cropStart(); // } else { // authorizeByWechatRecirect(); // } // } // } else if ((window.isInMqzone || !window.supportTouch) && window.p_uin.length > 0 && window.p_skey.length > 0) { // loadingStart(""); // $.get("api/getHeadIcon.php", function(data, status, xhr){ // if (status == "success" && data.length > 0) { // var photoImg = new Image(); // photoImg.onload = function(){ // loadingStop(); // cropLoaded(this); // } // photoImg.src = "data:image/jpeg;base64,"+data; // } else { // loadingStop(); // cropStart(); // } // }); // } else { // cropStart(); // } cropStart(); return preventEventPropagation(evt); } function cropStart(evt) { var $upload = $("#uploadInput"); $upload.unbind("change"); $upload.one("change", cropChanged); $upload.trigger("click"); if (window.isInMqq && window.self != window.top) { var followObj = { postcode: 'follow', data: {} } window.parent.postMessage(followObj, '*'); } return preventEventPropagation(evt); } function cropStop(evt) { var isSupportTouch = window.supportTouch; cropGesture.unbindEvents(); $("#cropBar .choose-btn").unbind(isSupportTouch ? "touchend" : "click"); $("#cropBar .next-btn").unbind(isSupportTouch ? "touchend" : "click"); $("#cropSection").css("display", "none"); $("#cropMaskUp").css("visibility", "hidden"); $("#cropMaskDown").css("visibility", "hidden"); $("#cropImg").css("display", "none"); $("#cropImg").attr("src", ""); $("#uploadInput").unbind("change"); loadingStop(); return preventEventPropagation(evt); } function cropChanged(evt) { if (this.files.length <= 0) { cropStop(); return preventEventPropagation(evt); } $("#cropSection").css("display", ""); loadingStart(""); var file = this.files[0]; var reader = new FileReader(); reader.onload = function() { // 转换二进制数据 var binary = this.result; var binaryData = new BinaryFile(binary); // 获取exif信息 var imgExif = EXIF.readFromBinaryFile(binaryData); var fullScreenImg = new Image(); fullScreenImg.onload = function(){ cropLoaded(this); loadingStop(); } var mpImg = new MegaPixImage(file); mpImg.render(fullScreenImg, {maxWidth:960, maxHeight:960, orientation:imgExif.Orientation}); } reader.readAsBinaryString(file); return preventEventPropagation(evt); } function cropLoaded(img) { var isSupportTouch = window.supportTouch; $("#cropSection").css("display", ""); var $cropLayer = $("#cropLayer"); var cropSectionHeight = $("#cropSection").height(); var cropBarHeight = $("#cropBar").height(); var cropLayerHeight = $cropLayer.height(); var cropLayerOriginY = (cropSectionHeight - cropBarHeight - cropLayerHeight) * 0.5; $cropLayer.css("top", [cropLayerOriginY * 100/cropSectionHeight, "%"].join("")); $("#cropMaskUp").css("height", [cropLayerOriginY * 100/cropSectionHeight, "%"].join("")); $("#cropMaskUp").css("top", 0); $("#cropMaskUp").css("visibility", "visible"); $("#cropMaskDown").css("height", [cropLayerOriginY * 100/cropSectionHeight, "%"].join("")); $("#cropMaskDown").css("top", [(cropLayerOriginY + cropLayerHeight) * 100/cropSectionHeight, "%"].join("")); $("#cropMaskDown").css("visibility", "visible"); var imgWidth = img.width; var imgHeight = img.height; var ratioWidth = $cropLayer.width() / imgWidth; var ratioHeight = $cropLayer.height() / imgHeight; var ratio = ratioWidth > ratioHeight ? ratioWidth : ratioHeight; cropGesture.targetMinWidth = imgWidth * ratio; cropGesture.targetMinHeight = imgHeight * ratio; var imgOriginX = ($cropLayer.width() - cropGesture.targetMinWidth) * 0.5; var imgOriginY = ($cropLayer.height() - cropGesture.targetMinHeight) * 0.5; var $cropImg = $("#cropImg"); $cropImg.css("display", ""); $cropImg.width(cropGesture.targetMinWidth); $cropImg.height(cropGesture.targetMinHeight); $cropImg.css("left", [imgOriginX, "px"].join("")); $cropImg.css("top", [imgOriginY, "px"].join("")); $cropImg[0].src = img.src; cropGesture.unbindEvents(); cropGesture.bindEvents(); $("#cropBar .choose-btn").unbind(isSupportTouch ? "touchend" : "click"); $("#cropBar .choose-btn").on(isSupportTouch ? "touchend" : "click", cropStart); $("#cropBar .next-btn").unbind(isSupportTouch ? "touchend" : "click"); $("#cropBar .next-btn").on(isSupportTouch ? "touchend" : "click", cropConfirm); return false; } function cropConfirm(evt) { var canvasScale = canvasDom.height / $("#cropLayer").height(); var $cropImg = $("#cropImg"); var imgOrigin = {x:parseInt($cropImg.css("left")) || 0, y:parseInt($cropImg.css("top")) || 0}; var imgSize = {width:$cropImg.width(), height:$cropImg.height()}; canvasCtx.clearRect(0, 0, canvasDom.width, canvasDom.height); canvasCtx.drawImage($cropImg[0], imgOrigin.x * canvasScale, imgOrigin.y * canvasScale, imgSize.width * canvasScale, imgSize.height * canvasScale); var dataURL = ""; if (window.isAndroid){ var imgEncoder = new JPEGEncoder(); dataURL = imgEncoder.encode(canvasCtx.getImageData(0, 0, canvasDom.width, canvasDom.height), 100, true); } else { dataURL = canvasDom.toDataURL("image/jpeg", 1.0); } var dataComponent = dataURL.split(","); if (dataComponent.length >= 2) { var dataBase64 = dataComponent[1]; if (dataBase64.length > 0) { cropStop(); hatStart(dataBase64); } } return preventEventPropagation(evt); } function hatStart(imgData) { $("#hatFace").attr("src", "data:image/jpeg;base64,"+imgData); $("#hatStamp")[0].className = "hat-stamp-on"; $("#hatSection").css("display", ""); var $hatLayer = $("#hatLayer"); var hatSectionHeight = $("#hatSection").height(); var hatBarHeight = $("#hatBar").height(); var hatLayerHeight = $hatLayer.height(); var hatLayerOriginY = (hatSectionHeight - hatBarHeight - hatLayerHeight) * 0.5; $hatLayer.css("top", [hatLayerOriginY * 100/hatSectionHeight, "%"].join("")); $("#hatMaskUp").css("height", [hatLayerOriginY * 100/hatSectionHeight, "%"].join("")); $("#hatMaskUp").css("top", 0); $("#hatMaskUp").css("visibility", "visible"); $("#hatMaskDown").css("height", [hatLayerOriginY * 100/hatSectionHeight, "%"].join("")); $("#hatMaskDown").css("top", [(hatLayerOriginY + hatLayerHeight) * 100/hatSectionHeight, "%"].join("")); $("#hatMaskDown").css("visibility", "visible"); var hatSectionWidth = $("#hatSection").width(); var hatStampWidth = $("#hatStamp").width(); $("#hatStamp").css("left", [(hatSectionWidth - hatStampWidth) * 0.5, "px"].join("")); $("#hatStamp").css("top", "0px"); } function hatConfirm(evt) { // $('.background').css('display','none'); $('.hat-anchor-ld').css('display','none'); $('.hat-anchor-rd').css('display','none'); $('#hatStamp').css('border','none'); var str = $('#hatLayer'); html2canvas([str.get(0)], { onrendered: function (canvas) { console.log(canvas); var dataurl = canvas.toDataURL('image/png'); $('#shareImg').attr('src',dataurl); $('#saveSection').css('display','block'); } }); } function hatTouchStart(evt) { var touches = evt.touches || evt.originalEvent.touches; var touch = touches[0]; var offset = { "x": touch.pageX, "y": touch.pageY }; hatDragStart(offset, touch.target); return preventEventPropagation(evt); } function hatTouchMove(evt) { var touches = evt.touches || evt.originalEvent.touches; var touch = touches[0]; var offset = { "x": touch.pageX, "y": touch.pageY }; hatDragMove(offset); return preventEventPropagation(evt); } function hatTouchEnd(evt) { hatDragEnd(); return preventEventPropagation(evt); } function hatMouseDown(evt) { var offset = { "x": evt.pageX, "y": evt.pageY }; hatDragStart(offset, evt.srcElement); return preventEventPropagation(evt); } function hatMouseMove(evt) { var offset = { "x": evt.pageX, "y": evt.pageY }; hatDragMove(offset); return preventEventPropagation(evt); } function hatMouseUp(evt) { hatDragEnd(); return preventEventPropagation(evt); } var hatMode = null; var hatOrigin = {}; var hatFrom = {}; function hatDragStart(pos, tgt) { var $hatStamp = $("#hatStamp"); var hatStampTransform = $hatStamp.css("-webkit-transform"); $hatStamp.css("transform", ""); $hatStamp.css("-webkit-transform", ""); var hatStampOrigin = $hatStamp.offset(); $hatStamp.css("transform", hatStampTransform); $hatStamp.css("-webkit-transform", hatStampTransform); var hatLayerOrigin = $("#hatLayer").offset(); if ($(tgt).attr("anchor") == "1") { hatMode = "anchor"; hatOrigin = { x:hatStampOrigin.left-hatLayerOrigin.left+hatStampOrigin.width*0.5, y:hatStampOrigin.top-hatLayerOrigin.top+hatStampOrigin.height*0.5, scale:parseFloat($hatStamp.attr("scale")), rotation:parseFloat($hatStamp.attr("rotation")) }; hatFrom = {x:pos.x-hatLayerOrigin.left-hatOrigin.x, y:pos.y-hatLayerOrigin.top-hatOrigin.y}; } else { hatMode = "drag"; hatOrigin = {x:hatStampOrigin.left-hatLayerOrigin.left, y:hatStampOrigin.top-hatLayerOrigin.top}; hatFrom = pos; } } function hatDragMove(pos) { var $hatStamp = $("#hatStamp"); if (hatMode == "anchor") { var hatLayerOrigin = $("#hatLayer").offset(); var hatTo = {x:pos.x-hatLayerOrigin.left-hatOrigin.x, y:pos.y-hatLayerOrigin.top-hatOrigin.y}; var distanceFrom = distanceBetweenPoints({x:0,y:0}, hatFrom); var distanceTo = distanceBetweenPoints({x:0,y:0}, hatTo); var scale = hatOrigin.scale * distanceTo / distanceFrom; var rotationFrom = angleBetweenPoints({x:0,y:0}, hatFrom); var rotationTo = angleBetweenPoints({x:0,y:0}, hatTo); var rotation = hatOrigin.rotation + rotationTo - rotationFrom; var degree = rotation * 180 / Math.PI; $hatStamp.attr("scale", scale); $hatStamp.attr("rotation", rotation); $hatStamp.css("transform", "scale("+scale+") rotate("+degree+"deg)"); $hatStamp.css("-webkit-transform", "scale("+scale+") rotate("+degree+"deg)"); } else if (hatMode == "drag") { var offset = {x:pos.x-hatFrom.x, y:pos.y-hatFrom.y}; var current = {x:hatOrigin.x+offset.x, y:hatOrigin.y+offset.y}; $hatStamp.css("left", [current.x, "px"].join("")); $hatStamp.css("top", [current.y, "px"].join("")); } } function hatDragEnd() { hatMode = null; } function sharePageByPlatform(evt) { var cosid = $("#saveSection .retry-btn").data("cosid"); var shareUrl = window.baseUrl + "index.html?id=" + cosid; var shareImg = $("#shareImg")[0].src; var imgData = $("#hatSection").data("result"); if (window.supportTouch) { if (window.isInMqq && window.self != window.top) { var shareObj = { postcode: "share", data: { title: $("meta[name=description]").attr("content"), desc: document.title, imageUrl: shareImg, url: shareUrl } } window.parent.postMessage(shareObj, '*'); } else { if (window.isInMqzone && imgData.length > 0 && window.p_uin.length > 0 && window.p_skey.length > 0) { sharePageByShuoshuoApi(imgData, window.baseUrl + "index.html"); } else { $("#shareSection").css("display", ""); } } } else { if (imgData && window.p_uin.length > 0 && window.p_skey.length > 0) { sharePageByShuoshuoApi(imgData, window.baseUrl + "index.html"); } else { sharePageByQZoneRedirect(shareImg, shareUrl); } } return preventEventPropagation(evt); } function setShareParams(shareImg, shareUrl) { var shareTitle = $("meta[name=description]").attr("content"); var shareDesc = document.title; if (window.isInWechat) { var shareParams = { title:shareTitle, desc:shareDesc, link:shareUrl, imgUrl:shareImg, success:function(){}, cancel:function(){} }; if (typeof(wx) == "object") { wx.onMenuShareTimeline(shareParams); wx.onMenuShareAppMessage(shareParams); wx.onMenuShareQQ(shareParams); wx.onMenuShareWeibo(shareParams); wx.onMenuShareQZone(shareParams); } else { loadScript("http://res.wx.qq.com/open/js/jweixin-1.0.0.js", function(){ loadScript("http://tu.qq.com/websites/wxBridge.php", function(){ wx.ready(function(){ wx.onMenuShareTimeline(shareParams); wx.onMenuShareAppMessage(shareParams); wx.onMenuShareQQ(shareParams); wx.onMenuShareWeibo(shareParams); wx.onMenuShareQZone(shareParams); }); }); }); } } else if (window.isInMqq) { var shareParams = { share_url:shareUrl, title:shareTitle, desc:shareDesc, image_url:shareImg }; if (typeof(mqq) == "object") { mqq.data.setShareInfo(shareParams); } else { loadScript("http://pub.idqqimg.com/qqmobile/qqapi.js?_bid=152", function(){ mqq.data.setShareInfo(shareParams); }); } } else if (window.isInMqzone) { if (typeof(QZAppExternal) == "object") { QZAppExternal.setShare(function(data){ }, { 'type' : "share", 'image': [shareImg, shareImg, shareImg, shareImg, shareImg], 'title': [shareTitle, shareTitle, shareTitle, shareTitle, shareTitle], 'summary': [shareDesc, shareDesc, shareDesc, shareDesc, shareDesc], 'shareURL': [shareUrl, shareUrl, shareUrl, shareUrl, shareUrl] }); } else { loadScript("http://qzs.qq.com/qzone/phone/m/v4/widget/mobile/jsbridge.js", function(){ QZAppExternal.setShare(function(data){ }, { 'type' : "share", 'image': [shareImg, shareImg, shareImg, shareImg, shareImg], 'title': [shareTitle, shareTitle, shareTitle, shareTitle, shareTitle], 'summary': [shareDesc, shareDesc, shareDesc, shareDesc, shareDesc], 'shareURL': [shareUrl, shareUrl, shareUrl, shareUrl, shareUrl] }); }); } } } function retryButtonPressed() { window.location.reload(); } function indexPageReady() { var cosid = pageGetParam("id"); document.getElementById("loadingSection").style.display = "none"; if (!window.supportTouch && !window.isWebkit) { var pageUrl = window.baseUrl + "index.html?id=" + cosid; var qrcodeUrl = "http://test.tu.qq.com/websites/qrcode.php?url=" + encodeURIComponent(pageUrl); document.getElementById("qrcodeImg").src = qrcodeUrl; document.getElementById("qrcodeSection").style.display = ""; return; } window.p_uin = pageGetCookie("uin").replace(/o/, ""); window.p_skey = pageGetCookie("p_skey"); var shouldSetDefaultShareParams = true; var wxState = pageGetParam("state"); var wxHeadImgUrl = pageGetParam("wxheadimgurl") || pageGetCookie("ttpt-wxheadimgurl"); if (window.isInWechat && wxState && wxHeadImgUrl.length > 0) { loadingStart(""); $.get("api/getHeadIcon.php?url="+encodeURIComponent(wxHeadImgUrl), function(data, status, xhr){ if (status == "success" && data.length > 0) { var photoImg = new Image(); photoImg.onload = function(){ loadingStop(); cropLoaded(this); $("#welcomeSection").css("display", ""); } photoImg.src = "data:image/jpeg;base64,"+data; } else { loadingStop(); $("#welcomeSection").css("display", ""); } }); } else { if (cosid.length > 0) { shouldSetDefaultShareParams = false; loadingStart(""); var cgiUrl = "../../cgi/queryCosInfo.php?id=" + cosid; $.getJSON(cgiUrl, function(data, status, xhr){ if (status == "success") { var photoImg = new Image(); photoImg.onload = function(){ loadingStop(); $("#resultImg").attr("src", this.src); $("#resultSection").css("display", ""); }; photoImg.src = data.rawPhotoUrl; // set share params var shareUrl = window.baseUrl + "index.html?id=" + cosid; setShareParams(data.rawPhotoUrl, shareUrl); } else { loadingStop(); $("#welcomeSection").css("display", ""); // set share params var shareImg = $("#defaultImg").attr("src"); var shareUrl = window.baseUrl + "index.html?id=" + cosid; setShareParams(shareImg, shareUrl); } }); } else { if (window.isInMqzone && window.p_uin.length > 0 && window.p_skey.length > 0) { loadingStart(""); $.get("api/getHeadIcon.php", function(data, status, xhr){ if (status == "success" && data.length > 0) { var photoImg = new Image(); photoImg.onload = function(){ loadingStop(); cropLoaded(this); $("#welcomeSection").css("display", ""); } photoImg.src = "data:image/jpeg;base64,"+data; } else { loadingStop(); $("#welcomeSection").css("display", ""); } }); } else { $("#welcomeSection").css("display", ""); } } } window.setTimeout(function(){ // init welcome section event $("#welcomeSection .choose-btn").on("click", cropChoose); // init result section event $("#resultSection .choose-btn").on("click", cropChoose); // init crop section event cropGesture = new EZGesture($("#cropLayer")[0], $("#cropImg")[0], {targetMinWidth:420, targetMinHeight:420}); var $canvas = $("#cropCanvas"); canvasDom = $canvas[0]; canvasCtx = canvasDom.getContext("2d"); cropGesture.targetMinWidth = canvasDom.width; cropGesture.targetMinHeight = canvasDom.height; $("#cropSection").css("visibility", "hidden"); $("#cropSection").css("display", ""); var cropLayerHeight = ($("#cropSection").width() * canvasDom.height * 100 / (canvasDom.width * $("#cropSection").height())).toFixed(2); $("#cropLayer").css("height", [cropLayerHeight, "%"].join("")); $("#cropSection").css("display", "none"); $("#cropSection").css("visibility", "visible"); // init hat section event var $hatSection = $("#hatSection"); var $hatLayer = $("#hatLayer"); $hatSection.css("visibility", "hidden"); $hatSection.css("display", ""); var hatLayerHeight = ($hatSection.width() * canvasDom.height * 100 / (canvasDom.width * $hatSection.height())).toFixed(2); $hatLayer.css("height", [hatLayerHeight, "%"].join("")); $hatSection.css("display", "none"); $hatSection.css("visibility", "visible"); if ((window.isInMqzone || !window.supportTouch) && window.p_uin.length > 0 && window.p_skey.length > 0) { $("#hatSection .confirm-btn").text("设为空间头像"); } $("#hatSection .confirm-btn").on("click", hatConfirm); if (window.supportTouch) { $hatLayer.on("touchstart", hatTouchStart); $hatLayer.on("touchmove", hatTouchMove); $hatLayer.on("touchend", hatTouchEnd); } else { $hatLayer.on("mousedown", hatMouseDown); $hatLayer.on("mousemove", hatMouseMove); $hatLayer.on("mouseup", hatMouseUp); } // init save section event $("#saveSection .share-btn").on("click", sharePageByPlatform); $("#saveSection .retry-btn").on("click", retryButtonPressed); $("#saveSection .download-btn").on("click", function(){ window.location = "http://tu.qq.com/downloading.php?by=124"; }); // init share section event $("#shareSection").on("click", function(){ $("#shareSection").css("display", "none"); }); if (shouldSetDefaultShareParams) { // set share params var shareImg = $("#defaultImg").attr("src"); var shareUrl = window.baseUrl + "index.html"; setShareParams(shareImg, shareUrl); } // pv var pf_flag = "other"; if (window.isInWechat) { pf_flag = "wechat"; } else if (window.isInMqzone) { pf_flag = "mqzone"; } else if (window.isInMqq) { pf_flag = "mqq"; } pageRecordPV(location.pathname + "-" + pf_flag); }, 0); } function indexPageResize() { }
/** * Function that builds an array of inputs based on values * in unspentOutputs and the satoshisToSend * @returns {Object} { inputs, remainingSatoshis } * @param {Object[]} unspentOutputs * @param {number} satoshisToSend */ export function getInputs(unspentOutputs, satoshisToSend) { const inputs = []; let totalInputSatoshis = 0; for (let i = 0; i < unspentOutputs.length; i++) { const unspentOutput = unspentOutputs[i]; totalInputSatoshis += unspentOutput.satoshis; inputs.push({ txid: unspentOutput.txid, vout: unspentOutput.vout, scriptPubKey: unspentOutput.scriptPubKey, }); if (totalInputSatoshis >= satoshisToSend) { break; } } const remainingSatoshis = totalInputSatoshis - satoshisToSend; return { inputs, remainingSatoshis, }; }
/** * Created by Preet on 8/22/2015. */ var componentApiApp = angular.module('ConfirmationBoxModule', []) .controller('confirmationController', ['$scope', function($scope) { $scope.configObject = { message : "This is a Yes No Test", header : "Confirmation Box", dialogId : 'myModal', closeModal : function (value) { $('#'+$scope.configObject.dialogId).modal("hide"); }, showModal : function () { $('#'+$scope.configObject.dialogId).modal(); } }; }]);
import React from 'react'; import { GiBrazil, /*GiInfo,*/ GiWorld } from 'react-icons/gi'; import SidebarItem from "./sidebarItem/sidebarItem"; import styles from './sidebar.module.scss'; const Sidebar = () => ( <div className={styles.sidebar}> <SidebarItem title="Brasil" link="/" > <GiBrazil /> </SidebarItem> <SidebarItem title="Mundo" link="/worldwide" > <GiWorld /> </SidebarItem> {/* <SidebarItem title="Sobre" link="/about" > <GiInfo /> </SidebarItem> */} </div> ); export default Sidebar;
/** * @note * * @param url * @return {Promise} */ export default url => { const Img = new Image(); return new Promise((reslove,reject)=>{ Img.onload = ()=>{ reslove("success"); }; Img.onerror = ()=>{ reject("error"); }; setTimeout(()=>{reject("timeout")},2000); Img.src = url; }); }
var chai = require('chai'); var chaiHttp = require('chai-http'); var server = require('../../bin/www'); var expect = chai.expect; chai.use(chaiHttp); var _ = require('lodash'); chai.use(require('chai-things')); describe('Customers', function() { describe('customerss', function() { beforeEach(function() { while (datastore.length > 0) { datastore.pop(); } datastore.push({ id: 1234567, firstName: 'Emma', secondName: 'O Donnell', email: 'emma.odonnell2@live.com', password: 'fullclip', phone: '0877877654', address: 'Deerpark East' }); datastore.push({ id: 7654321, firstName: 'Jaja', secondName: 'O Donnell', email: 'jaja.odonnell2@live.com', password: 'lololo', phone: '0873426754', address: 'Cork' }); }); }); describe('GET /customers', function() { it('should return all the customers in an array', function(done) { chai.request(server) .get('/customers') .end(function(err, res) { expect(res).to.have.status(200); expect(res.body).to.be.a('array'); expect(res.body.length).to.equal(2); var result = _.map(res.body, function(customer) { return { id: customer.id, firstName: customer.firstName }; }); expect(result).to.include({ id: 1234567, firstName: 'Emma' }); expect(result).to.include({ id: 7654321, firstName: 'Jaja' }); done(); }); }); }); describe('POST /customers', function() { it('should return confirmation message and update datastore', function(done) { var customer = { firstName: 'Manuel', secondName: 'Doudi', email: 'Manue2274@live.com', password: 'axdevf', phone: '0899789887', address: 'Lismore' }; chai.request(server) .post('/customers') .send(customer) .end(function(err, res) { expect(res).to.have.status(200); expect(res.body).to.have.property('message').equal('customer Added!'); done(); }); }); }); describe('DELETE /customers/:id', function() { it('should delete customer with a valid id', function(done) { chai.request(server) .delete('/customers/1234567') .end(function(err, res) { expect(res).to.have.status(200); done(); }); }); it('should return a 404 status for invalid customer id to delete', function(done) { chai.request(server) .delete('/customers/1100001') .end(function(err, res) { expect(res).to.have.status(200); done(); }); }); }); describe('GET /customers/:id', function() { it('should return a specific customer with a valid id', function(done) { chai.request(server) .get('/customers/1234567') .end(function(err, res) { expect(res).to.have.status(200); done(); }); }); it('should return a 404 status and message for invalid customer id', function(done) { chai.request(server) .get('/customers/1100001') .end(function(err, res) { expect(res).to.have.status(200); expect(res.body).to.have.property('message').equal('customer NOT Found!'); done(); }); }); }); });
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module('appAnalist').controller('andashboardController',function($scope,$http,$interval,$rootScope){ $scope.s={}; $scope.alerta = 'default'; $scope.presenca = JSON.parse(sessionStorage.userData).presenca; console.log($scope.presenca); //Get parceiros $http({ url:'php/getData.php', method:'POST', data:'cad_parceiros' }).then(function(answer){ $scope.parceiros = answer.data; }); //Get utilizadores $http({ url:'php/getData.php', method:'POST', data:'cad_utilizadores' }).then(function(answer){ $scope.utilizadores = answer.data; }); //Get LEADS information getInfo(); $interval(getInfo,120000); // $scope.hoje = answer.data.hoje; //Mural $scope.selectDestino = function(conv){ if(!$scope.clicked || $scope.clicked!=conv.id){ $scope.clicked = conv.id; $scope.destino = conv.origem; } else{ $scope.clicked =0; $scope.destino = 0; } $rootScope.flagMural=""; $scope.alerta = 'default'; } //Botão enviar para $scope.enviarPara = function(u){ conversa = {'id':'', 'origem': sessionStorage.userId, 'destino': u.id, 'assunto': $scope.assunto, 'dataenvio': '', 'datavisto':'' , 'status':0, 'sentido': 'msg-out' }; $http({ url:'php/enviarParaMural.php', method:'POST', data:JSON.stringify(conversa) }).then(function(answer){ getInfo(); }); $scope.assunto=''; $scope.clicked=0; } //Enviar resposta para o selecionado $scope.enviarResposta = function(){ if($scope.clicked && $scope.clicked!=sessionStorage.userId){ conversa = {'id':'', 'origem': sessionStorage.userId, 'destino': $scope.destino, 'assunto': $scope.assunto, 'dataenvio': '', 'datavisto':'' , 'status':0, 'sentido': 'msg-out' }; $http({ url:'php/enviarParaMural.php', method:'POST', data:JSON.stringify(conversa) }).then(function(answer){ getInfo(); }); $scope.assunto=''; $scope.clicked=0; } } $scope.seeDetailAnalise = function(lead) { window.location.href = "#!/form1/"+ lead; }; function getInfo(){ //Get LEADS information $http({ url:'php/analista/andashboardinfo.php', method:'POST', data:sessionStorage.userData }).then(function(answer){ $scope.paraAnalise = answer.data.paraAnalise; $scope.ativa = answer.data.ativa; $scope.emAnalise = answer.data.emAnalise; $scope.listaEmAnalise = answer.data.listaEmAnalise; $scope.aprovados = answer.data.aprovados; $scope.listaAprovados = answer.data.listaAprovados; $scope.listaResultados = answer.data.listaResultados; $scope.financiados = answer.data.financiados; $scope.financiadosACP = answer.data.financiadosACP; $scope.financiadosRCP = answer.data.financiadosRCP; $scope.suspensos = answer.data.suspensos; $scope.alertaACP = answer.data.alertaACP; $scope.docOk = answer.data.docOk; if(answer.data.alertaACP>0){ $rootScope.alertaACP = '!!'; } else { $rootScope.alertaACP = ''; } $rootScope.valorFinanciado = answer.data.valorFinanciado; $scope.recusados = answer.data.recusados; //Mural $scope.conversas = answer.data.conversas; var convArray = answer.data.conversas; $rootScope.flagMural = ""; var now = Date.now(); for(var i= convArray.length-1; i > 0; i--){ if(convArray[i].sentido == "msg-in" && Math.floor((now - Date.parse(convArray[i].dataenvio))/60000)<2){ $rootScope.flagMural = "[msg]" ; $scope.alerta = 'danger'; break; } } }); } $scope.searchLead = function(s){ if(!s.lead && !s.nome && !s.telefone && !s.email && !s.nif && !s.process && !s.parceiro && !s.leadorig){ alert("Tem de preencher pelo menos um campo!"); } else{ window.location.replace("#!/listPesq/"+JSON.stringify(s)); } }; //Clear fields $scope.clearSearch = function(){ $scope.s ={}; }; });
const router = require("express").Router(); const sequelize = require("../../config/connection"); const withAuth = require("../../utils/auth"); const { weight_posts, users } = require("../../models"); router.get("/", (req, res) => { weight_posts .findAll({ attributes: ["id", "user_id", "date", "weight"], include: [ { model: users, attributes: ["username"], }, ], }) .then((weight_postsData) => res.json(weight_postsData)) .catch((err) => { console.log(err); res.status(500).json(err); }); }); router.get("/:id", (req, res) => { weight_posts .findOne({ where: { id: req.params.id, }, attributes: ["id", "user_id", "date", "weight"], include: [ { model: users, attributes: ["username"], }, ], }) .then((weight_postsData) => { if (!weight_postsData) { res.status(404).json({ message: "No Weight Post found with this id" }); return; } res.json(weight_postsData); }) .catch((err) => { console.log(err); res.status(500).json(err); }); }); router.post("/", withAuth, (req, res) => { weight_posts .create({ weight: req.body.weight, user_id: req.session.user_id, }) .then((weight_postsData) => res.json(weight_postsData)) .catch((err) => { console.log(err); res.status(500).json(err); }); }); router.delete("/:id", withAuth, (req, res) => { console.log("id", req.params.id); weight_posts .destroy({ where: { id: req.params.id, }, }) .then((weight_postsData) => { if (!weight_postsData) { res.status(404).json({ message: "No weight post found with this id" }); return; } res.json(weight_postsData); }) .catch((err) => { console.log(err); res.status(500).json(err); }); }); module.exports = router;
var mym = require('./mymodule.js'); //name of the module/path of the module - import console.log(mym.numbers[1]); console.log(mym.msg); console.log(mym.person.fname); console.log(mym.calArea(4.5));
import React from "react"; import { withStyles } from "@material-ui/core/styles"; import { CSSTransition } from "react-transition-group"; import Category from "../components/Category"; import { categories, category } from "../categories"; const styles = theme => ({ menu: { alignItems: "center", display: "flex", justifyContent: "center", height: "100%", transform: "rotate(-180deg)", transformOrigin: "center", transition: theme.transitions.create("transform", { duration: 1000 }), width: "100%" }, loaded: { transform: "rotate(0)" } }); class App extends React.Component { render() { const { classes } = this.props; return ( <CSSTransition appear timeout={1} in classNames={{ enterDone: classes.loaded }} > <div className={classes.menu}> {categories.map(c => <Category key={c.id} {...category(c.id)} />)} </div> </CSSTransition> ); } } export default withStyles(styles)(App);
export const transparentHeaderStyle = { backgroundColor: 'transparent', position: 'absolute', top: 0, left:0, right: 0, borderBottomWidth: 0, elevation: 0, }; //elevation
/** * Copyright © 2014 Julian Reyes Escrigas <julian.reyes.escrigas@gmail.com> * * This file is part of concepto-sises. * * concepto-sises * can not be copied and/or distributed without the express * permission of Julian Reyes Escrigas <julian.reyes.escrigas@gmail.com> */ ; (function () { "use strict"; angular.module(G.APP) .directive('transform', ['$filter', function($filter) { return { restrict: 'A', require: '?ngModel', scope: { transform: '@' }, link: function(scope, el, attrs, ngModel) { var transformers = { currency: { formatter: function(value) { return $filter('currency')(value, '$', 2); }, parser: function(value) { return +value.replace(/[^0-9.]+/g, ''); }, events: [ { name: 'focus', func: function() { var val = +ngModel.$modelValue; el.val(!isNaN(val) ? val : ngModel.$modelValue); } }, { name: 'blur', func: function() { el.val(transformers.currency.formatter(ngModel.$modelValue)); } } ] } }; if (typeof ngModel === 'undefined') { return; } if (typeof scope.transform === 'undefined' || scope.transform === null || scope.transform === '') { return; } var t = transformers[scope.transform]; if (!t) { throw "No existe el transformer '" + scope.transform + "'"; } ngModel.$formatters.push(t.formatter); ngModel.$parsers.push(t.parser); if (t.events && t.events.length > 0) { angular.forEach(t.events, function(event) { el.on(event.name, event.func) }) } } } }]); })();
import './style/global.css' import './style/topic_news.css' import FastForwardIcon from '@material-ui/icons/FastForward' let html = (<> <div className="news_container"> {/* Barra de navegação */} <div className="topnavbar"> <FastForwardIcon /> <a href="/">Página Inicial</a> <a className="active" href="/movimento_estudantil">Movimento Estudantil</a> <a href="#comp">Espaço da Computação</a> <a href="#about">Sobre nós</a> </div> {/* Pagina das notícias */} <div id="principal_news"> <h1 className="news_title">Movimento estudantil</h1> <h4 className="news_subtitle">Descrição sobre movimento estudantil</h4> </div> </div> </>); export default function News() { return html; }
function removeFirstAndLastCharacter(stringParam) { // returning a value of string return } // call the function console.log(removeFirstAndLastCharacter("malam")) // expected output // "ala"
console.log('start') chrome.action.onClicked.addListener(tab => { console.log('click') console.log(tab) var el = document.createElement('textarea'); var url = tab.url; console.log(url) el.value = window.location.href; document.body.appendChild(el); el.select(); el.setSelectionRange(url.lastIndexOf('/') + 1, url.length) document.execCommand('copy'); document.body.removeChild(el); }); console.log('aaa')
import { find } from "lodash"; import { API_HOST_URL, GEOSERVER_HOST_URL, BUILD_ID, } from "@/store/modules/_constants"; import { toISODate } from "@/store/stats"; export const WMS_SERVER_URI = "geoserver/SKOPE/wms?"; export const DEFAULT_CENTERED_SMOOTHING_WIDTH = 11; export const DEFAULT_MAX_PROCESSING_TIME = 10000; // in ms export const SKOPE_WMS_ENDPOINT = `${GEOSERVER_HOST_URL}/${WMS_SERVER_URI}`; export const TIMESERIES_ENDPOINT = `${API_HOST_URL}/timeseries`; export const METADATA_ENDPOINT = `${API_HOST_URL}/metadata`; export const LEAFLET_PROVIDERS = [ { name: "CartoDB.Positron", url: "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", visible: 2, attribution: 'OpenStreetMap &copy; <a href="//carto.com/attributions">CARTO</a>', subdomains: "abcd", }, { name: "Stamen.TonerLite", url: "https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}{r}.png", visible: false, attribution: 'Tiles &copy; <a href="//stamen.com">Stamen Design</a> <a href="https://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>', }, { name: "Esri.WorldTerrain", url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}", visible: false, attribution: "Tiles &copy; Esri &mdash; Source: USGS, Esri, TANA, DeLorme, and NPS", }, { name: "Esri.WorldTopoMap", url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", attribution: "Tiles &copy; Esri et al", visible: 1, }, ]; export class BaseMapProvider { static get(name) { return find(LEAFLET_PROVIDERS, { name }); } } export function buildReadme(requestData) { return ` # SKOPE data for ${requestData.dataset_id} / ${requestData.variable_id} ### [version: ${BUILD_ID}](https://github.com/openskope/skopeui) ## Terms of Service By using the SKOPE application, you assume any risk associated with its use. You are solely responsible for any damage or loss you may incur resulting from your reliance on or use of information provided by SKOPE. ## Citation Use of data, graphics, or other information provided by SKOPE should be accompanied by a citation of the original data source (provided by SKOPE in the dataset metadata) and of the SKOPE application Web page. Example reference: (SKOPE 2021). Example Citation: > SKOPE 2021 SKOPE: Synthesizing Knowledge of Past Environments. https://app.openskope.org/. Accessed 1 July 2021. ## Contact For comments, feedback, or questions, please use the "Email Us" button on the application navigation bar or send us a note at skope-team@googlegroups.com Time range: ${requestData.time_range.gte} - ${requestData.time_range.lte} CE Location: ${JSON.stringify(requestData.selected_area, null, 2)} ## Files - \`skope-request.json\` - A plaintext JSON file with all input parameters needed to recreate this analysis. Load this file into the SKOPE app to regenerate the data in this zipfile. - \`summary-statistics.json\` - The computed mean, median, and standard deviation of the time series data. - \`plot.png\` and \`plog.svg\` - Graph of the time series data. - \`time-series.json\` and \`time-series.csv\` - time series data in JSON and long form CSV formats. - \`study-area.geojson\` - GeoJSON file with the defined study area. `; } // constants data structure of available smoothing options to present in the UI export const SMOOTHING_OPTIONS = [ { label: "None (time steps individually plotted)", id: "none", type: "NoSmoother", method: "none", toRequestData: function (analyzeVue) { return { type: this.type, }; }, fromRequestData: function (analyzeVue, requestData) { analyzeVue.smoothingOption = this.id; }, }, { label: "Centered Running Average", id: "centeredAverage", method: "centered", type: "MovingAverageSmoother", toRequestData: function (analyzeVue) { return { type: this.type, method: this.method, width: analyzeVue.smoothingTimeStep, }; }, fromRequestData: function (analyzeVue, requestData) { analyzeVue.smoothingOption = this.id; analyzeVue.smoothingTimeStep = requestData.width; }, }, { label: "Trailing Running Average (- window width)", id: "trailingAverage", method: "trailing", type: "MovingAverageSmoother", toRequestData: function (analyzeVue) { return { type: this.type, method: this.method, width: analyzeVue.smoothingTimeStep, }; }, fromRequestData: function (analyzeVue, requestData) { analyzeVue.smoothingOption = this.id; analyzeVue.smoothingTimeStep = requestData.width; }, }, ]; // constants data structure for available transform options to display in the UI export const TRANSFORM_OPTIONS = [ { label: "None: Modeled values displayed", id: "none", type: "NoTransform", toRequestData: function () { return { type: this.type, }; }, fromRequestData: function (analyzeVue) { analyzeVue.transformOption = this.id; }, }, { label: "Z-Score wrt selected interval", id: "zscoreSelected", type: "ZScoreFixedInterval", toRequestData: function () { return { type: this.type, }; }, fromRequestData: function (analyzeVue, requestData) { if (requestData.time_range) { // FIXME: refactor this, we have two mappings for ZScoreFixedIntervals and // the only way to disambiguate them at the moment is testing for requestData.time_range analyzeVue.transformOption = "zscoreFixed"; analyzeVue.time_range = requestData.time_range; } else { analyzeVue.transformOption = this.id; } }, }, { label: "Z-Score wrt fixed interval", id: "zscoreFixed", type: "ZScoreFixedInterval", toRequestData: function (analyzeVue) { return { type: this.type, time_range: { gte: toISODate(analyzeVue.timeRange.lb.year), lte: toISODate(analyzeVue.timeRange.ub.year), }, }; }, fromRequestData: function (analyzeVue, requestData) { // FIXME: this does not get called due to multiple mappings for ZScoreFixedIntervals analyzeVue.transformOption = this.id; analyzeVue.time_range = requestData.time_range; }, }, { label: "Z-Score wrt moving interval", id: "zscoreMoving", type: "ZScoreMovingInterval", toRequestData: function (analyzeVue) { return { type: this.type, width: analyzeVue.zScoreMovingIntervalTimeSteps, }; }, fromRequestData: function (analyzeVue, requestData) { analyzeVue.transformOption = this.id; analyzeVue.zScoreMovingIntervalTimeSteps = requestData.width; }, }, ];
/** * Misc constants for a gameplay * * @type Object */ var GameConst = { // how often worker (woodcutter, mason) is gonna get material [s] worker_period : 5, goldmine_period : 5, farm_period : 5, // how far a worker can go to get to his material source furthest_possible_material : 9, // how far gold can be to collect furthest_possible_gold : 7, } Sprites.init(); //Sprites.get(Sprites); current_map.load_map_from_tiled(game_data.map); current_map.load_materials(Materials, units); config.update(); //current_map.init(); //var map = current_map.GetMap(); var map_w = Math.floor(config.map_width / config.tile_width); var map_h = Math.floor(config.map_height / config.tile_height); b1 = new Building(building_knights_main); b1.construction_progress = 100; b1.x = current_map.knights_start_x; b1.y = current_map.knights_start_y; b3 = new Building(building_skeletons_main); b3.construction_progress = 100; b3.x = current_map.skeletons_start_x; b3.y = current_map.skeletons_start_y; b2 = new Building(building_knights_barracks); b2.x = 12; b2.y = 4; //t1 = new Material('tree', Materials['stone_class_7'], 1, 4); units.push(b1); units.push(b2); units.push(b3); //units.push(t1); // popups var popups = {}; popups['not_enough_to_build'] = new Popup("This building cannot be built.<br />You do not have enough materials.", 300, 150); popups['not_enough_to_train'] = new Popup("You cannot recruit this unit.<br />You do not have enough materials.", 300, 150); popups['max_three_units_in_training'] = new Popup("You cannot recruit more<br />than three units at the same time.", 300, 150); popups['no_wood_for_woodcutter'] = new Popup("Woodcutter cannot find trees nearby.<br />Build woodcutter's hut closer<br />to the trees.", 300, 150); popups['no_stone_for_mason'] = new Popup("Mason cannot find stone nearby.<br />Build mason's hut closer to the stone.", 300, 150); popups['no_mountains_nearby'] = new Popup("Goldmine cannot work because<br />it's too far away from the mountains.", 300, 150); prices = { // Knights 'farm': { gold: 5, material: 10 }, 'woodcutter': { gold: 5, material: 10 }, 'ktower': { gold: 5, material: 10 }, 'kbarracks': { gold: 5, material: 10 }, 'kgoldmine': { gold: 5, material: 10 }, // Skeletons 'temple': { gold: 5, material: 10 }, 'mason': { gold: 5, material: 10 }, 'stower': { gold: 5, material: 10 }, 'sbarracks': { gold: 5, material: 10 }, 'sgoldmine': { gold: 5, material: 10 }, // Units 'kwarrior': { gold: 5, food: 5 }, 'karcher': { gold: 7, food: 6 }, 'kknight': { gold: 10, food: 10 }, 'kpaladin': { gold: 20, food: 15 }, 'swarrior': { gold: 5, food: 5 }, 'sarcher': { gold: 7, food: 6 }, 'sknight': { gold: 10, food: 10 }, 'smonk': { gold: 20, food: 15 }, }
export const state = () => ({ cartInfo: "" }); export const getters = {}; export const mutations = { setCartInfo(state, v) { state.cartInfo = v; } }; export const actions = { async updateShippingAddress({ dispatch, state, commit }, obj) { let r = await this.$axios .post("/api/checkout/updateShippingAddress", { checkoutId: state.cartInfo.id, shippingAddress: obj.shippingAddress }) .then(); if (r.id) { commit("setCartInfo", r); } }, async addCart({ dispatch, state, commit }, obj) { if (state.cartInfo.id) { let r = await this.$axios .post("/api/cart/add", { variantId: obj.variantId, cartId: state.cartInfo.id }) .then(); if (r.id) { dispatch("info/success", "成功", { root: true }); commit("setCartInfo", r); return r.id; } } else { let r = await this.$axios.post("api/cart/create-checkout", obj).then(); console.dir("加入购物车成功后返回"); console.log(JSON.stringify(r)); if (r.id) { dispatch("info/success", "成功", { root: true }); commit("setCartInfo", r); return r.id; } } } };
/* The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? */ var helper = require('./helper.js'), div = 0, max = 0, num = 1, result = 0; function divisorsCount(num) { var limit = ~~Math.sqrt(num), result = 0; while (limit > 0) { if (num % limit-- === 0) { result += 2; } } return result; } do { result += num; div = divisorsCount(result); if (max < div) { max = div; } } while (max < 500 && num++); helper(result);
"use strict"; /// <reference path="../../../default/scene/ComponentConfig.d.ts" /> Object.defineProperty(exports, "__esModule", { value: true }); const P2BodyConfig_1 = require("./P2BodyConfig"); SupCore.system.registerPlugin("componentConfigs", "P2Body", P2BodyConfig_1.default);
import { Provider } from 'react-redux'; import { initializeStore } from './store'; let reduxStore; export const getInitializeStore = (initialState) => { if (typeof window === 'undefined') { return initializeStore(initialState); } if (!reduxStore) { reduxStore = initializeStore(initialState); } return reduxStore; }; const withRedux = (PageComponent) => { const createWrapper = ({ initialReduxState, ...props }) => { const store = getInitializeStore(initialReduxState); return ( <Provider store={store}> <PageComponent {...props} /> </Provider> ); }; return createWrapper; }; export default withRedux;
const test = require('tape'); const JSONToFile = require('./JSONToFile.js'); test('Testing JSONToFile', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof JSONToFile === 'function', 'JSONToFile is a Function'); t.pass('Tested on 09/02/2018 by @chalarangelo'); //t.deepEqual(JSONToFile(args..), 'Expected'); //t.equal(JSONToFile(args..), 'Expected'); //t.false(JSONToFile(args..), 'Expected'); //t.throws(JSONToFile(args..), 'Expected'); t.end(); });
import React from "react"; import { useRouter } from "next/router"; import { useDispatch, useSelector } from "react-redux"; import { CANCEL_POST } from "../../actions/types"; import styled from "styled-components"; import { Button, Modal } from "antd"; import { LeftOutlined, RightOutlined, ExclamationCircleOutlined, } from "@ant-design/icons"; import { publishPost } from "../../actions/publishPost"; const { confirm } = Modal; const Container = styled.section` display: flex; `; const NavButtons = ({ step, handleStepChange }) => { const router = useRouter(); const dispatch = useDispatch(); const location = useSelector((state) => state.currentLocation.location); const imgList = useSelector((state) => state.imgUpload.imgList); const formData = useSelector((state) => state.createPostForm); const isLoading = useSelector((state) => state.createPostForm.isLoading); const isMapLoading = useSelector( (state) => state.currentLocation.isMapLoading ); function handleCancelConfirm() { confirm({ title: router.pathname === "/createpost" ? "Cancel Post" : "Cancel Update", icon: <ExclamationCircleOutlined />, content: "Are you sure you want to cancel?", okText: "Yes", okType: "danger", cancelText: "No", onOk() { dispatch({ type: CANCEL_POST }); router.push("/"); }, }); } const redirectToAccount = () => { router.push("/account?view=overview"); }; const handlePublish = () => { dispatch( publishPost( location, imgList, formData, redirectToAccount, router.query.postId ) ); }; return ( <Container> <Button onClick={handleCancelConfirm} type='danger' ghost style={{ margin: "0.5rem" }} > Cancel </Button> {step !== 0 && ( <Button onClick={() => handleStepChange(step - 1)} style={{ marginRight: "5px" }} type='primary' ghost disabled={step < 1 ? true : false} style={{ margin: "0.5rem" }} > <LeftOutlined /> Previous </Button> )} <span style={{ flex: 1 }} /> {step !== 2 && ( <Button onClick={() => handleStepChange(step + 1)} type='primary' ghost disabled={step > 1 ? true : false} style={{ margin: "0.5rem" }} > Next <RightOutlined /> </Button> )} {step === 2 && ( <Button onClick={() => handleStepChange(3)} type='primary' disabled={step !== 2} style={{ margin: "0.5rem" }} disabled={ !formData.title || !formData.price || !location.lat || !location.lng || isMapLoading } > Preview <RightOutlined /> </Button> )} {step === 3 && ( <Button onClick={() => handlePublish()} loading={isLoading} type='primary' disabled={ !formData.title || !formData.price || !location.lat || !location.lng || isMapLoading } style={{ margin: "0.5rem" }} > {router.pathname.includes("/editpost/") && "Update"} {router.pathname === "/createpost" && "Publish"} </Button> )} </Container> ); }; export default NavButtons;
import { createStore, applyMiddleware, combineReducers } from "redux"; import { createLogger } from 'redux-logger' import thunk from 'redux-thunk' import { selectedSub, postsBySub } from './reducers' const logger = createLogger() const rootReducer = combineReducers({ selectedSub, postsBySub }) const configureStore = preloadedState => createStore( rootReducer, preloadedState, applyMiddleware( thunk, logger ) ) export default configureStore
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "c9643c8993e0769462ba1a7a39ab26aa", "url": "/my-portfolio/index.html" }, { "revision": "a76aaec645b7309eb62a", "url": "/my-portfolio/static/css/main.d1b05096.chunk.css" }, { "revision": "1fba77d7f6a1246d25a5", "url": "/my-portfolio/static/js/2.7d6da53f.chunk.js" }, { "revision": "99bd0487192ec9e7d9ee8fbbd91ee444", "url": "/my-portfolio/static/js/2.7d6da53f.chunk.js.LICENSE.txt" }, { "revision": "a76aaec645b7309eb62a", "url": "/my-portfolio/static/js/main.06b3989e.chunk.js" }, { "revision": "164cd71dc8e56a933ce3", "url": "/my-portfolio/static/js/runtime-main.d96a2d46.js" } ]);
google.charts.load("current", {packages:["corechart", "table", "annotatedtimeline"]}); google.charts.setOnLoadCallback(firstRun); function drawCharts() { if(isDataRangeValid()) { $("#preloader").show(); $("#result").html(""); $("#timeseries").html(""); $.ajax({ type: "GET", url: "/admin/get-questions", contentType: "application/json", success: function (questions) { $("#preloader").hide(); for (let i in questions) { drawChart(questions[i]["key"], questions[i]["text"], $("#from_date").val(), $("#to_date").val()); changeTo("chart", "timeseries", "table"); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status); console.log(thrownError); } }); let payload = '{ "from": "' + $("#from_date").val() + '", "to": "' + $("#to_date").val() + '" }' $.ajax({ type: "POST", url: "/admin/get-answers-by-day", contentType: "application/json", data: payload, success: function (answers) { $("#totalnum").html("Numero di risposte nel periodo: " + answers['total']); drawTimeSeries(answers); }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status); console.log(thrownError); } }); } } function drawTimeSeries(answers) { $("#timeseries").html(""); let data = new google.visualization.DataTable(); data.addColumn('date', 'Data'); data.addColumn('number', 'Risposte'); let rows = []; $.each(answers['data'], function( index, value ) { rows.push([new Date(value[0]), value[1]]); }); data.addRows(rows); $("#timeseries").append('<div class="row"><div class="col s12" style="margin-top: 20px">Serie temporale</div></div>'); $("#timeseries").append('<div class="row"><div class="col s12"><div id="timechart" style="width: 100%; height: 500px;"></div></div></div>'); let chart = new google.visualization.AnnotatedTimeLine(document.getElementById('timechart')); chart.draw(data, { displayAnnotations: false, width: '100%', height: '100%' }); } function drawChart(qid, title, from, to) { let payload = '{ "qid": "' + qid + '", "from": "' + from + '", "to": "' + to + '" }' $.ajax({ type: "POST", url: "/admin/get-answers", contentType: "application/json", data: payload, success: function (answers) { $("#result").append('<div class="row"><div class="col s12 title" style="margin-top: 20px">' + title + '</div></div>'); $("#result").append('<div class="row"><div class="col s12"><div class="chart" id="'+ qid +'"></div></div><div class="col s12"><div style="display:none" class="table" id="'+ qid +'_table"></div></div></div>'); let data = google.visualization.arrayToDataTable(answers); var options = { width: '100%', height: '100%', legend: 'right', pieSliceText: 'percentage', backgroundColor: {strokeWidth: 1 }, chartArea:{left:20,top:20,width:'80%',height:'80%'} }; let currChart = new google.visualization.PieChart(document.getElementById(qid)); currChart.draw(data, options); let dataTable = new google.visualization.DataTable(); dataTable.addColumn('string', 'Risposta'); dataTable.addColumn('number', 'Numero risposte'); dataTable.addRows(answers.slice(1)); let table = new google.visualization.Table(document.getElementById(qid +'_table')); table.draw(dataTable, { showRowNumber: false, width: '100%', height: '100%', cssClassNames: { headerRow : "bcol" } }); }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status); console.log(thrownError); } }); } function changeTo(toshow, tohide1, tohide2) { $( "." + tohide1 ).each(function( index ) { $( this ).hide(); }); $( "." + tohide2 ).each(function( index ) { $( this ).hide(); }); $( "." + toshow ).each(function( index ) { $( this ).show(); }); if (toshow == "timeseries") { $( ".title" ).each(function( index ) { $( this ).hide(); }); } else { $( ".title" ).each(function( index ) { $( this ).show(); }); } } function showTimeSeries() { if($("#timeseries").is(":visible")) { $("#timeseries").hide(); } else { $("#timeseries").show(); } } /** //google.charts.load('current', {'packages':['table']}); google.charts.setOnLoadCallback(drawTable); function drawTable() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Risposta'); data.addColumn('number', 'Numero risposte'); data.addRows([ ['Mike', 123], ['Jim', 4333], ['Alice', 3433] ]); var table = new google.visualization.Table(document.getElementById('table_div')); table.draw(data, { showRowNumber: false, width: '100%', height: '100%', cssClassNames: { headerRow : "bcol" } }); } */ function setActive(id) { $(".mynavbtn").each(function( index ) { $( this ).removeClass("active"); }); $("#"+id).addClass("active"); } function firstRun() { $("#date_range").hide(); setActive("month"); var today = new Date(); $("#from_date").val("01-" + (today.getMonth()+1) + "-" + today.getFullYear()); $("#to_date").val(today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear()); drawCharts(); } function drawToday() { $("#date_range").hide(); setActive("today"); var today = new Date(); var todayString = today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear(); $("#from_date").val(todayString); $("#to_date").val(todayString); drawCharts(); } function drawMonth() { $("#date_range").hide(); setActive("month"); var today = new Date(); $("#from_date").val("01-" + (today.getMonth()+1) + "-" + today.getFullYear()); $("#to_date").val(today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear()); drawCharts(); } function drawYear() { $("#date_range").hide(); setActive("year"); var today = new Date(); $("#from_date").val("01-01-" + today.getFullYear()); $("#to_date").val(today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear()); drawCharts(); } function showCustom() { $("#date_range").show(); setActive("custom"); } function isDataRangeValid() { if ($("#from_date").val() && $("#to_date").val() && $("#from_date").val() != "" && $("#to_date").val() != "") { let fromDateSplitted = $("#from_date").val().split("-"); let currFrom = new Date(parseInt(fromDateSplitted[2]), parseInt(fromDateSplitted[1]), parseInt(fromDateSplitted[0]), 0, 0, 0); let toDateSplitted = $("#to_date").val().split("-"); let currTo = new Date(parseInt(toDateSplitted[2]), parseInt(toDateSplitted[1]), parseInt(toDateSplitted[0]), 23, 59, 59); if (currTo > currFrom) { return true; } M.toast({html: 'Date non compatibili!'}); return false; } }
import React, { useState, createContext, useEffect } from "react"; export const Context = createContext(); const ContextProvider = props => { const [thisMonthTweets, setThisMonthTweets] = useState([]); const [todayTweets, setTodayTweets] = useState({}); const [selectedComponent, setSelectedComponent] = useState("LiveStream"); const [hashtags, setHashtags] = useState([]); const [monthlyTweetsEmotions, setMonthlyTweetsEmotions] = useState([]); const [thisMonthTweetsCollection, setThisMonthTweetsCollection] = useState( [] ); return ( <Context.Provider value={{ thisMonthTweets, setThisMonthTweets, thisMonthTweetsCollection, setThisMonthTweetsCollection, todayTweets, setTodayTweets, selectedComponent, setSelectedComponent, hashtags, setHashtags, monthlyTweetsEmotions, setMonthlyTweetsEmotions }} > {props.children} </Context.Provider> ); }; export default ContextProvider;
const token = process.env.API_TOKEN || require('../../config/token'); const axios = require('axios'); const getNypdData = function (year) { if (!year || year === Date().split(' ')[3]) { return axios.get(`https://data.cityofnewyork.us/resource/5ucz-vwe8.json?statistical_murder_flag=Y&$$app_token=${token}`); } else { return axios.get(`https://data.cityofnewyork.us/resource/833y-fsy8.json?statistical_murder_flag=true&$where=occur_date%20between%20%27${year}-01-01T00:00:00%27%20and%20%27${year}-12-31T00:00:00%27&$$app_token=${token}`); } } module.exports = { getNypdData: getNypdData }
'use strict'; /** * Link.js controller * * @description: A set of functions called "actions" for managing `Link`. */ module.exports = { /** * Retrieve link records. * * @return {Object|Array} */ find: async (ctx, next, { populate } = {}) => { if (ctx.query._q) { return strapi.services.link.search(ctx.query); } else { return strapi.services.link.fetchAll(ctx.query, populate); } }, /** * Retrieve a link record. * * @return {Object} */ findOne: async (ctx) => { if (!ctx.params._id.match(/^[0-9a-fA-F]{24}$/)) { return ctx.notFound(); } return strapi.services.link.fetch(ctx.params); }, /** * Count link records. * * @return {Number} */ count: async (ctx) => { return strapi.services.link.count(ctx.query); }, /** * Create a/an link record. * * @return {Object} */ create: async (ctx) => { return strapi.services.link.add(ctx.request.body); }, /** * Update a/an link record. * * @return {Object} */ update: async (ctx, next) => { return strapi.services.link.edit(ctx.params, ctx.request.body) ; }, /** * Destroy a/an link record. * * @return {Object} */ destroy: async (ctx, next) => { return strapi.services.link.remove(ctx.params); } };
import path from 'path' module.exports = { // 导入别名 alias: { '/@/': path.resolve(__dirname, './src'), '/@/': path.resolve(__dirname, './src/views'), '/@components/': path.resolve(__dirname, './src/components'), '/@utils/': path.resolve(__dirname, './src/utils'), }, css: { loaderOptions: { sass: { prependData: `@import "@/assets/scss/style.scss";` } } }, // 配置Dep优化行为 optimizeDeps: { include: ["lodash"] }, // 为开发服务器配置自定义代理规则。 proxy: { '/api': { target: '', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } // ... }
import 'bootstrap/dist/css/bootstrap.min.css' import '../styles/globals.css' import '../styles/header.css' import '../styles/mainPage.css' import '../styles/form.css' import '../styles/programs.css' import '../styles/coursecard.css' import '../styles/carouselPage.css' import '../styles/contacts.css' import '../styles/profileMain.css' import '../styles/pricePage.css' import '../styles/profileSettings.css' import '../styles/userImage.css' import '../styles/coursePreview.css' import '../styles/editorPage.css' import '../styles/lesson.css' import '../styles/loader.css' import React, { useEffect } from 'react' import { wrapper } from '../store/store' import App from 'next/app' import NextNprogress from 'nextjs-progressbar' import Head from 'next/head' import { useDispatch } from 'react-redux' // import { getCookie } from '../components/utils/cookieFunctions' import { authUser } from '../store/auth/auth.thunks' import { appWithTranslation } from 'next-i18next' function MyComponent({ children }) { const dispatch = useDispatch() useEffect(() => { // if (getCookie('authToken')) { dispatch(authUser()) // } }, [dispatch]) return <>{children}</> } class MyApp extends App { static async getServer({ Component, context }) { const pageProps = Component.getInitialProps ? await Component.getInitialProps(context) : {} return { pageProps } } render() { const { Component, pageProps } = this.props return ( <MyComponent> <Head> <meta charSet="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="theme-color" content="#000000"/> <title>Platform LEM</title> </Head> <NextNprogress color="#29D" startPosition={0.3} stopDelayMs={200} height="3" /> <Component {...pageProps} /> </MyComponent> ) } } export default wrapper.withRedux(appWithTranslation(MyApp))
import React from "react"; import { Link } from "react-router-dom"; import { createUseStyles } from "react-jss"; import { ArrowLeft, ArrowRight } from "@material-ui/icons"; import MdParser from "../../utils/MdParser"; const useStyles = createUseStyles({ container: { maxWidth: "400px", }, toggleIcon: { width: "100px", height: "100px", cursor: "pointer", }, contentCard: { minWidth: "250px", backgroundColor: "#FFF", borderRadius: "10px", padding: "15px", margin: "10px 0", boxShadow: "0 3px 14px rgba(0,0,0,0.4)", }, navCard: { opacity: "0.8", }, arrowContainer: { display: "flex", alignItems: "center", fontSize: "12px", "& button": { width: "25px", height: "25px", padding: "0", borderRadius: "5px", cursor: "pointer", "&:disabled": { backgroundColor: "#DDD", color: "#333", cursor: "default", }, }, }, }); const Guide = (props) => { const classes = useStyles(); const { text, navIndex, maxIndex, currentLessonID } = props; return ( <div className={classes.container}> {!!text && ( <div className={classes.contentCard}> <MdParser>{text}</MdParser> </div> )} <div className={`${classes.contentCard} ${classes.navCard}`}> <div className={classes.arrowContainer}> <p style={{ margin: "7px", color: "#333" }}> Progress: {navIndex}/{maxIndex} </p> <div style={{ flexGrow: 2 }}></div> <Link to={`/lesson/${currentLessonID}/index/${navIndex - 1}`} onClick={(e) => (navIndex <= 1 ? e.preventDefault() : () => null)} // prevents navigating out of bounds > <ArrowLeft /> </Link> <Link to={`/lesson/${currentLessonID}/index/${navIndex + 1}`} onClick={(e) => navIndex >= maxIndex ? e.preventDefault() : () => null } // prevents navigating out of bounds > <ArrowRight /> </Link> </div> </div> </div> ); }; export default Guide;
const express = require('express'); const mongoose = require('mongoose'); const shop = require('./routes/shop'); const admin = require('./routes/admin'); const auth = require("./routes/auth"); const user = require('./routes/user'); const Sadmin = require('./routes/sAdmin'); const multer = require('multer'); const app = express(); mongoose.connect('mongodb://localhost/shop1') .then(() => console.log('Database is Connected...')) .catch(() => console.log("Database is not Conncted")); app.use(express.json()); const fileStorage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'images'); }, filename: (req, file, cb) => { cb(null, new Date().valueOf() + '-' + file.originalname); } }); const fileFilter = (req, file, cb) => { if ( file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg' ) { cb(null, true); } else { cb(null, false); } }; app.use( multer({ storage: fileStorage, fileFilter: fileFilter }).single('image') ); app.use('/shopforu/shop', shop); app.use('/shopforu/admin', admin); app.use('/shopforu/user', user); app.use('/shopforu/auth', auth); app.use('/shopforu/sadmin',Sadmin); const port = process.env.PORT || 4000; app.listen(port, () => console.log(`Listening Port ${port}...`))
$(".top-nav>ul>li").on('mouseenter',function(){ $(this).css( "background-color","#F10180" ) $(this) }) $(".top-nav>ul>li").on('mouseleave',function(){ $(this).css( "background-color","#262626" ) }) $(".top-nav>ul>li:nth-child(2)").on('mouseleave',function(){ $(this).css( "background-color","#F10180" ) }) $(".bottom-nav>a>i").on('mouseleave',function(){ $(this).css( "background-color","#262626" ) }) $(".bottom-nav>a>i").on('mouseenter',function(){ $(this).css( "background-color","#F10180" ) }) $(".bottom-nav>a:nth-child(2)").click(function(){ console.log($(".bottom-nav>a:nth-child(2)")); $("html,body").animate({ scrollTop:0 }) return; }) $('.top-nav>ul>li:nth-child(2)').click(function(){ changelogin(); location.href='./cart.html' })
class InfiniteTweets { constructor() { } } //class module.exports = InfiniteTweets;
var express = require('express'); var router = express.Router(); const ItemController = require('../controllers/ItemController'); const apiConfig =require('../config/apiConfig'); router.get('/', function(req, res, next) { res.send('respond with a resource'); }); /*router.use(function(req,res,next){ return apiConfig.tokenAuthenticate(req,res,next); });*/ router.post('/get_items', ItemController.get_items); router.post('/get_my_items',function(req,res, next) { apiConfig.tokenAuthenticate(req, res, next); }, ItemController.get_my_items); router.post('/get_items_count',function(req,res, next) { apiConfig.tokenAuthenticate(req, res, next); }, ItemController.get_items_count); router.post('/add_new_item',function(req,res, next) { apiConfig.tokenAuthenticate(req, res, next); }, ItemController.add_new_item); router.post('/add_item_images', function(req,res, next) { apiConfig.tokenAuthenticate(req, res, next); },ItemController.add_item_images); router.put('/update_item/:id',function(req,res, next) { apiConfig.tokenAuthenticate(req, res, next); }, function(req,res,next){ ItemController.update_item(req.params.id,req,res); }); router.delete('/del_item/:id',function(req,res, next) { apiConfig.tokenAuthenticate(req, res, next); }, function(req ,res, next){ var id = req.params.id; ItemController.del_item(id, req ,res); }); router.post('/get_item/:id', function(req ,res, next){ var id = req.params.id; ItemController.get_item(id, req ,res); }); module.exports = router;
import styled from 'styled-components' const CartCont = styled.div` width:100%; height:100%; overflow:hidden; ` const CartWrap = styled.div` width:100%; display:flex; flex-direction:column; ` const Ctitle =styled.div` width:100%; display:flex; justify-content:center; align-items:center; position:relative; height:.44rem; background:#fff; font-size:.18rem i{ position:absolute; display:flex; justify-content:center; align-items:center; left:0; top:0; width:.44rem; height:.44rem; /* background:#cc3; */ } span{ position:absolute; right:0; top:0; width:.44rem; height:.44rem; /* background:#c33; */ display:flex; justify-content:center; align-items:center; font-size:.12rem; color:#999; } ` const Ctips = styled.div` width:100%; height:.3rem; display: flex; padding: .01rem .1rem 0; justify-content:space-between; background-color: #f9c0cb; p{ color:#fff; font-size:.15rem; font-weight:500; line-height:.3rem; span{ color:#fff; font-size:.15rem; font-weight:500; b{ color:#fff; font-size:.15rem; font-weight:500; } } } div{ color:#ee2e52; font-size:.12rem; font-weight:500; line-height:.3rem; display:flex; i{ display:flex; justify-content:center; align-items:center; margin-left:.03rem; } } ` const ListWrap = styled.div` height:100%; width:100%; overflow:scroll; ` const List = styled.ul` height:max-content; width:100%; ` const ListItem = styled.li` height:.98rem; width:100%; margin-bottom:.03rem; display:flex; align-items:center; background:#fff; span{ height:100%; width:.30rem; display:flex; justify-content:center; align-items:center; img{ width:.17rem; height:.17rem; border-radius:.2rem; } } div{ width:100%; display:flex; padding:.07rem 0 .08rem; /* background:#c33; */ align-items:center; height:100%; .Img{ width: .7031rem!important; height:.7031rem ; padding:0; border:.01rem solid #eee; img{ width:100; height:100%; } } ul{ width:100%; margin-left:.1rem; padding-top:.08rem; height:100%; li{ width:100%; color:#000; font-size:.14rem; display:flex; justify-content:space-between; padding-right:.05rem; span{ color:#999; font-size:.12rem; } } li{ p{ color:#ee2e52; font-size:.14rem; } } li:nth-child(3){ height:.28rem; div{ height:100%; color:#000; font-size:.14rem; border:.01rem solid #eee; display:flex; width:.98rem; line-height:.28rem; b:nth-child(1){ width:.4rem; border-right:.01rem solid #eee; text-align:center; } input{ border:none; width:.4rem; height:100%; text-align:center; } b:nth-child(3){ width:.4rem; text-align:center; border-left:.01rem solid #eee; } } } } } ` const BottomWrap = styled.div` width:100%; height:.45rem; display:flex; background:#fff; position:fixed; bottom: .5rem; .check{ line-height:.45rem; span{ margin:0 .07rem 0 .08rem; } } ` const BottomToBuy =styled.div` flex:1; /* background:#c33; */ display:flex; justify-content:flex-end; ` const BottomDetail = styled.ul` flex:1; /* background:#800; */ padding:.03rem 0 ; li{ color:#999; font-size:.12rem; text-align:end; } li:nth-child(1){ color:#262626; span{ color:#ee2e52; padding-right:.04rem; } } li:nth-child(2){ color:#999; span{ color:#999; padding:0 .04rem; } } ` const BottomBuy = styled.b` width:1.01rem; height:100%; color:#fff; background:#77bc1f; font-size:.17rem; font-weight:normal; display:flex; /* flex-direction:column; align-items:center; */ justify-content:center; padding-top:.04rem; position:relative; span{ font-size:.14rem; position:absolute; top:.24rem; } ` const BottomToDel =styled.div` flex:1; /* background:#933; */ display:flex; justify-content:flex-end; padding:.08rem .1rem .08rem 0; display:none; span{ padding:.04rem .25rem; border:.01rem solid #ee2e52; color:#ee2e52; font-size:.14rem; border-radius:.02rem; } ` export { CartCont, CartWrap, Ctitle, Ctips, ListWrap, List, ListItem, BottomWrap, BottomToBuy, BottomBuy, BottomToDel, BottomDetail }
const {User} = require('../models/User'); module.exports = { oneUser: (req, res) => { User.findOne({_id: req.params.id}) .then( User => res.json(User)) .catch( err => res.status(400).json(err)) }, allUsers: (req, res) => { User.find({}) .then( Users => res.json(Users)) .catch( err => res.status(400).json(err)) }, createUser: (req, res) => { User.create(req.body) .then( user => res.json(user)) .catch( err => res.status(400).json(err)) }, updateUser: (req, res) => { User.findByIdAndUpdate({_id: req.params.id}, req.body, {new: true, runValidators: true}) .then( updatedUser => res.json(updatedUser)) .catch( err => res.status(400).json(err)) }, deleteUser: (req, res) => { User.findByIdAndDelete({ _id: req.params.id}) .then(delConfirm => res.json(delConfirm)) .catch( err => res.status(400).json(err)) } }
import { nanoid } from "nanoid"; import prisma from "../prisma/client.js"; import s3 from "../config/s3.js"; export const updateProfile = async (req, res) => { try { const { userId } = req.params; const { id, fullname, username, email, profile_photo, about, contact_telegram, contact_messenger, contact_whatsapp, } = await prisma.user.update({ where: { id: parseInt(userId) }, data: { ...req.body }, }); const data = { id, fullname, email, username, profile_photo, about, contact_telegram, contact_messenger, contact_whatsapp, }; res.status(200).json({ success: true, message: "Your information has been updated!", data }); } catch (error) { res.status(400).json({ success: false, message: error.message }); } }; export const uploadProfilePhoto = async (req, res) => { try { const { userId } = req.params; const { photo } = req.body; // Upload profile photo to S3 const fileName = nanoid(); const data = Buffer.from(photo.replace(/^data:image\/\w+;base64,/, ""), "base64"); const params = { Bucket: process.env.S3_BUCKET_NAME, Body: data, Key: "profile-photos/" + fileName, ACL: "public-read", ContentEncoding: "base64", ContentType: "image/jpeg", }; await s3.upload(params).promise(); // Store the profile photo file name to the database await prisma.user.update({ where: { id: parseInt(userId), }, data: { profile_photo: fileName, }, }); res.status(200).json({ success: true, data: { message: "Your new profile photo has been set!", photo_key: fileName } }); } catch (error) { res.status(400).json({ success: false, message: error.message }); } }; export const getMyProfile = async (req, res) => { try { const { id } = req.user; const user = await prisma.user.findUnique({ where: { id: id, }, select: { id: true, fullname: true, username: true, email: true, profile_photo: true, about: true, contact_telegram: true, contact_messenger: true, contact_whatsapp: true, }, }); if (!user) return res.status(404).json({ success: false, message: "User with the given ID does not exist!" }); res.status(200).json({ success: true, data: user }); } catch (error) { res.status(400).json({ success: false, message: error.message }); } }; export const getProfilePosts = async (req, res) => { try { const { userId } = req.params; const { id } = req.user; const posts = await prisma.post.findMany({ where: { user_id: parseInt(userId), }, select: { id: true, description: true, is_public: true, latitude: true, longitude: true, views: true, created_at: true, user: { select: { fullname: true, profile_photo: true, }, }, _count: { select: { comments: true, likes: true, }, }, comments: { select: { id: true, text: true, created_at: true, user: { select: { id: true, fullname: true, }, }, }, }, likes: { select: { user_id: true, }, }, photos: { select: { photo_key: true, }, }, }, orderBy: { created_at: "desc", }, }); res.status(200).json({ success: true, data: posts.map((post) => { const postUsersLiked = post.likes.map((post) => post.user_id); delete post.likes; return { ...post, liked: postUsersLiked.includes(id), }; }), }); } catch (error) { res.status(400).json({ success: false, message: error.message }); } }; export const getProfile = async (req, res) => { try { const { userId } = req.params; const { id } = req.user; // Check if user is a connection const isConnection = await prisma.connection.findFirst({ where: { OR: [ { user1_id: { equals: parseInt(userId), }, user2_id: { equals: id, }, }, { user2_id: { equals: parseInt(userId), }, user1_id: { equals: id, }, }, ], accepted: true, }, }); // Get mutual connections const mutualConnections = await prisma.$queryRaw` SELECT u.id, u.profile_photo FROM user u WHERE u.id IN ( SELECT UserAConnections.id FROM ( SELECT user2_id id FROM connection WHERE user1_id = ${userId} UNION SELECT user1_id id FROM connection WHERE user2_id = ${userId} ) AS UserAConnections JOIN ( SELECT user2_id id FROM connection WHERE user1_id = ${id} UNION SELECT user1_id id FROM connection WHERE user2_id = ${id} ) AS UserBConnections ON UserAConnections.id = UserBConnections.id JOIN user ON user.id = UserAConnections.id ) `; // If is connection, return all user's information if (isConnection) { // Get user information const user = await prisma.user.findUnique({ where: { id: parseInt(userId), }, select: { id: true, fullname: true, username: true, profile_photo: true, about: true, contact_telegram: true, contact_messenger: true, contact_whatsapp: true, }, }); // Get user's posts const posts = await prisma.post.findMany({ where: { user_id: parseInt(userId), }, select: { id: true, description: true, is_public: true, latitude: true, longitude: true, views: true, created_at: true, user: { select: { fullname: true, profile_photo: true, }, }, _count: { select: { comments: true, likes: true, }, }, comments: { select: { id: true, text: true, created_at: true, user: { select: { id: true, fullname: true, }, }, }, }, photos: { select: { photo_key: true, }, }, }, }); return res.status(200).json({ success: true, data: { user, mutualConnections, posts, connected: true } }); } // If user is not connection, return restricted amount of information for that user const user = await prisma.user.findUnique({ where: { id: parseInt(userId), }, select: { id: true, fullname: true, username: true, profile_photo: true, about: true, }, }); const requestSent = await prisma.connection.findFirst({ where: { OR: [ { user1_id: { equals: parseInt(userId), }, user2_id: { equals: id, }, }, { user2_id: { equals: parseInt(userId), }, user1_id: { equals: id, }, }, ], }, }); res.status(200).json({ success: true, data: { user, mutualConnections, requestSent: requestSent ? true : false, connected: false } }); } catch (error) { res.status(400).json({ success: false, message: error.message }); } };
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap'; // importing components import Search from './components/search'; import Results from './components/results'; import NavBar from './components/navigation' class App extends Component { constructor(){ super(); // initialising data with an empty array to be filled after the call back from child component at following line <Search parent={this.bindParent.bind(this)}/> this.state = {data: []}; } //call this function on callback from child component bindParent(childdata) { //set the state of the data with the data that has been recieved from child component // console.log(childdata) this.setState({data : childdata}); console.log('inside bindparent function of App', childdata) } render() { var divStyle={ backgroun: '#MMMMMM' }; // console.log("from render of APPS",this.state.data); return ( <div className = "container"> <NavBar/> <Search parent={this.bindParent.bind(this)}/> <Results datatochild={this.state.data}/> </div> ); } } //<Search parent={this.bindParent.bind(this)}/> // significanse: to get the call back from the child component and setState({data}) to be called and set the state of the parent using child's data //<Results datatochild={this.state.data}/> //significanse: passing data to child component using {this.state.data} export default App;
const mongoose = require("mongoose"); const productSchema = mongoose.Schema({ name: { type: String, required: [true, "Please Enter the Product Name"], trim: true, maxLength: [100, "Procut Name is Too lengthy"], }, description: { type: String, }, shortDescription: { type: String, }, sku: { type: String, }, price: { type: Number, required: [true, "please enter the price"], }, tags: [{ type: String }], images: [ { public_id: { type: String, required: true, }, url: { type: String, required: true, }, }, ], isPremium: { type: Boolean, default: false, }, isFeatured: { type: Boolean, default: false, }, onSale: { type: Boolean, default: false, }, saleFrom: { type: Date, }, saleTo: { type: Date, }, salePrice: { type: Number, }, shot: { type: String, }, ratings: { type: Number, default: 0, }, category: { type: mongoose.Schema.ObjectId, ref: "Category", required: true, }, productInfo: [ { title: { type: String, required: [true, "Please enter the title"], }, desc: { type: String, required: [true, "please enter description"], }, }, ], stock: { type: Number, required: [true, "please enter the stock"], maxLength: [5, "stock cannot exceed 5 charactors"], }, numOfReviews: { type: Number, default: 0, }, reviews: [ { user: { type: mongoose.Schema.ObjectId, res: "User", required: true, }, name: { type: String, required: true, }, rating: { type: Number, required: true, }, comment: { type: String, required: true, }, }, ], createdBy: { type: mongoose.Schema.ObjectId, res: "User", required: true, }, createAt: { type: Date, default: Date.now, }, }); module.exports = mongoose.model("Product", productSchema);
import React, {Component} from 'react' import {withStyles} from 'material-ui/styles' import Typography from 'material-ui/Typography' const style = theme => ({ root: { padding: '1em', } }) @withStyles(style) class ColumnsHeading extends Component { render() { const {classes, children} = this.props return ( <div className = {classes.root}> <Typography component={'h1'} type={'display1'}> {children} </Typography> </div> ) } } export default ColumnsHeading
var moduleController = { connectionStart: undefined, MODULES: [], modules: [], init: function( onmousedown ){ var list = document.getElementById("list"); for( var name in this.MODULES ){ var node = document.createElement("LI"); node.innerText = name; node.dataset["index"] = name; node.onmousedown = onmousedown; list.appendChild( node ); } }, createModule: function( module ){ if(typeof module == "string" ) module = this.MODULES[module]; if(typeof module == "function" ){ var m = new module(); moduleController.modules.push( m ); return m; } return false; }, update: function(){ this.modules.forEach( (module)=>{ module.update(); }); }, draw: function(){ this.modules.forEach( (module)=>{ module.draw(); }); }, mousePressed: function( e ){ this.modules.forEach( (module)=>{ module.mousePressed( e ); }); }, mouseReleased: function( e ){ this.modules.forEach( (module)=>{ module.mouseReleased( e ); }); this.connectionStart = undefined; }, keyPressed: function( e ){ this.modules.forEach( (module)=>{ module.keyPressed( e ); }); }, keyReleased: function( e ){ this.modules.forEach( (module)=>{ module.keyReleased( e ); }); }, addModule: function( module ){ this.MODULES[ module.name ] = module; }, deleteModule: function( module ){ console.log( module ); var i = this.modules.indexOf( module ); if( i >= 0 ){ this.modules.splice( i, 1 ); } }, makeConnection: function( connector ){ if( this.connectionStart !== undefined ){ if( connector.isInput != this.connectionStart.isInput ){ var output = (connector.isInput)?this.connectionStart:connector; var input = (connector.isInput)?connector:this.connectionStart; output.connect( input ); //input.updateValue(); } } } };
(function(){ var module = angular.module("psMovies"); module.component("movieOverview",{ template: "psMovies/movie.overveiw.component.html" }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetAbsoluteRect = exports.GetViewportRect = exports.GetScrollOffset = exports.GSAPScrollBehavior = exports.ScrollBehavior = exports.ViewportCoordinateScrollAction = exports.TRANSITION_LEAVE = exports.TRANSITION_ENTER = exports.TRANSITION_NONE = exports.DIRECTION_BACKWARD = exports.DIRECTION_FORWARD = exports.DIRECTION_NONE = exports.STATE_AFTER = exports.STATE_INSIDE = exports.STATE_BEFORE = exports.STATE_UNKNOWN = exports.ScrollAction = exports.ScrollElement = exports.ScrollController = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = require('underscore'); var _underscore2 = _interopRequireDefault(_underscore); var _rxDom = require('rx-dom'); var _rxDom2 = _interopRequireDefault(_rxDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var cssSizeValue = function cssSizeValue(attr) { return typeof attr === 'number' ? attr + 'px' : attr; }; var cssBoundingRect = function cssBoundingRect(e, origin, size) { e.setAttribute("style", "visibility:hidden;position:fixed;top:" + origin.y + ";left:" + origin.x + ";width:" + size.width + ";height:" + size.height); document.firstElementChild.appendChild(e); var rect = e.getBoundingClientRect(); e.remove(); return rect; }; var ScrollController = exports.ScrollController = function () { function ScrollController(container, options) { var _this = this; _classCallCheck(this, ScrollController); this._container = container; this._options = options; this._elements = []; this.updateSizeProperties(this._container); this._update$ = new _rxDom2.default.BehaviorSubject({ updateAll: true, controller: this, scrollOffset: this._scrollOffset, containerSize: this._containerSize, scrollSize: this._scrollSize, scrollProgress: this._scrollProgress }); this.update$ = this._update$.observeOn(_rxDom2.default.Scheduler.requestAnimationFrame); this.resize$ = new _rxDom2.default.Subject(); this.viewport$ = new _rxDom2.default.BehaviorSubject(this._containerSize); this.resize$.distinctUntilChanged().subscribe(function (size) { _this.viewport$.onNext(_this._containerSize); }); this.update$.filter(function (v) { return v.updateAll === true; }).subscribe(function (v) { // console.log("--- NEEDS UPDATE ---", Date.now()) // This just sets the child element as dirty. // The next subscription makes sure // that all elements get updated at the same // time in a case of a full repaint (scroll) // e.needsUpdate = true _underscore2.default.each(_this._elements, function (e) { e.needsUpdate = true; }); }); // this.update$.subscribe(() => {}, () => {}, () => { // this._needsUpdate = false // }) window.addEventListener("mousewheel", function () {}); this.attachEvents(container); this._update$.subscribe(function (s) { // con sole.log(s) }); } _createClass(ScrollController, [{ key: 'updateSizeProperties', value: function updateSizeProperties(container) { this._scrollOffset = this.calculateScrollOffset(container); this._containerSize = this.calculateContainerSize(container); this._scrollSize = this.calculateScrollSize(container); this._scrollProgress = this.calculateScrollProgress(this._scrollSize, this._containerSize, this._scrollOffset); } }, { key: 'attachEvents', value: function attachEvents(container) { var _this2 = this; var c = this; this.scroll = _rxDom2.default.DOM.scroll(container).map(function (e) { //observeOn(Rx.Scheduler.requestAnimationFrame). e.offset = c.calculateScrollOffset(e.currentTarget); return e; }).filter(function (e) { var offset = e.offset; return offset.x != c._scrollOffset.x || offset.y != c._scrollOffset.y; }).map(function (e) { var offset = e.offset; c._scrollOffset = offset; return [offset, e]; }); this.resize = _rxDom2.default.DOM.resize(container).map(function (e) { e.size = c.calculateContainerSize(e.currentTarget); e.scrollSize = c.calculateScrollSize(e.currentTarget); return e; }).filter(function (e) { var size = e.size; return size.width != c._containerSize.width || size.height != c._containerSize.height; }).map(function (e) { var size = e.size; _this2.updateSizeProperties(c._container); _this2.resize$.onNext(size); return [size, e]; }); _rxDom2.default.Observable.merge(this.scroll, this.resize).subscribe(function (v) { _this2._scrollProgress = c.calculateScrollProgress(c._scrollSize, c._containerSize, c._scrollOffset); // console.log("---- Scroll / Resize ----") _this2.needsUpdate = true; }); } }, { key: 'addElement', value: function addElement(e) { this._elements.push(e); } }, { key: 'calculateContainerSize', value: function calculateContainerSize(container) { var rect = container === window ? { width: window.innerWidth, height: document.documentElement.clientHeight } : container.getBoundingClientRect(); return { width: rect.width, height: rect.height }; } }, { key: 'calculateScrollOffset', value: function calculateScrollOffset(container) { return GetScrollOffset(container); } }, { key: 'calculateScrollSize', value: function calculateScrollSize(container) { var scrollSize = null; if (container == window) { var body = document.body; var html = document.documentElement; scrollSize = { height: Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight), width: Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth) }; // console.log("Scroll Size: ", scrollSize) } else { scrollSize = { height: container.scrollHeight, width: container.scrollWidth }; } return scrollSize; } }, { key: 'calculateScrollProgress', value: function calculateScrollProgress(scrollSize, containerSize, offset) { return { x: offset.x != 0 ? offset.x / (scrollSize.width - containerSize.width) : 0, y: offset.y != 0 ? offset.y / (scrollSize.height - containerSize.height) : 0 }; } }, { key: 'container', set: function set(container) { this._container = container; this.attachEvents(this._container); }, get: function get() { return this._container; } }, { key: 'containerSize', get: function get() { return this._containerSize; } }, { key: 'scrollSize', get: function get() { return this._scrollSize; } }, { key: 'scrollProgress', get: function get() { return this._scrollProgress; } }, { key: 'scrollOffset', get: function get() { return this._scrollOffset; } }, { key: 'needsUpdate', set: function set(needsUpdate) { this._needsUpdate = needsUpdate; if (needsUpdate) { // console.log("--- Set Needs Update ----") this._update$.onNext({ updateAll: true, controller: this, scrollOffset: this._scrollOffset, containerSize: this._containerSize, scrollSize: this._scrollSize, scrollProgress: this._scrollProgress }); this.needsUpdate = false; } // else { // this._update$.onNext(false) // } } }, { key: 'needsResize', set: function set(needsResize) { if (needsResize) { this.updateSizeProperties(this._container); this.resize$.onNext(this._containerSize); } } }]); return ScrollController; }(); var ScrollElement = exports.ScrollElement = function () { function ScrollElement(element, options) { var _this3 = this; _classCallCheck(this, ScrollElement); this._nonFixedPosition = null; this._element = element; this._elementOffset = { x: 0, y: 0 }; this._triggers = []; this._anchorPoint = { x: 0, y: 0 }; this._needsUpdate = false; this.action$ = new _rxDom2.default.BehaviorSubject(null); this.update$ = new _rxDom2.default.BehaviorSubject(false); this.viewportOffset$ = new _rxDom2.default.BehaviorSubject(this.viewportOffsetWithAnchor); this._scrollBehavior = null; this._scrollAttached = false; this._scrollAttachmentInitialValue = 0; this.update$.filter(function (needsUpdate) { return needsUpdate; }).subscribe(function (v) { _this3.update(); _this3.needsUpdate = false; }); } _createClass(ScrollElement, [{ key: 'update', value: function update() { // console.log(Date.now()) this.viewportOffset$.onNext(this.viewportOffsetWithAnchor); this.needsUpdate = false; } }, { key: 'anchorPoint', set: function set(point) { this._anchorPoint = point; } }, { key: 'element', set: function set(element) { this._element = element; } }, { key: 'needsUpdate', get: function get() { return this._needsUpdate; }, set: function set(needsUpdate) { this._needsUpdate = needsUpdate; this.update$.onNext(needsUpdate); } }, { key: 'viewportOffsetWithAnchor', get: function get() { var rect = GetViewportRect(this._element); var anchor = this._anchorPoint; // Incorporate the anchor point. return { x: rect.left + anchor.x * rect.width, y: rect.top + anchor.y * rect.height }; } }, { key: 'absoluteRect', get: function get() { return GetAbsoluteRect(this._element); } }, { key: 'viewportRect', get: function get() { return GetViewportRect(this._element); } }, { key: 'scrollBehavior', set: function set(scrollBehavior) { this._scrollBehavior = scrollBehavior; } }, { key: 'scrollAttached', set: function set(scrollAttached) { this._scrollAttached = scrollAttached; } }]); return ScrollElement; }(); var ScrollAction = exports.ScrollAction = function () { function ScrollAction(controller, options) { _classCallCheck(this, ScrollAction); this.viewport$ = new _rxDom2.default.BehaviorSubject(controller.containerSize); this._containerSize$ = new _rxDom2.default.BehaviorSubject(controller.containerSize); this.controller = controller; this._options = options; this._elements = []; } _createClass(ScrollAction, [{ key: 'addElement', value: function addElement(e) { this._elements.push(e); this._controller.addElement(e); } }, { key: 'controller', set: function set(controller) { this._controller = controller; // this._containerSize$.onNext(controller.containerSize) controller.resize$.subscribe(this._containerSize$); } }]); return ScrollAction; }(); var STATE_UNKNOWN = exports.STATE_UNKNOWN = "UNKNOWN"; var STATE_BEFORE = exports.STATE_BEFORE = "BEFORE"; var STATE_INSIDE = exports.STATE_INSIDE = "INSIDE"; var STATE_AFTER = exports.STATE_AFTER = "AFTER"; var DIRECTION_NONE = exports.DIRECTION_NONE = "NONE"; var DIRECTION_FORWARD = exports.DIRECTION_FORWARD = "FORWARD"; var DIRECTION_BACKWARD = exports.DIRECTION_BACKWARD = "BACKWARD"; var TRANSITION_NONE = exports.TRANSITION_NONE = "NONE"; var TRANSITION_ENTER = exports.TRANSITION_ENTER = "ENTER"; var TRANSITION_LEAVE = exports.TRANSITION_LEAVE = "LEAVE"; var ViewportCoordinateScrollAction = exports.ViewportCoordinateScrollAction = function (_ScrollAction) { _inherits(ViewportCoordinateScrollAction, _ScrollAction); function ViewportCoordinateScrollAction(controller, options) { _classCallCheck(this, ViewportCoordinateScrollAction); var _this4 = _possibleConstructorReturn(this, (ViewportCoordinateScrollAction.__proto__ || Object.getPrototypeOf(ViewportCoordinateScrollAction)).call(this, controller, options)); _this4._sizeE = document.createElement('div'); _this4.scrollOptions = options; _this4._containerSize$.subscribe(function (newSize) { // console.log("> Container Size Update: ", newSize) _this4.updateSizeProperties(_this4._sizeE, _this4._cssOrigin, _this4._cssSize, _this4._padding); _this4.viewport$.onNext(newSize); }); var nullAction = { element: null, state: { x: STATE_UNKNOWN, y: STATE_UNKNOWN }, direction: { x: DIRECTION_NONE, y: DIRECTION_NONE }, transition: { x: TRANSITION_NONE, y: TRANSITION_NONE }, progress: { x: 0, y: 0 }, paddingProgress: { x: 0, y: 0 } }; _this4.action$ = new _rxDom2.default.BehaviorSubject(nullAction); _this4.distinctElementState$ = new _rxDom2.default.BehaviorSubject(nullAction); _this4.transition$ = _this4.action$.distinctUntilChanged(function (a) { return [a.transition.x, a.transition.y, a.element]; }); _this4.progress$ = _this4.action$.distinctUntilChanged(function (a) { return [a.progress.x, a.progress.y, a.element]; }); _this4.state$ = _this4.action$.distinctUntilChanged(function (a) { return [a.state.x, a.state.y, a.element]; }); _this4.paddingProgress$ = _this4.action$.distinctUntilChanged(function (a) { return [a.paddingProgress.x, a.paddingProgress.y, a.state.x, a.state.y, a.element]; }); return _this4; } _createClass(ViewportCoordinateScrollAction, [{ key: 'updateSizeProperties', value: function updateSizeProperties(e, origin, size, padding) { var rect = cssBoundingRect(this._sizeE, origin, size); this._origin = { x: rect.left, y: rect.top }; this._size = { width: rect.width, height: rect.height }; this._padding = padding; } }, { key: 'addElement', value: function addElement(e) { var _this5 = this; this._controller.addElement(e); e.stateAction$ = e.action$.filter(function (a) { return a != null; }).distinctUntilChanged(function (a) { return [a.state]; }); e.stateAction$.subscribe(this.distinctElementState$); e.viewportOffset$.pairwise().subscribe(function (v) { var actions = _this5.calculateAction(v[0], v[1], e); for (var i = 0; i < actions.length; i++) { e.action$.onNext(actions[i]); _this5.action$.onNext(actions[i]); } }); } }, { key: 'calculateAction', value: function calculateAction(prevValue, newValue, element) { var origin = this._origin; var size = this._size; var padding = this._padding; var action = { state: { x: STATE_UNKNOWN, y: STATE_UNKNOWN }, direction: { x: DIRECTION_NONE, y: DIRECTION_NONE } }; // console.log("Origin: ", origin, "Size :", size, "New Value: ", newValue.y) action.direction.x = this.calculateDirection(prevValue.x, newValue.x); action.direction.y = this.calculateDirection(prevValue.y, newValue.y); action.state = this.calculateState(newValue); var prevState = this.calculateState(prevValue); var transitions = [this.calculateTransitions(prevState.x, action.state.x), this.calculateTransitions(prevState.y, action.state.y)]; var actions = []; if (transitions[0].length == transitions[1].length) { for (var i = 0; i < transitions[0].length; i++) { var a = { element: element, state: action.state, direction: action.direction, transition: { x: transitions[0][i], y: transitions[1][i] }, progress: this.calculateProgress(action.state, origin, size, { x: newValue.x, y: newValue.y }), paddingProgress: this.calculatePaddingProgress(action.state, origin, size, padding, { x: newValue.x, y: newValue.y }) }; actions.push(a); } } return actions; } }, { key: 'calculateState', value: function calculateState(newValue) { var origin = this._origin; var size = this._size; var state = { x: STATE_UNKNOWN, y: STATE_UNKNOWN }; if (newValue.x > origin.x + size.width) { state.x = STATE_AFTER; } else if (newValue.x < origin.x) { state.x = STATE_BEFORE; } else { state.x = STATE_INSIDE; } if (newValue.y > origin.y + size.height) { state.y = STATE_AFTER; } else if (newValue.y < origin.y) { state.y = STATE_BEFORE; } else { state.y = STATE_INSIDE; } return state; } }, { key: 'calculateTransitions', value: function calculateTransitions(prevState, newState) { if (prevState == STATE_BEFORE && newState == STATE_INSIDE) { return [TRANSITION_ENTER]; } else if (prevState == STATE_BEFORE && newState == STATE_AFTER) { return [TRANSITION_LEAVE]; //TRANSITION_ENTER, } else if (prevState == STATE_AFTER && newState == STATE_INSIDE) { return [TRANSITION_ENTER]; } else if (prevState == STATE_AFTER && newState == STATE_BEFORE) { return [TRANSITION_LEAVE]; //TRANSITION_ENTER, } else if (prevState == STATE_INSIDE && (newState == STATE_AFTER || newState == STATE_BEFORE)) { return [TRANSITION_LEAVE]; } else { return [TRANSITION_NONE]; } } }, { key: 'calculateDirection', value: function calculateDirection(prevValue, newValue) { if (prevValue < newValue) { return DIRECTION_FORWARD; } else if (prevValue > newValue) { return DIRECTION_BACKWARD; } else { return DIRECTION_NONE; } } }, { key: 'calculateProgress', value: function calculateProgress(state, origin, size, value) { var p = { x: 0, y: 0 }; var s = { x: size.width, y: size.height }; for (var key in p) { if (state[key] == STATE_AFTER) { p[key] = 1.0; } else if (state[key] == STATE_BEFORE) { p[key] = 0; } else if (state[key] == STATE_UNKNOWN) { p[key] = 1; } else { p[key] = (value[key] - origin[key]) / s[key]; } } return p; } }, { key: 'calculatePaddingProgress', value: function calculatePaddingProgress(state, origin, size, padding, value) { var p = { x: 0, y: 0 }; var s = { x: size.width, y: size.height }; var pad = { x: [padding.left, padding.right], y: [padding.top, padding.bottom] }; for (var key in p) { if (state[key] == STATE_INSIDE) { p[key] = 0; } else if (state[key] == STATE_BEFORE) { var d = origin[key] - value[key]; if (d > pad[key][0]) { p[key] = 1; } else { p[key] = d / pad[key][0]; } } else if (state[key] == STATE_AFTER) { var _d = value[key] - origin[key]; if (_d > pad[key][0]) { p[key] = 1; } else { p[key] = _d / pad[key][0]; } } else { p[key] = 0; } } return p; } }, { key: 'scrollOptions', set: function set(props) { this._options = _underscore2.default.defaults(props || {}, { origin: { x: 0, y: 0 }, size: { width: '100vw', height: '100vh' }, padding: { top: 0, left: 0, bottom: 0, right: 0 } }); var origin = this._options.origin; this._cssOrigin = { x: cssSizeValue(origin.x), y: cssSizeValue(origin.y) }; var size = this._options.size; this._cssSize = { width: cssSizeValue(size.width), height: cssSizeValue(size.height) }; this.updateSizeProperties(this._sizeE, this._cssOrigin, this._cssSize, this._options.padding); } }]); return ViewportCoordinateScrollAction; }(ScrollAction); var ScrollBehavior = exports.ScrollBehavior = function () { function ScrollBehavior(controller, options) { var _this6 = this; _classCallCheck(this, ScrollBehavior); this._containerSize$ = new _rxDom2.default.BehaviorSubject(controller._containerSize); this.controller = controller; this.viewport$ = new _rxDom2.default.BehaviorSubject(this._containerSize); this._options = _underscore2.default.defaults(options || {}, { velocity: 1, applyVertical: true, applyHorizontal: false, defaultScrollStartOffset: { x: 0, y: 0 }, defaultScrollDistance: this.defaultScrollDistance, scrollStartOffset: null, scrollDistance: null }); this._sizeE = document.createElement('div'); this.scrollOptions = { scrollStartOffset: this._options.scrollStartOffset, scrollDistance: this._options.scrollDistance }; this._containerSize$.subscribe(function (newSize) { _this6.updateContainerProperties(controller); _this6._options.defaultScrollDistance = _this6.defaultScrollDistance; _this6.updateScrollProperties(_this6._options); _this6.viewport$.onNext(newSize); }); this.progress$ = new _rxDom2.default.BehaviorSubject(this.progress); } _createClass(ScrollBehavior, [{ key: 'updateScrollProperties', value: function updateScrollProperties(options) { var startOffset = options.scrollStartOffset || options.defaultScrollStartOffset; startOffset.x = cssSizeValue(startOffset.x); startOffset.y = cssSizeValue(startOffset.y); this._cssStartOffset = startOffset; var distance = options.scrollDistance || options.defaultScrollDistance; distance.width = cssSizeValue(distance.width); distance.height = cssSizeValue(distance.height); this._cssDistance = distance; var rect = cssBoundingRect(this._sizeE, startOffset, distance); this._scrollStartOffset = { x: rect.left, y: rect.top }; this._scrollDistance = { width: rect.width, height: rect.height }; } }, { key: 'updateContainerProperties', value: function updateContainerProperties(controller) { this._fullScrollSize = controller.scrollSize; this._fullScrollProgress = controller.scrollProgress; this._containerSize = controller.containerSize; } }, { key: 'calculateProgress', value: function calculateProgress(current, start, length) { if (current <= start) { return 0; } else if (current >= start + length) { return 1; } else { return (current - start) / length; } } }, { key: 'scrollOptions', set: function set(props) { this._options.scrollDistance = props.scrollDistance; this._options.scrollStartOffset = props.scrollStartOffset; this.updateScrollProperties(this._options); } }, { key: 'progress', get: function get() { var offset = this._controller.scrollOffset; var progress = { x: this.calculateProgress(offset.x, this._scrollStartOffset.x, this._scrollDistance.width), y: this.calculateProgress(offset.y, this._scrollStartOffset.y, this._scrollDistance.height) }; return progress; } }, { key: 'defaultScrollDistance', get: function get() { return { width: this._fullScrollSize.width - this._containerSize.width, height: this._fullScrollSize.height - this._containerSize.height }; } }, { key: 'controller', set: function set(controller) { var _this7 = this; if (this._controllerSubscription != null) { this._controller.update$.unusbscribe(this._controllerSubscription); } this._controller = controller; this.updateContainerProperties(controller); controller.resize$.subscribe(this._containerSize$); this._controllerSubscription = controller.update$.subscribe(function (v) { // console.log(Date.now()) _this7._fullScrollSize = v.scrollSize; _this7._fullScrollProgress = v.scrollProgress; _this7._containerSize = v.containerSize; _this7.progress$.onNext(_this7.progress); }); // console.log(controller.update$) } }]); return ScrollBehavior; }(); var GSAPScrollBehavior = exports.GSAPScrollBehavior = function (_ScrollBehavior) { _inherits(GSAPScrollBehavior, _ScrollBehavior); function GSAPScrollBehavior(controller, options) { _classCallCheck(this, GSAPScrollBehavior); var _this8 = _possibleConstructorReturn(this, (GSAPScrollBehavior.__proto__ || Object.getPrototypeOf(GSAPScrollBehavior)).call(this, controller, options)); _this8._options = _underscore2.default.defaults(options || {}, { tween: { x: null, y: null }, reverseTween: { x: null, y: null }, autoProgress: true }); _this8.tween = _this8._options.tween; _this8.reverseTween = _this8._options.tween; if (_this8._options.autoProgress) { _this8.progress$.distinctUntilChanged().pairwise().subscribe(function (v) { var p = v[1]; var prev = v[0]; _this8.applyProgress(p, prev); }); } return _this8; } _createClass(GSAPScrollBehavior, [{ key: 'applyProgress', value: function applyProgress(p, prev) { var direction = { x: DIRECTION_FORWARD, y: DIRECTION_FORWARD }; if (prev.x > p.x) { direction.x = DIRECTION_BACKWARD; } if (prev.y > p.y) { direction.y = DIRECTION_BACKWARD; } if (this._tween.x != null && (direction.x == DIRECTION_FORWARD || this._reverseTween.x == null)) { this._tween.x.progress(p.x); this._controller.needsUpdate = true; } else if (direction.x == DIRECTION_BACKWARD && this._reverseTween.x != null) { this._reverseTween.x.progress(1 - p.x); this._controller.needsUpdate = true; } if (this._tween.y != null && (direction.y == DIRECTION_FORWARD || this._reverseTween.y == null)) { this._tween.y.progress(p.y); // console.log("Progress", p.y) this._controller.needsUpdate = true; } else if (direction.y == DIRECTION_BACKWARD && this._reverseTween.y != null) { this._reverseTween.y.progress(1 - p.y); this._controller.needsUpdate = true; } } }, { key: 'tween', set: function set(newTween) { this._tween = newTween; this.progress$.onNext(0); this.progress$.onNext(this.progress); } }, { key: 'reverseTween', set: function set(newTween) { this._reverseTween = newTween; this.progress$.onNext(0); this.progress$.onNext(this.progress); } }]); return GSAPScrollBehavior; }(ScrollBehavior); var GetScrollOffset = exports.GetScrollOffset = function GetScrollOffset(el) { var scrollTop = el && typeof el.scrollTop === 'number' ? el.scrollTop : window.pageYOffset || 0; var scrollLeft = el && typeof el.scrollLeft === 'number' ? el.scrollLeft : window.pageXOffset || 0; return { x: scrollLeft, y: scrollTop }; }; var GetViewportRect = exports.GetViewportRect = function GetViewportRect(el, container) { var rect = el.getBoundingClientRect(); return rect; }; var GetAbsoluteRect = exports.GetAbsoluteRect = function GetAbsoluteRect(el, container) { var rect = el.getBoundingClientRect(); var absRect = { bottom: rect.bottom, height: rect.height, left: rect.left, right: rect.right, top: rect.top, width: rect.width }; var rel = container === undefined ? document : container; var scrollTop = rel && typeof rel.scrollTop === 'number' ? rel.scrollTop : window.pageYOffset || 0; var scrollLeft = rel && typeof rel.scrollLeft === 'number' ? rel.scrollLeft : window.pageXOffset || 0; absRect.top += scrollTop; absRect.left += scrollLeft; absRect.bottom += scrollTop; absRect.right += scrollLeft; return absRect; };
var L = require('leaflet'); require('leaflet-providers'); var config = require('../config.json'); var grayscale = L.tileLayer.provider('CartoDB.Positron'); var map = L.map('map', { center: config.map_center, // Austin! zoom: 12, scrollWheelZoom: false, layers: [grayscale], }); var baseMaps = { 'Grayscale': grayscale, }; function getAgeUnder19Score(ageRatioUnder19) { if (ageRatioUnder19 < 0.10) { return 0; } if (ageRatioUnder19 < 0.15) { return 1; } if (ageRatioUnder19 < 0.20) { return 2; } if (ageRatioUnder19 < 0.25) { return 3; } if (ageRatioUnder19 < 0.30) { return 4; } if (ageRatioUnder19 < 0.35) { return 5; } if (ageRatioUnder19 < 0.40) { return 6; } return 7; } function getMultihousingRatioScore(multihousingRatio) { if (multihousingRatio > 0.80) { return 0; } if (multihousingRatio > 0.70) { return 1; } if (multihousingRatio > 0.60) { return 2; } if (multihousingRatio > 0.50) { return 3; } if (multihousingRatio > 0.40) { return 4; } if (multihousingRatio > 0.30) { return 5; } if (multihousingRatio > 0.20) { return 6; } return 7; } function getHealthInsuranceScore(healthInsuranceCoverage) { if (healthInsuranceCoverage > 40) { return 0; } if (healthInsuranceCoverage > 35) { return 1; } if (healthInsuranceCoverage > 30) { return 2; } if (healthInsuranceCoverage > 25) { return 3; } if (healthInsuranceCoverage > 20) { return 4; } if (healthInsuranceCoverage > 15) { return 5; } if (healthInsuranceCoverage > 10) { return 6; } return 7; } window.scores = []; // higher value = more need for (var i = 0; i <= censusTract.length - 1; i++) { var current = censusTract[i].demographics; var needScore = 0; needScore += getAgeUnder19Score(current.ageRatioUnder19); needScore += getHealthInsuranceScore(current.healthInsuranceCoverage); var multihousingRatio = (parseFloat(current.unitsSingleAttached) + parseFloat(current.unitsSingleDetached) + parseFloat(current.unitsTwo)) / parseFloat(current.unitsTotal); needScore += getMultihousingRatioScore(multihousingRatio); scores.push(needScore); } function onEachCensusFeature(feature, layer) { var score = feature.demographics.needScore; var children = feature.demographics.ageRatioUnder19; var health = feature.demographics.healthInsuranceCoverage; var apartment = feature.demographics.multihousingRatio; popupContent = '<p><span class="park-title">Need Score: ' + score + '</span> \ <br>Pop Under 19: ' + children + ' \ <br>Health Insurance Coverage : ' + health + ' \ <br>Ratio Single Unit Housing : ' + apartment + '</p>'; if (feature.properties) { layer.bindPopup(popupContent); } } function getColor(d) { if (d < 13) { return '#f7fcfd'; } if (d < 14) { return '#e0ecf4'; } if (d < 15) { return '#bfd3e6'; } if (d < 16) { return '#9ebcda'; } if (d < 17) { return '#8c96c6'; } if (d < 18) { return '#8c6bb1'; } if (d < 19) { return '#88419d'; } return '#6e016b'; } // Adding Census Tract Shapefiles to Map var censusLayer = L.geoJson(censusTract, { style: function style(feature) { return { // fillColor: getAgeColor(feature.demographics.ageRatioUnder19), fillColor: getColor(feature.demographics.needScore), weight: 1, opacity: 1, color: 'white', dashArray: '3', fillOpacity: 0.7, }; }, onEachFeature: onEachCensusFeature, }).addTo(map); censusLayer.bringToBack(); function onEachParkFeature(feature, layer) { var parkName = feature.properties.PARK_NAME; var parkAcres = feature.properties.PARK_ACRES.toFixed(2); var parkType = feature.properties.PARK_TYPE; var popupContent = '<p><span class="park-title">' + parkName + '</span> \ <br>' + parkAcres + ' Acres \ <br>Park Type: ' + parkType + '</p>'; if (feature.properties) { layer.bindPopup(popupContent); } } // adding parks shapefiles to Map var parkLayer = L.geoJson(parks, { style: function style() { return { fillColor: '#56DD54', weight: 1, opacity: 0.7, color: '#44A048', fillOpacity: 0.7, }; }, onEachFeature: onEachParkFeature, }).addTo(map); var overlayMaps = { 'Parks': parkLayer, }; L.control.layers(baseMaps, overlayMaps, { collapsed: true, autoZIndex: true, }).addTo(map);
import './Checkbox.css'; import React from 'react'; export default (props) => { return ( <div className="checkbox-div"> <input type="checkbox" id="vegetaian" checked={props.vegebox} onChange={props.change} /> <label className="vegetarian"> dla wegetarian </label> </div> ) };
import CsvFileService from '@/services/CsvFileService' export const namespaced = true export const state = { files: [] } export const mutations = { SET_CSV_FILES(state, files) { state.files = files }, ADD_CSV_FILE(state, file) { state.files.push(file) } } export const actions = { fetchFileNames({ commit, dispatch }) { return CsvFileService.fetchFileNames() .then(result => { commit('SET_CSV_FILES', result.data.files) return result.data.files }) .catch(error => { if (error.response.status === 401) { dispatch( 'authentication/logout', { message: 'Unauthorized access, you are logged out', type: 'error' }, { root: true } ) } else { dispatch('notifications/addNotification', {}, { root: true }) } }) }, uploadFile({ commit, dispatch }, { formData, fileName }) { console.log(formData) CsvFileService.uploadFile(formData) .then(result => { commit('ADD_CSV_FILE', fileName) dispatch('notifications/addNotification', result.data, { root: true }) }) .catch(() => { dispatch('notifications/addNotification', {}, { root: true }) }) } } export const getters = { checkFiles(state) { return state.files.length >= 1 } }
var loggedInUser = ""; $(document).ready(function() { $("#go").click(function() { var user = $("#user").val(); var pass = $("#pass").val(); login(user,pass); }); $("#register").click(function() { var reguser = $("#reguser").val(); var regpass = $("#regpass").val(); if(reguser.length == 0) { alert("Pls enter username");// FIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIX } else if(regpass.length == 0) { alert("Plz enter a password");// FIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIX } else if(reguser.length > 19) { alert("Too long username, Please enter a username between 3-19 character long"); // FIIIIIIIIIIIIIIIIIIIIIIIIIIX } else { reg(reguser,regpass) $("#Regdrop").modal("hide") } }); $(".change").click(function() { if(loggedInUser!= "") { if(this.id == "profile") { template(this.id); prof(loggedInUser); } else if(this.id == "friends") { template(this.id); friends(); } else if(this.id == "logout") { template(this.id); logout(); } else if(this.id == "home") { } } else { alert("your not logged in dipshit"); } }); $("#home").click(function() { if(loggedInUser == "") { location.reload(); } }); $("#sendpost").live('click', function() { $.ajax({ }); }); $(".friendlisted").live('click', function() { }); }); //End document ready function template(thisid) { return $.ajax({ url: "http://localhost:8888/content?template="+thisid, success : function(data,err) { $("#content").html(data); } }); } function prof(userprof) { return $.ajax({ url: "http://localhost:8888/profile?user="+userprof, dataType : "json", success : showProfile }); } function friends() { return $.ajax({ url: "http://localhost:8888/friends?user="+loggedInUser, dataType : "json", success : showFriends }); } function log(user,pass) { return $.ajax({ url: "http://localhost:8888/login?user="+user+"&pw="+pass, success : function(data,err) { loggedInUser = user; } }); } function login(user,pass) { $.when(log(user, pass)).done(function(){ $.when(template("profile")).done(function() { prof(loggedInUser); }); }); } function logout() { return $.ajax({ url: "http://localhost:8888/logoff?user="+loggedInUser, success : function(data,err) { loggedInUser = ""; } }); } function showProfile(data,err) { $.map(data["posts"], function(post){ var member = $(document.createElement("div")) .attr("class", "posts") .append("<pre>"+post["post"]+"</pre>") .append("<p class=\"postname\">"+"- "+post["user"]+"</p>") $("#oldposts").prepend(member); }); $("#username").html(data["username"]); } function showFriends(data,err) { for(var i = 0; i < data.length; i++) { var flist = $(document.createElement("div")) .attr("class", "friendlisted") .append("<pre>" + data[i] + "</pre>") $("#friendlist").append(flist); } } function reg(user,pass) { $.ajax({ url: "http://localhost:8888/register?user="+user+"&pw="+pass, success : function(data,err) { alert(data);// FIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIX } }); } function flag(id) { $.ajax({ url: "http://localhost:8888/flag?ID="+id, success : function() { $("#flag"+id).html("Read"); } }); } function clear() { $("#divMessages").html(""); } function save(post) { $.ajax({ url: "http://localhost:8888/save?POST="+post, success : function(err,data) { clear(); update(); } }); }
import { createStore } from "redux"; const setAddressee = (state = 'John Bow', action) => { switch (action.type) { case "SET_ADDRESSEE": { return action.payload.addressee; } default: { return state; } } }; export default createStore(setAddressee, 'Carl Anon');
const ForumQuestion = require('../../../models/forumQuestion'); const User = require('../../../models/user'); const { TransformObject } = require('./merge'); exports.createForumQuestion = async (args, req) => { try { if (!req.isTheUserAuthenticated) { throw new Error('Unauthenticated!'); } const forumQuestion = new ForumQuestion({ course: args.forumQuestionInput.course, title: args.forumQuestionInput.title, body: args.forumQuestionInput.body, sectionIndex: args.forumQuestionInput.sectionIndex, videoIndex: args.forumQuestionInput.videoIndex, exercise: args.forumQuestionInput.exercise, creator: args.forumQuestionInput.creator, date: new Date().toISOString() }); let createdForumQuestion; const result = await forumQuestion.save(); createdForumQuestion = TransformObject(result); const user = await User.findById(result.creator); user.createdForumQuestions.push(forumQuestion); await user.save(); return createdForumQuestion; } catch (e) { throw e } };
'use strict'; const test = require('tape'); const OGMNeoIndex = require('../lib/ogmneo-index'); test('Test create an index', (assert) => { OGMNeoIndex.create('object', ['name','test']).then((result) => { assert.notEqual(result, null); assert.end(); }); }); test('Test create index with a string param', (assert) => { OGMNeoIndex.create('object', 'string').then((result) => { assert.notEqual(result, null); assert.end(); }); }); test('Test FAIL to create an index with a string param', (assert) => { OGMNeoIndex.create('object', '').catch((error) => { assert.equals(error.message, 'You must provide and label and an array with at least one field name or a string name'); assert.end(); }); }); test('Test FAIL to create index', (assert) => { OGMNeoIndex.create(null, ['name','tes']).catch((error) => { assert.equals(error.message, 'You must provide and string as label param'); assert.end(); }); }); test('Test FAIL to create index with invalid parameters', (assert) => { OGMNeoIndex.create('object', []).catch((error) => { assert.equals(error.message, 'You must provide and label and an array with at least one field name or a string name'); assert.end(); }); }); test('Test drop index', (assert) => { OGMNeoIndex.drop('object', ['name','test']).then((result) => { assert.notEqual(result, null); assert.end(); }); });
if(typeof Global ==="undefined"){ Global={}; } if(!Global.productDirLoader){ Global.productDirLoader = new Ext.tree.TreeLoader({ iconCls : 'lanyo-tree-node-icon', url : "productDir.ejf?cmd=getProductDirTree&pageSize=-1&treeData=true", listeners : { 'beforeload' : function(treeLoader, node) { treeLoader.baseParams.id = (node.id.indexOf('root')<0 ? node.id : ""); if(typeof node.attributes.checked!=="undefined"){ treeLoader.baseParams.checked=false; } } } }); } ProductListPanel=Ext.extend(Disco.Ext.CrudPanel,{ pageSize:20, id:"productListPanel", gridForceFit : false, baseUrl:"product.ejf", searchWin:{title:"产品高级查询",width:538,height:220}, viewWin:function(){ var size = this.getDefaultWinSize(); return { width : size.width , height : size.height+30, title : '产品详情查看' } }, createForm:function(){ var formPanel=new Ext.form.FormPanel({ frame:true, labelWidth:70, labelAlign:'right', fileUpload : true, items:[ {xtype:"hidden",name:"id"}, Disco.Ext.Util.twoColumnPanelBuild( {fieldLabel:'产品名称',name:'title',allowBlank:false}, {fieldLabel:'产品编号',name:'sn',allowBlank:false}, { name:"dir", allowBlank:false, xtype:"treecombo", fieldLabel:"所属目录", hiddenName:"dir", displayField:"title", tree:new Ext.tree.TreePanel({ root:new Ext.tree.AsyncTreeNode({ id:"root", text:"产品目录", expanded:true, iconCls : 'treeroot-icon', loader:Global.productDirLoader }) })/*, listeners:{ select:function(c,node){this.loadPropertys(c.getValue());}, scope:this }*/ }, //ConfigConst.BASE.getDictionaryCombo("dir","分类","ProductDir",null,false), ConfigConst.BASE.getDictionaryCombo("brand","品牌","ProductBrand"), ConfigConst.BASE.getDictionaryCombo("unit","计量单","ProductUnit"), {fieldLabel:'产品图片',name:'imgPath',xtype:"fileuploadfield"}, {fieldLabel:'规格',name:'spec'}, {fieldLabel:'型号',name:'model'}, {fieldLabel:'等级',name:'level'}, {fieldLabel:'进价',name:'buyPrice',xtype:"numberfield"}, {fieldLabel:'销售价',name:'salePrice',xtype:"numberfield"} ), {fieldLabel:'产品描述',xtype:"textarea",name:'content',anchor:"-20",height:80} ] }); return formPanel; }, onView : function(win,r){ var imgPath = r.imgPath ? "upload/product/"+r.imgPath : Ext.BLANK_IMAGE_URL; this.viewPanel.imgPath.el.dom.src = imgPath; }, createViewPanel: function(){ var objectRender = Disco.Ext.Util.objectRender("title"); var viewPanel = new Ext.FormPanel({ frame:true, labelWidth:70, //labelAlign:'right', bodyStyle:'padding:10px;', items:[ {xtype:"hidden",name:"id"}, { height:170, xtype : 'panel', layout : 'hbox', layoutConfig : {align:'stretch'}, defaults : {flex:1}, items : [ { layout : 'form', xtype:'panel', defaultType:'labelfield', items : [ {fieldLabel:'产品名称',name:'title',allowBlank:false}, {fieldLabel:'产品编号',name:'sn',allowBlank:false}, {fieldLabel:'所属目录',name:'dir',renderer:objectRender,allowBlank:false}, {fieldLabel:'品牌',name:'brand',renderer:objectRender}, {fieldLabel:'计量单',name:'unit',renderer:objectRender}, {fieldLabel:'规格',name:'spec'}, {fieldLabel:'型号',name:'model'}, {fieldLabel:'等级',name:'level'} ] },{ xtype : 'fieldset', title : '产品图片', items : { xtype:'box', ref:'../../imgPath', autoEl:{tag:'img',style:'width:100%;height:100%;',src:Ext.BLANK_IMAGE_URL} } } ] },Ext.apply( Disco.Ext.Util.buildColumnForm('labelfield', {fieldLabel:'进价',name:'buyPrice'}, {fieldLabel:'销售价',name:'salePrice'} ), {style:'margin-top:5px;'} ),{ fieldLabel:'产品描述', xtype : 'labelfield', name : 'content' } ] }); return viewPanel; }, addPropertysField:function(dp){ var p=dp.parameter; var panel=this.fp.findById("propertysPanel"); var config={name:"propertys"+dp.id,fieldLabel:p.title}; if(!dp.canEmpty)config.allowBlank=false; var bz=p.dw; config.listeners={"render":function(f){ f.el.dom.parentNode.appendChild(document.createTextNode(bz)); }}; if(p.theType=="0"){ config.xtype="textfield"; } else if(p.theType=="1"){ config.xtype="numberfield"; } else if(p.theType=="2"){ var values=p.theValue.split(","); var vs=[]; for(var i=0;i<values.length;i++){ if(values[i]){ var index=vs.length; vs[index]=[]; vs[index][0]=values[i]; vs[index][1]=values[i]; } } Ext.apply(config,{ xtype:"combo", hiddenName:config.name, displayField:"title", valueField:"value", store: new Ext.data.SimpleStore({ fields: ['title', 'value'], data : vs }), editable:false, mode: 'local', triggerAction: 'all', emptyText:'请选择...' }); } else if(p.theType=="3"){ config.xtype="numberfield"; var values=p.theValue.split(","); config.minValue=values[0]; config.maxValue=values[1]; } else if(p.theType=="4"){ config.xtype="textarea"; config.height=50; } else{ config.xtype="textfield"; }; panel.add(config); }, loadPropertys:function(id,callback){ var n=parseFloat(id); if(n){ Ext.Ajax.request({url:"productDir.ejf?cmd=getDir", params:{id:id}, success:function(response,options){ eval("var ret="+response.responseText); var owner=this.fp.findById("propertysPanel").ownerCt; var panel=owner.remove(0); owner.add(panel.initialConfig); var ps=ret.parameters; for(var i=0;i<ps.length;i++){ this.addPropertysField(ps[i]); } owner.doLayout(); if(callback)callback(); }, scope:this }); } }, /** * 创建高级查询窗口 * @return {Ext.FormPanel} */ searchFormPanel:function(){ var formPanel = new Ext.form.FormPanel({ frame : true, labelWidth : 80, labelAlign : "right", items : [{ xtype : "fieldset", title : "查询条件", autoHeight : true, items : [ Disco.Ext.Util.buildColumnForm({fieldLabel:'编码',name:'sn'},{fieldLabel:'材料名称',name:'title'}, { name:"dir", allowBlank:false, xtype:"treecombo", fieldLabel:"所属目录", hiddenName:"dir", displayField:"title", tree:new Ext.tree.TreePanel({ root:new Ext.tree.AsyncTreeNode({ id:"root", text:"产品目录", expanded:true, iconCls : 'treeroot-icon', loader:Global.productDirLoader }) }) }, ConfigConst.BASE.getDictionaryCombo("brand","品牌","ProductBrand"), {fieldLabel:'产品规格',name:'spec'}, {fieldLabel:'型号',name:'model'}, {fieldLabel : "最低价格",name : "salePrice_start",xtype : 'numberfield'}, {fieldLabel : "最高价格",name : "salePrice_end",xtype : 'numberfield'} )] }] }); return formPanel; }, getDefaultWinSize : function(){ return { width : 538, height : 330 } }, createWin:function(callback, autoClose) { var s = this.getDefaultWinSize(); return this.initWin(s.width,s.height,"产品信息录入",callback, autoClose); }, storeMapping:["id","title","sn","spec","model","level","buyPrice","salePrice","content","dir","brand","unit","imgPath"], beforeDestroy : function(){ Ext.destroy(this.gridTip); delete this.gridTip; ProductListPanel.superclass.beforeDestroy.call(this); }, initRowTip : function(grid){ this.gridTip = new Ext.ToolTip({ width : 200, height:150, autoHeight:false, target: grid.getView().mainBody, delegate: 'div.icon-img', tipAnchor : 'r', anchor : 'left', //anchorOffset: 3, mouseOffset : [5,0], onTargetOver : function(e){ this.constructor.prototype.onTargetOver.call(this,e); var t = e.getTarget(this.delegate,null,true); if(t){ var row = t.parent('div.x-grid3-row',true); this.targetRow = row.rowIndex; } }, listeners:{ scope : this, beforeshow : function(tip){ if(Ext.isDefined(tip.targetRow)){ var record = this.grid.getStore().getAt(tip.targetRow); var imgPath = record.get('imgPath'); var t = String.format('<img style="width:100%;height:100%" src="upload/product/{0}" />',imgPath); if(tip.rendered){ tip.update(t); }else{ tip.html=t; } } } } }); }, downloadProductImg : function(){ var records = this.grid.getSelections(); if(records && records.length){ var r = records[0]; window.open('product.ejf?cmd=downProductImg&id='+r.get('id')); } }, onCreate : function(){ ProductListPanel.superclass.onCreate.call(this); this.fp.form.findField("dir").setValue(this.parentId); }, initComponent : function(){ this.cm=new Ext.grid.ColumnModel([ {header: "产品名称", sortable:true,width: 100, dataIndex:"title"}, { header: "图片", sortable:true, width: 35, align:'center', dataIndex:"imgPath", renderer:function(v){ if(v){ return '<div style="width:12px;height:12px;" class="icon-img"></div>' }else{ return '' } } }, {header: "产品编号", sortable:true,width: 100, dataIndex:"sn"}, {header: "分类", sortable:true,width: 100, dataIndex:"dir",renderer:this.objectRender("title")}, {header: "品牌", sortable:true,width: 100, dataIndex:"brand",renderer:this.objectRender("title")}, {header: "单位", sortable:true,width: 100, dataIndex:"unit",renderer:this.objectRender("title")}, {header: "规格", sortable:true,width: 100, dataIndex:"spec"}, {header: "型号", sortable:true,width: 100, dataIndex:"model"}, {header: "等级", sortable:true,width: 100, dataIndex:"level"}, {header: "进价", sortable:true,width: 100, dataIndex:"buyPrice"}, {header: "销售价", sortable:true,width: 100, dataIndex:"salePrice"}, {header: "简介", sortable:true,width: 300, dataIndex:"content"} ]); this.gridButtons = [{ text : '下载图片', scope : this, iconCls : 'down', handler: this.downloadProductImg }]; ProductListPanel.superclass.initComponent.call(this); this.grid.on('render',this.initRowTip,this); } }); ProductManagePanel = Ext.extend(Disco.Ext.TreeCascadePanel,{ treeCfg : { rootText : '所有目录', rootIconCls : 'treeroot-icon', loader : Global.productDirLoader }, queryParam : 'dir', onTreeClick : function(node){ var id = (node.id != 'root' ? node.id : ""); this.getPanel().parentId =id?{id:id,title:node.text}:null; ProductManagePanel.superclass.onTreeClick.apply(this,arguments); }, getPanel : function(){ if(!this.panel) this.panel = new ProductListPanel(); return this.panel; } });
const path = require('path'); const webpack = require('webpack'); const IS_DEV_SERVER = process.argv[1].indexOf('webpack-dev-server') >= 0; module.exports = { mode: IS_DEV_SERVER ? 'development' : 'production', entry: { bundle: path.resolve(__dirname, 'src') }, devtool: IS_DEV_SERVER ? 'eval' : 'source-map', output: { filename: 'app.js', path: path.resolve(__dirname, 'dist'), library: 'app' }, resolve: { modules: ['node_modules', 'src'], extensions: ['.ts', '.tsx', '.js', '.json'] }, module: { rules: [ { test: /\.(woff|woff2|eot|svg|png|jpg|ttf|gif)$/, use: 'url-loader' }, { test: /\.(css|scss)$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }, { test: /\.tsx?$/, loader: 'ts-loader' }, { enforce: 'pre', test: /\.tsx?$/, loader: 'tslint-loader', options: { configFile: path.join(__dirname, 'tslint.json'), emitErrors: true, failOnHint: true, typeCheck: true, tsConfigFile: path.join(__dirname, 'tsconfig.json') } }, { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' } ] }, devServer: { host: '0.0.0.0', port: 3333, hot: true, inline: true, contentBase: path.join(__dirname, 'public'), historyApiFallback: true, compress: true, open: false }, plugins: IS_DEV_SERVER ? [new webpack.HotModuleReplacementPlugin()] : [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), BUILD: JSON.stringify('build') } }) ] };
const Admin = require('../models/admin/admin'); const auth = async (ctx, next) => { const token = ctx.headers['x-auth']; const admin = await Admin.findByToken(token); if (!admin) { ctx.status = 401; return; } ctx.request.admin = admin; ctx.request.token = token; await next(); }; module.exports = auth;
QUnit.test("Test the validPhone function.", function (assert) { var num = "(415) 555-5555"; var result = validPhone(num); assert.deepEqual(result, true, "validPhone function passed.") }); QUnit.test("Errors thrown for validPhone", function (assert) { assert.throws(function () { validPhone("(415) 55-555"); }, "Invalid phone number: (415) 55-555"); assert.throws(function () { validPhone("(abc) efg-hijk"); }, "Invalid phone number: (abc) efg-hijk"); }); QUnit.test("Test the getAreaCode function.", function (assert) { var num = "(415) 555-5555"; var result = getAreaCode(num); assert.deepEqual(result, "415", "Valid area code test passed."); }); QUnit.test("Errors thrown for getAreaCode", function (assert) { assert.throws(function () { getAreaCode("415)444-5555"); }, "Missing '('. An error should have been thrown."); assert.throws(function () { getAreaCode("(415 444-5555"); }, "Missing ')'. An error should have been thrown."); }); QUnit.test("Test the getCoCode function", function (assert) { var num = "(415) 555-5555"; var result = getCoCode(num); assert.deepEqual(result, "555", "Valid CO code test passed."); }); QUnit.test("Errors thrown for getCoCode", function (assert) { assert.throws(function () { getCoCode("(415) 55-5555"); }, "Invalid CO code: 55"); assert.throws(function () { getCoCode("(415) abc-5555"); }, "Invalid CO code: abc"); }); QUnit.test("Test the getLineCode function", function (assert) { var num = "(415) 555-5555"; var result = getLineCode(num); assert.deepEqual(result, "5555", "Valid line code test passed."); }); QUnit.test("Errors thrown for getLineCode", function (assert) { assert.throws(function () { getLineCode("(415) 555-555"); }, "Invalid line code: 555"); assert.throws(function () { getLineCode("(415) 555-abcd"); }, "Invalid line code: abcd"); });
import React from 'react'; import { Redirect } from 'react-router-dom'; import Home from '../view/Home'; import Recommend from '../view/Recommend'; import Singer from '../view/Singer'; import Rank from '../view/Rank'; export default [ { path: "/", component: Home, routes: [ { path: "/", exact: true, render: () => ( <Redirect to={"/recommend"} /> ) }, { path: "/recommend", component: Recommend, }, { path: "/singer", component: Singer, }, { path: "/rank", component: Rank, } ] } ]
'use strict' const AuthorizationException = require('../Exceptions') class Is { async handle ({ imperium }, next, [role]) { if (await imperium.isnot(role)) throw new AuthorizationException('Unauthorized', 403, 'E_UNAUTHORIZED') await next() } async wsHandle ({ imperium }, next, [role]) { if (await imperium.isnot(role)) throw new AuthorizationException('Unauthorized', 403, 'E_UNAUTHORIZED') await next() } } module.exports = Is
"use strict"; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } (function (f) { if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined") { module.exports = f(); } else if (typeof define === "function" && define.amd) { define([], f); } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { g = this; } g.ChunkHandler = f(); } })(function () { var define, module, exports; return function () { function r(e, n, t) { function o(i, f) { if (!n[i]) { if (!e[i]) { var c = "function" == typeof require && require; if (!f && c) return c(i, !0); if (u) return u(i, !0); var a = new Error("Cannot find module '" + i + "'"); throw a.code = "MODULE_NOT_FOUND", a; } var p = n[i] = { exports: {} }; e[i][0].call(p.exports, function (r) { var n = e[i][1][r]; return o(n || r); }, p, p.exports, r, e, n, t); } return n[i].exports; } for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) o(t[i]); return o; } return r; }()({ 1: [function (require, module, exports) { /* ChunkHandler v1.6.0 | (c) 2021 M ABD AZIZ ALFIAN | MIT License | https://github.com/aalfiann/chunk-handler */ 'use strict'; /** * Chunk Handler Class */ var ChunkHandler = /*#__PURE__*/function () { /** * Constructor */ function ChunkHandler() { _classCallCheck(this, ChunkHandler); this.body = {}; } /** * Determine value is string * @param {*} value * @return {bool} */ _createClass(ChunkHandler, [{ key: "isString", value: function isString(value) { return typeof value === 'string' || value instanceof String; } /** * Determine value is array * @param {*} value * @return {bool} */ }, { key: "isArray", value: function isArray(value) { if (value === undefined || value === '') { return false; } return value && _typeof(value) === 'object' && value.constructor === Array; } /** * Determine value is object * @param {*} value * @return {bool} */ }, { key: "isObject", value: function isObject(value) { if (value === undefined || value === '') { return false; } return value && _typeof(value) === 'object' && value.constructor === Object; } /** * Determine value is empty * @param {const} value * @return {bool} */ }, { key: "isEmpty", value: function isEmpty(value) { return value === undefined || value === null || value === ''; } /** * Determine value is empty and array * @param {*} value * @return {bool} */ }, { key: "isEmptyArray", value: function isEmptyArray(value) { return value === undefined || value === null || value.length === 0; } /** * Determine object value is empty * @param {*} value * @return {bool} */ }, { key: "isEmptyObject", value: function isEmptyObject(value) { return value === undefined || value === null || Object.keys(value).length === 0 && value.constructor === Object; } /** * Blocking test for asynchronous * @param {integer} ms this is miliseconds value for event block * @return {int} */ }, { key: "blockingTest", value: function blockingTest() { var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000; var start = Date.now(); var time = start + ms; while (Date.now() < time) { // empty progress } return start; } /** * Get best size to chunk * @param {int|string} length this is the maximum array/string length number * @param {int|string} split [optional] split value will create maximum (value*10) means if split is 5 then will make array length not more than 50 * @return {int} */ }, { key: "getBestSize", value: function getBestSize(length) { var split = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5; length = parseInt(length); split = parseInt(split); if (split < 1 || split > 10) { throw new Error('Split value must be between 1-10'); } if (length <= 100000 && split > 1) { split = 1; } if (length > 100000 && length <= 1000000 && split === 1) { split = 5; } var max = split * 10; var start = max - Math.ceil(max / 10); var slice = max - start; switch (true) { case length <= 5000000 && length > 4000000: return Math.ceil(length / (max - slice * 1)); case length <= 4000000 && length > 3500000: return Math.ceil(length / (max - slice * 2)); case length <= 3500000 && length > 3000000: return Math.ceil(length / (max - slice * 3)); case length <= 3000000 && length > 2500000: return Math.ceil(length / (max - slice * 4)); case length <= 2500000 && length > 2000000: return Math.ceil(length / (max - slice * 5)); case length <= 2000000 && length > 1500000: return Math.ceil(length / (max - slice * 6)); case length <= 1500000 && length > 1000000: return Math.ceil(length / (max - slice * 7)); case length <= 1000000 && length > 500000: return Math.ceil(length / (max - slice * 8)); case length <= 500000 && length > 100000: return Math.ceil(length / (max - slice * 9)); case length <= 100000 && length > 50000: return Math.ceil(length / 3); case length <= 50000 && length > 10000: return Math.ceil(length / 2); case length <= 10000 && length > 1: return Math.ceil(length / 1); default: return Math.ceil(length / max); } } /** * Get random number between min and max values * @param {int} min min random value (included) * @param {int} max max random value (included) */ }, { key: "getRandomInt", value: function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Make value to be chunked * @param {string|array} value this is value to be chunked * @param {string|int} size [optional] if value is type string then size will make split from letters per size number * @return {array} */ }, { key: "make", value: function make(value) { var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; size = parseInt(size); if (!this.isString(value) && !this.isArray(value)) throw new Error('Value must be string or array'); if (this.isString(value)) { var i = 0; var o = 0; var numChunks = Math.ceil(value.length / size); var chunks = new Array(numChunks); for (i, o; i < numChunks; ++i, o += size) { chunks[i] = value.substr(o, size); } return chunks; } else { var result = []; // add each chunk to the result var x = 0; var len = Math.ceil(value.length / size); for (x; x < len; x++) { var start = x * size; var end = start + size; result.push(value.slice(start, end)); } return result; } } /** * Make aleatory chunks from value * @param {array} value this is the array to be aleatory chunked * @param {int} numberOfChunks the number of chunks that will be created */ }, { key: "makeAleatory", value: function makeAleatory(value, numberOfChunks) { var array = value; var result = new Array([]); var chunkSize = parseInt(value.length / numberOfChunks, 10); var chunkIndex = 0; for (chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++) { result[parseInt(chunkIndex, 10)] = []; for (var itemIndex = 0; itemIndex < chunkSize; itemIndex++) { // Gets a random index to be included in the chunk var randomIndex = this.getRandomInt(0, array.length - 1); // Inserts the item and remove it from array result[parseInt(chunkIndex, 10)].push(array.splice(randomIndex, 1)[0]); } } // Add the remaining items if (array.length > 0) { var _result$parseInt; (_result$parseInt = result[parseInt(chunkIndex - 1, 10)]).push.apply(_result$parseInt, _toConsumableArray(array)); } return result; } /** * Merge data chunked * @param {object} data data is an array from this.get(name) * @return {mixed} could be string or array */ }, { key: "merge", value: function merge(data) { if (!this.isArray(data) && this.isEmptyArray(data)) return ''; var file = ''; var i = 0; var len = data.length; if (!this.isEmpty(data[0].data)) { if (!this.isEmpty(data[0].part)) { data.sort(function (a, b) { return parseFloat(a.part) - parseFloat(b.part); }); } if (this.isArray(data[0].data)) { file = []; } for (i; i < len; i++) { if (this.isArray(data[i].data)) { file = file.concat(data[i].data); } else { file += data[i].data; } } } else { if (this.isArray(data[0])) { file = []; } for (i; i < len; i++) { if (this.isArray(data[i])) { file = file.concat(data[i]); } else { file += data[i]; } } } return file; } /** * Add new or replace data chunk by it's name * @param {string} name * @param {object} data * @param {int} part * @return {this} */ }, { key: "add", value: function add(name, data) { var part = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; if (this.isString(name)) { name = name.replace(/[^A-Z0-9]/ig, '_'); if (data) { if (!this.isEmpty(part)) { part = parseInt(part); if (this.isEmpty(this.body[name])) { this.body[name] = []; this.body[name].push({ part: part, data: data }); } else { this.body[name].push({ part: part, data: data }); } } else { if (this.isEmpty(this.body[name])) { this.body[name] = []; this.body[name].push({ data: data }); } else { this.body[name].push({ data: data }); } } } } return this; } /** * Remove data chunk by name * @param {string} name * @return {this} */ }, { key: "remove", value: function remove(name) { if (this.isString(name)) { name = name.replace(/[^A-Z0-9]/ig, '_'); delete this.body[name]; } return this; } /** * Cleanup all data chunk */ }, { key: "clean", value: function clean() { this.body = {}; return this; } /** * Get data chunk by name * @param {string} name * @return {string} */ }, { key: "get", value: function get(name) { name = name.replace(/[^A-Z0-9]/ig, '_'); return this.body[name]; } /** * Get all data chunk * @return {object} */ }, { key: "getBody", value: function getBody() { return this.body; } /** * Make asynchronous process with Promise * @param {*} fn * @return {this} */ }, { key: "promisify", value: function promisify(fn) { var self = this; return new Promise(function (resolve, reject) { try { resolve(fn.call(self, self)); } catch (err) { reject(err); } }); } }]); return ChunkHandler; }(); module.exports = ChunkHandler; }, {}] }, {}, [1])(1); });
import express from 'express' import { uploadGroupPhoto,uploadProfilePhoto,uploadMsgs } from '../controllers/upload.js' import multer from 'multer' import path from 'path' import auth from '../middlewares/auth.js' const storage = multer.diskStorage({ destination: (req,file,cb)=>{ cb(null,'static/imgs/') }, filename: (req,file,cb) =>{ cb(null,req.user.id+Date.now()+path.extname(file.originalname)) } }) const upload = multer({ storage, limits: {fileSize: 10000000} }) const router = express.Router() router.post('/profile',[ auth, upload.single('img'), uploadProfilePhoto ]) router.post('/group/:conv_id',[ auth, upload.single('img'), uploadGroupPhoto ]) router.post('/message/:conv_id',[ auth, upload.single('img'), uploadMsgs ]) export default router
var App = require('app'); /** * Users View Controller * * @namespace App * @extends {Ember.ObjectController} */ App.UsersViewController = Em.ObjectController.extend({ });
const mongoose = require('mongoose'); const Joi = require('joi'); const discountSchema = mongoose.Schema({ _id : mongoose.Schema.Types.ObjectId, menu : { type : String }, menuId : { type : mongoose.Schema.Types.ObjectId }, typeofDiscount : { type : String }, discountAmt : { type : Number , required : true }, description : { type : String }, discountCode : { type : String }, available : { type : Boolean }, discountFrom : { type : Date }, discountTo : { type : Date }, createdAt : { type : Date , default : Date.now}, createdBy : { type : Number }, }); module.exports = mongoose.model('discounts',discountSchema);
import { React } from 'react'; import './Data.css'; export function Data(props){ const imgSrc = 'http://openweathermap.com/img/w/'+(props.state.icon)+'.png'; const temp = Math.round(parseFloat(props.state.temp)-273.15); const weather = (props.state.desc).toUpperCase(); const city = (props.state.city).toUpperCase(); if (props.state.loading){ return <p>Loading..</p> } else{ return( <div className={"wrap"}> <img src={imgSrc} alt={"description"}/> <p>Temperature of {city} : {temp} °</p> <p>Weather in {city} : {weather}</p> </div> ) } }
import React from 'react' import MonsterConfigListData from 'components-lib/monsterConfigList/MonsterConfigListData' import MonsterConfig from 'components-lib/monsterConfig/MonsterConfig' import SWPanel from 'components-lib/ui/SWPanel' import {Utils} from 'ap-react-bootstrap' import './MonsterConfigList.scss'; /* This class was auto-generated by the JavaScriptWriter */ class MonsterConfigList extends React.Component { constructor(props) { super(props); } componentWillMount() { MonsterConfigListData.register(this) } componentWillUnmount() { MonsterConfigListData.unregister() } _buildMonstersConfig(monsterConfig) { return (<MonsterConfig key={monsterConfig.id} monsterConfig={monsterConfig} onClick={this.onClickDeleteMonsterConfig}/>) } render() { return ( <div className={"sm-builds-monsters " + (this.state.haveBuild ? "" : "sm-hide")} size="lg"> <div className="sm-builds-monsters-scroll"> {Utils.map(this.state.monstersConfig, this._buildMonstersConfig.bind(this))} <div className={"sm-builds-monster-add1 " + (Object.keys(this.state.monstersConfig).length === 0 ? "sm-builds-monster-empty" : "")} onClick={this.onClickAddMonsterConfig.bind(this)}> <i className="glyphicon glyphicon-plus-sign sm-builds-monster-add"></i> <span>Add New<br/>Monster Config</span> </div> </div> </div> ); } } export default MonsterConfigList;
// @param {number} N // @return {number} const fib = N => { let first = 1; let second = 0; let temp = null; while (N >= 0) { temp = first; first = first + second; second = temp; N--; } return first - second; }; export default fib;
module.exports = { app: { id: '365c9c6a-5602-4bc6-942c-7084beada709' //change this to your app's client id }, appWallet: { client: { //if you have an app wallet, add your client id and secret here id: 'ad2c4eb9-bc22-4000-b17e-54dd1e568440', secret: '56iBfVL]fxB-pRyS}19[er9lBxuD}MvcUV6P0Yl7UE]pNjJR}ntkVkC-Iysg6raDt' }, auth: { tokenHost: 'https://account.bitski.com', tokenPath: '/oauth2/token' } }, environments: { development: { network: 'development', //ethereum network to use for local dev redirectURL: 'http://localhost:3000/callback.html' //url the popup will redirect to when logged in }, production: { network: 'kovan', //ethereum network to use for production redirectURL: 'https://mydomain.com/callback.html' //url the popup will redirect to when logged in } }, networkIds: { kovan: 'kovan', rinkeby: 'rinkeby', live: 'mainnet', development: 'http://localhost:9545' //Update this if you use Ganache or another local blockchain } };
// Data for the "HTML Audio" Page var audio = { controls: true, source: [ {src: "https://scs.senecac.on.ca/~tanvir.alam/shared/fall-2018/web222/Track03.mp3", type: "audio/mpeg"}, {src: "https://scs.senecac.on.ca/~tanvir.alam/shared/fall-2018/web222/Track03.ogg", type: "audio/ogg"} ] }; window.addEventListener('load', function() { var aud = ""; var a = audio.source if (audio.controls){ aud += "<audio controls>" a.forEach(function(ado){ aud += "<source src=" + ado.src + " type=" + ado.type + ">"; }); } else { aud += "<audio>" a.forEach(function(ado){ aud += "<source src=" + ado.src + " type=" + ado.type + ">"; }); } document.getElementById("audio").innerHTML = aud + '</audio>'; });
import React from "react"; const CheckList = () => ( <div> <h2>Check List for New PHM Devs</h2> <h4>Welcome to Plaza Home Mortgage IT Department!</h4> <p> In order to get started contributing code there are a few things you'll want to make sure you have a grasp of. Ask around to people in IT until you figure out the following: </p> <ol> <li> Overview of inside.plazahomemortgage.com, plazahomemortgage.com, and Breeze client and external portals. Find out about how all these sites/webapps relate, what they do differently and who uses and develops on which platform. </li> <li> Find out about the various databases. Plaza uses multiple databases so that development and reporting can happen without jeopordizing the main database. Depending on what you are working on and in what enviroment, you will be accessing different databases. Find out what UAT, Dev, and PROD are and when you would want to use each. </li> <li> Your Dev enviroment. Find out how you will get into the code bases. Ask for help until you know exactly how to login to Citrix and how to RDP into a Dev workstation that has the code you will be working on. Don't feel dumb for asking simple stuff like how to navigate Plaza's systems. </li> <li> Ask about the company shared folders and how to access files and folders across Plaza's network. </li> <li> Find out about source control. How will you be contributing code to a project once it is tested and approved. How will you revert this code if it breaks in production? </li> </ol> </div> ); export default CheckList;
import Vue from "vue"; import axios from "axios"; const skill = { template: "#skill", props: { skillName: String, skillPercents: Number }, methods: { drawCircle() { const circle = this.$refs["color-circle"]; const dashOffset = parseInt( getComputedStyle(circle).getPropertyValue("stroke-dashoffset") ); const persents = (dashOffset / 100) * (100 - this.skillPercents); addEventListener("scroll", function() { const elementSkills = document.querySelector('.skills'); var skillsPosition = elementSkills.getBoundingClientRect(); if (skillsPosition.top < 400) { circle.style.strokeDashoffset = persents; } }); } }, mounted() { console.log(localStorage); this.drawCircle(); } }; const skillsRow = { template: "#skills-row", components: { skill }, props: { skill: Object } }; new Vue({ el: "#skills-container", components: { skillsRow }, data: { skills: {} }, created() { const data = require("../../../data/skills.json"); this.skills = data; //console.log(data); }, /* mounted() { axios.get(`http://webdev-api.loftschool.com/skills/13`).then(response => { //console.log(Array.from(response.data)); var arr = Array.from(response.data); var skillsAdmin = [{}]; arr.forEach(function(item, i, arr) { var skilltitle = item.title; skillsAdmin.push({ 'skillsGroup': item.category, 'skills': { 'skillName': item.title, 'skillPercents': item.percents } }); }); console.log(skillsAdmin); //this.skills = skillsAdmin.slice(); this.skills = response.data; console.log(this.skills); }); }, */ template: "#skills-list" });
$(document).ready(function() { var color; $(this).mousemove(function() { color = 'rgb(' + (Math.floor(Math.random() * 256)) + ', ' + + (Math.floor(Math.random() * 256)) + ', ' + (Math.floor(Math.random() * 256)) + ')'; $('#chunk').css({ 'background-color': color, 'left': event.pageX - 5, 'top': event.pageY - 10 }); }); })
var searchData= [ ['filereadexception',['FileReadException',['../structfsml_1_1FileReadException.html',1,'fsml']]], ['filewriteexception',['FileWriteException',['../structfsml_1_1FileWriteException.html',1,'fsml']]], ['flatmachine',['FlatMachine',['../structfsml_1_1FlatMachine.html',1,'fsml']]], ['flatstep',['FlatStep',['../structfsml_1_1FlatStep.html',1,'fsml']]] ];