text
stringlengths
7
3.69M
import { h, createElement } from 'preact' import { useState, useEffect, useRef } from 'preact/hooks'; const LazyObserver = ({ componentDir, componentProps }) => { const ref = useRef(null) const [Component, setComponent] = useState(null) let io = null useEffect(() => { const loadComponent = async () => { const module = await import(/* webpackChunkName: "LazyObserver-Component" */ "./" + componentDir) const element = createElement(module.default, {...componentProps}) setComponent(element) } io = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting && !Component) { loadComponent() } }) }) io.observe(ref.current) return function cleanup() { if (io) { io.disconnect() } } }) return ( <div ref={ref} style={{ height: 150 }}> {Component ? Component : <div>Loading...</div>} </div> ) } export default LazyObserver
var express = require('express'); var app = express(); const {notes} = require('../db/db.json'); app.get('*', (req, res) => { res.sendFile(path.join(__dirname + '/index.html')); }); app.get('/notes', (req, res) => { res.sendFile(path.join(__dirname + '/notes.html')); }); app.get('/api/notes', (req, res) => { var fs = require('fs'); var dbInfo = fs.readFile('db.json'); var info = JSON.parse(info); console.log(info); }); import { uniqueNamesGenerator, Config, colors } from 'unique-names-generator'; const config = Config = { dictionaries: [colors] } var id = uniqueNamesGenerator(config); app.post('/api/notes', (res, req) => { var title = document.getElementsByClassName('note-title'); var body = document.getElementsByClassName('note-textarea'); db.title = title; db.text = body; db.id = id; }) app.listen(3001, () => { console.log('API server now on port 3001! Good Job!'); });
import React, { Component } from 'react'; import { Container } from 'react-bootstrap'; // Note: // catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI // Also, remember that errors are caught in render but are not caught in event handlers. class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service //logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <Container><h1>Something went wrong.</h1></Container>; } return <Container>{this.props.children}</Container>; } } export default ErrorBoundary;
import React from 'react'; import './Promo.css'; const Promo = () => { return ( <section className='promo'> <div className='container'> <div className='row'> <div className='col-lg-6 mx-auto'> <h1>Welcome to My Portfolio.</h1> <p className='lead'>Hi there, I am Monir Hossain. I build websites that are fast, secure and ease to mange.</p> </div> </div> </div> </section> ); }; export default Promo;
import elasticsearch from 'elasticsearch'; export default class ES { constructor(props) { this.indexname = props.indexname; this.doctype = props.doctype; this.schema = props.schema; this.search = new elasticsearch.Client({host: props.url}); } indexCreate() { return new Promise((resolve, reject) => { this.search.indices.create({ index: this.indexname, body: {}, //This lets us ignore the error when the index already exists. ignore:[400] }) .then(body => { /* If we were being clever we could read this from a seperate file */ this.search.indices.putMapping({ index: this.indexname, type:this.doctype, body: this.schema }) .then(resolve) .catch(reject); }) .catch(reject); }); } addItems(items) { return new Promise((resolve, reject) => { this.search.bulk({ index: this.indexname, type: this.doctype, body: items }, function(err, response) { if (err) { return reject(JSON.stringify(err)); } return resolve(JSON.stringify(response)); }); }); } }
import models from '../../../models'; export default function (req, res, next) { return models.user.findOne({ where: { id: req.user.id } }).then(user => { return models.address.create({ number: req.body.number, street: req.body.street, complement: req.body.complement, post_code: req.body.post_code, city: req.body.city, latitude: req.body.latitude, longitude: req.body.longitude }).then(address => { return models.bar.create({ name: req.body.name, description: req.body.description, addresses_id: address.id, users_id: user.id, phone: req.body.phone, type: req.body.type, created_by: user.id, is_active: 1 }).then(bar => { res.send({bar, address}) }).catch(err => { next(err); }) }); }); }
'use strict'; var _botkit = require('botkit'); var _botkit2 = _interopRequireDefault(_botkit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } console.log('hi'); var fn = function fn(_ref) { var hi = _ref.hi, there = _ref.there, more = _ref.more; var a = more.a, b = more.b; console.log(hi, there, a, b); }; fn({ hi: 'hi', there: 'there', more: { a: 1, b: 2 } });
import React, { PureComponent } from 'react' import { Button, Col, Form, Icon, Input, message, Row } from 'antd' import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale' import styles from './styles.less' import { currentUser, userLogin } from '../../services/userLogin' import Link from 'umi/link' import router from 'umi/router' import { reloadAuthorized } from '../../utils/Authorized' @Form.create() class Login extends PureComponent { componentWillMount() { if (null == sessionStorage.getItem('autoLogin')) { currentUser() .then(resp => { if (null != resp && 200 == resp.code) { const user = JSON.parse(resp.data) if (user.authenticated && user.username !== 'anonymousUser') { setTimeout(function () { message.success(formatMessage({ id: 'user.login.welcome' })) sessionStorage.setItem('autoLogin', 1) // 设置umi菜单权限 sessionStorage.setItem('antd-pro-authority', JSON.stringify(user.authorities)) reloadAuthorized() // 重新读取授权信息 router.push('/') }, 200) } } }) .catch(error => { message.error(formatMessage({ id: 'Bad credentials' })) }) } } handleOk = e => { e.preventDefault() this.props.form.validateFields((err, values) => { if (!err) { // spring security 后台实现只会返回重定向响应头, 这里暂时兼容一下 // 后台已修改, 针对 Accept: application/json 的 form表单登录请求返回json userLogin(values.username, values.password) .then(resp => { if (null != resp && 200 == resp.code) { const user = JSON.parse(resp.data) if (user.authenticated && user.username !== 'anonymousUser') { message.success(formatMessage({ id: 'Login Success' })) // 设置umi菜单权限 sessionStorage.setItem('antd-pro-authority', JSON.stringify(user.authorities)) reloadAuthorized() // 重新读取授权信息 router.push('/welcome') } } }) } }) } oauth = (app) => { sessionStorage.removeItem('oauthCallback') window.location = `/oauth/login/${ app }` } render() { const { form } = this.props const { getFieldDecorator } = form return ( <Row justify="space-around" type="flex" className={ styles.main }> <Col xs={ 16 } sm={ 12 } md={ 8 } lg={ 6 } xl={ 4 }> <Form> <Form.Item> { getFieldDecorator('username', { rules: [ { required: true, message: formatMessage({ id: 'user.login.usernameOrEmail.errorMessage' }), }, ], })( <Input name="username" suffix={ <Icon type="user" style={ { color: 'rgba(0,0,0,.25)' } }/> } onPressEnter={ this.handleOk } placeholder={ formatMessage({ id: 'user.login.usernameOrEmail' }) } />, ) } {/*邮箱后缀补全*/ } {/*<AutoComplete*/ } {/* dataSource={this.state.emailSuffix}*/ } {/* onChange={this.handleChange}*/ } {/* placeholder={formatMessage({id: 'user.login.username'})}*/ } {/*/>*/ } </Form.Item> <Form.Item> { getFieldDecorator('password', { rules: [ { required: true, message: formatMessage({ id: 'user.login.password.errorMessage' }), }, ], })( <Input.Password type="password" autoComplete="false" allowClear suffix={ <Icon type="eye-invisible" style={ { opacity: 0.5 } }/> } onPressEnter={ this.handleOk } placeholder={ formatMessage({ id: 'user.login.password' }) } />, ) } </Form.Item> <Row> <Button type="primary" className={ styles.button } onClick={ this.handleOk }> { <FormattedMessage id={ 'user.login.signIn' }></FormattedMessage> } </Button> {/*/!*文字左对齐*!/*/ } {/*<Row justify="space-between">*/ } {/* <Col span={12}>*/ } {/* <Text>*/ } {/* {<FormattedMessage id={'user.login.Username'}></FormattedMessage>}: guest*/ } {/* </Text>*/ } {/* </Col>*/ } {/* <Col span={12}>*/ } {/* <Text justify="end">*/ } {/* {<FormattedMessage id={'user.login.Password'}></FormattedMessage>}: guest*/ } {/* </Text>*/ } {/* </Col>*/ } {/*</Row>*/ } </Row> <Row> <Col span={ 12 } style={ { textAlign: 'left', } }> <Link to="/user/reset"> <Button type="link" style={ { padding: '0' } }> <FormattedMessage id={ 'user.register.forgetPassword' }/> </Button> </Link> </Col> <Col span={ 12 } style={ { textAlign: 'right' } }> <Link to="/user/register"> <Button type="link" style={ { padding: '0' } }> {/*&lt;&lt;<FormattedMessage id={'user.register.toLogin'}/>*/ } <FormattedMessage id={ 'user.login.toRegister' }/>&gt;&gt; </Button> </Link> </Col> </Row> {/*文字两端对齐*/ } <Row justify="space-between" type="flex"> <span> { <FormattedMessage id={ 'user.login.username.forTest' }></FormattedMessage> }: test </span> <span> { <FormattedMessage id={ 'user.login.Password' }></FormattedMessage> }: 123456 </span> </Row> <div className={ styles.other }> <FormattedMessage id="user.login.oauth"/> <Icon key="oauth.github" type="github" className={ styles.icon } theme="outlined" onClick={ this.oauth.bind(this, 'github') }/> <Icon key="oauth.alipay" type="alipay-circle" className={ styles.icon } theme="outlined" onClick={ this.oauth.bind(this, 'alipay') }/> </div> </Form> </Col> </Row> ) } } export default Login
var React = require('react'); var Router = require('react-router').Router; var PostStore = require("../stores/post_store"); var PostIndexItem = require('./PostIndexItem'); var HomeIndexItem = require('./HomeIndexItem'); var ClientActions = require('../actions/client_actions'); var CommentForm = require("./CommentForm"); var NavBar = require('./NavBar'); var PostForm = require('./PostForm'); var LikeButton = require('./LikeButton'); var LikeCount = require('./LikeCount'); var NavBar = require('./NavBar'); var LikeStore = require('../stores/like_store'); var SessionStore = require('../stores/session_store'); var HomeIndex = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, getInitialState: function() { this.infiniteScrollStatus = false; return { posts: [], following: false }; }, componentDidMount: function() { this.postStorelistener = PostStore.addListener(this._onChange); // infinte scroll -start this.infiniteScrollCallback = function(e) { if ( window.location.hash.slice(0,3) !== "#/?" ) { // if we leave homeIndex page, we removeEventListener window.removeEventListener("scroll", this.infiniteScrollCallback); return; } if ( (window.innerHeight + window.scrollY - 78 === document.body.offsetHeight) && this.infiniteScrollStatus ) { // " - 78 " to account for the homeIndex top positioning this.fetchFive(); this.infiniteScrollStatus = false; // console.log("---------------"); // console.log(window.innerHeight + window.scrollY - 78); // console.log(document.body.offsetHeight); // console.log("---------------"); } }.bind(this); window.addEventListener("scroll", this.infiniteScrollCallback); // infinte scroll -end ClientActions.fetchFive(null, this.state.following, true); }, _onChange: function() { if ( this.state.posts.length !== PostStore.all().length ) { this.infiniteScrollStatus = true; } this.setState( { posts: PostStore.all() } ); }, fetchFive: function() { var lastPost = this.state.posts[ this.state.posts.length - 1 ]; ClientActions.fetchFive(lastPost.id, this.state.following, false); }, renderFetchFive: function() { if ( PostStore.all().length > this.state.posts.length ) { return ( <div className="fetch-five" onClick={this.fetchFive}></div> ); } }, handleSwitch: function() { if ( this.state.following ) { this.state.following = false; } else { this.state.following = true; } window.scrollTo(0, 0); ClientActions.fetchFive(null, this.state.following, true); }, handleClick: function(id) { this.context.router.push( "/users/" + id ); }, componentWillUnmount: function() { this.postStorelistener.remove(); }, renderMessage: function() { if ( this.state.following && this.state.posts.length === 0 ) { return <p className="message"> You are not following anyone at the moment. <br/> Find users to follow by clicking the blue button above to see the most recent posts or by navigating users and hashtags with the search bar. </p>; } }, render: function() { return( <div> <NavBar handleSwitch={this.handleSwitch} following={this.state.following}/> <div className="home-index"> <div className="spacing-above-post-form-home"></div> <PostForm userId={SessionStore.currentUser().id}/> <div className="spacing-below-post-form-home"></div> { this.renderMessage()} <ul> {this.state.posts.map( function(post, idx) { var millisecondDay = 1000*60*60*24; var currentDate = new Date(); var createAtDate = new Date(post.created_at); var daysSince = Math.ceil( (currentDate - createAtDate) / millisecondDay ); var timeSince = 0; var timeUnit = 0; if( daysSince/7 < 1 ) { timeSince = daysSince; timeUnit = "d"; } else { timeSince = Math.floor(daysSince/7); timeUnit = "w"; } return ( <li key={idx}> <HomeIndexItem post={post} timeSincePosted={timeSince + timeUnit}/> </li> ); }.bind(this) )} </ul> <div className="floor"/> </div> </div> ); } }); module.exports = HomeIndex;
import React, { Component } from 'react' import { View, Text, Image, StyleSheet } from 'react-native' export default class TopCardTitle extends Component { render() { return ( <View style={ styles.container }> <View style={ styles.pad }> <Image style={ styles.img } source={ this.props.img } /> </View> <View> <Text style={ styles.txt }> Monitor </Text> </View> </View> ) } } const styles = StyleSheet.create({ container: { borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255, 0.6)', flexDirection: 'row', alignContent: 'flex-start', backgroundColor: '#34b8ed' }, img: { width: 25, height: 25 }, pad: { paddingHorizontal: 18, paddingVertical: 10, }, txt: { justifyContent: 'center', color: '#fff', fontSize: 18, fontWeight: '500', paddingVertical: 10 } })
const DataModel = require('../models/viajes'); module.exports = app => { app.get('/viajes/:id', (req, res) => { var id = req.params.id; DataModel.get(id,(err, data) => { res.status(200).json(data); }); }); app.get('/viajes', (req, res) => { DataModel.gets((err, data) => { res.status(200).json(data); }); }); app.post('/viajes', (req, res) => { var userData = { Id: null, Cliente: req.body.Cliente, AsignacionOperador: req.body.AsignacionOperador, Mercancia:req.body.Mercancia, Origen:req.body.Origen, Destino: req.body.Destino, FechaTraslado: req.body.FechaTraslado, FechaEntrega:req.body.FechaEntrega, Costo:req.body.Costo, EstadoViaje:req.body.EstadoViaje, AsignacionCaja:req.body.AsignacionCaja, AsignacionCamion:req.body.AsignacionCamion, Tipo:req.body.Tipo, Pago:req.body.Pago, PagoMin:req.body.PagoMin }; DataModel.insert(userData, (err, data) => { try { if (data && data.insertId) { res.status(200).json({ success: true, msg: "Inserted a new user", data: data }); // res.redirect('/viajes/' + data.insertId); } else { res.status(500).json({ success: false, msg: "Error" }); } } catch (error) { } }); }); app.put('/viajes/:id', (req, res) => { const userData = { Id: req.params.id, Cliente: req.body.Cliente, AsignacionOperador: req.body.AsignacionOperador, Mercancia:req.body.Mercancia, Origen:req.body.Origen, Destino: req.body.Destino, FechaTraslado: req.body.FechaTraslado, FechaEntrega:req.body.FechaEntrega, Costo:req.body.Costo, EstadoViaje:req.body.EstadoViaje, AsignacionCaja:req.body.AsignacionCaja, AsignacionCamion:req.body.AsignacionCamion, Tipo:req.body.Tipo, Pago:req.body.Pago, PagoMin:req.body.PagoMin }; DataModel.update(userData, function (err, data) { if (data && data.msg) { res.status(200).json({data}); } else { res.status(500).json({ success: false, msg: 'Error' }); } }); }); app.delete('/viajes/:id', (req, res) => { var id = req.params.id; DataModel.delete(id, (err, data) => { if (data && data.msg === 'deleted' || data.msg == 'not Exists') { res.json({ success: 'true', data }); } else { res.status(500).json({ msg: 'Error' }); } }); }); };
/* * Kita * * debug.js * * A debug library within the Kita JS framework * * Shann McNicholl (@shannmcnicholl) * * License Pending. */ define( [], function() { if(!window || !window.console) { return { log: function() {}, warn: function() {}, error: function() {}, trace: function() {} }; } return { // Debug is on by default debug: true, log: function log(msg) { if(!this.debug || !msg) return false; // debugging is off window.console.log("["+ log.caller.name +"]", msg, this.getArguments(arguments, true)); return true; }, warn: function warn(msg) { if(!this.debug || !msg) return false; // debugging is off window.console.warn("["+ warn.caller.name +"]", msg); return true; }, error: function error(msg) { if(!this.debug || !msg) return false; // debugging is off window.console.error("["+ error.caller.name +"]", msg); return true; }, trace: function trace() { if(!this.debug) return false; // debugging is off window.console.trace(); return true; }, getArguments: function getArguments(args, skipFirst) { var items = [], i = 0, count; if(typeof skipFirst === "undefined") skipFirst = true; if(!args || (typeof args !== "object") || !args.length) return []; if(skipFirst) i++; for(count = args.length; i < count; i++) { items.push(args[i]); } return items; } }; });
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); /* GET home page. */ var MongoClient = require('mongodb').MongoClient; router.get('/', async (req, res) => { var url = "mongodb://localhost:27017/"; await MongoClient.connect(url, { useNewUrlParser: true }, async (err, db) => { if (err) throw err; var dbo = db.db("manage_testscript"); await dbo.collection("TestTemplate").find({}).toArray(function (err, result) { if (err) throw err; res.json({ data: result, status: 200, msg: 'ok', }); db.close(); }); }); }); var ObjectId = require('mongodb').ObjectID; router.get('/:id', async (req, res) => { var url = "mongodb://localhost:27017/"; await MongoClient.connect(url, { useNewUrlParser: true }, async (err, db) => { if (err) throw err; var dbo = db.db("manage_testscript"); var id = req.params.id; var listTestScript; await dbo.collection("TestScript").find({}).toArray(async (err, data) => { listTestScript = data; }); var listTestClassSelected = []; dbo.collection("TestTemplate").findOne({ _id: new ObjectId(id) }, async (err, template) => { await initListTestClassAvailable(template['testcases'], listTestScript); var listTestClassAvailable = JSON.parse(JSON.stringify(listTestScript).split('"_id":').join('"testscript-id":')); for (var i = 0; i < template.testcases.length; i++) { item = template.testcases[i]; var test = { "run": item['run'], "testscript-id": item['testscript-id'], "testclass-name": item['testclass-name'], "test-methods": [ { "testmethod-id": item['testmethod-id'], "testmethod-name": item['testmethod-name'], "test-type": item['test-type'], "testcases": [ { "testcase-id": item['testcase-id'], "testcase-name": item['testcase-name'], } ] } ] }; if (listTestClassSelected.length === 0) { listTestClassSelected.push(test); continue; } else { var check = await checkTestClassExist(item, listTestClassSelected); if (check === false) { listTestClassSelected.push(test); } } } db.close(); res.json({ status: 200, msg: 'ok', listTestClassSelected: listTestClassSelected, listTestClassAvailable: listTestClassAvailable, }) }); }); }); initListTestClassAvailable = async (listTestCase, listTestScript) => { for (var i = 0; i < listTestCase.length; i++) { for (var j = 0; j < listTestScript.length; j++) { if (listTestCase[i]['testscript-id'].equals(listTestScript[j]['_id'])) { for (k = 0; k < listTestScript[j]['test-methods'].length; k++) { if (listTestCase[i]['testmethod-id'].equals(listTestScript[j]['test-methods'][k]['testmethod-id'])) { for (var m = 0; m < listTestScript[j]['test-methods'][k]['testcases'].length; m++) { if (listTestCase[i]['testcase-id'].equals(listTestScript[j]['test-methods'][k]['testcases'][m]['testcase-id'])) { // pop listTestScript[j]['test-methods'][k]['testcases'].splice(m, 1); } } } } } } } } checkTestClassExist = (item, listTestClassSelected) => { for (var i = 0; i < listTestClassSelected.length; i++) { if (listTestClassSelected[i]['testscript-id'].equals(item['testscript-id'])) { for (var j = 0; j < listTestClassSelected[i]['test-methods'].length; j++) { if (item['testmethod-id'].equals(listTestClassSelected[i]['test-methods'][j]['testmethod-id'])) { var testCase = { "testcase-id": item['testcase-id'], "testcase-name": item['testcase-name'], } listTestClassSelected[i]['test-methods'][j]['testcases'].push(testCase); return true; } } var method = { "testmethod-id": item['testmethod-id'], "testmethod-name": item['testmethod-name'], "test-type": item['test-type'], "testcases": [{ "testcase-id": item['testcase-id'], "testcase-name": item['testcase-name'], }], }; listTestClassSelected[i]['test-methods'].push(method); return true; } } return false; } module.exports = router;
import Link from 'next/link' import { BasicButton, SecondaryButton } from './buttons' export default function LinkButton(props) { return ( <Link href={ props.href } as={props.href}> { props.secondary ? <SecondaryButton as="a" href={props.href} id={props.id}> {props.children} </SecondaryButton> : <BasicButton as="a" href={props.href} id={props.id}> {props.children} </BasicButton> } </Link> ) }
"use strict"; var arr = [1, 2, 3, 4, 5]; arr.map(function (item) { return item + 10; }); var arrSum = arr.map(function (item) { return item + 10; }); console.log(arr); console.log(arrSum);
import React, {createContext, useState} from 'react' import {posts} from '../utils/Dbtasks' export const TaskContext = createContext() export const TaskContextProvider = ({children}) => { const initialState = posts const [task, setTask] = useState(initialState) const taskValue = { task, setTask} return ( <TaskContext.Provider value={taskValue}> {children} </TaskContext.Provider> ) }
// Create a VideoRepo object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof window.VideoRepo !== 'object') { window.VideoRepo = {}; } (function () { 'use strict'; var url, cameras, videos, lastTimestamp, firstTimestamp; // If the VideoRepo object does not yet have a getMore method, give it one. if (typeof VideoRepo.getMore !== 'function') { url = "http://bodyflight.arcanel.se/history.html"; VideoRepo.getMore = function (foo) { var i; firstTimestamp = ''; lastTimestamp = ''; return JSON.stringify(foo); }; } }());
"use strict"; var WebSocketServer = require('websocket').server; var http = require('http'); var GamesManagement = require('./lib/GamesManagement'); var server = http.createServer(function (request, response) { }); server.listen(8000, function () { console.log('Listening on port ' + server.address().port); }); var wsServer = new WebSocketServer({ httpServer: server }), gamesManagement = new GamesManagement(); // WebSocket server wsServer.on('request', function (request) { var connection = request.accept(null, request.origin); var key = gamesManagement.addConnection(connection); connection.on('message', function (message) { if (message.type === 'utf8') { console.log(message, key); gamesManagement.processMessage(message, key); } }); connection.on('close', function (connection) { gamesManagement.removeConnection(key); }); });
import React from 'react'; import AuthenticatedLayout from '@/components/AuthenticatedLayout'; import illustration from '@/icons/Home/illustration.jpg'; import Image from 'next/image'; import withAuth from '@/core/utils/protectedRoute'; const AuthenticatedHomePage = () => { return ( <AuthenticatedLayout> <section> <div className='flex p-4 flex-row gap-4 self-stretch rounded-lg border border-gray-100 bg-white mt-6 mx-12 '> <div className='flex flex-col items-start gap-4'> <div className='flex items-center pt-12 w-303 h-92 '> <div className=' flex items-center justify-center border border-gray-100 ' style={{ width: '303px', height: '92px' }}> Welcome to AirQo Analytics </div> </div> </div> <div className='flex flex-1 flex-col items-start justify-end'> <div className='flex items-start ml-auto '> <Image src={illustration} alt='Home' width='450px' height='216px' /> </div> </div> </div> </section> </AuthenticatedLayout> ); }; export default withAuth(AuthenticatedHomePage);
$(document).ready(function(){ // console.log("ready!"); }) var imagen=false; var texto=false; var dibujo=0; var canvas; jQuery(function($){ canvas = new fabric.Canvas('c'); var context = canvas.getContext('2d'); $("#addImage").click(function(){ var url = $("#urls").val(); fabric.Image.fromURL(""+url+"", function(img){ var imaeegn = img; imagen=true; canvas.add(img); }); $("#urls").val(""); // var imageUrl = $("#urls").val(); // // // Define // canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), { // // Optionally add an opacity lvl to the image // backgroundImageOpacity: 0.5, // // should the image be resized to fit the container? // backgroundImageStretch: false // }); }); $("#texto").click(function(){ text = new fabric.Text($("#txt").val(), { left: 100, top: 100 }); canvas.add(text); texto=true; $("#txt").val(""); }); var click=0; $("#dibujar").click(function(imaeegn,text){ if (click==0) { $("#dibujar").css({"background-color":"#CCCCCB"}); click=1; lienzo(); }else if(click==1){ $("#dibujar").css({"background-color":"#E8E8E6"}); click=0; lienzo(); } }); }); function lienzo(){ $(function () { if(dibujo==0){ canvas.backgroundColor = 'white'; canvas.isDrawingMode= 1; canvas.freeDrawingBrush.color = "black"; canvas.freeDrawingBrush.width = 5; canvas.renderAll(); dibujo=1; }else { canvas.isDrawingMode= 0; dibujo=0; } }); } function color(id){ // console.log(id); canvas.freeDrawingBrush.color = id; } function tam(value){ // console.log(value); canvas.freeDrawingBrush.width = value; } function download() { var download = document.getElementById("download"); var image = document.getElementById("c").toDataURL("image/png") .replace("image/png", "image/octet-stream"); download.setAttribute("href", image); // download.setAttribute("download","MRH.png"); } // _canvasObject= new fabric.Canvas('c'); // function dataURLtoBlob(dataurl) { // var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], // bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); // while(n--){ // u8arr[n] = bstr.charCodeAt(n); // } // return new Blob([u8arr], {type:mime}); // } // // function download(){ // var link = document.createElement("a"); // var imgData = _canvasObject.toDataURL({ format: 'png', // multiplier: 4}); // var strDataURI = imgData.substr(22, imgData.length); // var blob = dataURLtoBlob(imgData); // var objurl = URL.createObjectURL(blob); // // link.download = "MRh.png"; // // link.href = objurl; // // link.click(); // }
/*jshint node:true */ module.exports = function( grunt ) { var Path = require('path'); grunt.loadNpmTasks( 'grunt-webpack' ); grunt.loadNpmTasks( 'grunt-contrib-uglify' ); grunt.loadNpmTasks( 'grunt-header' ); grunt.loadNpmTasks( 'grunt-replace' ); grunt.loadNpmTasks( 'grunt-closure-compiler' ); const banner = [ '/*!', ' * <%= pkg.name %> <%= pkg.version %>', ' * <%= pkg.repository.url %>', ' */\n' ].join('\n'); grunt.initConfig({ pkg: require('./package.json') , webpack: { dist: { // webpack options entry: './src/index.js' , output: { path: 'dist/' , filename: 'jquery.dgtable.js' , library: 'DGTable' , libraryTarget: 'umd' } , module: { loaders: [ { test: /\.js$/ , exclude: /(node_modules|bower_components)/ , loader: 'babel' , query: { sourceMap: false , presets: ['es2015'] , plugins: [ 'transform-es3-member-expression-literals' , 'transform-es3-property-literals' , 'transform-merge-sibling-variables' , 'transform-object-assign' , 'transform-property-literals' , 'transform-remove-debugger' , 'transform-es2015-modules-commonjs' ] , compact: false } } ] } , externals: { 'jquery': { commonjs: 'jquery' , commonjs2: 'jquery' , amd: 'jquery' , root: 'jQuery' } } } } , replace: { dist: { options: { patterns: [ { match: 'VERSION', replacement: require('./package.json').version }, { match: /return __webpack_require__\(0\)/g, replacement: 'return __webpack_require__(0).default' } ] }, files: [ { expand: true, flatten: true, src: ['dist/jquery.dgtable.js'], dest: 'dist/'} ] } } , uglify: { dist: { files: { 'dist/jquery.dgtable.min.js': ['dist/jquery.dgtable.js'] } } } , 'closure-compiler': { 'dist': { js: 'dist/jquery.dgtable.js' , jsOutputFile: 'dist/jquery.dgtable.min.js' , noreport: true , maxBuffer: 500 , closurePath: 'closure-compiler' , options: { compilation_level: 'ADVANCED_OPTIMIZATIONS' , language_in: 'ECMASCRIPT5_STRICT' , externs: [ 'closure-compiler/externs/jquery-1.9.externs' , 'closure-compiler/externs/underscore-1.5.2.externs' , 'closure-compiler/externs/backbone-1.1.0.externs' ] , create_source_map: 'dist/jquery.dgtable.min.js.map' , source_map_format: 'V3' } } } , 'add-map-directive': { 'dist': { paths: 'dist/jquery.dgtable.min.js' } } , 'clean-source-map-paths': { 'dist': { paths: 'dist/jquery.dgtable.min.js.map' } } , header: { dist: { options: { text: banner }, files: { 'dist/jquery.dgtable.js': 'dist/jquery.dgtable.js' , 'dist/jquery.dgtable.min.js': 'dist/jquery.dgtable.min.js' } } } }); grunt.registerMultiTask('add-map-directive', 'Append source-map directive to output file', function() { var paths = grunt.file.expand(this.data.paths); paths.forEach(function(path) { grunt.file.write(path, grunt.file.read(path) + '//# sourceMappingURL=DGTable.min.js.map'); }); }); grunt.registerMultiTask('clean-source-map-paths', 'Fix source map paths', function() { var paths = grunt.file.expand(this.data.paths); paths.forEach(function(path) { var map = JSON.parse(grunt.file.read(path)); map.file = Path.basename(map.file); map.sources = map.sources.map(x => Path.basename(x)); grunt.file.write(path, JSON.stringify(map)); }); }); grunt.registerTask( 'compile-with-closure', [ 'closure-compiler', 'add-map-directive', 'clean-source-map-paths' ] ); grunt.registerTask( 'build', [ 'webpack:dist', 'replace:dist', 'uglify:dist', 'header:dist' ] ); grunt.registerTask( 'default', [ 'build' ] ); };
import React from 'react'; import { Container } from 'react-bootstrap'; import Slot from './Slot'; function SlotDetails({slots}) { if(slots != undefined && slots.length != 0) { return ( <div className="container py-5"> <h2 className="text-center">Available Slots</h2> { slots && slots.map((slt, key) => { return ( <Slot key={key} {...slt}/> ) }) } </div> ) } else if(slots != undefined && slots.length == 0) { return ( <h3 className="mt-4 text-center">No Slots Available</h3> ) } else { return ( null ) } } export default SlotDetails
const User = require('../models/user'); const Car = require('../models/car'); exports.get_cars = async (req, res, next) => { const cars = await Car.find({}); res.status(200).json(cars); }; exports.create_car = async (req, res, next) => { console.log(req.value); // Find Seller const user = await User.findById(req.value.body.seller); // Create Car const carData = req.value.body; delete carData.seller; const car = await Car.create({ ...carData, seller: user }); // Add new car to seller user.cars.push(car); await user.save(); res.status(201).json(car); }; exports.get_car = async (req, res, next) => { const { carId } = req.value.params; const car = await Car.findById(carId); res.status(200).json(car); }; exports.replace_car = async (req, res, next) => { const { carId } = req.value.params; const carData = req.value.body; await Car.findByIdAndUpdate(carId, carData); const updatedCar = await Car.findById(carId); res.status(200).json(updatedCar); }; exports.update_car = async (req, res, next) => { const { carId } = req.value.params; const carData = req.value.body; await Car.findByIdAndUpdate(carId, carData); const updatedCar = await Car.findById(carId); res.status(200).json(updatedCar); }; exports.delete_car = async (req, res, next) => { const { carId } = req.value.params; // Get car const car = await Car.findById(carId); if (!car) return res.status(404).json({ error: `Car doesn't exist` }); // Get seller const sellerId = car.seller; const seller = await User.findById(sellerId); // Remove car and remove from user cars list car.remove(); seller.cars.pull(car); await seller.save(); res.status(200).json({ success: true }); };
const NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: './frontend/js/index.js', output: { filename: './server/public/js/index.js' }, devtool: 'source-map', watch: (NODE_ENV === 'development' ? true : false) };
import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; /** * Компонент "Погода" */ function Weather({ forecast, icon, link, temp }) { return ( <div> <a href={link}> <img src={icon} alt="" /> {temp} {forecast.map(f => ( <Fragment key={f}> <span>{f}</span><br /> </Fragment> ))} </a> </div> ); } Weather.propTypes = { /** Прогноз погоды */ forecast: PropTypes.arrayOf(PropTypes.string).isRequired, /** Иконка текущей погоды */ icon: PropTypes.string.isRequired, /** Текущая температура */ temp: PropTypes.string.isRequired, /** Ссылка на прогноз погоды */ link: PropTypes.string.isRequired }; export default Weather;
'use strict' require('shelljs/global') global.config.silent = true const errorExit = require('../helper/error_exit') const Lint = require('../helper/lint') const isMatch = require('../helper/is_match') const findIgnoreFiles = require('../helper/find_ignore_files') const readPkg = require('../helper/read_pkg') const fs = require('fs') if (!which('git')) { errorExit('Sorry, this script requires git') } let root = exec('git rev-parse --show-toplevel') /** * git 和 eslint 环境检测 */ let rootPath, eslintPath if (root.code === 0) { rootPath = root.stdout.replace('\n', '') } else { errorExit('no git res') } const PACKAGE = readPkg(rootPath) eslintPath = `${rootPath}/node_modules/.bin/eslint` try { fs.statSync(eslintPath) } catch (e) { errorExit('请安装并配置好eslint') } /** * 获取待lint的文件和被忽略的文件 * @type {any} */ let lintFiles = exec('git diff --cached --name-only --diff-filter=ACM') .grep(/\.js$|vue$/).stdout let ignoreFiles = findIgnoreFiles(rootPath) ignoreFiles.push('.eslintrc.js') let lintFileList = lintFiles .split('\n') .filter(file => file !== '' && !isMatch(file, ignoreFiles)) /** * 从package.json内读取配置信息 */ let pkgMode = PACKAGE.config && PACKAGE.config.lint && PACKAGE.config.lint.mode let lint = new Lint(lintFileList, Lint.MODE_MAP[pkgMode] || Lint.MODE_MAP.strict) let pass = lint.exec() if (!pass) { errorExit('you may not pass lint, error show above!') } else { echo('eslint pass!') }
$(document).ready(function() { function addPrototype(container, index) { container.append(container.attr('data-prototype') .replace(/__name__label__/g, 'Spécificité n°' + (index+1)) .replace(/__name__/g, index)); } function addSpecificity(container, index) { addPrototype(container, index); formatSpecificity(index); } function formatSpecificity(index) { if(index > 0) { $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index).prepend('<hr />'); } $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index).prev().hide(); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_title').parent().addClass('row form-group'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_title').prev().wrap('<div class="col-sm-3 control-label"></div>'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_title').wrap('<div class="col-sm-9"></div>'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_title').addClass('form-control'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_description').parent().addClass('row form-group'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_description').prev().wrap('<div class="col-sm-3 control-label"></div>'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_description').wrap('<div class="col-sm-9"></div>'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_description').addClass('form-control'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_levelMin').parent().addClass('row form-group'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_levelMin').prev().wrap('<div class="col-sm-3 control-label"></div>'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_levelMin').wrap('<div class="col-sm-8"></div>'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_levelMin').addClass('form-control'); $('#dndrules_classdndbundle_classspecificities_classSpecificities_' + index + '_levelMin').parent().parent().append('' + '<div class="col-sm-1">' + ' <button class="btn btn-warning" type="button" id="remove-'+index+'"><i class="fa fa-remove"></i></button>' + '</div>'); $('#remove-'+index).on('click', function() { $(this).parent().parent().parent().remove(); }); } var container = $('#dndrules_classdndbundle_classspecificities_classSpecificities'); //$('#dndrules_classdndbundle_classspecificities_classSpecificities').prev().hide(); var index = container.children().length; if(index > 0) { $.each(container.children(), function() { formatSpecificity($(this).index()); }); } $('#dndrules_classdndbundle_classspecificities_classSpecificities').before('' + '<div class="text-right">' + ' <button type="button" class="btn btn-primary" id="addSpecificity"><i class="fa fa-plus"></i></button>' + '</div>'); $('#addSpecificity').on('click', function() {addSpecificity(container, index); index++;}); });
/** * @fileOverview View methods for the use case "update person" * @authors Gerd Wagner & Juan-Francisco Reyes */ /*************************************************************** Import classes, datatypes and utility procedures ***************************************************************/ import { db } from "../../c/initialize.mjs"; import { fillSelectWithOptions, createChoiceWidget, displaySegmentFields, undisplayAllSegmentFields, fillSelectWithOptionsClub, createMultiSelectionWidget } from "../../../lib/util.mjs"; import Person, { GenderEL, PersonTypeEL } from "../../m/Person.mjs"; import Player from "../../m/Player.mjs"; import FootballAssociation from "../../m/FootballAssociation.mjs"; import FootballClub from "../../m/FootballClub.mjs"; import Member from "../../m/Member.mjs"; import Coach from "../../m/Coach.mjs"; import President from "../../m/President.mjs"; /*************************************************************** Load data ***************************************************************/ const personRecords = await Person.retrieveAll(); /*************************************************************** Declare variables for accessing UI elements ***************************************************************/ const formEl = document.forms["Person"], submitButton = formEl["commit"], selectPersonEl = formEl.selectPerson, typeFieldsetEl = formEl.querySelector("fieldset[data-bind='type']"), genderFieldsetEl = formEl.querySelector("fieldset[data-bind='gender']"), assoClubsUpWidget = formEl.querySelector(".MultiSelectionWidgetClub"), assoAssociationsUpWidget = formEl.querySelector(".MultiSelectionWidgetAsso"); let selectClubPlayerEl = formEl.selectClubPlayer, selectClubCoachEl = formEl.selectClubCoach, selectAssoPresidentEl = formEl.selectAssoPresident; formEl.reset(); /*************************************************************** Initialize subscription to DB-UI synchronization ***************************************************************/ let cancelSyncDBwithUI = null; /*************************************************************** Set up selection lists and widgets ***************************************************************/ // set up the person selection list fillSelectWithOptions( selectPersonEl, personRecords, {valueProp:"personId", displayProp:"name"}); undisplayAllSegmentFields( formEl, PersonTypeEL.labels); // load all football association records const associationRecords = await FootballAssociation.retrieveAll(); createMultiSelectionWidget( assoClubsUpWidget, [], "upAssoClubs", "Enter ID", 0); createMultiSelectionWidget( assoAssociationsUpWidget, [], "upAssoAssociations", "Enter ID", 0); // for type 'Player' (associated clubs) fillSelectWithOptionsClub( selectClubPlayerEl, await FootballClub.retrieveAll().then(value=>value), "clubId", "name"); // for type 'Coach' (associated clubs) fillSelectWithOptionsClub( selectClubCoachEl, await FootballClub.retrieveAll("clubId").then(value=>value), "clubId", "name"); // for type 'President' (associated associations) for (const associationRec of associationRecords) { const optionEl = document.createElement("option"); optionEl.text = associationRec.name; optionEl.value = associationRec.assoId; selectAssoPresidentEl.add( optionEl, null); } // when a person is selected, fill the form with its data selectPersonEl.addEventListener("change", async function () { const personId = selectPersonEl.value; if (personId) { // retrieve up-to-date person record const personRec = await Person.retrieve( personId); formEl.personId.value = personRec.personId; formEl.name.value = personRec.name; formEl.dateOfBirth.value = personRec.dateOfBirth; // set up the gender radio button group createChoiceWidget( genderFieldsetEl, "gender", [personRec.gender], "radio", GenderEL.labels); // set up the type check box createChoiceWidget( typeFieldsetEl, "type", personRec.type, "checkbox", PersonTypeEL.labels); typeFieldsetEl.addEventListener("change", handleTypeSelectChangeEvent); if (personRec.type.length > 0) { for (const v of personRec.type) { displaySegmentFields( formEl, PersonTypeEL.labels, parseInt(v)); if (v === PersonTypeEL.MEMBER) { const assoClubs = await Member.retrieve(personId).then(value => value.assoClubs); const assoAssociations = await Member.retrieve(personId).then(value => value.assoAssociations); if (typeof assoClubs !== 'undefined') { createMultiSelectionWidget(assoClubsUpWidget, assoClubs, "upAssoClubs", "Enter ID", 0); } if (typeof assoAssociations !== 'undefined') { createMultiSelectionWidget(assoAssociationsUpWidget, assoAssociations, "upAssoAssociations", "Enter ID", 0); } } else if (v === PersonTypeEL.PLAYER) { const playerRetrieveCheck = (await db.collection("players").doc( personId) .withConverter( Player.converter).get()).data(); if (typeof playerRetrieveCheck !== 'undefined') { selectClubPlayerEl.value = await Player.retrieve(personId).then(value => value.assoClub); } } else if (v === PersonTypeEL.COACH) { const coachRetrieveCheck = (await db.collection("coaches").doc( personId) .withConverter( Coach.converter).get()).data(); if (coachRetrieveCheck !== 'undefined') { selectClubCoachEl.value = await Coach.retrieve(personId).then(value => value.assoClub); } } else if (v === PersonTypeEL.PRESIDENT) { const presidentRetrieveCheck = (await db.collection("presidents").doc( personId) .withConverter( President.converter).get()).data(); if (presidentRetrieveCheck !== 'undefined') { selectAssoPresidentEl.value = await President.retrieve(personId).then(value => value.assoAssociation); } } } } else { undisplayAllSegmentFields( formEl, PersonTypeEL.labels); } } else { formEl.reset(); typeFieldsetEl.innerHTML = ""; } }); async function handleTypeSelectChangeEvent(e) { const formEl = e.currentTarget.form, selectedValues = []; var checkboxes = document.getElementsByName("type"); for (let i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { selectedValues.push(i); if (i === ((PersonTypeEL.MEMBER) - 1)) { } else if (i === ((PersonTypeEL.PLAYER) - 1)) { formEl.selectClubPlayer.addEventListener("change", function () { formEl.selectClubPlayer.setCustomValidity( (formEl.selectClubPlayer.value.length > 0) ? "" : "No associated club selected!" ); }); } else if (i === ((PersonTypeEL.COACH) - 1)) { formEl.selectClubCoach.addEventListener("change", function () { formEl.selectClubCoach.setCustomValidity( (formEl.selectClubCoach.value.length > 0) ? "" : "No associated club selected!" ); }); // formEl.selectClubCoach.addEventListener("input", function () { // formEl.selectClubCoach.setCustomValidity( // Coach.checkAssoClub(formEl.selectClubCoach.value).message); // }); } else if (i === ((PersonTypeEL.PRESIDENT) - 1)) { formEl.selectAssoPresident.addEventListener("change", function () { formEl.selectAssoPresident.setCustomValidity( (formEl.selectAssoPresident.value.length > 0) ? "" : "No associated association selected!" ); }); // formEl.selectAssoPresident.addEventListener("input", function () { // formEl.selectAssoPresident.setCustomValidity( // President.checkAssoAssociation(formEl.selectAssoPresident.value).message); // }); } } } if (selectedValues.length > 0) { for (const v of selectedValues) { displaySegmentFields(formEl, PersonTypeEL.labels, parseInt(v + 1)); } } else { undisplayAllSegmentFields(formEl, PersonTypeEL.labels); } } // set up listener to document changes on selected person record selectPersonEl.addEventListener("change", async function () { cancelSyncDBwithUI = await Person.syncDBwithUI( selectPersonEl.value); }); /*************************************************************** Add event listeners for responsive validation ***************************************************************/ formEl.name.addEventListener("input", function () { formEl.name.setCustomValidity( Person.checkName( formEl.name.value).message); }); formEl.dateOfBirth.addEventListener("input", function () { formEl.dateOfBirth.setCustomValidity( Person.checkDateOfBirth( formEl.dateOfBirth.value).message); }); genderFieldsetEl.addEventListener("change", function () { genderFieldsetEl.setCustomValidity( (!genderFieldsetEl.value) ? "A gender must be selected!":"" ); }); typeFieldsetEl.addEventListener("click", function () { const val = typeFieldsetEl.getAttribute("data-value"); formEl.type[0].setCustomValidity( (!val || Array.isArray(val) && val.length === 0) ? "At least one type form must be selected!":"" ); }); /****************************************************************** Add further event listeners, especially for the save/delete button ******************************************************************/ // Set an event handler for the submit/save button submitButton.addEventListener("click", handleSubmitButtonClickEvent); // neutralize the submit event formEl.addEventListener( "submit", function (e) { e.preventDefault(); }); // Set event cancel of DB-UI sync when the browser window/tab is closed window.addEventListener("beforeunload", function () { cancelSyncDBwithUI; }); async function handleSubmitButtonClickEvent() { const formEl = document.forms['Person'], selectPersonEl = formEl.selectPerson, personId = selectPersonEl.value, assoClubsListEl = assoClubsUpWidget.querySelector("ul"), assoAssociationsListEl = assoAssociationsUpWidget.querySelector("ul"); if (!personId) return; const slots = { personId: formEl.personId.value, name: formEl.name.value, dateOfBirth: formEl.dateOfBirth.value, gender: genderFieldsetEl.getAttribute("data-value"), type: JSON.parse(typeFieldsetEl.getAttribute("data-value")) }; // set error messages in case of constraint violations formEl.name.setCustomValidity(Person.checkName(slots.name).message); formEl.dateOfBirth.setCustomValidity(Person.checkDateOfBirth(slots.dateOfBirth).message); formEl.gender[0].setCustomValidity(Person.checkGender(slots.gender).message); formEl.type[0].setCustomValidity(Person.checkTypes(slots.type).message); if (formEl.checkValidity()) { await Person.update(slots); } if (slots.type) { // check type and save association entities depending on types if (slots.type.includes(PersonTypeEL.MEMBER)) { const assoClubIdRefsToAdd = [], assoClubIdRefsToRemove = []; for (const assoClubItemEl of assoClubsListEl.children) { if (assoClubItemEl.classList.contains("removed")) { assoClubIdRefsToRemove.push(assoClubItemEl.getAttribute("data-value")); } if (assoClubItemEl.classList.contains("added")) { assoClubIdRefsToAdd.push(assoClubItemEl.getAttribute("data-value")); } } // if the add/remove list is non-empty, create a corresponding slot if (assoClubIdRefsToRemove.length > 0) { slots.assoClubIdRefsToRemove = assoClubIdRefsToRemove; } if (assoClubIdRefsToAdd.length > 0) { slots.assoClubIdRefsToAdd = assoClubIdRefsToAdd; } if (slots.assoClubIdRefsToAdd) { for (const ac of slots.assoClubIdRefsToAdd) { let responseValidation = await Member.checkAssoClub( ac); if (responseValidation.message !== "") { formEl["upAssoClubs"].setCustomValidity( responseValidation.message); break; } else formEl["upAssoClubs"].setCustomValidity(""); } } // construct assoAssociationIdRefs-ToAdd/ToRemove lists const assoAssociationIdRefsToAdd = [], assoAssociationIdRefsToRemove = []; for (const assoAssociationItemEl of assoAssociationsListEl.children) { if (assoAssociationItemEl.classList.contains("removed")) { assoAssociationIdRefsToRemove.push(assoAssociationItemEl.getAttribute("data-value")); } if (assoAssociationItemEl.classList.contains("added")) { assoAssociationIdRefsToAdd.push(assoAssociationItemEl.getAttribute("data-value")); } } // if the add/remove list is non-empty, create a corresponding slot if (assoAssociationIdRefsToRemove.length > 0) { slots.assoAssociationIdRefsToRemove = assoAssociationIdRefsToRemove; } if (assoAssociationIdRefsToAdd.length > 0) { slots.assoAssociationIdRefsToAdd = assoAssociationIdRefsToAdd; } if (slots.assoAssociationIdRefsToAdd) { for (const aa of slots.assoAssociationIdRefsToAdd) { let responseValidation = await Member.checkAssoAssociation( aa); if (responseValidation.message !== "") { formEl["upAssoAssociations"].setCustomValidity( responseValidation.message); break; } else formEl["upAssoAssociations"].setCustomValidity(""); } } if (formEl.checkValidity()) { const memberExistCheck = (await db.collection("members").doc( personId) .withConverter( Member.converter).get()).data(); if (typeof memberExistCheck === 'undefined') { await Member.add(slots); } else { await Member.update(slots); } assoClubsListEl.innerHTML = ""; assoAssociationsListEl.innerHTML = ""; } } else { const memberExistCheck = (await db.collection("members").doc( personId) .withConverter( Member.converter).get()).data(); if (typeof memberExistCheck !== 'undefined') { await Member.destroy(personId); } } if (slots.type.includes(PersonTypeEL.PLAYER)) { formEl.selectClubPlayer.setCustomValidity( (formEl.selectClubPlayer.value.length > 0) ? "" : "No associated club selected!" ); if (formEl.checkValidity()) { const playerExistCheck = (await db.collection("players").doc( personId) .withConverter( Member.converter).get()).data(); slots.assoClub_id = parseInt(formEl.selectClubPlayer.value); if (typeof playerExistCheck === 'undefined') { await Player.add(slots); } else { await Player.update(slots); } } } else { const playerRetrieveCheck = (await db.collection("players").doc( personId) .withConverter( Member.converter).get()).data(); if (playerRetrieveCheck) { await Player.destroy(personId); } } if (slots.type.includes(PersonTypeEL.COACH)) { formEl.selectClubCoach.setCustomValidity( formEl.selectClubCoach.value.length > 0 ? "" : "No associated club selected!" ); if (formEl.checkValidity()) { const coachExistCheck = (await db.collection("coaches").doc( personId) .withConverter( Member.converter).get()).data(); slots.assoClub_id = parseInt(formEl.selectClubCoach.value); if (typeof coachExistCheck === 'undefined') { await Coach.add(slots); } else { await Coach.update(slots); } } } else { const coachRetrieveCheck = (await db.collection("coaches").doc( personId) .withConverter( Member.converter).get()).data(); if (coachRetrieveCheck) { await Coach.destroy(personId); } } if (slots.type.includes(PersonTypeEL.PRESIDENT)) { formEl.selectAssoPresident.setCustomValidity( formEl.selectAssoPresident.value.length > 0 ? "" : "No associated association selected!" ); if (formEl.checkValidity()) { // const presidentExistCheck = await President.retrieve(personId); const presidentExistCheck = (await db.collection("presidents").doc( personId) .withConverter( Member.converter).get()).data(); slots.assoAssociation_id = parseInt(formEl.selectAssoPresident.value); if (typeof presidentExistCheck ==='undefined') { await President.add(slots); } else { await President.update(slots); } } } else { // const presidentRetrieveCheck = await President.retrieve(personId); const presidentRetrieveCheck = (await db.collection("presidents").doc( personId) .withConverter( Member.converter).get()).data(); if (presidentRetrieveCheck) { await President.destroy(personId); } } } if (formEl.checkValidity()) { await Person.update(slots); // update the selection list option selectPersonEl.options[selectPersonEl.selectedIndex].text = slots.name; undisplayAllSegmentFields( formEl, PersonTypeEL.labels); formEl.reset(); } }
$(document).ready(function(){ $(".js-basket_top_button").click(function(){ if ($("body").width() > 880){ if ($(".sub_basket").hasClass("openned")) { $(".sub_basket").toggleClass("openned"); setTimeout(function(){ $(".sub_basket").toggle("fast"); },200); }else{ closeBasket(); } return false; } }); function closeBasket(){ $(".sub_basket").toggle("fast"); setTimeout(function(){ $(".sub_basket").toggleClass("openned"); },200); } /* $(document).on('click', function(e) { if (!$(e.target).closest(".sub_basket").length && document.querySelector('.sub_basket').classList.contains('openned')) { closeBasket(); } e.stopPropagation(); });*/ //добавление элемента LITE $(".js-add_lite").click(function(){ if (!$(this).hasClass("disabled")){ $(".page_buy_p_lite_elements").append('<div class="page_buy_p_lite_element new"><div class="page_buy_p_lite_element_content"><div class="page_buy_p_lite_element_name">РЕДАКЦИЯ<span>LITE</span></div><div class="page_buy_p_lite_element_description">Статичная редакция с ограниченным функционалом</div><div class="page_buy_p_lite_element_price rub">8 000</div><div class="page_buy_p_lite_element_button"><div class="page_buy_button btn_n" onclick="to_basket(this);">В Корзину</div></div></div></div>'); $(".page_buy_p_lite_elements .page_buy_p_lite_element.new").toggle('fast').removeClass("new"); scale_price(); } }); //js input_range $(".input_range").each(function(i,n){ let min = $(this).find('input').attr('min'); let max = $(this).find('input').attr('max'); $(this).find('.min').text(min); $(this).find('.max').text(max); }); setInterval(function(){ $(".input_range").each(function(i,n){ let min = $(this).find('input').attr('min'); let max = $(this).find('input').attr('max'); let val = $(this).find('input').val(); let percent = 100 / (Number(max)-1) * (Number(val)-1); $(this).find('.val').text(val); $(this).find('.val').css("left",percent+"%"); }); },66); ///скрипты вывода таба по ралиокнопке/ЛК $(".js-tab_inputs input, .tab_nav_element").change(function(){ if ($(".page_basket_personal_info_type_tab.active").length > 0){ if ($(".page_basket_personal_info_type_tab.active").attr("data-target") != $(this).val()){ $(".page_basket_personal_info_type_tab.active").toggle("fast"); $(".page_basket_personal_info_type_tab.active").removeClass("active"); $(".page_basket_personal_info_type_tab[data-target='"+$(this).val()+"']").toggle("fast"); $(".page_basket_personal_info_type_tab[data-target='"+$(this).val()+"']").addClass("active"); } }else{ $(".page_basket_personal_info_type_tab[data-target='"+$(this).val()+"']").toggle("fast"); $(".page_basket_personal_info_type_tab[data-target='"+$(this).val()+"']").addClass("active"); } }); $(".tab_nav_element:not(.link)").click(function(){ $(".tab_nav_element.active").removeClass("active"); $(this).addClass("active"); if ($(".page_basket_personal_info_type_tab.active").length > 0){ if ($(".page_basket_personal_info_type_tab.active").attr("data-target") != $(this).attr("data-target")){ $(".page_basket_personal_info_type_tab.active").toggle("fast"); $(".page_basket_personal_info_type_tab.active").removeClass("active"); $(".page_basket_personal_info_type_tab[data-target='"+$(this).attr("data-target")+"']").toggle("fast"); $(".page_basket_personal_info_type_tab[data-target='"+$(this).attr("data-target")+"']").addClass("active"); } }else{ $(".page_basket_personal_info_type_tab[data-target='"+$(this).attr("data-target")+"']").toggle("fast"); $(".page_basket_personal_info_type_tab[data-target='"+$(this).attr("data-target")+"']").addClass("active"); } }); }); function to_basket(d_this,parent){ if (!$(d_this).hasClass("disabled") && !$(d_this).hasClass("solid")){ let for_main = $(d_this).parent().parent(); if (!parent){ for_main = for_main.parent(); } $(d_this).addClass("solid").text("В корзине"); for_main.addClass("in_basket"); if (!parent){ $(d_this).parent().append('<a href="javascript:void(0);" class="page_buy_delete_basket" onclick="cancle_buy(this);">убрать из корзины</a>'); }else{ $(d_this).parent().append('<a href="javascript:void(0);" class="page_buy_delete_basket" onclick="cancle_buy(this,true);">убрать из корзины</a>'); } scale_price(); } } function cancle_buy(d_this,parent = false){ let for_button = $(d_this).parent().find(".btn_n"); let for_main = $(d_this).parent().parent(); if (!parent){ for_main = for_main.parent(); } for_button.removeClass("solid").text("В корзину"); for_main.removeClass("in_basket"); $(d_this).remove(); scale_price(); } function scale_price(){ //lite if ($(".page_buy_p_lite_elements .page_buy_p_lite_element").length > $(".page_buy_p_lite_elements .page_buy_p_lite_element.in_basket").length){ $(".js-add_lite").addClass("disabled"); }else{ $(".js-add_lite").removeClass("disabled"); } //pro //update if ($(".page_buy_p_updates_elements .page_buy_p_total_element.in_basket").length > 0){ $(".page_buy_p_updates_elements .btn_n:not('.solid')").addClass("disabled"); }else{ $(".page_buy_p_updates_elements .btn_n").removeClass("disabled"); } }
import {omit} from 'lodash' import {UserAccountRepository} from '../repository' import {makeFindAllHandler, makeFindById, makeHandlePost, makeHandleArchive, makeHandleRestore} from './StandardController' import {entityFromBody} from '../middlewares/entityFromBody' import {accountSchema, newAccountSchema} from '../../modules/accounts/schema' import bcrypt from 'bcryptjs' import {boolean, Schema, string} from 'sapin' import {parseFilters, parsePagination, requiresRole} from '../middlewares' import ROLES from '../../modules/accounts/roles' const ACCEPTED_SORT_PARAMS = ['fullName'] const OMITED_FIELDS = ['passwordHash'] const filtersSchema = new Schema({ contains: string, isArchived: boolean }) const hashPassword = (req, res, next) => { const password = req.entity.password if (password && password.length > 0) { bcrypt.hash(password, 8) .then(hashedPassword => { req.entity = omit(req.entity, ['password', 'confirmPassword']) req.entity.passwordHash = hashedPassword next() }) } else { req.entity = omit(req.entity, ['password', 'confirmPassword']) next() } } const updateAccount = (req, res, next) => { const repo = new UserAccountRepository(req.database) repo.findById(req.entity.id) .then(function (entity) { if (entity) { entity.firstName = req.entity.firstName entity.lastName = req.entity.lastName entity.roles = req.entity.roles entity.organismRole = req.entity.organismRole entity.modifiedOn = new Date() if (req.entity.passwordHash) { entity.passwordHash = req.entity.passwordHash } return repo.update(entity) .then(function () { const ret = omit(entity, 'passwordHash') res.result = ret // return untransformed entity so id is used instead of _id next() }) .catch(next) } else { next({httpStatus: 404, message: 'entity not found'}) } }) .catch(next) } export default (router) => { router.use('/accounts', requiresRole(ROLES.usersManager, false)) router.route('/accounts') .get([ parsePagination(ACCEPTED_SORT_PARAMS), parseFilters(filtersSchema), makeFindAllHandler(UserAccountRepository, OMITED_FIELDS) ]) .post([ entityFromBody(newAccountSchema), hashPassword, makeHandlePost(UserAccountRepository) ]) router.route('/accounts/archive') .post(makeHandleArchive(UserAccountRepository)) router.route('/accounts/restore') .post(makeHandleRestore(UserAccountRepository)) router.route('/accounts/:id') .get(makeFindById(UserAccountRepository, OMITED_FIELDS)) .put([ entityFromBody(accountSchema), hashPassword, updateAccount ]) }
import React from "react"; import ChatUser from "./ChatUser"; class ChatUserList extends React.Component{ render(){ return ( <div className="user-list"> <ul> <h3>Users</h3> {this.props.users.map((user,index) => { return <ChatUser key={index} username={user.username} /> }) } </ul> </div> ); } } export default ChatUserList;
//利用縮寫表示法建立變數 //方法1 let price = 5; let quantity = 14; let total = price * quantity; //方法2 let price, quantity,total; price = 5; quantity = 14; total = price * quantity; //方法3 let price = 5,quantity=14; let total = price*quantity; //方法4 let el = document.getElementById('cost'); el.textContent = '$' + total;
import React from 'react'; import cover from '../../assets/cover.jpg'; export default function Banner() { return ( <div> <img src={cover} alt='' style={{ position: 'fixed', width: '100%', height: '100%', objectFit: 'cover', }} /> </div> ) }
import { combineReducers } from 'redux'; import gameStateReducer from './gameState'; const rootReducer = combineReducers({ game: gameStateReducer }); export default rootReducer;
'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const pingMiddleware = require('./middleware/ping'); const assetsMiddleware = require('./middleware/assets'); const indexPageMiddleware = require('./middleware/index-page'); const notFoundMiddleware = require('./middleware/not-found'); const errorMiddleware = require('./middleware/error'); const api = require('./api'); const app = express(); const mainRouter = new express.Router(); mainRouter .get('/ping', pingMiddleware) .use('/build', assetsMiddleware) .use(bodyParser.json()) .use('/api', api.getRouter()) .get('/*', indexPageMiddleware) .use(notFoundMiddleware) .use(errorMiddleware); app .use(mainRouter); module.exports = app;
// "Lucky Wheel" //Structure containing "Event label", number export const BinomialVariable = { eventTab : ["C'est la crise, les prix des installations augmentent de 25%", "Tata Monique est passé te voir ce WE, tu commences avec 100 pièces de plus !", "Les banques, ce n'est plus ce que c'était, tu as 50 pièces de moins pour débuter!", "T'as rien gagné, mais t'as rien perdu", "Braderie générale, toutes les installations à -30% !", "On m'annonce à l'oreillette qu'il va pleuvoir aujourd'hui", "Merveilleux temps pour toute la durée de la partie !", "On ne peut pas toujours gagner quelque-chose", "Malheureusement, tu vas devoir fermer plus tôt aujourd'hui", "Ton fournisseur t'as fait une fleur et a garanti une réinstallation en cas de panne pour chaque bâtiment"], n : 9 , // eventTab.size() p : 0, //probability chosen => it will be redefine } // return an array with the probability of each event function probability(n,p) { var tab = [] for (let k=0; k<=n; ++k) { tab.push(k_parmi_n(k,n) * Math.pow(p,k) * Math.pow(1-p,n-k)) } return tab } function factorielle(n) { if (n==0 || n==1) return 1 for (let i=0; i<n; i++) { return n*factorielle(n-1) } } function k_parmi_n(k,n) { if (k == n || k ==0) { return 1 } return factorielle(n)/(factorielle(k)* factorielle(n-k) ) } //return the range of the event export function findEventBinom(n,p) { let tab = probability(n,p) const t = Math.random() // return a pseudo random number between [0,1] let k=0 let proba = tab[0] // tab of proba value in BinomialVariable while (proba < t) { k++ proba += tab[k] } return k==9 ? k-1 : k } //Weather period //Here we'll X^r ~ B(1/r, 1) --> Density graph ~ decresed line // a>0, b>0, r>0 to respect the condition // faire B(a,b) ==> b>1 // alpha =1 bêta = 1 export function Beta(a, b ,r) { var t = Math.random() //return a number between [a,b] ** r var x = a + (b - a)* Math.pow(t,r) // (a^1/r + (b^1/r-a^1/r)t)^r return x } /* gamma (1, lambda) ~ exp param lambda => -(1/lambda) * Math.log(t), t ~ U([0,1]) gamma ( alpha , lambda) = sum alpha fois (-(1/lambda) * Math.log(t)) Beta (alpha, beta ) ~ X / (X + Y) , X ~ G(alpha, lamda), Y ~ G(beta, lamda) Beta(alpha, beta) = (sum (alpha times) (-(1/lambda) * Math.log(t))) / sum (alpha + beta times) (-(1/lambda) * Math.log(t)) */ export function Beta2(a, b, alpha, beta) { const gammaX = gamma(alpha, 1) const gammaY = gamma(beta, 1) const f = gammaX / (gammaX + gammaY) //return a number between [a,b] ** r return a + (b-a) * f } export function gamma(alpha,lambda) { let t=0 let sumExp = 0 for (let i = 0; i <alpha; i++ ) { t = Math.random(); sumExp += Math.log(t) } return -lambda * sumExp } //Number of visitors //--> Value of lambda is the average number of the visitor //poisson //1 st Modelise a variable dependent of a exponential law //U de loi uniforme sur [0,1]. Alors X = -1/lambda * ln(U) export function Poisson(lambda = 0) { //Lambda the parameter of Poisson law is the average number of visitors /*let lambda = 0 if (weather == "sun") lambda = 25 else if (weather == "clouds") lambda = 15 else if (weather == "rain") lambda = 5 else throw console.error("weather is not correctly defined")*/ //simulation of poisson law let t = Math.random() // return a pseudo random number between [0,1] let ExpSum = (-1/lambda) * Math.log(t) let k=0 while (ExpSum <=1) { t = Math.random() // return a pseudo random number between [0,1] ExpSum += (-1/lambda) * Math.log(t) k++ } return k-1 } //Broken or not Broken //Bernoulli // p is the "durability attribut" of the tested installation // t is a value randomly chosen in [0,1] export function isBroken(p) { const t= Math.random() // return a pseudo random number between [0,1] // if t<=p, the machine continue to work if (t<=p) return false // t>p the machine is broken else return true } // exports.default = { // BinomLaw() { // findEventBinom() // } // }
const initialState = { allAlgorithmList: [], ownedAlgorithmList: [], }; const algoReducer = (state = initialState, action) => { switch (action.type) { case 'RESET': console.log(state); return initialState; case 'GET_OWNED_ALGORITHM': return {...state, ownedAlgorithmList: action.data}; case 'GET_ALL_ALGORITHM': return {...state, allAlgorithmList: action.data}; case 'DELETE_ALGORITHM': const deletedAlgorithmList = state.ownedAlgorithmList.filter( (algo) => algo.id !== action.data, ); return {...state, ownedAlgorithmList: deletedAlgorithmList}; default: break; } return state; }; export default algoReducer;
var request = require("request") var express = require("express") var app = express() var LIFX_TOKEN='adbadbadbadbadbabdabdabdbad4adbadbadbadbadbabdbadbabdabdbadbabdb'; var HUE_TOKEN='adbadbadbadbadbabdabdab'; var HUE_IP="192.168.0.100"; app.get("/", function (req, res) { res.send("Hello World!") }) app.get("/do", function (req, res) { var action = req.query.action; console.log("action received: ",action); if (action == "party") { request({uri:"http://192.168.0.107/power/on"}); request({ uri:"https://api.lifx.com/v1/lights/all/state", method:"PUT", headers: { "Authorization":"Bearer "+LIFX_TOKEN }, body: JSON.stringify({"color":"purple"}), }); request({ uri: "http://"+HUE_IP+"/api/"+HUE_TOKEN+"/lights/3/state", method: "PUT", body: JSON.stringify({"on":true,"sat":254,"bri":254,"hue":52792}), }); } res.send("OK") }) app.listen(3000, function () { console.log("Example app listening on port 3000!") })
// @flow strict import * as React from 'react'; import { View, Platform } from 'react-native'; import { Translation } from '@kiwicom/mobile-localization'; import { StyleSheet, TextIcon, Touchable } from '@kiwicom/mobile-shared'; import { defaultTokens } from '@kiwicom/mobile-orbit'; type Props = {| +passengerFullName: string, +onPress: () => void, +disabled?: boolean, +passengerSubtitle?: React.Node, +menuRightContent?: React.Node, |}; const PassengerMenuItem = (props: Props) => { const disabled = props.disabled ?? false; const passengerSubtitle = props.passengerSubtitle ?? null; const menuRightContent = props.menuRightContent ?? null; return ( <Touchable onPress={props.onPress} disabled={disabled}> <View style={styles.container}> <View> <Translation passThrough={props.passengerFullName} /> {passengerSubtitle} </View> <View style={styles.rightContent}> {menuRightContent} {Platform.select({ android: null, ios: disabled === false && ( <TextIcon code="&#xe01F;" style={styles.icon} /> ), })} </View> </View> </Touchable> ); }; export default PassengerMenuItem; const styles = StyleSheet.create({ container: { flexDirection: 'row', padding: 15, justifyContent: 'space-between', alignItems: 'center', }, rightContent: { flexDirection: 'row', alignItems: 'center', }, icon: { fontSize: 26, color: defaultTokens.paletteProductNormal, }, });
var searchData= [ ['updatechecker',['updateChecker',['../classams_1_1update_checker.html',1,'ams']]], ['userinterface',['UserInterface',['../classams_1_1_user_interface.html',1,'ams']]] ];
import React,{Component,PropTypes} from 'react'; import {Table} from 'antd'; export default class MyTable extends Component{ static propTypes = { dataSource: PropTypes.array, columns: PropTypes.array, getTableData: PropTypes.func, count: PropTypes.number, }; constructor(props){ super(props); this.state = { pageSize: 5, current: 1, }; } componentWillMount(){ this.props.getTableData(1,this.state.pageSize); } onChange = (page, pageSize)=>{ console.log('分页变化', page, pageSize); this.props.getTableData(page, pageSize); this.setState({ current: page, }); }; onShowSizeChange = (current, size)=>{ console.log('每页数目的变化', current, size); this.setState({ pageSize: size, current: 1, }); this.props.getTableData(1,size); }; render(){ let {dataSource,columns,count,...others} = this.props; return ( <Table {...others} dataSource={dataSource} columns={columns} pagination={{ current: this.state.current, total:count, showSizeChanger:true, showQuickJumper: true, hideOnSinglePage: true, pageSize: this.state.pageSize, pageSizeOptions: ['5','10','15'], onChange:this.onChange, onShowSizeChange: this.onShowSizeChange }} > </Table> ); } }
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import Vant from 'vant' import 'vant/lib/index.css' import FormBuilder from 'element-form-builder' /* eslint-disable */ Vue.config.productionTip = false const templates = require.context('./components/', true, /\.vue/); templates.keys().forEach(fileName => { const reqCom = templates(fileName) const reqComNames = fileName.split('/') const reqComName = fileName.split('/')[reqComNames.length - 1] const realName = reqComName.split('.')[0] Vue.component(realName, reqCom.default || reqCom) }) Vue.use(ElementUI) Vue.use(Vant) Vue.use(FormBuilder) new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
/// <reference types="cypress" /> describe('Navigate to a product detail', () => { it('Opens the first product detail page', () => { cy.request('https://fakestoreapi.com/products') cy.visit('http://localhost:3000') cy.contains(/Fjallraven/i).click() cy.get('h1').should('have.text', 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops') cy.contains('p', 'Price: 109.95') }) it('Back to home page from the detail page', () => { cy.request('https://fakestoreapi.com/products') cy.visit('http://localhost:3000') cy.contains(/Fjallraven/i).click() cy.get('h1').should('have.text', 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops') cy.contains(/Home/i).click() cy.get('h1').should('have.text', 'Amazing products') }) })
import React from 'react'; import {Link} from "react-router-dom"; import { Switch,Route,browserHistory, IndexRoute,BrowserRouter as Router ,HashRouter} from 'react-router-dom'; // import logo from './logo.svg'; import './App.css'; import Home from "./home.js"; import About from "./about.js"; import Contact from "./contact.js"; // import Main from "./routes.js" // const Main = () => ( // <main> // <Switch> // <Route exact path='/' component={Home}/> // <Route path='/about' component={About}/> // <Route path='/contact' component={Contact}/> // </Switch> // </main> // ) class App extends React.Component { render() { return ( <div className="App" > {/*<div className = "App-header" > <img src = { logo } className = "App-logo" alt = "logo" / > <h2> Welcome to React </h2> </div> <p className = "App-intro" >To get started, edit <code> src / App.js </code> and save to reload. </p>*/ } <div> <ul> <li><Link to="/home">Home</Link></li> <li><Link to="/nested">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/contact">Contact</Link></li> </ul> <div> <h1>Hello World</h1> {this.props.children} </div> </div> </div> ); } } export default App;
$(document).ready(function () { $('.flatpickr').flatpickr(); $('.tip').tipr({ 'mode': 'above' }); $('.image').MyFadeOverImage({ normalAlpha:0.9, hoverAlpha: 2, normalToneColor:"#000", }); $("#sticker").sticky({topSpacing:0}); $('.main-carousel').flickity({ // options cellAlign: 'center', contain: true }); $('#showModalButton').on('click', function() { $('#modal').removeClass('hidden'); }) $('#closeButton').on('click', function() { $('#modal').addClass('hidden'); }) });
// React imports import React from 'react' // File imports import { Button } from './Button' import '../../App.css' import './WelcomeSection.css' function WelcomeSection() { return ( <div className='hero-container'> <h1>Adventure Awaits</h1> <p>What are you waiting for?</p> <div className='hero-btns'> <Button path='/sign-up' className='btns' buttonStyle='btn--outline' buttonSize='btn--large'> Get Started Today </Button> </div> <div className='hero-btns'> <Button path={{pathname: 'https://www.youtube.com/watch?v=zJCrrTk-dLQ'}} className='btns' buttonStyle='btn--primary' buttonSize='btn--large'> Watch Trailer <i className='far fa-play-circle' /> </Button> </div> </div> ); } export default WelcomeSection;
import CrudLayout from "./CrudLayout"; export {CrudLayout} export default CrudLayout
(function () { var timeElement, eventTime, currentTime, duration, interval, intervalId; interval = 1000; // 1 second // get time element timeElement = document.getElementById("day"); // calculate difference between two times eventTime = moment.tz("2040-11-15T09:00:00", "America/Los_Angeles"); // based on time set in user's computer time / OS currentTime = moment.tz(); // get duration between two times duration = moment.duration(eventTime.diff(currentTime)); // loop to countdown every 1 second setInterval(function() { // get updated duration duration = moment.duration(duration - interval, 'milliseconds'); // if duration is >= 0 if (duration.asSeconds() <= 0) { clearInterval(intervalId); // hide the countdown element timeElement.classList.add("hidden"); } else { // otherwise, show the updated countdown timeElement.innerText = duration.days(); } }, interval); }()); (function () { var timeElement, eventTime, currentTime, duration, interval, intervalId; interval = 1000; // 1 second // get time element timeElement = document.getElementById("hour"); // calculate difference between two times eventTime = moment.tz("2040-11-15T09:00:00", "America/Los_Angeles"); // based on time set in user's computer time / OS currentTime = moment.tz(); // get duration between two times duration = moment.duration(eventTime.diff(currentTime)); // loop to countdown every 1 second setInterval(function() { // get updated duration duration = moment.duration(duration - interval, 'milliseconds'); // if duration is >= 0 if (duration.asSeconds() <= 0) { clearInterval(intervalId); // hide the countdown element timeElement.classList.add("hidden"); } else { // otherwise, show the updated countdown timeElement.innerText = duration.hours(); } }, interval); }()); (function () { var timeElement, eventTime, currentTime, duration, interval, intervalId; interval = 1000; // 1 second // get time element timeElement = document.getElementById("min"); // calculate difference between two times eventTime = moment.tz("2040-11-15T09:00:00", "America/Los_Angeles"); // based on time set in user's computer time / OS currentTime = moment.tz(); // get duration between two times duration = moment.duration(eventTime.diff(currentTime)); // loop to countdown every 1 second setInterval(function() { // get updated duration duration = moment.duration(duration - interval, 'milliseconds'); // if duration is >= 0 if (duration.asSeconds() <= 0) { clearInterval(intervalId); // hide the countdown element timeElement.classList.add("hidden"); } else { // otherwise, show the updated countdown timeElement.innerText = duration.minutes(); } }, interval); }()); (function () { var timeElement, eventTime, currentTime, duration, interval, intervalId; interval = 1000; // 1 second // get time element timeElement = document.getElementById("sec"); // calculate difference between two times eventTime = moment.tz("2040-11-15T09:00:00", "America/Los_Angeles"); // based on time set in user's computer time / OS currentTime = moment.tz(); // get duration between two times duration = moment.duration(eventTime.diff(currentTime)); // loop to countdown every 1 second setInterval(function() { // get updated duration duration = moment.duration(duration - interval, 'milliseconds'); // if duration is >= 0 if (duration.asSeconds() <= 0) { clearInterval(intervalId); // hide the countdown element timeElement.classList.add("hidden"); } else { // otherwise, show the updated countdown timeElement.innerText = duration.seconds(); } }, interval); }());
import jsonp from 'js/jsonp' import {recommendParams,ERR_OK} from './config' export const getRank = () => { const url ='https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg'; const data = Object.assign({},recommendParams,{ g_tk: 1928093487, uin: 0, needNewCode: 1, platform: 'h5' }); return jsonp(url,data,{ param: 'jsonpCallback' }).then(res => { if(res.code === ERR_OK) { return res.data.topList; } throw new Error('没有获取到排行榜数据'); }).catch(err => { if(err) { console.log('获取排行数据错误' + err); } }) }
export default class Filter { constructor() { } invert(pixelsArray) { for (let x = 0, lenX = pixelsArray.length; x < len; x += 1) { for (let y = 0, lenY = pixelsArray[x].length; y < lenY; y += 1) { let pixel = pixelsArray[x][y]; pixel.Red = 255 - Pixel.Red; pixel.Green = 255 - Pixel.Green; pixel.Blue = 255 - Pixel.Blue; pixel.Alpha = 255; } } } }
'use strict'; var http = require('http'); var Dawgs = require('./dawgs.js'); var route = require('./route.js'); var dawgs = new Dawgs('/dawgs'); var server = http.createServer(function (req, res) { route.processRoute(req, res, dawgs); }); server.listen(3000, function () { console.log('listening on port 3000...'); }); module.exports = server;
// Generated by CoffeeScript 1.6.3 var BuildTask, ExpectedError, Future, mkdirp, path, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; path = require('path'); mkdirp = require('mkdirp'); Future = require('../../utils/Future'); ExpectedError = (function(_super) { __extends(ExpectedError, _super); ExpectedError.prototype.name = 'ExpectedError'; function ExpectedError(underlyingError) { this.underlyingError = underlyingError; this.underlyingError = underlyingError; ExpectedError.__super__.constructor.call(this, this.underlyingError.message, this.underlyingError.id); } return ExpectedError; })(Error); BuildTask = (function() { /* Base class for all build tasks. @abstract */ BuildTask.ExpectedError = ExpectedError; BuildTask.prototype.readyPromise = null; function BuildTask(params) { this.params = params; this.readyPromise = Future.single(); } BuildTask.prototype.run = function() { /* Actual task executor. Should be implemented in concrete task class. readyPromise must be completed here. */ throw new Error('BuildTask.run() method must be overriden by concrete task!'); }; BuildTask.prototype.ready = function() { return this.readyPromise; }; return BuildTask; })(); module.exports = BuildTask;
/*import { reducer as sematable } from 'sematable';*/ import { combineReducers } from 'redux'; import { GET_STUDENTS, GET_REQUEST, GET_DATA_SUCCESS, GET_DATA_ERROR, GET_LUK_CURRICULUM_SUCCESS, GET_CURRICULUM_GROUP_SUCCESS } from '../actions/actions.js'; function students (state = [], action) { switch (action.type) { case "GET_REQUEST": console.log('reducer got request'); return state; case "GET_DATA_SUCCESS": console.log('reducer got success'); console.log(action.data.students); return { students: action.data.students }; default: console.log('reducer got default'); return state; } } function lukCurriculum (state = [], action) { switch (action.type) { case "GET_LUK_CURRICULUM_SUCCESS": console.log('success in getting curriculum'); console.log(action.data); return { lukCurriculum: action.data }; default: console.log('reducer got default'); return state; } } function curriculumGroup (state = [], action) { switch (action.type) { case "GET_CURRICULUM_GROUP_SUCCESS": console.log('success in getting curriculumGroup'); console.log(action.data); return { groupList: action.data }; default: console.log('curriculum group reducer got default action'); return state; } } const studentModule = combineReducers({ lukCurriculum, students, curriculumGroup }); export default studentModule;
/* ** http-proxy-simple -- Simple HTTP proxy, allowing protocol and payload interception ** Copyright (c) 2013-2019 Dr. Ralf S. Engelschall <rse@engelschall.com> ** ** Permission is hereby granted, free of charge, to any person obtaining ** a copy of this software and associated documentation files (the ** "Software"), to deal in the Software without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Software, and to ** permit persons to whom the Software is furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be included ** in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* load Node module requirements (built-in) */ /* global require: true */ var os = require("os"); var fs = require("fs"); var path = require("path"); var url = require("url"); var http = require("http"); var events = require("events"); /* load Node module requirements (external) */ var req = require("request"); /* export the API */ /* global module: true */ module.exports = { createProxyServer: function (opts) { /* prepare settings */ opts = opts || {}; var serverHost = opts.host || "127.0.0.1"; var serverPort = parseInt(opts.port, 10) || 3128; var serverName = opts.servername || os.hostname(); var proxy = opts.proxy || ""; /* determine service identifier */ var id = opts.id; if (typeof id === "undefined" || (id + "").match(/^[a-zA-Z0-9_-]+\/[0-9](?:\.[0-9])*$/) === null) { /* global __dirname: true */ var pjson = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf8")); id = pjson.name + "/" + pjson.version; } /* create event emitting proxy object */ var proxyserver = new events.EventEmitter(); /* helper function: emit event or run fallback action */ var emitOrRun = function (eventName, callback) { if (!proxyserver.listeners(eventName).length) callback(); else { var args = Array.prototype.slice.call(arguments, 2); args.unshift(eventName); proxyserver.emit.apply(proxyserver, args); } }; /* create HTTP server */ var httpServer = http.createServer(function (request, response) { /* determine connection id */ var cid = request.connection.remoteAddress + ":" + request.connection.remotePort; /* for interception ensure there is no compression */ request.headers["accept-encoding"] = "identity"; delete request.headers["proxy-connection"]; /* provide forwarding information (1/2) */ var clientIp = request.connection.remoteAddress; if (request.headers["x-forwarded-for"]) request.headers["x-forwarded-for"] += ", " + clientIp; else request.headers["x-forwarded-for"] = clientIp; request.headers["forwarded-for"] = request.headers["x-forwarded-for"]; /* provide forwarding information (2/2) */ request.headers.via = request.httpVersion + " " + serverName; var localAddr = request.connection.address(); if (localAddr !== null) request.headers.via += ":" + request.connection.address().port; request.headers.via += " (" + id + ")"; /* assemble request information */ var remoteRequest = { url: request.url, method: request.method, headers: request.headers, body: request.body, followRedirect: false, encoding: null }; if (proxy !== "") { var hostname = url.parse(remoteRequest.url).hostname; if (hostname !== "localhost" && hostname !== "127.0.0.1") remoteRequest.proxy = proxy; } /* helper function for fixing the upper/lower cases of headers */ var fixHeaderCase = function (headers) { var result = {}; for (var key in headers) { if (!headers.hasOwnProperty(key)) continue; var newKey = key.split("-") .map(function(token) { return token[0].toUpperCase() + token.slice(1); }) .join("-"); result[newKey] = headers[key]; } return result; }; /* perform the HTTP client request */ var performRequest = function (remoteRequest) { /* adjust headers */ remoteRequest.headers = fixHeaderCase(remoteRequest.headers); try { req(remoteRequest, function (error, remoteResponse, remoteResponseBody) { /* perform the HTTP client response */ if (error) { proxyserver.emit("http-error", cid, error, request, response); response.writeHead(400, {}); response.end(); } else { var performResponse = function (remoteResponse, remoteResponseBody) { response.writeHead(remoteResponse.statusCode, remoteResponse.headers); response.write(remoteResponseBody); response.end(); }; emitOrRun("http-intercept-response", function () { performResponse(remoteResponse, remoteResponseBody); }, cid, request, response, remoteResponse, remoteResponseBody, performResponse); } }); } catch (error) { proxyserver.emit("http-error", cid, error, request, response); response.writeHead(400, {}); response.end(); } }; emitOrRun("http-intercept-request", function () { performRequest(remoteRequest); }, cid, request, response, remoteRequest, performRequest); }); /* react upon HTTP server events */ httpServer.on("connection", function (socket) { var cid = socket.remoteAddress + ":" + socket.remotePort; proxyserver.emit("connection-open", cid, socket); socket.on("close", function (had_error) { proxyserver.emit("connection-close", cid, socket, had_error); }); socket.on("error", function (error) { proxyserver.emit("connection-error", cid, socket, error); }); }); httpServer.on("clientError", function () { /* already handled above on socket directly */ }); httpServer.on("request", function (request, response) { if (typeof request.connection.remoteAddress === "undefined" || typeof request.connection.remotePort === "undefined" ) return; var cid = request.connection.remoteAddress + ":" + request.connection.remotePort; proxyserver.emit("http-request", cid, request, response); }); httpServer.on("connect", function (request, socket) { var cid = request.connection.remoteAddress + ":" + request.connection.remotePort; proxyserver.emit("http-error", cid, "CONNECT method not supported", request, socket); }); httpServer.on("upgrade", function (request, socket) { var cid = request.connection.remoteAddress + ":" + request.connection.remotePort; proxyserver.emit("http-error", cid, "protocol upgrade not supported", request, socket); }); /* listen for connections */ httpServer.listen(serverPort, serverHost); return proxyserver; } };
let generateResponse = (error, message, status, data) => { let apiResponse = { error: error, message: message, status: status, data: data }; return apiResponse; } module.exports = { generate: generateResponse }
// ==UserScript== // @version 3.02 // @name MyEpisodes Enhanced // @description Adds download links, a progress bar, season premiere alerts, better searching, and a whole lot of customization to MyEpisodes.com // @include *://*myepisodes.com/* // @exclude *://*myepisodes.com/forum* // @exclude *://dev.myepisodes.com* // @require https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js // @grant GM_getValue // @grant GM_setValue // @grant GM_listValues // @grant GM_xmlhttpRequest // ==/UserScript== var isNow = new Date() if (GM_getValue("settings", "")==""){//initial setup of the script GM_setValue("settings", '1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~#a0c0ff~~#60ffc0~~1~~s(S)e(E) / (F)~~http://en.wikipedia.org/wiki/Special:Search?search=list+of+SHOWNAME+episodes~~1~~1~~1~~~~15~~1~~-720p -1080p~~1~~1~~') GM_setValue("gmdate", isNow.getDate()) GM_setValue("UseCache", false) GM_setValue("UseProgCache", false) GM_setValue("chFilter", "") GM_setValue("searchBuddy", "") } else { if (GM_getValue("gmdate") != isNow.getDate()){ //first website load of the day GM_setValue("gmdate", isNow.getDate()) isRefresh = false //this is just because I decided to abbreviate Comedy Central between v3 and 3.01. This will be removed in the next update if (GM_getValue("tvRage").match(";;Comedy Central;;")){ GM_setValue("tvRage", GM_getValue("tvRage").replace(/;;Comedy Central;;/g, ';;Com. Central;;')) } if (GM_getValue("chFilter").match(";Comedy Central;")){ GM_setValue("chFilter", GM_getValue("chFilter").replace(/;Comedy Central;/g, ';Com. Central;')) } } else{ isRefresh = true } } //parse out the settings settingsArr = GM_getValue("settings").split('~~') pAlert = Boolean(Number(settingsArr[0]));uAlert = Boolean(Number(settingsArr[1]));ukAlert = Boolean(Number(settingsArr[2]));caAlert = Boolean(Number(settingsArr[3])); auAlert = Boolean(Number(settingsArr[4]));anim = Boolean(Number(settingsArr[5]));award = Boolean(Number(settingsArr[6]));docu = Boolean(Number(settingsArr[7])); game = Boolean(Number(settingsArr[8]));mini = Boolean(Number(settingsArr[9]));news = Boolean(Number(settingsArr[10]));real = Boolean(Number(settingsArr[11])); scrip = Boolean(Number(settingsArr[12]));sport = Boolean(Number(settingsArr[13]));talk = Boolean(Number(settingsArr[14]));variy = Boolean(Number(settingsArr[15])); hColor = settingsArr[16];pColor = settingsArr[17];countdown = Boolean(Number(settingsArr[18]));namer = settingsArr[19];hLink = settingsArr[20]; nzbOld = Boolean(Number(settingsArr[21]));nzbTod = Boolean(Number(settingsArr[22]));nzbdl = Boolean(Number(settingsArr[23]));nzbUrl = settingsArr[24]; nzbMrkOld = Number(settingsArr[25]);nzbMrk = Boolean(Number(settingsArr[26]));nzbdf = settingsArr[27];torOld = Boolean(Number(settingsArr[28])); torTod = Boolean(Number(settingsArr[29]));torUrl = settingsArr[30]; //add the configuration Screen configScreen = document.createElement('div') configScreen.style.display = "none" configScreen.id = 'configScreen' configScreen.innerHTML = "<br><br>" + '<div style="height:416px;border:1px solid black;float:left;padding:5px">' + '<div>' + '<h2 style="background-color:#CCC;text-align:center;border-bottom:1px solid black">My List Settings</h2>' + '<p><input type="checkbox" id="pAlert"> Season premiere alert header</p>' + '<p><input type="checkbox" id="countdown"> Enable episode countdown</p>' + '<p style="border-top:1px solid red">Highlight color for season premieres</p>' + '<input type="text" id="hColor" style="width:50px">(hex color only)' + '<p style="border-top:1px solid red">Highlight color for series premieres</p>' + '<input type="text" id="pColor" style="width:50px">(hex color only)' + '<p style="border-top:1px solid red">Naming format of the progress bar.<br>' + '(s)=season#, (e)=episode#, (f)=finale#.<br>' + 'Use caps to add a leading zero</p>' + '<input type="text" id="namer" style="width:180px" value="' + namer + '">' + '<p style="border-top:1px solid red">Hyperlink embedded in the progress bar<br>' + 'Use variables:<br>SHOWNAME SEASON EPISODE</p>' + '<input type="text" id="hLink" style="width:180px" value="' + hLink + '">' + '</div>' + '</div>' + '<div style="height:416px;border:1px solid black;float: left;margin-left:5px;padding:5px">' + '<h2 style="background-color:#CCC;text-align:center;border-bottom:1px solid black">TVRage Series Premieres</h2>' + '<p style="font-weight:bold">Get shows from which countries</p>' + '<table>' + '<tr>' + '<td style="padding-left:5px" width="55px">US</td>' + '<td style="padding-left:5px" width="55px">UK</td>' + '<td style="padding-left:5px" width="55px">Canada</td>' + '<td style="padding-left:5px" width="55px">Australia</td>' + '</tr>' + '<tr>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="uAlert"></td>' + '<td><input type="checkbox" id="ukAlert"></td>' + '<td><input type="checkbox" id="caAlert"></td>' + '<td><input type="checkbox" id="auAlert"></td>' + '</tr>' + '</table>' + '<div style="float:left;display:inline">' + '<p style="font-weight:bold">Types of shows I want</p>' + '<table style="margin-top:-8px">' + '<tbody>' + '<tr>' + '<td><input type="checkbox" id="anim"></td>' + '<td>Animated</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="award"></td>' + '<td>Award Shows</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="docu"></td>' + '<td>Documentary</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="game"></td>' + '<td>Game Show</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="mini"></td>' + '<td>Mini-Series</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="news"></td>' + '<td>News</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="real"></td>' + '<td>Reality Shows</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="scrip"></td>' + '<td>Scripted</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="sport"></td>' + '<td>Sports</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="talk"></td>' + '<td>Talk Shows</td>' + '</tr>' + '<tr>' + '<td><input type="checkbox" id="variy"></td>' + '<td>Variety Shows</td>' + '</tr>' + '</tbody>' + '</table>' + '</div>' + '<div style="float:right; display:inline; margin-left: 20px; width:130px">' + '<p style="font-weight:bold">Blocked Channels</p>' + '<select id="channelFilterList" multiple="multiple" size="16" style="width:130px;height:238px;margin-top:-3px"></select>' + '<input id="removeSelBtn" type="button" disabled="true" value="Unblock Selected" style="margin-left:12px;margin-top:2px">' + '</div>' + '</div>' + '<div style="height:416px;border:1px solid black;float:left;margin-left:5px;padding:5px">' + '<h2 style="background-color:#CCC;text-align:center;border-bottom:1px solid black">Downloads</h2>' + '<div style="float:left;border-right:1px solid grey">' + '<h2 style="text-align:center">NZB</h2>' + '<p><input type="checkbox" id="nzbTod">Add links for today</p>' + '<p><input type="checkbox" id="nzbOld">Add links for the past</p>' + '<div id="hasNzbDownloads">' + "<p>Age considered 'the past' (days)?</p>" + '<input type="number" id="nzbMrkOld" style="width:40px" value="' + nzbMrkOld + '">' + '<p><input type="checkbox" id="nzbdl">Enable Bulk Download</p>' + '<p><input type="checkbox" id="nzbMrk">Mark acquired when NZB found</p>' + '<p style="border-top:1px solid red">Use a different NZB source<br>' + 'SHOWNAME SEASON EPISODE</p>' + '<p><input type="text" id="nzbUrl" style="width:165px" value="' + nzbUrl + '"></p>' + '<p style="border-top:1px solid red">NZB download filter</p>' + '<p><input type="text" id="nzbdf" style="width:165px" value="' + nzbdf + '"></p>' + '</div>' + '</div>' + '<div style="float:left;padding-left:5px">' + '<h2 style="text-align:center">TOR</h2>' + '<p><input type="checkbox" id="torTod">Add links for today</p>' + '<p><input type="checkbox" id="torOld">Add links for the past</p>' + '<div id="hasTorDownloads">' + '<p style="border-top:1px solid red">Use a different Torrent source<br>' + 'SHOWNAME SEASON EPISODE</p>' + '<p><input type="text" id="torUrl" style="width:165px" value="' + torUrl + '"></p>' + '</div>' + '</div>' + '</div>' + '<div style="text-align: center;padding-top:15px;clear:both">' + "<input type='button' name='Restore the default settings (doesn't affect Blocked Channels)' id='restoreDefault' style='width:70px;background-color: #a0c0ff; border-radius:10px; cursor:pointer;' value='Restore'>" + '<input type="button" name="Save settings and refresh page" id="saveReload" style="width:70px;background-color: #a0c0ff; border-radius:10px; cursor:pointer; margin-left:15px" value="Save">' + '<input type="button" name="Discard any changes made" id="cancelSettings" style="width:70px;background-color: #a0c0ff; border-radius:10px; cursor:pointer; margin-left:15px" value="Cancel">' + '</div>' $('#divContainer').parent().prepend(configScreen); $('#cancelSettings').click(function(){ //cancel and exit settings toggleConfig() }) $('#restoreDefault').click(function(){ //restore defaults restoreDefault() }) $('#saveReload').click(function(){ //save button saveReload() }) $('#channelFilterList').click(function(){ //enable remove selected button when clicking on filtered channel list $('#removeSelBtn').removeAttr("disabled") }) $('#removeSelBtn').click(function(){ //remove selected items from list $("#channelFilterList option:selected").remove(); }) $('#hColor').keyup(function(){//checks if text is a hex color. if it is, changes background color if ((this.value.length==3 || this.value.length==6) && /^#/.test(this.value)==false){ this.value = "#" + this.value } if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(this.value) && this.value!=$(this).css('background-color')){ if(this.value=="#000"){ $(this).css('color','white') } else{ $(this).css('color','black') } $(this).css('background-color',this.value) } }) $('#pColor').keyup(function(){//checks if text is a hex color. if it is, changes background color if ((this.value.length==3 || this.value.length==6) && /^#/.test(this.value)==false){ this.value = "#" + this.value } if (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(this.value) && this.value!=$(this).css('background-color')){ if(this.value=="#000"){ $(this).css('color','white') } else{ $(this).css('color','black') } $(this).css('background-color',this.value) } }) $('#nzbTod').click(function(){ showNzbSettings() }) $('#nzbOld').click(function(){ showNzbSettings() }) $('#torTod').click(function(){ showTorSettings() }) $('#torOld').click(function(){ showTorSettings() }) //add User Config button, search bar and Status List link extraLine = document.createElement('div'); extraLine.setAttribute("style", "padding-top:3px;") extraLine.innerHTML = '<b>&nbsp;&nbsp;<a href="http://www.myepisodes.com/shows.php?type=list" style="font-size:11px; color: #054f5c; font-family: Tahoma; text-decoration: none" >Status List</a></b>' configButton = document.createElement('input'); configButton.setAttribute('type','button'); configButton.setAttribute('id','configButton') configButton.setAttribute('style','float:right; background-color: #a0c0ff; border-radius:5px; cursor:pointer') configButton.setAttribute('value','MyEpisodes Enhanced Config'); configButton.addEventListener('click',toggleConfig,true); extraLine.appendChild(configButton) $('#menuText').css('white-Space', 'no-wrap'); $('#menuText').append('<form style="float:right" action="search.php" method="POST"><input type="text" style="width:178px;border-width: 1px;border-style:solid;border-color: black" autocomplete="off" name="tvshow" tabindex="1" id="r"></form>') $('#menuText').after(extraLine); $('#r').parent().submit(function(){ $(this).attr('id','q') GM_setValue("searchBuddy", $(this).children().val() + ";;" + '0') }) /*****************************END OF USER CONFIG CODE*****************************/ //resize the layout to accomodate all the extra data $('#divContainer').attr('id','divContainers') $('td:eq(0)').width(0) $('td:last').width(0) $('td:eq(1)').width('900px') rageCount = 0 if (!uAlert){rageCount = rageCount+1} if (!ukAlert){rageCount = rageCount+1} if (!caAlert){rageCount = rageCount+1} if (!auAlert){rageCount = rageCount+1} classFliter = "" if (anim){classFliter=classFliter + "A"} if (award){classFliter=classFliter + 'W'} if (docu){classFliter=classFliter + 'D'} if (game){classFliter=classFliter + 'G'} if (mini){classFliter=classFliter + 'M'} if (news){classFliter=classFliter + 'N'} if (real){classFliter=classFliter + 'R'} if (scrip){classFliter=classFliter + 'S'} if (sport){classFliter=classFliter + 'P'} if (talk){classFliter=classFliter + "T"} if (variy){classFliter=classFliter + "V"} if (nzbOld || nzbTod){hasNzb = true} else{hasNzb = false} if (torOld || torTod){hasTor = true} else{hasTor = false} nzbdf = nzbdf.replace(/ /g, "+"); var myMonth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] var idList = new Array myURL = window.location.href if (myURL.match(/.*epsbyshow.*/)){ //working on the individual show pages //add the header for data pulled from tvrage tvRageShowHeader = document.createElement('div') tvRageShowHeader.setAttribute('style', 'border-bottom:1px solid grey;border-right:1px solid grey;width:100%;height:auto;margin:-12px 0px 5px 0px;display:none') tvRageShowHeader.setAttribute('id', 'tvRageShowHeader') addShowHeader($('.flatbutton:eq(0)').attr('href')) $('.pageheader').after(tvRageShowHeader) if($('.flatButton:eq(0)').attr('value') != 'Add Show'){ $('.pageheader').html(function(){ //Change the old header to the show name $(this).children().remove() newHeaderImg = document.createElement('div') newHeaderImg.setAttribute('style', 'width:60px;height:32px;background-image:url("img/header_episodes_by_show.jpg")') newHeader = document.createElement('div') newHeader.setAttribute('style', 'position:relative;top:-30px;width:100%;color:#799BA5;font-size:200%;text-align:center;font-weight:bold') newHeader.innerHTML = $('.flatbutton:eq(0)').text() $(this).append(newHeaderImg) $(this).append(newHeader) }) //formatting and adding year/day of the week to airdate $('.date').html(function(index, oldhtml){ if ($(this).text() != "Unknown"){ myDate = cleanDate($(this).html()) d = new Date(myDate) myDate = d.toDateString().replace(/^(.*?) (.*) (.*)/, "$1, $2, $3") myDate = oldhtml.replace(/(.*)>.*?</, "$1>" + myDate + "<") $(this).html(myDate) } }); $('.date').css('text-align', 'left'); $('.showname').css('text-align', 'center'); $('.longnumber').attr('width', '6%'); $('.longnumber').css('text-align', 'left'); if ($("th.season").length > 1){ //create the reverse season order button newDiv = document.createElement("div") newDiv.setAttribute('style','float: right') revOrder = document.createElement('input'); revOrder.setAttribute('type','button'); revOrder.setAttribute('id','revOrder') revOrder.setAttribute('title',"This will disable 'Save Status'") revOrder.setAttribute('style','background-color: #DADADA; border: 1px solid gray; text-align:center; float:right; margin-bottom: 5px') revOrder.setAttribute('value','Reverse Season Order'); newDiv.appendChild(revOrder) revOrder.addEventListener('click',reverse,true); $(".mylist").before(newDiv) for (i=6; i<$("th.season").length+6; i++){ //the header looks better red $("tbody tr.header:eq(" + i + ")").css('color', 'red'); } } } } //Episodes List only d = new Date(); if (myURL.match(/views.php$/) || myURL.match(/views.php.$/) || myURL.match(/views.php..$/)){ //add new Series table, and run function to find upcoming series premieres from TVRage if (uAlert || ukAlert || caAlert || auAlert){ var tvRageHeader = document.createElement('table'); tvRageHeader.setAttribute('id', 'newSeriesList'); tvRageHeader.setAttribute('width', '50%'); tvRageHeader.setAttribute('align', 'left'); tvRageHeader.setAttribute('style', 'text-align: center; padding:2px') tvRageHeader.setAttribute('cellspacing', "0") tvRageHeader.innerHTML = '<tbody id="tvRageHeader"><tr><td colspan="6" nowrap style="cursor:pointer;background-color: #CCC"><a>Upcoming Series Premieres (from TVRage)<span id="tvRageCount"></span></a></td></tr></tbody>' tvRageList = document.createElement('tbody'); tvRageList.setAttribute('id', 'tvRageList'); tvRageList.setAttribute('style', 'text-align: left; display:none') $('.mylist').before(tvRageHeader) $('#newSeriesList').append(tvRageList) } //add Premiere alert if (pAlert && !myURL.match(/showid/) && !myURL.match(/quickcheck/)){ var newTable = document.createElement('table'); newTable.setAttribute('id', 'PremiereAlert'); newTable.setAttribute('width', '50%'); newTable.setAttribute('align', 'right'); newTable.setAttribute('style', 'text-align: center; padding:2px') newTable.setAttribute('cellspacing', "0") newTable.innerHTML = '<tbody><tr><td id="isPremiere" colspan="4" style="cursor:pointer; background-color: #CCC"><a>Season Premieres in My List</a></td></tr></tbody><tbody id="premiereList" style="display: none"></tbody>'; $('.mylist').before(newTable) $('#isPremiere').click(function(){togglepAlert()}) } //add the coundown column $('.Episode_PastOne td:first-child').attr("class", "airDate") $('.Episode_PastTwo td:first-child').attr("class", "airDate") $('.Episode_Today td:first-child').attr("class", "airDate") $('.Episode_One td:first-child').attr("class", "airDate") $('.Episode_Two td:first-child').attr("class", "airDate") if (countdown){ //add in the current time header var weekday=new Array(7); weekday=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] AMPM = "am" hours = d.getHours() if (hours >= 12){ AMPM = "pm" hours = hours - 12 } minutes = '' + d.getMinutes() if (minutes.length < 2) {minutes = '0' + minutes;} myHtml = 'Air Date<br><font color="#c06080">' + weekday[d.getDay()] + ' ' + hours + ':' + minutes + '' + AMPM + "</font>" $('th:first').html(myHtml) $('th:first').attr('colspan','2') //add the countdown for each row $('.airDate').each(function(){ //find the air date of episodes, and format it airDate = cleanDate($(this).html()) var d2 = new Date(airDate) var myDate = new Date(airDate); //time math airTime = $(this).next().html() //$(this).attr('width','7%') $(this).css('vertical-align', 'top') $(this).css('padding', '2px 5px 2px 5px') $(this).css('white-space', 'nowrap') findHour = airTime.replace(/(\d{1,2}):.*/, "$1") findHour = airTime.replace(/^0/, "") findHour = parseInt(findHour) if (airTime.match("pm")){findHour = findHour + 12} else if (airTime.match('12:')){findHour = findHour - 12} findMin = airTime.replace(/.*:(\d{2})/, "$1") findMin = parseInt(findMin) d2.setHours(findHour) d2.setMinutes(findMin) d2.setSeconds(0) d2.setMilliseconds(0) cDownTD = document.createElement('td'); cDownTD.setAttribute('class', 'countdown') //Countdown feature for all shows before today if ($(this).parent().attr('class').match("Episode_Past")){ cDown = Math.abs(parseInt((new Date()-myDate)/86400000)) cDownTD.setAttribute('style', 'float:left;color: #ff3000;padding:2px 5px 2px 3px;margin-right:3px;white-space: nowrap;height:20px') if (cDown == 1){ cDownTD.innerHTML = 'Yesterday' } else { cDownTD.innerHTML = cDown + ' Days Ago' } } //Countdown feature for shows in todays list else if ($(this).parent().attr('class') == "Episode_Today"){ cDown = (d2 - new Date()) / 3600000 theHour = Math.abs(parseInt(cDown)) theMinutes = Math.abs(parseInt(60*(cDown-theHour))) if (theHour == 0 && theMinutes == 0){ //air time is Now cDownTD.setAttribute('style', 'float:left;color: #ff3000;padding:2px 5px 2px 3px;margin-right:3px;white-space: nowrap;height:20px') cDownTD.innerHTML = 'Now' } else if (cDown > 0){ //air time is later today if (theMinutes + d.getMinutes != 60){theMinutes = theMinutes + 1} if (theMinutes==60){myTime = theHour + 1 + " h"} else if (theMinutes==0){myTime = theHour + " h"} else if (theHour==0){myTime = theMinutes + " min"} else {myTime = theHour + " h " + theMinutes + " min"} cDownTD.setAttribute('style', 'float:left;color: #00c000;padding:2px 5px 2px 3px;margin-right:3px;white-space: nowrap;height:20px') cDownTD.innerHTML = myTime } else{ //air time already passed theHour = Math.abs(Math.ceil(cDown)) theMinutes = Math.abs(parseInt(60*(-cDown-theHour))) if (theMinutes==60){myTime = theHour + 1 + " h"} else if (theMinutes==0){myTime = theHour + " h"} else if (theHour==0){myTime = theMinutes + " min"} else {myTime = theHour + " h " + theMinutes + " min"} cDownTD.setAttribute('style', 'float:left;color: #ff3000;padding:2px 5px 2px 3px;margin-right:3px;white-space: nowrap;height:20px') cDownTD.innerHTML = myTime } } //Countdown feature for all shows scheduled for the future dates else { cDownTD.setAttribute('style', 'float:left;color: #00c000;padding:2px 5px 2px 3px;margin-right:3px;white-space: nowrap;height:20px') cDown = Math.abs(parseInt((myDate-new Date())/86400000))+1 if (cDown == 1){ cDownTD.innerHTML = 'Tomorrow' } else{ cDownTD.innerHTML = '<span>' + cDown + ' Days</span>' } } $(this).before(cDownTD) }) } else{ $('.airDate').each(function(){ $(this).css('vertical-align', 'top') $(this).css('padding', '2px 5px 2px 5px') $(this).css('white-space', 'nowrap') }) } //add links to remove or ignore show removeShow = document.createElement('div'); removeShow.setAttribute('style', 'display:none;border:1px solid blue; height:8px;width:8px; margin-top:3px; margin-left:6px; float:left; cursor:pointer; text-align:center') removeShow.setAttribute('title', 'Remove Show') removeShow.setAttribute('class', 'showRemove') removeShow.innerHTML = "<p style='position:relative;top:-10px;color:red;font-size:75%;font-weight:bold'>R</p>" ignoreShow = document.createElement('div'); ignoreShow.setAttribute('style', 'display:none;border:1px solid blue; height:8px;width:8px; margin-top:3px; margin-left:2px; float:left; cursor:pointer; text-align:center') ignoreShow.setAttribute('title', 'Ignore Show') ignoreShow.setAttribute('class', 'showIgnore') ignoreShow.innerHTML = "<p style='position:relative;top:-10px;color:red;font-size:75%;font-weight:bold'>I</p>" $('.showname').children().css('float', 'left') $('.showname').append(removeShow) $('.showname').append(ignoreShow) $('.showname').hover(function(){ $(this).find(">:nth-last-child(1)").toggle() $(this).find(">:nth-last-child(2)").toggle() }) $('.showRemove').click(function(){ showID = $(this).parent().html().replace(/.*?showid\=(.*?)".*/, "$1") showName = $(this).prev().text() ignoreRemove(showID,showName,'Remove') }) $('.showIgnore').click(function(){ showID = $(this).parent().html().replace(/.*?showid\=(.*?)".*/, "$1") showName = $(this).prev().prev().text() ignoreRemove(showID,showName,'Ignore') }) //Create progress bar $('.longnumber').html(function(index, oldhtml){ $(this).attr('id', $(this).text()) showNameFull = $(this).prev().find('>:first-child').text() showName = cleanShowName(showNameFull) showID = $(this).prev().html().replace(/.*?showid\=(.*?)".*/, "$1") var progBar = document.createElement('td'); var tempArray = $(this).text().split("x"); epNb = "s" + tempArray[0] + "e" +tempArray[1]; ep = epNb.replace(/.*?e(..).*/, "$1") se = epNb.replace(/s(..).*/, "$1") se1 = se.replace(/^0/, "") ep1 = ep.replace(/^0/, "") reNamer = namer.replace("(S)", se) reNamer = reNamer.replace("(E)", ep) reNamer = reNamer.replace("(s)", se1) reNamer = reNamer.replace("(e)", ep1) reNamer = reNamer.replace(/ /g, "&nbsp;") reNamer = reNamer.replace(/$/, "&nbsp;") myUrl = cleanUserURL(hLink,showName,se1,ep1) thisShow = showID + "s" + se progBar.setAttribute('class', 'ProgBar' + thisShow); progBar.setAttribute('title', ep); progBar.innerHTML = '<b><div style="border: 1px solid black; background-color:white"><div style="background-color:white; width:0%">&nbsp;<a class="emptyBar" href="' + myUrl + '" target="_blank">' + reNamer + '</a></div></div></b>'; $(this).html(progBar) //add lines to season/series premiere table if (pAlert && (ep1 == 0 || ep1 == 1) && $('#' + showName).length == 0){ newTr = document.createElement('tr'); newTr.setAttribute('id',showName) //newTr.setAttribute('style',';border:1px solid black') newTd = document.createElement('td'); newTd2 = document.createElement('td'); newTd3 = document.createElement('td'); newTd4 = document.createElement('td'); newTd.setAttribute('style', 'padding:2px;border-bottom:1px solid grey;text-align: left') newTd2.setAttribute('style', 'padding:2px;border-bottom:1px solid grey;text-align: left') newTd3.setAttribute('style', 'padding:2px;border-bottom:1px solid grey') newTd4.setAttribute('style', 'padding:2px;border-bottom:1px solid grey') if (se1==1){ newTr.setAttribute("style", "background-color:rgba(255,255,0,0.4)") $(this).parent().css("background-color", "rgba(255,255,0,0.4)") $(this).parent().attr('class','Episode_series_premiere') } else{ $(this).parent().css("background-color", "rgba(255,0,0,0.2)") $(this).parent().attr('class','Episode_premiere') } newTd.setAttribute('width', '10%') newTd.innerHTML = $('.myDate:eq(' + index + ")").text() newTd2.innerHTML = showNameFull link = 'http://www.nzbindex.nl/search/?q=' + showName + '+preair+|+' + showName + '+dvdscr+|+' + showName + '+' + epNb + '&age=&max=25&minage=&sort=agedesc&minsize=20&maxsize=&dq=&poster=&nfo=&complete=1&hidespam=0&hidespam=1&more=1' link2 = 'http://thepiratebay.sx/search/' + showName + '+preair/0/99/0' newTr.appendChild(newTd) newTr.appendChild(newTd2) if (hasNzb){ newTd3.innerHTML = '<a style="text-decoration:none" href="' + link + '" target="_blank">NZB</a>' newTr.appendChild(newTd3) } if (hasTor){ newTd4.innerHTML = '<a style="text-decoration:none" href="' + link2 + '" target="_blank">TOR</a>' newTr.appendChild(newTd4) } if (se=='01' && $('#seriesPremiereMyList').length==0){ //the separated header for series premieres newRow = document.createElement('tr'); newLine = document.createElement('td'); newRow.setAttribute('id','seriesPremiereMyList') newLine.setAttribute('colspan','4') newLine.setAttribute('style','background-color:#CCC;text-align:center') newLine.innerHTML = 'Series Premieres' newRow.appendChild(newLine) $("#premiereList").append(newRow) } if (se=='01'){ $("#premiereList").append(newTr) } else if ($('#seriesPremiereMyList').length>0){ $('#seriesPremiereMyList').before(newTr) } else{ $("#premiereList").append(newTr) } } ct = $("#premiereList").children().length if ($('#seriesPremiereMyList').length>0){ ct = $("#premiereList").children().length - 1 } $("#isPremiere").html("<a>Upcoming Season Premieres in My List (<b>" + ct + "</b>)</a>") //Begin to actually build the progress bars airDate = cleanDate($('.airDate:eq(' + index + ')').html()) var d2 = new Date(airDate) searchShow = false if (typeof isRefresh === "undefined" || GM_getValue("ProgBarCache","")==""){ searchShow = true } else if (!isRefresh && d2.getDate() - d.getDate() >=0 && d2.getDate() - d.getDate() <=3){//determine if the show is airing between today and 3 days from now searchShow = true } else{ //search the cache for the show var reg = new RegExp("^" + thisShow + 'e') if (GM_getValue("ProgBarCache").match(reg)){fd = 0} else{fd = GM_getValue("ProgBarCache").indexOf("," + thisShow + 'e')} if (fd<0){searchShow = true} } if (searchShow){ found = undefined; for (y=0; y < idList.length; y++){ //prevent addition of duplicates if (thisShow === idList[y]){ found = true; break; } } if (!found){ idList.push(thisShow) } } }) //make the newly colored rows highlight on hover $('.Episode_series_premiere').hover(function(){ $(this).css('background-color', '') }, function(){ $(this).css("background-color", "rgba(255,255,0,0.4)") }) $('.Episode_premiere').hover(function(){ $(this).css('background-color', '') }, function(){ $(this).css('background-color', 'rgba(255,0,0,0.2)') }) //tvrage data gathering if (typeof isRefresh === "undefined" || GM_getValue('tvRage','')==''){Upcoming(0)} else{tvRageChecker()} if (typeof isRefresh !== "undefined" && !isRefresh && GM_getValue('tvRage','')!=''){Upcoming(0)} //refresh the data in the background - data will show up on next refresh Arr = new Array() if (GM_getValue("UseProgCache")){//place any progress bar data we have parseProgBarCache(0) } else {//Start collecting progress bar data GM_setValue("UseProgCache", true) GM_setValue("ProgBarCache", "null") ProgCacheBuilder(0) } } //functions running on Episodes List / Quick Check / Show pages (i.e. NZB/Torrent) if ((myURL.match(/views.php$/) || myURL.match(/views.php.$/) || myURL.match(/views.php..$/) || myURL.match("quickcheck") || myURL.match('epsbyshow')) && $('.flatButton:eq(0)').attr('value') != 'Add Show'){ //Insert new column for NZB/Torrent links, if (myURL.match("quickcheck") || myURL.match('epsbyshow')){ c = 4 if (myURL.match("quickcheck")){$('.headershowname').attr('colspan','6')} else{$('.season').attr('colspan','6')} } else{c=5} if (hasTor){ $('th:eq(' + c + ')').before('<th width="4%" style="text-align:left">TOR</th>') $('.epname').after('<td class="TOR" style="padding:2px 2px 2px 2px;vertical-align:top"></td>') } if (hasNzb){ $('th:eq(' + c + ')').before('<th width="4%" style="text-align:left">NZB</th>') $('.epname').after('<td class="NZB" style="padding:2px 2px 2px 2px;vertical-align:top"></td>') } if (hasNzb || hasTor){ var past = new Date(); past.setHours(0) past.setMinutes(0) past.setSeconds(0) past.setTime(past.getTime() - (nzbMrkOld*86400000)); if (hasNzb){ if (nzbdl){ var bulkSearch = document.createElement('div'); bulkSearch.style.display="none"; bulkSearch.setAttribute('id', 'BulkDownload'); bulkSearch.setAttribute('style', 'display:none;clear:both;float:right;cursor:pointer'); bulkSearch.innerHTML = '<a id="bulkDl" onClick="">' + nzb_img_src() + '<font color="red" font size="2"> (All <span id="bulkDlCt"></span>)</font></a>'; $('.mylist').before(bulkSearch) } rssList = [] $('.NZB').html(function(index, oldhtml){ if (myURL.match("quickcheck") || myURL.match('epsbyshow')){ myDate = cleanDate($('.date:eq(' + index + ')').html()) } else{ myDate = cleanDate($('.airDate:eq(' + index + ')').html()) } myDate = new Date(myDate) //add NZB elements if ((nzbOld && myDate <= past) || (nzbTod && myDate > past && myDate <= isNow)) { if (myURL.match('epsbyshow')){showName = cleanShowName($('.showname:eq(' + index + ')').text())} else{showname = cleanShowName($('.showname:eq(' + index + ')').find(">:first-child").text())} if (myURL.match("quickcheck") || myURL.match('epsbyshow')){longNb = $('.longnumber:eq(' + index + ')').text()} else{longNb = $('.longnumber:eq(' + index + ')').attr('id')} epNb = longNb.replace(/.*x/, "") sNb = longNb.replace(/x.*/, "") //build NZB Links rss = showName + '+s' + sNb + "e" + epNb link = 'http://www.nzbindex.nl/search/?q=' + rss + "&age=30&max=25&g[]=42&g[]=687&g[]=657&g[]=356&minage=&sort=agedesc&minsize=20&maxsize=&dq=" + nzbdf + '&poster=&nfo=&complete=1&hidespam=1&more=1' link = link.replace("++", "+") if (nzbUrl != "") {link = cleanUserURL(nzbUrl,showName,sNb,epNb)} else if (myURL.match("quickcheck") || myURL.match('epsbyshow')){link = 'http://www.nzbindex.nl/search/?q=' + rss + '&age=30&max=25&minage=&sort=agedesc&minsize=20&maxsize=&dq=&poster=&nfo=&complete=1&hidespam=0&hidespam=1&more=1'} else if (myDate <= past){link = 'http://www.nzbindex.nl/search/?q=' + showName + '&age=30&max=25&minage=&sort=agedesc&minsize=20&maxsize=&dq=&poster=&nfo=&complete=1&hidespam=0&hidespam=1&more=1'} $(this).html('<a href ="' + link + '" target="_blank">NZB</a>') if (myDate > past && myDate <= isNow){ $(this).attr('id', 'NzbLinkNew' + index) if (myURL.match(/views.php$/) || myURL.match(/views.php.$/) || myURL.match(/views.php..$/)){rssList.push(rss + ";;" + index)} } else{$(this).attr('class', 'NZBlink')} } }) if (myURL.match(/views.php$/) || myURL.match(/views.php.$/) || myURL.match(/views.php..$/)){ NzbStart() } } if (hasTor){ $('.TOR').html(function(index, oldhtml){ if (myURL.match("quickcheck") || myURL.match('epsbyshow')){ myDate = cleanDate($('.date:eq(' + index + ')').html()) } else{ myDate = cleanDate($('.airDate:eq(' + index + ')').html()) } myDate = new Date(myDate) //add Torrent elements if ((torOld && myDate <= past) || (torTod && myDate > past && myDate <= isNow )){ if (myURL.match('epsbyshow')){showName = cleanShowName($('.showname:eq(' + index + ')').text())} else{showname = cleanShowName($('.showname:eq(' + index + ')').find(">:first-child").text())} if (myURL.match("quickcheck") || myURL.match('epsbyshow')){longNb = $('.longnumber:eq(' + index + ')').text()} else{longNb = $('.longnumber:eq(' + index + ')').attr('id')} epNb = longNb.replace(/.*x/, "") sNb = longNb.replace(/x.*/, "") //build Torrent Links link = 'http://thepiratebay.sx/search/' + showName + '+s' + sNb + "e" + epNb + '/0/99/0' if (torUrl != "") {link = cleanUserURL(torUrl,showName,sNb,epNb)} else if (myURL.match("quickcheck") || myURL.match('epsbyshow')){link = 'http://thepiratebay.sx/search/' + showName + "+s" + sNb + "e" + epNb + '/0/99/0'} else if (myDate <= past){link = 'http://thepiratebay.sx/search/' + showName + '/0/99/0'} $(this).html('<a href ="' + link + '" target="_blank">TOR</a>') if(myDate > past && myDate <= d){$(this).attr('class', 'torLinkNew');} else{$(this).attr('class', 'torLink');} } }) } } } //search results pages if (myURL.match(/search.php/)){ if ($('#divContainers table tbody tr td').length == 1){//there was only 1 search result, redirect to the page window.location.assign($('#divContainers table tbody tr td a').attr('href')) } searchVal = "" if (GM_getValue('searchBuddy') != ""){ //use the searchBuddy to figure out what show was searched for src = "" if (GM_getValue('searchBuddy').replace(/.*(.$)/,"$1") == 0){ //only put this info if its a myepisodes result search searchBuddyResults = document.createElement('p') searchBuddyResults.setAttribute('margin-top','2px') searchBuddyResults.innerHTML = 'Search Source: <strong>myepisodes.com</strong>' $('u:eq(0)').parent().after(searchBuddyResults) } searchVal = GM_getValue('searchBuddy').replace(/...$/,"") GM_setValue("searchBuddy","") } //add the search bar to all search results pages notResults = document.getElementById('showlist') if (!notResults){ //keeps us from adding junk to the blank search page var searchBar = document.createElement('form'); searchBar.setAttribute('action', 'search.php'); searchBar.setAttribute('method', 'POST'); searchBar.innerHTML = '<br><div><input type="text" value="' + searchVal + '" style="width: 100%;" autocomplete="off" name="tvshow" tabindex="1" id="q"><br></div><br><table cellspacing="0" cellpadding="0" width="100%"><tbody><tr><td width="45%" valign="top"><input type="submit" value="Search myepisodes.com" name="action" tabindex="2"><br><br>Search myepisodes.com for a show stored localy on this site.</td><td align="center" width="10%">- <b>OR</b> -</td><td align="right" width="45%" valign="top"><input type="submit" value="Search tvrage.com" name="action" tabindex="3"><br><br>If you can' + "'t find the show in a myepisodes.com search.<br>Then you can try <b>adding</b> it directly from tvrage.com.<br>All you do is press this search button instead,<br>then add the show you are looking for to our site.<br></td></tr></tbody></table>" $('div:last').before(searchBar) } $('input:last').click(function(){ //bind searchbuddy to tvrage search GM_setValue("searchBuddy", $('#q').val() + ";;" + '1') }) $('input:nth-last-child(3)').click(function(){ //bind searchbuddy to myEpisodes search GM_setValue("searchBuddy", $('#q').val() + ";;" + '0') }) $('#q').parent().submit(function(){ //bind searchbuddy to a search performed by clicking enter, rather than a button GM_setValue("searchBuddy", $(this).children().val() + ";;" + '0') }) } function nzb_img_src(){ var nzb_img_src = '<img alt="" src="data:image/png;base64,' + 'iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAewQAAHsEBw2lUUwAAAAd0SU1FB9kCEgEkJcIbdOUAAAAZdEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjQ+jcx2AAADF0lEQVRIS8WVX0hTcRTHv0EPK1HIP6lz6kwtp3NqmqbOZs6ZFaXWCEuyeigJIhatQoiEyojAFv2BVlJGREXmiiikHpIihCB6KqiM9exTIkSkdTrn3t05zfQSQj/4cn/3d87vfM45v9/dgP8x4vIQzXLE5aJWj2JzkK07z/h8xCfY8DGpHJRcoSop9NTeI59iW1yEH4uysVsXJKEAbZaWBXRv9CT1fu/UpR09' + 'FcSVfmaAYVYIZ+O1eQzko2bqIrcutT61UbwVwxw8ZlZAYgm8eV7QtvFo2joepUuu/ijiyvUBkkoZcBjUNKpfVY9ACUU6Acnl8FrbQRuHVW0IaaZ5ZS8fdLFOgNEOb/5R0PovrODftfYDyB4AFZwAZe8EJZbqBKQ4+JA7QPXvI/RuYl73FlRxGyRJ5HpAOXsZsIuvcrlegBPeguOgujcgV6Reg6oegorPgQpPgWzHQNYjKmTZHv5e7DMAUuuRlroGDSFdl7JXPwfVvFDl6AeV3wSV+kElF0DLuyYgeQzJ2QdKqcFXowPNWhxjNTLCVzZtHQaXtoEsnE3uATWQBF31WM3afl9ty8obbLvCkIshSGeoVQdBGVtA5s2sJlB6AwNr8Sn84Zlc2J/VirGq' + 'B5zxy5A4c6mi+hnDnjCIbZV3uRINch6Uyb3PrTVRvstM6SWxlNkKytquAH7GF+IqA+ZrVcxLcaJlSQu+ScZykNL/Wu6785UKkorEVnmHK+kBrbgMSt0ECgaDJMPn81FGs1LBWGw+Tk/92bDyQnV0BjqMTowXnQWVSabXuB3ckuJLoCIfX8kz3BI+nzy+QZZDfPcdkwEJZfi10IhbHMvJkpjqMJvNAR40VX6/n9j8x7rmJzatgqGhoUl+EjMMsNlsAaVOHt3d3TQwMKDMZbME8Xg8YfX19Wmuik0DyB7Zqw2JOS2gsbFR6WckQAKJ3G43CUCyFZ9IgLzL3n8GmEwmGhwcpJGREdJaN6eAyNuiVTRngHDdUyaRgKk+k87AYDC0y4IoJiYmYDQalbnF' + 'YpGDUubTSWziM51NYs767zYXDr8BFT1PtO2OLbgAAAAASUVORK5CYII=" />' return nzb_img_src } var amzImgSrc = 'data:image/png;base64,' + 'iVBORw0KGgoAAAANSUhEUgAAAH4AAAAYCAYAAAA8jknPAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAZuSURBVGhD7Zk7bixFFIY7IPIKvAOvAW/BW/AeHLMFL4DcbIDc2c3MCiwSAgdIQASWrhHmurlf+37o96Gqp+YhJ0xLrZmpPnVe/3l1zTQ3rsfHx5n7va+Xl5dF7vPz83uLPpi8Ud2hG6VFuR7tNjzSyMkfOPz6+no+Pz+fz87O5tPT0+U7a7/8+tsbx9zc3MxXV1fz5eXlfH9/P9/d3S3foeeT31w8c/3i4mJmX+u6vb1d6JTLJ79Zzws9lMvz1l33pG5VP3njPOyEH/z5ja7o7J6Hh4du' + 'cLgfWv22yVbotFN/KQBduOULHTe6iQX66DPkIm+bIJjIMpjAeJqm5g3jrAA4RFqUwYjcy28AaPGsDmF/Ty7r0qMngdSjPTk5WZ7Bjwt69rqe+1jDsRn0aQPPqhxsaVVBnJ3+wFfuTRkGk89MMH6jTwYsstSR59BqB7LEi7WU1wu2VsQuwKfiOIBIyjWEG4Ew4bkGtByrMS2QMMrIxNikQSa8EwTon56eFt0xmGfeOih5YHwrSHBQOok9ZhqAGqQ9ewzCmlXI4xn7CUxkw1cbsvrJW4DMaPZDjx7sF2jopYW3OmoLa1wGqjxG+tZE6UhjVbQGBKDYayrwKNfKcLKP9QwiZFk2M9vhKf8MiKTnufMHn+lgM0PnpY7qXoMWB8ozq5MZiB7pG6tJVgr3' + 'pd8SDPeoT/LAx+lnQTZAs2JYwQxyQddn7sn1tQCYiDqIMbL2mgSm5zwMQimupMchXj0gCQBk8jzLaJZ0HF+NqQ6zwkhXg9kqgD5mqHugxQcJvA6vZdz+r13obrbrA5/BFzDcUwMkQVEnfSmIFQ/9aMAmDwOr7umBv5T6NMThyUHFCOtlvJmaUa4zNgHPc2cMjLfF1OxrRXHtw9nfBETds3/W9sLvCrz06JaVI21lj7wyKVqONpBr9dL+GkC97FVe6iGPrYFnI4rV/lf7cy/jCRSDJ8GAn+u9jOd5a5Cqg1gFnt9ZgtHNKoA9FfjMglZQtIC3l/eAz+qxCXhl0oPrG1Lqa4/eFnh4JPC1+rSCcWJwygzjO0D5ujCa8RXETaW+TrlOsbadHB7zVaqC' + 'VJ3pcJXBkxk/Cry9M4GvPd4SvQZ8DprYuAl47NsX+LXe7rMpHVH76UiP72X8GvAYT8Dl9J58ao8HeDOwvv4tJT7alRWsTvqttuNkv2vGr/VcAxuanDmc/BOcymdf4IcyPocdgMgrK4EDBQa1yl/N+BxAaqnHEXUAy4EqdcrXrtqfnSXQk6zzsClfz6DJTM3WYmmt9FaInq36yABtVZ3s/76i+UqYPs5XOn2wL/BDGV+diXAyrHWwAm0deHbNeJydfRpjkYuMeiAEqDho02GPIKczfUemsnFnMBsQLeBbPT5t1bm+quK3zDTXPVEz4OpETgJoL4F0iFI/lPE4uw5yAlIB8NVkJOM39fgaQPXQJ4MCPWgNCTzPPfasgx6gVDCrjXkSV9vOpoz3GBqg' + 'si2hn0e9nit4+JTtxCNWaA3EDKp3yXin03piRcRilJGa5bIOPJum+jpHOKzxWd8mABOHOLl7IqaenuGTKR8//5fDzXdkoGOeMMK/nkACiMee6t0CvpfxrJsQvgqib00S7Kr9vPf2hN7ooD7vArzCUAoDPIXz9QiF6qGAk7fTv2UPAFjj9hUMPp6yeUiUpQj+rCsbsFIngyRf1+ZPf87zHz/N888fXm++f14DlOTNd9+34U9Q2K4qXdpUD5O0SV08dMrjW/2HDGSZ6bXfOvRJV33rWwDr9XhYX7X+MFL/ntyqx7//zo0MBPOP3706eYfrDXBl/9qzN6TI/uGbef72q//e3389z3/93tTMAFhTe6Qvpp7DOq8I7fFwvafTIWSPA0+WATxOx/kdJ+8Q' + 'E+NbkI9sM53PDAR0PF5DHhgHHnYvf7863YwThCFRhyFaDpgJuijxiz5k/PEa9sCWwH851yezcLQBwPc92sCQtsisGS74VqEhRkciPLAd8NVngJ0BYOZZCXacBxYxZDX7Le/Z15EJ6JzYWer3kfU/jIXdgf8yMS8A9QYuAwGgoOEGyOzRfGdNgKGBvgaUvKCzl1t52HO8tvLA7sArxnNyAqBVAVoT+LZrthJkALYyCRqneeaP4zXsgf2BzwBIQMzcbUGuVWKthBsIw+YeCfXA4YBf86m9Osu5pT9bgAMigOY/bsdsPnjE/gPkLld1SQxVWQAAAABJRU5ErkJggg=='; /*****************************FUNCTIONS ONLY BEYOND THIS POINT*****************************/ //open / close config screen function toggleConfig(){ if ($('#divContainers').is(":visible")){ applySettings() showNzbSettings() showTorSettings() } $('#configScreen').toggle('slow',function(){ $('#divContainers').toggle() }) } function applySettings(){ //most settings that are text based are entered on load of the script $('#pAlert').prop('checked', pAlert) $('#uAlert').prop('checked', uAlert) $('#ukAlert').prop('checked', ukAlert) $('#caAlert').prop('checked', caAlert) $('#auAlert').prop('checked', auAlert) $('#anim').prop('checked', anim) $('#award').prop('checked', award) $('#docu').prop('checked', docu) $('#game').prop('checked', game) $('#mini').prop('checked', mini) $('#news').prop('checked', news) $('#real').prop('checked', real) $('#scrip').prop('checked', scrip) $('#sport').prop('checked', sport) $('#talk').prop('checked', talk) $('#variy').prop('checked', variy) $('#hColor').val(hColor) $('#hColor').css('background-color', hColor) $('#pColor').val(pColor) $('#pColor').css('background-color', pColor) $('#countdown').prop('checked', countdown) $('#nzbOld').prop('checked', nzbOld) $('#nzbTod').prop('checked', nzbTod) $('#nzbdl').prop('checked', nzbdl) $('#nzbMrk').prop('checked', nzbMrk) $('#torOld').prop('checked', torOld) $('#torTod').prop('checked', torTod) //not sure why, but I need to empty out the option box first $('#channelFilterList option').each(function(){$(this).remove();}); //fill in the blocked channels cf = GM_getValue("chFilter").split(';;') cf[0] = cf[0].replace(/^;/,"") cf[cf.length-1] = cf[cf.length-1].replace(/;$/,"") cf.sort() for (i=0; i<cf.length; i++){ cfe = document.createElement('option') cfe.innerHTML = cf[i] $("#channelFilterList").append(cfe) } } //toggle for the season premiere table function togglepAlert(){ $('#premiereList').toggle('fast') } function toggleTvRage(){ $('#tvRageList').toggle('fast') } function colorToHex(color) { var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color); var red = parseInt(digits[2]); var green = parseInt(digits[3]); var blue = parseInt(digits[4]); var rgb = blue | (green << 8) | (red << 16); return digits[1] + '#' + rgb.toString(16); }; function saveReload(){ //save all the settings GM_setValue('settings', Number(document.getElementById("pAlert").checked) + '~~' + Number(document.getElementById("uAlert").checked) + '~~' + Number(document.getElementById("ukAlert").checked) + '~~' + Number(document.getElementById("caAlert").checked) + '~~' + Number(document.getElementById("auAlert").checked) + '~~' + Number(document.getElementById("anim").checked) + '~~' + Number(document.getElementById("award").checked) + '~~' + Number(document.getElementById("docu").checked) + '~~' + Number(document.getElementById("game").checked) + '~~' + Number(document.getElementById("mini").checked) + '~~' + Number(document.getElementById("news").checked) + '~~' + Number(document.getElementById("real").checked) + '~~' + Number(document.getElementById("scrip").checked) + '~~' + Number(document.getElementById("sport").checked) + '~~' + Number(document.getElementById("talk").checked) + '~~' + Number(document.getElementById("variy").checked) + '~~' + colorToHex($('#hColor').css("background-color")) + '~~' + colorToHex($('#pColor').css("background-color")) + '~~' + Number(document.getElementById("countdown").checked) + '~~' + $('#namer').val() + '~~' + $('#hLink').val() + '~~' + Number(document.getElementById("nzbOld").checked) + '~~' + Number(document.getElementById("nzbTod").checked) + '~~' + Number(document.getElementById("nzbdl").checked) + '~~' + $('#nzbUrl').val() + '~~' + $('#nzbMrkOld').val() + '~~' + Number(document.getElementById("nzbMrk").checked) + '~~' + $('#nzbdf').val() + '~~' + Number(document.getElementById("torOld").checked) + '~~' + Number(document.getElementById("torTod").checked) + '~~' + $('#torUrl').val() + '~~') //save blocked channels list myVar = "" $('#channelFilterList option').each(function(){ myVar = myVar + ";" + this.value + ";" }); GM_setValue("chFilter", myVar) location.reload() } function ignoreRemove(showID,showName,remove){ if (confirm(remove + " " + showName + "?")==true){ if(remove=='Remove'){remove='mode=del&showid=' + showID} else{remove='mode=ign&showid=' + showID + '&ignored=1'} GM_xmlhttpRequest({ method: 'GET', url: 'http://www.myepisodes.com/views.php?type=manageshow&' + remove, }) $('.showname').find('>:first-child').text(function(index, text){ if(text==showName){$(this).parent().parent().hide('slow')} }) } } function restoreDefault(){ if (confirm("Are you sure you want to restore all defaults? The list of blocked channels will not be changed")==true){ GM_setValue("settings", '1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~1~~#a0c0ff~~#60ffc0~~1~~s(S)e(E) / (F)~~http://en.wikipedia.org/wiki/Special:Search?search=list+of+SHOWNAME+episodes~~1~~1~~1~~~~15~~1~~-720p -1080p~~1~~1~~') location.reload() } } //Reverse the season order for shows function reverse(){ if ($('#revOrder').attr('value') == 'Reverse Season Order'){ $('#revOrder').attr('value', 'Refresh Page'); //disable the Save Status buttons $('.flatButton:eq(1)').attr('disabled','true') $('.flatButton:eq(4)').attr('disabled','true') $('.mylist tbody').append('<tr><td style="padding-top: 14px;"></td></tr>') b = $("th.season").length+5 //reverse the seasons for (i=6; i<$("th.season").length+5; i++){ $("tbody tr.header:eq(" + b + ")").nextUntil("tr.header").andSelf().insertBefore($("tbody tr.header:eq(" + i + ")")) } } else { location.reload(); } } function addShowHeader(url){ GM_xmlhttpRequest({ method: 'GET', url: url, headers: { 'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey', 'Accept': 'application/atom+xml,application/xml,text/xml', }, onload: function(responseDetails) { text = responseDetails.responseText // var reg = /padding.bottom.10.*?div>/gm var reg = /padding_bottom_10.*?<br>/gm var imgMatch = text.match(reg); if (imgMatch[0].match('src')){ //add the tvrage image (if there is one) $('#tvRageShowHeader').append(imgMatch[0].replace(/.*<img(.*?)>/, '<span style="float:left"><img id="tvRageImage"$1></span>')) $('#tvRageImage').css({ maxHeight: '150px', maxWidth: '270px', }) $('#tvRageImage').load(function(){resizeHeader()}) } //add the tvRage synopsis text = text + "" var reg = /show.synopsis.*/gm var txtMatch = text.split(reg); txtMatch = txtMatch[1].split(/.*?<div class/) myTxt = txtMatch[0] + "" myTxt = myTxt.replace(/^\s+/,"") txtHeader = document.createElement('p') txtHeader.innerHTML = myTxt txtHeader.setAttribute('id', 'tvRageTxt') txtHeader.setAttribute('style','margin:0px 0px 0px 5px;overflow:auto;float:left') $('#tvRageShowHeader').append(txtHeader) rating = $('#tvRageTxt strong').html() $('#tvRageTxt div').nextUntil().remove() $('#tvRageTxt div').prev().remove() if (rating==undefined){$('#tvRageTxt div').replaceWith('<br><br>')} else{$('#tvRageTxt div').replaceWith('<p style="margin-top:5px;font-weight:bold">'+rating+"</p>")} if($('#tvRageImage').length>0){ //pre-formatting if there is an image. We have to wait until the image loads $('#tvRageShowHeader').height('150px') $('#tvRageTxt').css({ height: '150px', width: '624px' }) } else{ //no image, slap the data onto the screen $('#tvRageShowHeader').css('border-left', '1px solid grey') $('#tvRageShowHeader').show() myHeight = $('#tvRageTxt').height() $('#tvRageShowHeader').height(myHeight) } $('#tvRageShowHeader').css('margin-left', '-1px') } }); } function resizeHeader(){ //after the image from tvrage loads we will resize everything around it $('#tvRageShowHeader').animate({'height':'toggle'}, 'slow', function(){ myHeight = $('#tvRageImage').height() myWidth = 894 - $('#tvRageImage').width() $('#tvRageTxt').css({ 'height': myHeight, 'width': myWidth }) $('#tvRageShowHeader').height(myHeight) }) } function cleanDate(text){ //make date fields readable by javascript myDate = text.replace(/.*?date\=(.*?)">.*/, "$1"); myDate = myDate.replace(/" name="yesterday.*/, ""); myDate = myDate.replace(/" name="today.*/, ""); myDate = myDate.replace(/-/gm, " "); return myDate } function showNzbSettings(){ if(Number(document.getElementById("nzbTod").checked) + Number(document.getElementById("nzbOld").checked) == 0){ $('#hasNzbDownloads').hide() } else{ $('#hasNzbDownloads').show() } } function showTorSettings(){ if(Number(document.getElementById("torTod").checked) + Number(document.getElementById("torOld").checked) == 0){ $('#hasTorDownloads').hide() } else{ $('#hasTorDownloads').show() } } function cleanShowName(showNameFull){ //prepares the showname for being used in a hyperlink showName = showNameFull.replace(" (US)", "") showName = showName.replace(" (UK)", "") showName = showName.replace(/ \(\d{4}\)$/, "") showName = showName.replace(/[^0-9a-zA-Z\.: ]+/gm, " ") showName = showName.replace(/\s{1,100}/gm, "+") showName = showName.replace(/\+$/g,"") showName = showName.replace(/:/g,"") showName = showName.replace(/'/g,"") showName = showName.replace(/\./g,"") return showName } function cleanUserURL(url,showName,sNb,epNb){ //user defined URL cleaning if(!url.match(/^http/)){url = "http://" + url} url = url.replace("SHOWNAME", showName) url = url.replace("EPISODE", epNb) url = url.replace("SEASON", sNb) return url } //will create the cache for the Progress Bar function ProgCacheBuilder(i){ showId = idList[i].replace(/;../,"") seasonNumber = idList[i].replace(/.*;/,"") GM_xmlhttpRequest({ method: 'GET', url: 'http://www.myepisodes.com/views.php?type=epsbyshow&showid=' + showId, headers: { 'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey', 'Accept': 'application/atom+xml,application/xml,text/xml', }, onerror: function(responseDetails){ GM_setValue("UseProgCache", false) }, onload: function(responseDetails) { var text = responseDetails.responseText; var reg = new RegExp(seasonNumber + "x\\d{2}", 'gm') var regMatch = text.match(reg) reg = /.....$/g regMatch = reg.exec(regMatch) reg = /..$/ epNumber = reg.exec(regMatch) id = showId + "s" + seasonNumber + "e" + epNumber if (GM_getValue("ProgBarCache","null")=="null"){ GM_setValue("ProgBarCache", id) } else { GM_setValue("ProgBarCache", GM_getValue("ProgBarCache") + "," + id) } if (i == idList.length-1){ parseProgBarCache(0) } else{ ProgCacheBuilder(i+1) } } }); } function parseProgBarCache(j){ if (Arr.length==0){ Arr = GM_getValue("ProgBarCache").split(",") } epVal = Arr[j].replace(/.*(..)$/, "$1") thisShow = Arr[j].replace(/...$/, "") isSent = false if($(".ProgBar" + thisShow).length==0){ //show isn't in list any more. Remove from array. Arr.splice(j,1) } else{ $(".ProgBar" + thisShow).html(function(){ if (!isSent){ var percent = ($(this).attr("title") / epVal)*100 var progChange = document.createElement('td'); progChange.setAttribute('class', 'ProgBar'); reg = /^0/ epVal2 = reg.exec(epVal) if (epVal2==null){ epVal2 = epVal } else{ reg = /.$/ epVal2 = reg.exec(epVal) } progChange.innerHTML = $(this).html().replace("(F)", epVal) progChange.innerHTML = progChange.innerHTML.replace("(f)", epVal2) if (percent > 100){ isSent = true loadShow(thisShow.replace(/s.*/,"")) } else{ if (percent == 100){ //add red bars on left and right for season finale episodes $(this).parent().parent().find(">:first-child").css("border-left", "3px solid red") $(this).parent().parent().find(">:last-child").css("border-right", "3px solid red") if (countdown){ $(this).parent().parent().find(">:first-child").css("padding-left", "1px") $(this).parent().parent().find(">:last-child").css("padding-right", "1px") } else{ $(this).parent().parent().find(">:first-child").css("padding-left", "2px") $(this).parent().parent().find(">:last-child").css("padding-right", "2px") } } progAdj = percentToObj(percent) progChange.innerHTML = progChange.innerHTML.replace("background-color:white; width:0%", progAdj) progChange.innerHTML = progChange.innerHTML.replace('class="emptyBar"', 'class="fullBar"') $(this).html(progChange); } } if (hLink.match('wikipedia')){ $(this).attr('title', 'Search Wikipedia') } else{ $(this).attr('title', 'Custom Search') } }) } if (j <= Arr.length-2){ parseProgBarCache(j+1) } else if ($('.emptyBar').length > 0){ //the parse is over. look for empty progress bars GM_setValue("ProgBarCache", Arr.join()) //save to cache (in case items were removed) newArr = new Array() for (i=0; i<$('.emptyBar').length; i++){ parentClass = $('.emptyBar:eq(' + i + ")").parent().parent().parent().parent().attr('class') if (newArr.indexOf(parentClass) == -1){ newArr.push(parentClass) GM_setValue("ProgBarCache", GM_getValue("ProgBarCache") + "," + parentClass.replace("ProgBar","") + "e01") loadShow(parentClass.replace(/ProgBar(.*?)s.*/,'$1')) } } } } function percentToObj(percent){ if (percent < 34){colorCode = '20ff40'} else if (percent > 34 && percent < 67){colorCode = 'ffff80' } else if (percent > 67 && percent <= 99.9){colorCode = 'a080ff'} else if (percent == 100){colorCode = 'ff6020'} progAdj = "background-color:#" + colorCode + "; width:" + percent + "%" return progAdj } function loadShow(showId){ GM_xmlhttpRequest({ method: 'GET', url: 'http://www.myepisodes.com/views.php?type=epsbyshow&showid=' + showId, headers: { 'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey', 'Accept': 'application/atom+xml,application/xml,text/xml', }, onload: function(responseDetails) { showId = responseDetails.finalUrl.replace(/.*\=/, "") seasonNumberArr = GM_getValue("ProgBarCache").split(",") var reg = new RegExp("^" + showId + "s") for (i=0;i<seasonNumberArr.length;i++){ if (seasonNumberArr[i].match(reg)){ seasonNumber = seasonNumberArr[i].replace(/.*s(.*?)e.*/,"$1") break } } var text = responseDetails.responseText; reg = new RegExp(seasonNumber + "x\\d{2}", 'gm') var regMatch = text.match(reg); reg = /.....$/g regMatch = reg.exec(regMatch) reg = /..$/ epVal = reg.exec(regMatch) $(".ProgBar" + showId + "s" + seasonNumber).html(function(){ var percent = ($(this).attr("title") / epVal)*100 var progChange = document.createElement('td'); progChange.setAttribute('class', 'ProgBar'); reg = /^0/ epVal2 = reg.exec(epVal) if (epVal2==null) { epVal2 = epVal } else { reg = /.$/ epVal2 = reg.exec(epVal) } progChange.innerHTML = $(this).html().replace("(F)", epVal) progChange.innerHTML = progChange.innerHTML.replace("(f)", epVal2) progAdj = percentToObj(percent) progChange.innerHTML = progChange.innerHTML.replace("background-color:white; width:0%", progAdj) progChange.innerHTML = progChange.innerHTML.replace("class=emptyBar", "class=fullBar") $(this).html(progChange); }) seasonNumberArr[i] = showId + "s" + seasonNumber + "e" + epVal GM_setValue("ProgBarCache", seasonNumberArr.join()) } }); } //begin the RSS search of NZB files function NzbStart(){ if (rssList.length>0){ NzbQuery(rssList[0].replace(/;;.*/, ""), rssList[0].replace(/.*?;;/, "")) rssList.splice(0,1) } } function NzbQuery(rss, i){ //loading the full page rather than the RSS feed. The RSS feed is way faster (about 25-40%), but spits out 'Service Unavailable' errors more than 40% of the time. GM_xmlhttpRequest({ method: 'GET', url: 'http://www.nzbindex.nl/search/?q=' + rss + "&age=30&max=25&g[]=42&g[]=687&g[]=657&g[]=356&minage=&sort=age&minsize=20&maxsize=&dq=" + nzbdf + '&poster=&nfo=&complete=1&hidespam=1&more=1', headers: { 'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey', 'Accept': 'application/atom+xml,application/xml,text/xml', }, onload: function(responseDetails) { var text = responseDetails.responseText; myLink = text.split('.nzb">Download') myLink = myLink[0].split('href="') myLink = myLink[myLink.length-1] + ".nzb" if (myLink.match('http://www.nzbindex.nl/download')){ var newNzbLink = document.createElement('td'); newNzbLink.setAttribute('class', 'NzbDirect'); newNzbLink.innerHTML = '<a href="' + myLink + '">' + nzb_img_src() + '</a>'; $('#NzbLinkNew' + i).replaceWith(newNzbLink) //automatically mark "Acquired" any items that have NZB results if(nzbMrk){$('.NzbDirect:last').nextUntil().prev().children().attr('checked', 'true')} //update the bulk download link if (nzbdl){ $('#bulkDlCt').html($('.NzbDirect').length) if ($('.NzbDirect').length == 2){ $('#BulkDownload').show() } $('#bulkDl').attr('onclick',function(index, attr){ if (attr == ""){ $(this).attr('onclick',"window.open('" + myLink + "')") } else{ $(this).attr('onclick',attr + ";window.open('" + myLink + "')") } }) } } NzbStart() } }); } //Upcoming series premieres from TVRage function Upcoming(b){ country = '' if (b==0 && uAlert){ thisUrl = "http://services.tvrage.com/tools/quickschedule.php" country = "US" } else if (b<=3){ if (b==1 && ukAlert){country = "GB"} else if (b==2 && caAlert){country = "CA"} else if (b==3 && auAlert){country = "AU"} thisUrl = "http://services.tvrage.com/tools/quickschedule.php?country=" + country } if (country != ''){ GM_xmlhttpRequest({ method: 'GET', url: thisUrl, headers: { 'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey', 'Accept': 'application/atom+xml,application/xml,text/xml', }, onerror: function(responseDetails){ GM_setValue("UseCache", false) }, onload: function(responseDetails) { var text = responseDetails.responseText; regMatch = text.match(/\[SHOW\].*?01x01.*?\[\/SHOW\]/g) t=0 country = responseDetails.finalUrl.replace(/.*(.).$/,"$1") if (country=="h"){country="U"} if (regMatch!=null){ while (regMatch[t]!=null){ regMatch[t] = regMatch[t].replace(/\[SHOW\](.*?)\[\/SHOW\]/, "$1") station = regMatch[t].replace(/(.*?)\^.*/, "$1") station = station.replace(" Channel"," Ch.") station = station.replace(" Network"," Net.") station = station.replace("Destination America","Dest. Amer.") station = station.replace("National Geographic","NatGeo") station = station.replace("ReelzChannel","Reelz") station = station.replace("SportsNet New York","SportsNet NY") station = station.replace("Investigation Discovery","Inv. Disc.") station = station.replace("BBC Red Button 1","BBC RedBtn1") station = station.replace("Comedy Central","Com. Central") sName = regMatch[t].replace(/.*?\^(.*?)\^.*/, "$1") sLink = regMatch[t].replace(/.*\^(.*?)/, "$1") if (sLink.match(/shows.id-/)){ sLink = sLink.replace(/.*(id-.*?)$/, "$1") } else { sLink = sLink.replace(/.*tvrage.com.(.*?)$/, "$1") } regMatch[t] = country + ";;" + sName + ";;" + sLink + ";;" + station // if (GM_getValue("tvRage", "null") == "null" || GM_getValue("tvRage") == ""){ // GM_setValue("tvRage", country + ";;" + sName + ";;" + sLink + ";;" + station) // } // else if (!GM_getValue("tvRage").match(country.substring(0,1) + ";;" + sName)){ // GM_setValue("tvRage", GM_getValue("tvRage") + "~~" + country + ";;" + sName + ";;" + sLink + ";;" + station) // } t = t+1 } if (GM_getValue('tvRage',"")==""){txtAdd = ""} else {txtAdd = "~~" + GM_getValue('tvRage')} GM_setValue("tvRage", regMatch.join('~~') + txtAdd) } rageCount = rageCount + 1 if (rageCount==4){ keys = new Array keys = GM_getValue("tvRage").split("~~") rageCount = 0 MoreData(0) } } }); } if (b<3){Upcoming(b+1)} } //check that all the data for tvRage got collected function tvRageChecker(){ keys = GM_getValue("tvRage").split("~~") for (t=0; t<keys.length; t++){ if (!keys[t].match(/;;.$/)){ rageCount = t MoreData(t) t=-1 break } } if (t>-1){SendData()} } //Gathers more info about each show (i.e. it's classification, and start date) function MoreData(t){ fart = false if (!keys[t].match(/;;.$/)){ sLink = keys[t].replace(/.*?;;.*?;;(.*?);;.*/, "$1") if (sLink.match(/^id-/)){ sLink = sLink.replace(/id-(.*)/, "http://services.tvrage.com/tools/quickinfo.php?sid=$1") } else { sLink = sLink.replace(/^/, "http://services.tvrage.com/tools/quickinfo.php?show=") } GM_xmlhttpRequest({ method: 'GET', url: sLink, headers: { 'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey', 'Accept': 'application/atom+xml,application/xml,text/xml', }, onerror: function(responseDetails){ GM_setValue("UseCache", false) }, onload: function(responseDetails) { var text = responseDetails.responseText; if(text.match(/Classification@Animation/)){sClass = 'A'} else if(text.match(/Classification@Award Show/)){sClass = 'W'} else if(text.match(/Classification@Documentary/)){sClass = 'D'} else if(text.match(/Classification@Game Show/)){sClass = 'G'} else if(text.match(/Classification@Mini-Series/)){sClass = 'M'} else if(text.match(/Classification@News/)){sClass = 'N'} else if(text.match(/Classification@Reality/)){sClass = 'R'} else if(text.match(/Classification@Scripted/)){sClass = 'S'} else if(text.match(/Classification@Sports/)){sClass = 'P'} else if(text.match(/Classification@Talk Shows/)){sClass = "T"} else if(text.match(/Classification@Variety/)){sClass = "V"} sAirDate = text.match(/Started@(.*)/) + "" sAirDate = sAirDate.replace(/Started@(.*?),.*/,"$1") keys[t] = keys[t] + ";;" + sAirDate + ";;" + sClass GM_setValue("tvRage", keys.join("~~")) rageCount = rageCount + 1 if (rageCount == keys.length-1){ //I have no idea why, but if I don't pause this function, the tvrage cache gets screwed up setTimeout(function(){SendData()},1000) } } }); } if (t<keys.length-1){MoreData(t+1)} } //This places the Series Premiere cache data onto the page function SendData(){ keys = new Array() bigKey = new Array() tempVar = GM_getValue("tvRage") bigKey = tempVar.split("~~") removeDups = [] doSave = false $.each(bigKey, function(i, el){ //remove any duplicates found if($.inArray(el, removeDups) === -1){ removeDups.push(el); doSave = true } }); bigKey = removeDups removeDups = "" for (t=0; t<bigKey.length; t++){ keys[t] = bigKey[t].split(";;") keys[t][6] = new Date(keys[t][4]) keys[t][4] = keys[t][6].toDateString() } //sort by date keys.sort(function(a,b){if(a[6] > b[6]) return 1;if(a[6] < b[6]) return -1;}) t = keys.length d = new Date(new Date().setDate(new Date().getDate()-3)) while (t--){ //remove any items that aired more than 3 days ago if (keys[t][6] < d){ keys.splice(t,1) doSave = true } } if ((typeof isRefresh === "undefined" && !isRefresh) || doSave){ //save the cache if dups or old info were found var myString = "" for (t=0; t<keys.length; t++){ myString = keys[t][0] + ";;" + keys[t][1] + ";;" + keys[t][2] + ";;" + keys[t][3] + ";;" + myMonth[keys[t][6].getMonth()] + "/" + keys[t][6].getDate() + "/" + keys[t][6].getFullYear() + ";;" + keys[t][5] + "~~" + myString } GM_setValue("tvRage", myString.replace(/~~$/, "")) } //end of data purge. Now we filter based on classification, and post the data to the page. for (t=0; t<keys.length; t++){ if (keys[t][2].match(/^id-/)){ keys[t][2] = keys[t][2].replace(/^/, "http://www.tvrage.com/shows/") } else { keys[t][2] = keys[t][2].replace(/^/, "http://www.tvrage.com/") } if (classFliter.match(keys[t][5]) && !GM_getValue("chFilter").match(";" + keys[t][3] + ";")){ if (keys[t][0]=='G'){keys[t][0]="UK"} else if (keys[t][0]=='U'){keys[t][0]="US"} else if (keys[t][0]=='C'){keys[t][0]="CA"} else if (keys[t][0]=='A'){keys[t][0]="AU"} if (keys[t][5]=="A"){keys[t][5]="Anim.";keys[t][6]="Animated"} else if (keys[t][5]=="W"){keys[t][5]="Award";keys[t][6]='Award Show'} else if (keys[t][5]=="D"){keys[t][5]="Docu.";keys[t][6]='Documentary'} else if (keys[t][5]=="G"){keys[t][5]="Game";keys[t][6]='Game Show'} else if (keys[t][5]=="M"){keys[t][5]="Mini";keys[t][6]='Mini-Series'} else if (keys[t][5]=="N"){keys[t][5]="News";keys[t][6]='News'} else if (keys[t][5]=="R"){keys[t][5]="Real";keys[t][6]='Reality'} else if (keys[t][5]=="S"){keys[t][5]="Scrip";keys[t][6]='Scripted'} else if (keys[t][5]=="P"){keys[t][5]="Sport";keys[t][6]='Sports'} else if (keys[t][5]=="T"){keys[t][5]="Talk";keys[t][6]='Talk Show'} else if (keys[t][5]=="V"){keys[t][5]="Var.";keys[t][6]='Variety'} premDate = document.createElement('td'); premShow = document.createElement('td'); premStation = document.createElement('td'); moreInfo = document.createElement('td'); premCountry = document.createElement('td'); premClass = document.createElement('td'); premDate.setAttribute('style', 'padding:2px') premShow.setAttribute('style', 'padding:2px') premStation.setAttribute('style', 'padding:2px;cursor:pointer') moreInfo.setAttribute('style', 'padding:2px') premCountry.setAttribute('style', 'padding:2px') premClass.setAttribute('style', 'padding:2px') premCountry.setAttribute('nowrap', true) premClass.setAttribute('nowrap', true) premDate.setAttribute('nowrap', true) premStation.setAttribute('nowrap', true) premStation.setAttribute('title', "Block all shows from " + keys[t][3]) moreInfo.setAttribute('nowrap', true) premShow.innerHTML = '<a id="' + keys[t][1] + '" style="cursor:pointer" title="Search on MyEpisodes">' + keys[t][1] + '</a>' premStation.innerHTML = '<a class="' + keys[t][3].replace(/[^0-9a-zA-Z]+/gm,"") + '" style="color:black;text-decoration: none">' + keys[t][3] + '</a>' premStation.setAttribute('class','channel') premDate.setAttribute('class', "premDate") premShow.setAttribute('class', "premShow") moreInfo.setAttribute('class', "moreInfo") premCountry.innerHTML = keys[t][0] premDate.innerHTML = keys[t][4].replace(/....(.*) .*/,"$1") premDate.setAttribute('title',keys[t][4].replace(/....(.*)/,"$1")) premClass.innerHTML = keys[t][5] premClass.setAttribute('title', keys[t][6]) moreInfo.innerHTML = '<a title="More Information about the show" href="' + keys[t][2] + '" target="_blank"><font size=1>TVRage</font></a>' newLine = document.createElement('tr'); newLine.setAttribute('class',"tvRageItem") newLine.appendChild(premDate) newLine.appendChild(premCountry) newLine.appendChild(premShow) newLine.appendChild(premClass) newLine.appendChild(premStation) newLine.appendChild(moreInfo) $('#tvRageList').append(newLine) } } $('#tvRageList').show() $('.channel').click(function(){ if ($(this).attr('class') === 'channel'){blockChannel($(this).find(">:first-child").attr('class'))} else{blockChannel($(this).attr('class'))} }) $('.channel').hover(function(){ if ($(this).attr('class') === 'channel'){ $(this).css('color', 'red') $(this).css('text-decoration','line-through')} else {$(this).parent().css('color', 'red') $(this).parent().css('text-decoration','line-through')} }, function(){ if ($(this).attr('class') === 'channel'){ $(this).css('color', 'black') $(this).css('text-decoration','none')} else{$(this).parent().css('color', 'black') $(this).parent().css('text-decoration','none')} }) $('.premShow').find(">:first-child").click(function(){ GM_setValue("searchBuddy",$(this).attr('id') + ";;" + '0') $('#r').attr('id','q') $('#q').val($(this).attr('id')) $('#q').parent().submit() $('#q').attr('value', '') }) $('.tvRageItem').hover(function(){ $(this).css('background-color', '#F5F5F5') }, function(){ $(this).css('background-color', '') }) $('#tvRageList').hide() $('#tvRageCount').html(" (<b>" + $('.channel').length + "</b>)") $('#tvRageHeader').click(function(){ toggleTvRage() }) GM_setValue("UseCache", true) } //allows user to block unwanted tv channels from the tvrage series premiere list function blockChannel(station){ if (confirm("Are you sure you want to block all shows from " + $('.' + station + ':eq(0)').text() + "?")==true){ GM_setValue("chFilter", GM_getValue("chFilter", "") + ";" + $('.' + station + ':eq(0)').text() + ";") $('.' + station).parent().parent().hide('slow') $('#tvRageCount').html(function(index, oldhtml){ ct = oldhtml.replace(/.*?>(.*?)<.*/,"$1") ct = ct - $('.' + station).length $(this).html(" (<b>" + ct + "</b>)") }) } }
import React, { Component } from 'react'; import { StyleSheet, DeviceEventEmitter } from 'react-native'; import { Container, Card, CardItem, Content, Button, Text } from 'native-base'; import {getDeck, isEmpty} from './helpers'; export default class IndividualDeckView extends Component { static navigationOptions = ({ navigation }) => ({ //title: 'Kewl', //headerTitleStyle: { textAlign: 'center', alignSelf: 'center' } }); constructor(props) { super(props); this.state = { deck: {} }; } _fetchDeck = async() => { const { navigation } = this.props; const deck = await getDeck(navigation.getParam('id')) if (deck != {}) { return this.setState({ deck }) } } componentDidMount() { DeviceEventEmitter.addListener("cardAdded", (e) => { return this._fetchDeck(); }) return this._fetchDeck(); } render() { const { deck } = this.state; const { navigate } = this.props.navigation; return ( <Container> {isEmpty(deck) ? ( <Text>Loading</Text> ) : ( <Content contentContainerStyle={styles.container}> <Card key={deck.id} style={styles.cardStyle}> <CardItem header> <Text style={styles.textColor}> {deck.title} </Text> </CardItem> <CardItem> <Text> {deck.questions.length} cards </Text> </CardItem> </Card> <Button style={styles.buttonStyle} onPress={() => navigate('NewQuestion', { id: deck.id })}> <Text>Add Card</Text> </Button> <Button style={styles.buttonStyle} success onPress={() => navigate('Quiz', { id: deck.id })}> <Text>Start Quiz</Text> </Button> </Content> )} </Container> ); } } const styles = StyleSheet.create({ titleStyle: { paddingLeft: 40, paddingRight: 40, textAlign: 'center' }, cardStyle:{ alignItems: 'center', justifyContent: 'center', width: 200, height:150 }, buttonStyle: { alignSelf: 'center', marginTop: 20 }, container: { flex: 1, //backgroundColor: 'rgb(50, 49, 78)', alignItems: 'center', justifyContent: 'center' }, cardStyles: { backgroundColor: 'rgb(50, 49, 78) !important', color: 'white' }, textColor: { color: 'rgb(50, 49, 78)' } });
import '../my_styles.css'; import { Row, Button, InputGroup, FormControl, Modal } from 'react-bootstrap'; import { useState } from 'react'; import { backendURL } from '../Environment'; function FooterText(props) { const [showNoMessage, setShowNoMessage] = useState(false); const [showNoUser, setShowNoUser] = useState(false); const [writingMessage, setWritingMessage] = useState(""); const readMessages = () => { props.readMessages(); } const handleClose = () => { setShowNoMessage(false); setShowNoUser(false); } const messageHandler = (event) => { setWritingMessage(event.target.value) } const messageSender = () => { const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: null, chat_id: { id: null, roomname: props.myRoomname, created_date: null }, chatroom_user_id: { id: null, username: props.myUser, date_of_birth: null }, message: writingMessage, created_date: null, image_path: null }) }; fetch(backendURL + '/api/save_message', requestOptions) .then(() => readMessages()) setWritingMessage(""); } const messageValidator = () => { if (props.myUser === "User") { setShowNoUser(true); } else if (writingMessage === "") { setShowNoMessage(true); } else { messageSender(); } } return ( <> <div className="pushUp"></div> <Row className="footerNavBar"> <InputGroup className="mb-3"> <FormControl placeholder="Message" aria-label="Message" aria-describedby="basic-addon2" value={writingMessage} onChange={(event) => messageHandler(event)} /> <Button variant="outline-secondary" id="button-addon2" onClick={() => messageValidator()} > Send </Button> </InputGroup> </Row> <Modal show={showNoMessage} onHide={() => handleClose()}> <Modal.Header closeButton> <Modal.Title>Keine Nachricht!</Modal.Title> </Modal.Header> <Modal.Body> Bitte geben Sie eine Nachricht ein. </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={() => handleClose()}> OK </Button> </Modal.Footer> </Modal> <Modal show={showNoUser} onHide={() => handleClose()}> <Modal.Header closeButton> <Modal.Title>Kein Benutzer</Modal.Title> </Modal.Header> <Modal.Body> Bitte wählen Sie einen Benutzer aus! </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={() => handleClose()}> OK </Button> </Modal.Footer> </Modal> </> ); } export default FooterText;
// 节流函数 export const throttle = (func, gapTime) => { let _lastTime = null return () => { let _nowTime = +new Date() if (!_lastTime || _nowTime - _lastTime > gapTime) { func() _lastTime = _nowTime } } } export const DepartmentRecursion = arr => { return arr.map(item => { if (item.hasOwnProperty('children') && item.children.length === 0) { const current = { ...item, } delete current.children return { ...current, } } else { return { ...item, children: DepartmentRecursion(item.children), } } }) }
/** * These rules enforce the Hack Reactor Style Guide * * Visit this repo for more information: * https://github.com/reactorcore/eslint-config-hackreactor */ module.exports = { "extends": 'airbnb', rules: { "no-console": "off", "no-undef": "off", "react/prop-types": "off", "const database = require('../database/data');": "off" // "indent": "off" } };
import React from 'react'; import { connect } from 'react-redux'; import Styles from './Cube.styles'; const Style = new Styles(); /** * Styled Wrappers */ const CubeMenuWrapper = Style.wrapper; class CubeMenu extends React.Component { constructor(props) { super(props); this.state = { ...props, }; } componentDidMount() { } render() { return( <CubeMenuWrapper> </CubeMenuWrapper> ); } }; // Retrieve data from store as props function mapStateToProps(store) { return { object: store.rubix, }; } export default connect(mapStateToProps)(CubeMenu);
module.exports = { "not found": `nexss py install <module> OR pip3 install <module>`, "ModuleNotFoundError: No module named 'bpy'": `This module needs to be run with blender compiler. Please make sure you have blender compiler added to the files section: files: - name: myfile.py compiler: blender nexsstest.blend --background Or please add to the top of your python file (example without .blend file): # nexss-compiler: blender --background `, "ImportError: No module named '(.*?)'": "nexss py install <module> OR pip3 install <module>", "ModuleNotFoundError: No module named '(.*?)'": "nexss py install <module> OR pip3 install <module>", "NameError: name 'reload' is not defined": "Probably you have run the template from Python2 instead Python3?\nAdd at the top of the file # nexss-compiler: python27", "No module named 'NexssInstall'": "Please update the Nexss Package to the latest version by: nexss pkg update Nexss", "requires-python:>=(?<pythonversion>.*?)\\)": "Module requires python at least <pythonversion>.\nTry to use `nexss py default compiler 'compilername'`", };
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ import userListTemplate from './userList.html'; class UserListController { static get $$ngIsClass() { return true; } static get $inject() { return ['maUser', '$scope']; } constructor(User, $scope) { this.User = User; this.$scope = $scope; } $onInit() { this.ngModelCtrl.$render = () => this.selectedUser = this.ngModelCtrl.$viewValue; this.query(); this.User.notificationManager.subscribe((event, item, attributes) => { attributes.updateArray(this.users, this.queryFilter.test); }, this.$scope); } $onChanges(changes) { if (changes.filter && !changes.filter.isFirstChange()) { this.query(); } } query() { const queryBuilder = this.User.buildQuery(); if (this.filter) { let filter = this.filter; if (!filter.includes('*') && !filter.includes('?')) { filter = '*' + filter + '*'; } queryBuilder.or() .match('username', filter) .match('name', filter) .up(); } this.queryFilter = queryBuilder.createFilter(); this.usersPromise = queryBuilder // TODO this is a unbounded query .query() .then(users => this.users = users); return this.usersPromise; } selectUser(user) { this.selectedUser = user; this.ngModelCtrl.$setViewValue(user); } } export default { controller: UserListController, template: userListTemplate, require: { 'ngModelCtrl': 'ngModel' }, bindings: { filter: '<?', showNewButton: '<?', newButtonClicked: '&' }, designerInfo: { translation: 'ui.components.maUserList', icon: 'people' } };
const request = require('request'); require('dotenv').config(); const Profile = require('../models/Profile'); module.exports.index = (req, res) => { return res.render('index', {message: ''}); }; module.exports.register = (req, res) => { if(req.body.email == '' || req.body.email == null || req.body.github == '' || req.body.github == null || req.body.linkedin == '' || req.body.linkedin == null || req.body.rollno == '' || req.body.rollno == null || req.body.year == '' || req.body.year == null || req.body.branch == '' || req.body.branch == null) { return res.render('index', {message: 'invalid details'}); } else { Profile.findOne({email: req.body.email}, (err, profile) => { if (err) { return res.render('index', {message: 'try again'}); } if (profile) { return res.render('index', {message: 'already registered'}); } Profile.create(req.body, (err, done) => { if (err) { return res.render('index', {message: 'try again'}); } return res.render('index', {message: 'success'}); }); }); } }; module.exports.admin = (req, res) => { let customHeaderRequest = request.defaults({ headers: {'User-Agent': 'request'} }); let token = process.env.GITHUB_TOKEN; let url = "https://api.github.com/orgs/dsckiet/memberships/" + req.body.github + "?access_token=" + token; customHeaderRequest .put(url) .on('error', (err) => { console.log(err) return res.render('index', {message:'try again'}); }) .on('response', (response) => { console.log(response.statusCode); return res.render('index', {message:'success'}); }); }; // module.exports.test = (req, res) => { // Profile.updateMany({}, {status: 0}, (err, updated) => { // if(err) throw err; // return res.send("done"); // }) // };
var celnum = 0; /** * @param i */ function setTab03Syn ( i ){ selectTab03Syn(i); } /** * @param i */ function selectTab03Syn ( i ){ switch(i){ case 1: document.getElementById("TabCon1").style.display="block"; document.getElementById("TabCon2").style.display="none"; document.getElementById("font1").style.color="#134FB3"; document.getElementById("font2").style.color="#000000"; document.getElementById("othernum").value = ""; document.getElementById("test").value = ""; break; case 2: document.getElementById("TabCon1").style.display="none"; document.getElementById("TabCon2").style.display="block"; document.getElementById("font1").style.color="#000000"; document.getElementById("font2").style.color="#134FB3"; document.getElementById("selfnum").value = ""; break; } } /** * @param id */ function player(id){ var id=document.getElementById(id); id.style.display="block"; } /** * @param id */ function clocer(id){ var id=document.getElementById(id); id.style.display="none"; } /** * @param id */ function clocer1(id){ var friend=document.form1.friend.value; if(friend==""){ var id=document.getElementById(id); id.style.display="none"; } } /** * @param num */ function checknum(num){ var reT = /\d\d\d\d/; var nvalue = num.value; if(reT.test(nvalue)){ celnum = 1; document.getElementById('sefcel').style.display = "none"; document.getElementById('othcel').style.display = "none"; } else{ celnum = 0; document.getElementById('sefcel').style.display = "block"; document.getElementById('othcel').style.display = "block"; // alert(celnum); } } /** * */ function cancelx(){ document.getElementById('sefcel').style.display = "none"; document.getElementById('othcel').style.display = "none"; } /** * */ function dosubmit(){ var form = document.getElementById('form'); if(celnum==1){ form.submit(); } }
const Manager = require("../lib/Manager"); describe("Manager", () => { //Testing that the manager has an office number it("Should return the phone number of (123)867-5309", () => { const obj = new Manager("Daniel", 1, "Daniel@fakeemail.com", 1238675309) expect(obj.officeNumber).toBe("(123)867-5309") }) //Testing that the getRole will return Manager it("Should return Manager", () => { const obj = new Manager("Daniel", 1, "Daniel@fakeemail.com", 1238675309) expect(obj.getRole()).toBe("Manager") }) //Testing the validation of the phone number it("Should throw error of Office Number needs to be a number", () => { const err = new Error("Office Number needs to be a number") expect(() => new Manager("Daniel", 1, "Daniel@fakeemail.com", "officeNumber")).toThrow(err) }) })
import Request from '../../../utils/request' export const fetchById = ({basePath, id}) => Request({ url: `/eas/${basePath}/${id}`, method: 'GET' }) export const syncOrder = data => Request({ url: '/eas/syncOrder', method: 'POST', data })
'use strict'; const $ = require('jquery'); const Marionette = require('backbone.marionette'); module.exports = Marionette.ItemView.extend({ template: require('templates/view-register-method-select.jade'), className: 'mdl-grid', channel: Backbone.Wreqr.radio.channel('register'), ui: { button: '.js-select-method-btn' }, events: { 'click @ui.button': 'onClickButton' }, onClickButton(event) { const $target = $(event.target); let $button; if ($target.hasClass('material-icons')) { $button = $target.parent(); } else { $button = $target; } const registerMethod = $button.data('method'); this.channel.vent.trigger('auth:social', registerMethod); }, register(event) { const $button = $(event.target); console.log(this.ui.button); if (!$button.closest()) return false; const registerMethod = $button.data('method'); } });
var saveRespuestas="https://www.silviabaptista.es/participar/insertar-respuestas.php"; var hostwork="https://www.silviabaptista.es/participar/"; var dataCuestionario="https://www.silviabaptista.es/participar/respuestas.php"; var i=0; var objeto; localStorage.removeItem("jsonData"); var jsonData=new Object(); localStorage.removeItem("jsonData"); // Carga la plantilla donde se iran cargando las preguntas url=hostwork+"leearchivo.php"; loadDoc(url); //alert(url); var survey=leeJSON(idcuestionario); function loadDoc(url) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("salida").innerHTML = this.responseText; } }; xhttp.open("GET", url, false); xhttp.send(); } function readBody(xhr) { var data; if (!xhr.responseType || xhr.responseType === "text") { data = xhr.responseText; } else if (xhr.responseType === "document") { data = xhr.responseXML; } else { data = xhr.response; } return data; } function leeJSON(idcuestionario) { var xhttp = new XMLHttpRequest(); //alert('cuestionario: '+idcuestionario); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status ==200) { var objeto=this.responseText; escribirHtml(xhttp.responseText); } }; xhttp.open("POST", dataCuestionario, true); // enviar por POST el id de cuestionario a visualizar xhttp.send('{\"id\":'+idcuestionario + '}'); } function insertarJSON(jsonChoices) { // Inserta el resultado en la base de datos // "https://www.silviabaptista.es/participar/insertar-respuestas.php"; var url = saveRespuestas; //alert(url); //var json = replaceAll(jsonChoices,'"','\"'); var json = jsonChoices; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status ==200) { url=hostwork+"leegracias.php"; console.log(url); loadDoc(url); } }; xhttp.onerror = function() { url=hostwork+"leegracias.php"; console.log(url); loadDoc(url); console.log('Hay un error!'); }; xhttp.open("POST", url, true); xhttp.setRequestHeader('Content-type','text/plain; charset=utf-8'); //ver=JSON.stringify(json); console.log('ver fin: '); //json=json.replace('"',''); console.log('{\"respuestas\":['+ json +']}'); xhttp.send('{\"respuestas\":['+ json +']}'); } function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); } function siguientePregunta(idchoice){ console.log('escribirHtml'); var jsonData =localStorage.getItem("jsonData"); var userSession; //alert('Contexta: '+jsonData); // Cargamos las respuestas que llevamos contestadas if (jsonData==null){ var arrayId = new Array(); //arrayId.push('{respuesta:['); }else{ var arrayId = new Array(jsonData); } //arrayId.push('{respuesta:' + idchoice.toString()+'}'); //if (i === objeto.length-1){ if (i === 0){ var nombreUser =sessionStorage.getItem("usuario"); arrayId.push('\"' + nombreUser.toString()+'\"'); //arrayId.push(']'); } arrayId.push('\"' + idchoice.toString()+'\"'); console.log(arrayId); //if (i >= objeto.length){ // si acabamos insertamos al final el nombre de usuario // userSession =sessionStorage.getItem(jsonUsuario); // arrayId.push('{usuario:' + userSession.toString()+'}'); //} jsonData=arrayId; localStorage.setItem("jsonData", jsonData); //Grabamos en el localStorage las respuestas i++; // Cargamos las siguientes respuestas if (i < objeto.length){ document.getElementById('pregunta').innerHTML=objeto[i].pregunta; document.getElementById("respuesta1").value=objeto[i].respuestas["respuesta1"].idchoice; document.getElementById('respuesta1-texto').innerHTML=objeto[i].respuestas["respuesta1"].choice; document.getElementById("respuesta1").checked = false; document.getElementById("respuesta2").value=objeto[i].respuestas["respuesta2"].idchoice; document.getElementById('respuesta2-texto').innerHTML=objeto[i].respuestas["respuesta2"].choice; document.getElementById("respuesta2").checked = false //salidaJSON(objeto); }else{ //var nombreUser =sessionStorage.getItem("usuario"); //localStorage.setItem("jsonData",'{usuario:' +nombreUser+'}'); //localStorage.setItem("jsonData",nombreUser); jsonAnswer =localStorage.getItem("jsonData"); console.log(jsonAnswer); insertarJSON(jsonAnswer); } } function salidaJSON(salida){ var z=1; for(var j in salida[i].respuestas) { console.log('j:'+j,' salida_id:'+salida[i].respuestas[j].idchoice, ' salida_texto:'+salida[i].respuestas[j].choice,false); createRadioElementOtros(j,salida[i].respuestas[j].idchoice,salida[i].respuestas[j].choice,false); z++; } } function escribirHtml(entrada){ if (entrada.length>0){ objeto=JSON.parse(entrada); console.log('escribirHtml'); console.log(objeto); document.getElementById('pregunta').innerHTML=objeto[i].pregunta; document.getElementById("respuesta1").value=objeto[i].respuestas["respuesta1"].idchoice; document.getElementById('respuesta1-texto').innerHTML=replaceAll(objeto[i].respuestas["respuesta1"].choice,"'","\""); document.getElementById("respuesta2").value=objeto[i].respuestas["respuesta2"].idchoice; document.getElementById('respuesta2-texto').innerHTML=replaceAll(objeto[i].respuestas["respuesta2"].choice,"'","\""); } }
const { response } = require('express') const empPassport = require('passport'), bcrypt = require('bcrypt'), LocalStrategy = require('passport-local').Strategy, Employee_Modal = require('../Sequelize Files/Sequelize Models/call_cent_employee'), login_logout_Modal = require('../Sequelize Files/Sequelize Models/login_logout') /** * Serialize and Deserialize will be use once * Goto passport.js * handle there */ empPassport.use('local-login-forEmployees', new LocalStrategy({ usernameField: 'login_email', passwordField: 'login_password', passReqToCallback: true }, authenticate_login)) function authenticate_login(req, email, password, done) { //hiting the database for once only... const user_Data_Response = Employee_Modal.findOne( { where: { emp_email: email } }) .then() .then((res) => { console.log(res) return res }) .catch((err) => { return err }) user_Data_Response.then((response) => { if (response == null) return done(null, false, req.flash('danger', 'Sorry! No user found')) // if (response.emp_deleted == null) // return done(null, false, req.flash('danger', 'Sorry! No user found')) if (validate_Password(password, response.emp_password)) { var d = new Date(), curr_date = d.getDate(), curr_month = d.getMonth() + 1, curr_year = d.getFullYear(), hours = d.getHours(), minutes = d.getMinutes(), seconds = d.getSeconds() /** * Adding the activity of the login * which will store the login activity */ login_logout_Modal.create({ loginTime: hours + ":" + minutes + ":" + seconds, activityDate: curr_date + "-" + curr_month + "-" + curr_year, logoutTime: null, ipAddress: req.connection.remoteAddress, emp_id: response.dataValues.emp_id }) .then((dbResult) => { if (dbResult) console.log("Login Activity Triggered !") }) .catch((error) => { console.log("Login Activity Error " + error) }) //sending the response, all went okay.... return done(null, response) } else return done(null, false, req.flash('danger', 'Incorrect Password')) }) } function validate_Password(user_loginForm_password, hashPassword) { return bcrypt.compareSync(user_loginForm_password, hashPassword) } module.exports = empPassport
let Article = require('../models').Article; let express = require('express'); let router = express.Router(); let middleware = require("../auth/middleware"); /* path /api/articles/ */ /* CREATE */ router.post('/', middleware.allowFor('database:articles'), async (req, res) => { const entity = Article.build(req.body); entity.save().then(value => { if (value) { res.status(201).send(value); } else { res.status(500).send({message: "an error occurred during operation"}); } }).catch(err => { console.error(err); res.status(400).send(); }); }); /* READ */ router.get('/', async (req, res) => { const offset = req.query.offset; const limit = req.query.limit; let articles; if (limit && offset) { articles = await Article.findAll({where: {}, limit: limit, offset: offset}); } else { articles = await Article.findAll(); } if (articles) { res.status(200).send(articles); } else { res.status(500).send([]); } }); router.get('/:id', async (req, res) => { const id = req.params.id; let article; if (id && !isNaN(id)) { article = await Article.findOne({where: {id: id}}); } else { res.status(400).send({message: `wrong value for parameter id: ${id}`}) } if (article) { res.status(200).send(article); } else { res.status(404).send(); } }); /* UPDATE */ router.put('/:id', middleware.allowFor('database:articles'), async (req, res) => { const id = req.params.id; if (id && !isNaN(id)) { Article.update(req.body, {where: {id: id}}).then(value => { res.status(200).send(); }).catch(err => { console.error(err); res.status(500).send(); }); } else { res.status(400).send({message: `wrong value for parameter id: ${id}`}) } }); /* DELETE */ router.delete('/:id', middleware.allowFor('database:articles'), async (req, res) => { const id = req.params.id; let deleted; if (id && !isNaN(id)) { deleted = await Article.destroy({where: {id: id}}); } else { res.status(400).send({message: `wrong value for parameter id: ${id}`}) } if (deleted) { res.status(200).send({success: true, message: "article with id " + id + " removed"}); } else { res.status(400).send({success: false, message: "wrong article id " + id}); } }); /* OTHER */ router.post('/count', (req, res) => { Article.findAndCountAll().then(value => { res.status(200).send({count: value.count}); }).catch(err => { res.status(500).send({count: 0}); }); }); module.exports = router;
import QUnit from 'steal-qunit'; import React from 'react'; import ReactDOM from 'react-dom'; import CanComponent from 'can-component'; import stache from 'can-stache'; // old stealjs does not seem to handle named exports properly const Component = React.Component; import canReactComponent from 'can-react-component'; function getTextFromFrag(node) { var txt = ""; node = node.firstChild; while(node) { if(node.nodeType === 3) { txt += node.nodeValue; } else { txt += getTextFromFrag(node); } node = node.nextSibling; } return txt; } QUnit.module('can-react-component', (moduleHooks) => { const container = () => document.getElementById("qunit-fixture"); moduleHooks.afterEach(() => { ReactDOM.unmountComponentAtNode(container()); }); QUnit.test('should be able to consume components', (assert) => { const ConsumedComponent = canReactComponent( 'ConsumedComponent', CanComponent.extend('ConsumedComponent', { tag: "consumed-component1", ViewModel: { first: { type: 'string', default: 'Christopher' }, last: 'string', name: { get() { return this.first + ' ' + this.last; } } }, view: stache("<div class='inner'>{{name}}</div>") }) ); const testInstanceRef = React.createRef(); ReactDOM.render(<ConsumedComponent last="Baker" ref={testInstanceRef} />, container()); const divComponent = container().getElementsByTagName('consumed-component1')[0]; assert.equal(testInstanceRef.current.constructor.name, 'ConsumedComponent'); assert.equal(getTextFromFrag(divComponent), 'Christopher Baker'); testInstanceRef.current.viewModel.first = 'Yetti'; assert.equal(getTextFromFrag(divComponent), 'Yetti Baker'); }); QUnit.test('should work without a displayName', (assert) => { const ConsumedComponent = canReactComponent( CanComponent.extend('ConsumedComponent', { tag: "consumed-component2", ViewModel: { first: { type: 'string', default: 'Christopher' }, last: 'string', name: { get() { return this.first + ' ' + this.last; } } }, view: stache("<div class='inner'>{{name}}</div>") }) ); const testInstanceRef = React.createRef(); ReactDOM.render(<ConsumedComponent last="Baker" ref={testInstanceRef} />, container()); const divComponent = container().getElementsByTagName('consumed-component2')[0]; assert.equal(testInstanceRef.current.constructor.name, 'ConsumedComponentWrapper'); assert.equal(getTextFromFrag(divComponent), 'Christopher Baker'); }); QUnit.test('should update the component when new props are received', (assert) => { const ConsumedComponent = canReactComponent( CanComponent.extend('ConsumedComponent', { tag: "consumed-component3", ViewModel: { first: { type: 'string', default: 'Christopher' }, last: 'string', name: { get() { return this.first + ' ' + this.last; } } }, view: stache("<div class='inner'>{{name}}</div>") }) ); class WrappingComponent extends Component { constructor() { super(); this.state = { first: 'Christopher', last: 'Baker' }; } changeState() { this.setState({ first: 'Yetti' }); } render() { return <ConsumedComponent first={this.state.first} last={this.state.last} />; } } const wrappingInstanceRef = React.createRef(); ReactDOM.render(<WrappingComponent ref={wrappingInstanceRef} />, container()); const divComponent = container().getElementsByTagName('consumed-component3')[0]; assert.equal(getTextFromFrag(divComponent), 'Christopher Baker'); wrappingInstanceRef.current.changeState(); assert.equal(getTextFromFrag(divComponent), 'Yetti Baker'); }); QUnit.test('should be rendered only once', (assert) => { assert.expect(3); const ConsumedComponent = canReactComponent( 'ConsumedComponent', CanComponent.extend('ConsumedComponent', { tag: "consumed-component4", ViewModel: { first: { type: 'string', default: 'Ivo' }, last: 'string', name: { get() { return this.first + ' ' + this.last; } }, connectedCallback(el){ if(el.getAttribute("auto-mount") === "false") { assert.equal(this.last, "Pinheiro", `'last' name should be 'Pinheiro'`); } } }, view: stache("<div class='inner'>{{name}}</div>") }) ); container().innerHTML= "<consumed-component4></consumed-component4>"; let divComponent = container().querySelector('consumed-component4'); assert.equal(getTextFromFrag(divComponent), 'Ivo undefined'); ReactDOM.render(<ConsumedComponent last={"Pinheiro"} />, container()); divComponent = container().querySelector('consumed-component4'); assert.equal(getTextFromFrag(divComponent), 'Ivo Pinheiro'); }); });
import React from "react"; import {shallow, mount} from "enzyme"; import ReactTestUtils from "react-addons-test-utils"; import SearchInput from "../../src/js/components/SearchInput"; describe("SearchInput", () => { var props; var component; var input; var form; beforeEach(() => { props = {value: "abc", onChange: expect.createSpy()}; component = mount(<SearchInput {...props}/>); input = component.find("input"); form = component.find("form"); }); it("should render the current value", () => { expect(input.get(0).value).toEqual("abc"); }); it("should call callback when input change", () => { input.get(0).value = 'giraffe'; input.simulate("change"); expect(props.onChange.calls[0].arguments).toEqual(["giraffe"]); }); it("should call callback when form submit", () => { input.get(0).value = 'giraffe'; form.simulate("submit"); expect(props.onChange.calls[0].arguments).toEqual(["giraffe"]); }); });
Ext.define('frontend.view.complaint.Create', { extend: 'Ext.window.Window', alias : 'widget.complaintCreate', requires: ['Ext.form.*'], title : 'Новое обращение', layout: 'fit', autoShow: true, width: 400, initComponent: function() { this.items = [ { xtype: 'form', padding: '5 5 0 5', border: false, style: 'background-color: #fff;', items: [ { xtype: 'textfield', name : 'email', fieldLabel: 'Email', invalidText: 'Not a valid time. Must be in the format "12:34 PM".' }, { xtype: 'textfield', name : 'phone', fieldLabel: 'Телефон', invalidText: 'Not a valid time. Must be in the format "12:34 PM".' }, { xtype: 'combobox', fieldLabel: 'Статус', store: 'Status', name: 'status', valueField:'id', displayField:'name', queryMode:'local' }, { xtype: 'textareafield', maxRows: 4, name : 'text', fieldLabel: 'Текст обращения' }, { xtype: 'textareafield', maxRows: 4, name : 'service_comment', fieldLabel: 'Служебный комментарий' } ] } ]; this.buttons = [ { text: 'Save', action: 'save' }, { text: 'Cancel', scope: this, handler: this.close } ]; this.callParent(arguments); } });
import React,{ useState,useEffect } from 'react' import { View,Text,FlatList,Image } from 'react-native' import { styles } from './styles' export const Swiper=({ data, renderItem, containerStyle, activeDotColor, inActiveDotColor, onScroll, initIndex }) => { const [interval,setInterval]=useState(1); const [intervals,setIntervals]=useState(1); const [width,setWidth]=useState(0); const init=(width) => { setWidth(width); setIntervals(data.length); { !!flatListRef&&flatListRef.scrollToIndex({ animated: false,index: initIndex }) } } const getInterval=(offset) => { for (let i=1;i<=intervals;i++) { if (offset<(width/intervals)*i*0.8) return i; if (i==intervals) return i; } } let bullets=[]; for (let i=1;i<=intervals;i++) { bullets.push( <Text key={i} style={styles.dot(interval===i,activeDotColor,inActiveDotColor)}> &bull; </Text> ); } return ( <View style={styles.root(containerStyle)}> <FlatList ref={(ref) => { flatListRef=ref; }} horizontal={true} contentContainerStyle={styles.flatListContainer()} showsHorizontalScrollIndicator={false} onContentSizeChange={(w,h) => init(w)} onScroll={data => { onScroll() setWidth(data.nativeEvent.contentSize.width); setInterval(getInterval(data.nativeEvent.contentOffset.x)); }} scrollEventThrottle={200} pagingEnabled decelerationRate="fast" data={data} bounces={false} renderItem={((data) => ( <View style={styles.swiperContnet()}> {renderItem(data)} </View> ))} /> <View style={styles.dotContent()}> {bullets} </View> </View> ) } export default Swiper;
'use-strict'; var rfr = require('rfr'); var AppPath = require('rfr')({ root : rfr.root + 'app' }); module.exports = AppPath;
*** OBJECT ORIENTED PROGRAMMING *** In OOP, objects and classes are used to organize code to describe things and what they can do Create a basic javascript object: let dog = { name: "doggie", numLegs: 4 }; Use dot notation to access the properties of an object: console.log(dog.name); Create a method on an object: objects can have a special type of property, called a method method are properties that are functions let dog = { name: "doggie", sayName: function(){return "woof woof "+dog.name;} }; Make code more reusable with the this keyword: in the current context, this refers to the object that the method is associated with if the object's name is changed, it is not necessary to find all its references in the code sayName: function(){return "woof woof "+this.name;} Define a constructor function: constructors are functions that create new objects function Bird() { this.name = "Albert"; this.color = "blue"; this.numLegs = 2; } constructors are defined with a capitalized name to distinguish them from other functions constructors use the keyword this to set properties of the object they will create constructors define properties and behaviors instead of returning a value as other functions might Use a constructor to create an object: let blueBird = new Bird(); // notice the use of the new operator Extend constructors to receive arguments: function Bird (name, color) { this.name=name; this.color=color; this.numLegs=4; } let newBird = new Bird("Bruce", "red"); Verify an object's constructor with instanceOf: anytime a constructor function creates a new object, that object is said to be an instance of its constructor instanceof allows you to compare an object to a constructor, returning true or false based on whether or not that object was created with the constructor instanceName instanceof ConstructorName; // returns true or false Understand own properties: own properties are defined as such because they are defined directly on the instance object Use prototype properties to reduce duplicate code: if a property will always be the same for each instance, properties in prototype are shared among all of them ContructorName.prototype.popertyName = x ; Iterate over all properties: for (property in duck){ if (duck.hasOwnProperty(property)){ ownProp.push(property); } else { protoProp.push(property); } } Understand the constructor property: instanceName.constructor === ConstructorName ; // returns true if the constructor created that instance Change the prototype to a new object: efficient way to set the prototype t a new object that aleady contains the properties: Bird.prototype = { numLegs: 2, eat: function() { console.log("nom nom nom"); } } Remember to set the constructor property when changing the prototype: manually setting up a prototype (as per previous step) erases the constructor property of the instance to fix this, define the constructor property whenever manually setting a new prototype Bird.prototype = { constructor: Bird, numLegs: 2, eat: function() { console.log("nom nom nom"); } } Understand where an object's prototype comes from: Bird.prototype.isPrototypeOf(duck); // returns true Understand the prototype chain: all objects have a prototype an object's prototype is also an object therefore an object's prototype can have its own prototype Object.prototype is the prototype of custom Constructor.prototype hasOwnProperty method is defined in Object.prototype Object.prototype is a supertype for Bird and duck duck is a subtype for Bird and Object.prototype Use inheritance so you don't repeat yourself: principle in programming called Don't Repeat Yourself (DRY) if for example a method is shared by objects of different prototypes, you can create a supertype including that method Inherit behaviors from a supertype: let duck = Object.create(Animal.prototype); Set the child's prototype to an instance of the parent: Bird.prototype = Object.Create(Animal.prototype); Reset an inherited constructor property: when an object inherits its prototype from another object, it also inherits the supertype's constructor property you can manually set Bird's constructor property to the Bird object function Animal() { } function Bird() { } Bird.prototype = Object.create(Animal.prototype); let duck = new Bird(); duck.constructor=Bird; Add methods after inheritance: Bird.prototype.functionName = function() { statements; }; Override inherited methods: it's possible to override an inherited method by adding a method to ChildObject.prototype using the same method name as the one to override Use a mixin to add common behavior between unrelated objects: there are cases where inheritance is not the best solution to share behavior Bird and Airplane can both fly() but don't inherit from a common parent a mixin allows other objects to use a collection of functions let flyMixin = function(obj) { obj.fly = function() { console.log("I'm flying!"); } }; flyMixin(bird); bird.fly(); Use closure to protect properties within an object from being modified eternally: an object's property declared basically can be modified unvoluntarily by some external code to prevent that, make the property private by creating a variable within the function (therefore only accessible within the constructor function) function Bird() { let hatchedEgg = 10; this.getHatchedEggCount = function() { return hatchedEgg; }; } Understand the immediately invoked function expression (IIFE): (function () { statements; })(); executes the function as soon as it is declared note that the function has no name and is not stored in a variable the () at the end provokes the immediate execution Use an IIFE to create a module: an IIFE is often used to group related functionality into a single object or module let motionModule = (function () { return { glideMixin: function(obj) { obj.glide = function() { console.log("Gliding on the water"); }; }, flyMixin: function(obj) { obj.fly = function() { console.log("Flying, wooosh!"); }; } } })(); motionModule.glideMixin(duck); duck.glide();
let employee = { empId : 1001, empName : 'Rajan', empEmail : 'rajan@gmail.com', designation : 'Manager' }; let tableBody = document.querySelector('#t_body'); // string Concatenation let htmlString = "<tr style='background-color: lightgreen'>" + "\n" + "<td>" + employee.empId + "</td>" + "\n" + "<td>" + employee.empName + "</td>" + "\n" + "<td>" + employee.empEmail + "</td>" + "\n" + "<td>" + employee.designation + "</td>" + "\n" + "</tr>"; tableBody.innerHTML = htmlString; // Template String (Back Tick Operator) let templateString = `<tr style="background-color: lightblue"> <td>${employee.empId}</td> <td>${employee.empName}</td> <td>${employee.empEmail}</td> <td>${employee.designation}</td> </tr>`; tableBody.innerHTML = templateString;
function makeGreeting(language) { return function(first, last) { if(language === "en") { console.log("Hello " + first + " " + last); } if(language === "de") { console.log("Hello " + first + " " + last); } } } var greetEnglish = makeGreeting("en"); var greetGerman = makeGreeting("de"); greetEnglish("Lars", "Schinkel"); greetGerman("Lars", "Schinkel");
var faves = function() { var $element; var init = function( element ){ $element = $(element); $element.on( 'click', '.thumb', function( event ){ viewModel.faves.pop( ko.dataFor(this) ); }); }; return{ init: init }; }();
const utility = require("./Utility/Utility"); do { console.log("Enter Year"); var year = utility.getInputNumber(); var temp = year; var count = 0; while (temp >= 1) { count = count + 1; temp /= 10; } console.log(count); if (count != 4) console.log("year must be four digit"); } while (count != 4); var isLeap = utility.isLeapYear(year); if (isLeap) console.log(`${year} is leap year`); else console.log(`${year} is NOT leap year`)
define([ 'extensions/collections/collection' ], function (Collection) { return Collection.extend({ initialize: function (models, options) { if(options !== undefined){ options.flattenEverything = false; } return Collection.prototype.initialize.apply(this, arguments); }, parse: function () { var data = Collection.prototype.parse.apply(this, arguments); var lines = this.options.axes.y; var hasOther = _.findWhere(lines, { groupId: 'other' }); if (this.options.groupMapping) { _.each(this.options.groupMapping, function (to, from) { from = new RegExp(from + ':' + this.valueAttr); _.each(data, function (model) { var toAttr = to + ':' + this.valueAttr; var sum = 0; _.each(model, function (val, key) { if (key.match(from)) { if (val) { sum += val; } delete model[key]; } }); if (model[toAttr] === undefined) { model[toAttr] = 0; } model[toAttr] += sum; }, this); }, this); } _.each(data, function (model) { var total = null, other = null; _.each(model, function (val, key) { var index = key.indexOf(this.valueAttr); if (index > 1 && model[key]) { // get the prefix value var group = key.replace(':' + this.valueAttr, ''); var axis = _.findWhere(lines, { groupId: group }); if (axis || hasOther) { total += model[key]; } if (!axis) { other += model[key]; delete model[key]; } } }, this); model['other:' + this.valueAttr] = other; model['total:' + this.valueAttr] = total; _.each(lines, function (line) { var prop = (line.key || line.groupId) + ':' + this.valueAttr; var value = model[prop]; if (value === undefined) { value = model[prop] = null; } if (model['total:' + this.valueAttr]) { model[prop + ':percent'] = value / model['total:' + this.valueAttr]; } else { model[prop + ':percent'] = null; } }, this); }, this); return data; }, getYAxes: function () { var axes = Collection.prototype.getYAxes.apply(this, arguments); _.each(this.options.groupMapping, function (to, from) { axes.push({ groupId: from }); }); return axes; } }); });
Ext.QuickTips.init(); var _cob; Ext.onReady(function(){ Ext.override(Ext.menu.DateMenu, { render : function() { Ext.menu.DateMenu.superclass.render.call(this); if (Ext.isGecko || Ext.isSafari || Ext.isChrome) { this.picker.el.dom.childNodes[0].style.width = '178px'; this.picker.el.dom.style.width = '178px'; } } }); var qrUrl = path + "/projectmgr/"; var order; store = new Ext.data.Store({ url : qrUrl+"listSearchNo", reader : new Ext.data.JsonReader({ root : 'data', fields : [ {name: 'search_no'}, {name : 'search_name'}, {name : 'create_date'}, {name : 'id'} ] }) // remoteSort : true }); store.load({params:{start:0,limit:20}}); var sm = new Ext.grid.CheckboxSelectionModel(); var column=new Ext.grid.ColumnModel( [ new Ext.grid.RowNumberer(), sm, {header:"编号",align:'center',dataIndex:"search_no",sortable:true}, {header:"名称",align:'center',dataIndex:"search_name",sortable:true}, {header:"操作",align:'center',dataIndex:"id",width:50, renderer: function (value, meta, record) { // console.log(record); var formatStr = "<input id = 'bt_edit_" + record.get('id') + "' onclick=\"showEditUser('" + record.get('id') + "','" + record.get('search_no') + "','" + record.get('search_name') + "');\" type='button' value='编辑' width ='15px'/>&nbsp;&nbsp;"; var deleteBtn = "<input id = 'bt_delete_" + record.get('id') + "' onclick=\"deleteUser('" + record.get('id') + "');\" type='button' value='删除' width ='15px'/>"; var resultStr = String.format(formatStr); if(loginUserId != record.id){ return "<div>" + resultStr+deleteBtn + "</div>"; }else{ return ""; } } .createDelegate(this) } ] ); var tbar = new Ext.Toolbar({ renderTo : Ext.grid.GridPanel.tbar,// 其中grid是上边创建的grid容器 items :['编号:', { id : 'researchNo', xtype : 'textfield', width : 115, },'名称:', { id : 'researchName', xtype : 'textfield', width : 115, }, { text : '查询', iconCls : 'Magnifier', handler : function() { reloadData(); } }, { text : '重置', iconCls : 'Reload', handler : function() { Ext.getCmp('researchNo').setValue(""); Ext.getCmp('researchName').setValue(""); } },{ text : '添加数据', iconCls : 'Add', handler : function() { showEditUser(); } },{ text : '导入Excel', iconCls : 'Add', handler : function() { showUploadExcel(); } }] }); grid = new Ext.grid.EditorGridPanel({ region:'center', border:false, // autoHeight:true, viewConfig: { forceFit: true, //让grid的列自动填满grid的整个宽度,不用一列一列的设定宽度。 emptyText: '系统中还没有任务' }, sm:sm, cm:column, store:store, autoExpandColumn:0, loadMask:true, frame:true, autoScroll:true, tbar:tbar, bbar:new Ext.PagingToolbar({ store : store, displayInfo : true, pageSize : 20, prependButtons : true, beforePageText : '第', afterPageText : '页,共{0}页', displayMsg : '第{0}到{1}条记录,共{2}条', emptyMsg : "没有记录" }), }); var mainPanel = new Ext.Panel({ region:"center", layout:'border', border:false, items:[grid], }); var viewport=new Ext.Viewport({ //enableTabScroll:true, layout:"border", items:[ mainPanel ] }); }); function reloadData(){ var researchNo = document.getElementById('researchNo').value ; var researchName = document.getElementById('researchName').value ;; store.baseParams['searchNo'] = researchNo; store.baseParams['searchName'] = researchName; store.reload({ params: {start:0,limit:20}, callback: function(records, options, success){ // console.log(records); }, scope: store }); } function deleteUser(id){ Ext.Msg.confirm('删除数据', '确认?',function (button,text){if(button == 'yes'){ Ext.Ajax.request({ url : path + "/projectmgr/deleteResearchInfo", method : 'post', params : { id:id }, success : function(response, options) { var o = Ext.util.JSON.decode(response.responseText); if(o.i_type && "success"== o.i_type){ reloadData(); }else{ Ext.Msg.alert('提示', o.i_msg); } }, failure : function() { Ext.Msg.alert('提示', '删除失败'); } }); }}); } function showEditUser(_id,_searchNo,_searchName){ if(typeof(_id) == "undefined" || _id == ""){ _id =""; } var _fileForm = new Ext.form.FormPanel({ frame: true, autoHeight: true, labelWidth: 80, labelAlign: "right", bodyStyle:"text-align:left", border : false, items: [ {xtype:"textfield", width:180,id: "eSearchNo",name: "eUserName", fieldLabel: "编号",value:_searchNo}, {xtype:"textfield", width:180,id: "eSearchName",name: "enewpwd", fieldLabel: "名称",value:_searchName} ], }); var _importPanel = new Ext.Panel({ layout : "fit", layoutConfig : { animate : true }, items : [_fileForm], buttons : [{ id : "btn_import_wordclass", text : "保存", handler : function() { var no = Ext.getCmp('eSearchNo').getValue(); var name = Ext.getCmp('eSearchName').getValue(); if(typeof(no) == "undefined" || no == ""){ Ext.Msg.alert('提示', '请填写编号'); return; } if(typeof(name) == "undefined" || name == ""){ Ext.Msg.alert('提示', '请填写名称'); return; } Ext.Ajax.request({ url : path + "/projectmgr/editReachInfo", method : 'post', params : { id:_id, name:name, no:no }, success : function(response, options) { var o = Ext.util.JSON.decode(response.responseText); if(o.i_type && "success"== o.i_type){ Ext.Msg.alert("success",'保存成功!',function(){ newWin.close(); reloadData(); }); }else{ Ext.Msg.alert('提示', o.i_msg); } }, failure : function() { Ext.Msg.alert('提示', '操作失败'); } }); } }] }); newWin = new Ext.Window({ width : 520, height:140, title : '用户编辑', defaults : {// 表示该窗口中所有子元素的特性 border : false // 表示所有子元素都不要边框 }, plain : true,// 方角 默认 modal : true, shim : true, collapsible : true,// 折叠 closable : true, // 关闭 closeAction: 'close', resizable : false,// 改变大小 draggable : true,// 拖动 minimizable : false,// 最小化 maximizable : false,// 最大化 animCollapse : true, constrainHeader : true, autoHeight : false, items : [_importPanel] }); newWin.show(); } function showUploadExcel(projrctId){ var winHeight=''; var isHid =null; var imisHid =null; if(typeof(projrctId) == "undefined" || projrctId == ""){ isHid = true; imisHid = false; winHeight = 200; }else{ winHeight = 200; isHid = false; imisHid = true; } var uxfile = new Ext.ux.form.FileUploadField({ width: 200, id : 'showFileName', name : 'uploadFile', fieldLabel : '文件名' }); uxfile.setValue(); var _fileForm = new Ext.FormPanel({ layout : "fit", frame : true, border : false, autoHeight : true, waitMsgTarget : true, defaults : { bodyStyle : 'padding:10px' }, margins : '0 0 0 0', labelAlign : "left", labelWidth : 80, fileUpload : true, items : [{ xtype:'hidden', fieldLabel: 'id', name: 'id'//, // value: '' },{ xtype : 'fieldset', title : '选择文件', autoHeight : true, //hidden:isHid, items : [{ id : 'sampleUploadFileId', name : 'uploadFile', xtype : "textfield", fieldLabel : '选择文件', inputType : 'file', anchor : '96%'//, // hidden:isHid, // hideLabel:isHid }] }] }); var _importPanel = new Ext.Panel({ layout : "fit", layoutConfig : { animate : true }, items : [_fileForm], buttons : [{ id : "btn_import_wordclass", text : "保存", handler : function() { // var vers = document.getElementById('importTitle').value ; // var reg = /^\d{8}$/; // if(vers.match(reg) == null){ // Ext.Msg.alert("error", "版本号只能填写8位数字,如20150101"); // return; // } var upval = Ext.getCmp("sampleUploadFileId").getValue(); if (!upval) { Ext.Msg.alert("error", "请选择你要上传的文件"); return; } else { if(typeof(projrctId) == "undefined" || projrctId == ""){ if(upval.indexOf('.xls') < 0 && upval.indexOf('.xlsx') < 0){ Ext.Msg.alert("error", "请选择正确的EXCEl文件"); return; } } this.disable(); var btn = this; // 开始上传 var sampleForm = _fileForm.getForm(); sampleForm.submit({ url : path +'/projectmgr/uploadSearchNoInfoFile', params : { }, success : function(form, action) { btn.enable(); var data = Ext.decode(action.response.responseText); // console.log(data); if(data.i_type == "success"){ Ext.Msg.alert("success",'上传成功!请耐心等待导入结果,详情请查询“操作记录”信息',function(){ newWin.close(); reloadData(); }); }else{ Ext.Msg.alert("Error",data.i_msg,function(){ //关闭后执行 newWin.close(); reloadData(); }); } }, failure : function(form, action) { var data = Ext.decode(action.response.responseText); Ext.Msg.alert("Error",data.msg,function(){ newWin.close(); reloadData(); }); } }); } } },{ id : "btn_import_wordclass_down", text : "下载示例文件", handler : function() { window.location= path+"/example/research_no_dictionary_example.xlsx"; } }] }); newWin = new Ext.Window({ width : 520, title : '导入数据', height : winHeight, defaults : {// 表示该窗口中所有子元素的特性 border : false // 表示所有子元素都不要边框 }, plain : true,// 方角 默认 modal : true, shim : true, collapsible : true,// 折叠 closable : true, // 关闭 closeAction: 'close', resizable : false,// 改变大小 draggable : true,// 拖动 minimizable : false,// 最小化 maximizable : false,// 最大化 animCollapse : true, constrainHeader : true, autoHeight : false, items : [_importPanel] }); newWin.show(); }
/* eslint-disable no-catch-shadow */ /* eslint-disable no-shadow */ /** * @param {string} endpoint Endpoint * @param {object{}} [token = null] API JWT token (optional) * @param {object{}} [options = {}] Fetch options (optional) * @param {string} [baseURL = 'https://dummybaseURL'] Base url (optional) * * @returns {object[]} [response, error, isLoading, dispatchFetch] */ import {useState} from 'react'; const useFetch = ( endpoint, token = null, options = {}, baseURL = 'https://dummybaseURL', ) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); // const [token, storeToken, removeToken] = useStorage('patricia_token'); const predefinedOptions = { method: 'GET', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', }, }; options = {...predefinedOptions, options}; const dispatchFetch = (body = {}) => { setIsLoading(true); const fetchData = async () => { try { options = token ? {...options, token} : options; const res = await fetch(baseURL + endpoint, options); const json = await res.json(); if (res.ok) { setResponse(json?.data); setIsLoading(false); } else { setError(json); setResponse(null); setIsLoading(false); } } catch (error) { setError(error); setResponse(null); setIsLoading(false); } }; fetchData(); }; return [response, error, isLoading, dispatchFetch]; }; export default useFetch;
const moment = require('moment'); const { ObjectId } = require('mongoose').Types; const Campaign = require('../models/campaign'); const Analytics = require('../models/analytics/event'); const createDateRange = (start, end) => { const dates = []; let current = start; while (current <= end) { dates.push(moment(current)); current = moment(current).add(1, 'days'); } return dates; }; const fillDayData = (date, days) => { const day = moment(date).format('YYYY-MM-DD'); for (let i = 0; i < days.length; i += 1) { const d = days[i]; if (d.date === day) { d.date = moment(day).toDate(); return d; } } const views = 0; const clicks = 0; const ctr = 0; return { date: moment(day).toDate(), views, clicks, ctr, }; }; const getCtrProject = () => ({ $cond: [{ $eq: ['$views', 0] }, 0.00, { $divide: [{ $floor: { $multiply: [10000, { $divide: ['$clicks', '$views'] }] } }, 100] }], }); module.exports = { /** * * @param {*} pushId */ async campaignSummary(pushId) { const campaign = await Campaign.findOne({ pushId }); if (!campaign) throw new Error(`No campaign record found for pushId '${pushId}'`); const cid = campaign.get('id'); const start = moment(campaign.get('criteria.start')).startOf('day'); const end = campaign.get('criteria.end') ? moment(campaign.get('criteria.end')).endOf('day') : moment().endOf('day'); const pipeline = [ { $match: { cid: new ObjectId(cid), e: { $in: ['view-js', 'click-js'] }, d: { $gte: start.toDate(), $lte: end.toDate() }, }, }, { $project: { date: { $dateToString: { format: '%Y-%m-%d', date: '$d' } }, view: { $cond: [{ $eq: ['$e', 'view-js'] }, 1, 0] }, click: { $cond: [{ $eq: ['$e', 'click-js'] }, 1, 0] }, }, }, { $group: { _id: '$date', views: { $sum: '$view' }, clicks: { $sum: '$click' }, }, }, { $sort: { date: 1 }, }, { $project: { date: '$_id', views: '$views', clicks: '$clicks', ctr: getCtrProject(), }, }, { $group: { _id: null, days: { $push: { date: '$date', views: '$views', clicks: '$clicks', ctr: '$ctr', }, }, views: { $sum: '$views' }, clicks: { $sum: '$clicks' }, }, }, { $project: { _id: 0, days: 1, views: 1, clicks: 1, ctr: getCtrProject(), }, }, ]; const results = await Analytics.aggregate(pipeline); const out = results[0]; if (!out) return this.emptySummary(); const dates = createDateRange(start, end); out.days = dates.map(d => fillDayData(d, out.days)); return out; }, /** * */ emptySummary() { return { views: 0, clicks: 0, ctr: 0, days: [], }; }, /** * * @param {*} pushId */ async campaignCreativeBreakdown(pushId) { const campaign = await Campaign.findOne({ pushId }); if (!campaign) throw new Error(`No campaign record found for pushId '${pushId}'`); const cid = campaign.get('id'); const creatives = campaign.get('creatives'); const creativeIds = []; const creativesById = []; creatives.forEach((creative) => { creativeIds.push(creative._id); creativesById[creative._id] = creative; }); const start = moment(campaign.get('criteria.start')).startOf('day'); const end = campaign.get('criteria.end') ? moment(campaign.get('criteria.end')).endOf('day') : moment().endOf('day'); const pipeline = [ { $match: { e: { $in: ['load-js', 'view-js', 'click-js', 'contextmenu-js'] }, d: { $gte: start.toDate(), $lte: end.toDate() }, cid: ObjectId(cid), cre: { $exists: true }, }, }, { $project: { date: { $dateToString: { format: '%Y-%m-%d', date: '$d' } }, e: '$e', cid: '$cid', cre: '$cre', }, }, { $group: { _id: { e: '$e', date: '$date', cre: '$cre', }, n: { $sum: 1 }, }, }, { $project: { _id: false, date: '$_id.date', cre: '$_id.cre', view: { $cond: [{ $eq: ['$_id.e', 'view-js'] }, '$n', 0] }, click: { $cond: [{ $eq: ['$_id.e', 'click-js'] }, '$n', 0] }, }, }, { $group: { _id: { date: '$date', cre: '$cre', }, views: { $sum: '$view' }, clicks: { $sum: '$click' }, }, }, { $project: { _id: false, date: '$_id.date', cre: '$_id.cre', views: '$views', clicks: '$clicks', ctr: getCtrProject(), }, }, { $sort: { date: 1 }, }, { $group: { _id: '$cre', days: { $push: '$$ROOT' }, clicks: { $sum: '$clicks' }, views: { $sum: '$views' }, }, }, { $project: { id: '$_id', cre: '$_id.cre', days: '$days', views: '$views', clicks: '$clicks', ctr: getCtrProject(), }, }, { $group: { _id: null, creatives: { $push: '$$ROOT' }, clicks: { $sum: '$clicks' }, views: { $sum: '$views' }, }, }, { $project: { _id: false, creatives: '$creatives', views: '$views', clicks: '$clicks', ctr: getCtrProject(), }, }, ]; const results = await Analytics.aggregate(pipeline); const out = results[0]; if (!out) return this.emptyCampaignBreakdown(creatives); const dates = createDateRange(start, end); for (let i = 0; i < out.creatives.length; i += 1) { const id = out.creatives[i]._id; out.creatives[i].creative = creativesById[id]; out.creatives[i].days = dates.map(d => fillDayData(d, out.creatives[i].days)); } return out; }, /** * * @param {*} creatives */ emptyCampaignBreakdown(creatives) { return { creatives: creatives.map(creative => ({ creative, views: 0, clicks: 0, ctr: 0, days: [], })), views: 0, clicks: 0, ctr: 0, }; }, };
// function createGreeter(language) { // switch (language) { // case 'en': // return () => console.log('Hello!'); // case 'es': // return () => console.log('Hola!'); // case 'fr': // return () => console.log('Bonjour!'); // } // } function createGreeter(language) { switch (language) { case 'en': return () => console.log('Hello!') case 'es': return function() { console.log('Hola!'); } case 'fr': return () => console.log('Bonjour!'); } } let greeterEs = createGreeter('es'); greeterEs(); // logs 'Hola!' greeterEs(); // logs 'Hola!' greeterEs(); // logs 'Hola!' let greeterEn = createGreeter('en'); greeterEn(); // logs 'Hello!'
var _window = window.parent, // window obj of the main page page = $(_window.document); // document obj of the main page var TuneUp = { imagePath: '/fiveruns_tuneup/images', parentStepOf: function(e) { return e.parent().parent().parent(); }, adjustFixedElements: function(e) { page.find('*').each(function() { if($(this).css("position") == "fixed") { TuneUp.adjustElement(e); } }); }, adjustElement: function(e) { var element = $(e) var top = parseFloat(element.css('top') || 0); var adjust = 0; if(!element.hasClass('tuneup-flash-adjusted')) { adjust = page.find('#tuneup-flash.tuneup-show').length ? 27 : -27; element.addClass('tuneup-flash-adjusted'); } if (element.hasClass('tuneup-adjusted')) { element.css({top: (top + adjust) + 'px'}); } else { element.css({top: (top + 50 + adjust) + 'px'}); element.addClass('tuneup-adjusted'); } }, adjustAbsoluteElements: function(base) { $(base).find('> *[id!=tuneup]').each(function() { switch($(this).css('position')) { case 'absolute': TuneUp.adjustElement(this); TuneUp.adjustAbsoluteElements(this); break; case 'relative': // Nothing break; default: TuneUp.adjustAbsoluteElements(this); } }); } } $(window).ready(function() { page.find('#tuneup-save-link').click(function () { var link = $(this); link.hide(); $.getJSON($(this).attr('href'), {}, function(data) { if (data.run_id) { var url = "http://tuneup.fiveruns.com/runs/" + data.run_id; var goToRun = function() { if(!_window.open(url)) { page.location = url; } return false; } link.html("Shared!"); link.click(goToRun); goToRun(); } else if (data.error) { alert(data.error); } link.show(); }); return false; }); page.find('#tuneup .with_children .tuneup-title a.tuneup-step-name').toggle( // Note: Simple 'parent' lookup with selector doesn't seem to work function() { TuneUp.parentStepOf($(this)).addClass('tuneup-opened'); }, function() { TuneUp.parentStepOf($(this)).removeClass('tuneup-opened'); } ); page.find('.tuneup-step-extras').hide().find('> div').prepend($('<a class="tuneup-close-link" href="#">Close</a>').click(function() { $(this).parent().parent().hide(); })); page.find('#tuneup .with_children .tuneup-title a.tuneup-step-extras-link').html( $("<img src='" + TuneUp.imagePath + "/magnify.png' alt=''/>") ).toggle( function() { TuneUp.parentStepOf($(this)).find('> .tuneup-step-extras').show(); }, function() { TuneUp.parentStepOf($(this)).find('> .tuneup-step-extras').hide(); } ) page.find('.tuneup-step-extra-extended').hide().each(function() { var extended = $(this); extended.before('<br/>'); extended.before($('<a class="tuneup-more-link" href="#">(Show&nbsp;' + extended.attr('title') + ')</a>').toggle( function() { extended.show(); $(this).html('(Hide&nbsp;' + extended.attr('title') + ')'); return false; }, function() { extended.hide(); $(this).html('(Show&nbsp;' + extended.attr('title') + ')'); return false; } )); }); TuneUp.adjustFixedElements(page); });
import fieldsBase from 'config/new.fields.js'; import AuthContext from 'context/auth/auth.context'; import { useContext, useEffect, useState } from 'react'; import apiService from 'services/api.service'; import fieldsService from './fields.service'; export default function useDetails(id) { const { isLoggedIn } = useContext(AuthContext); const [fields, setFields] = useState(fieldsBase); const [isLoading, setLoading] = useState(false); const [item, setItem] = useState(null); useEffect(() => { if (!isLoggedIn()) { return; } setLoading(true); apiService.getByID(id).then(item => { setItem(item) setFields(fieldsService.addDefaultValues(fields, item)); setLoading(false); }); }, [id, fields, isLoggedIn]); function editItem(v, history) { setLoading(true); v.id = id; apiService.editItem(v) .then(() => { history.push(`/details/${id}`); }) .catch(err => { alert('Error:', err); }) .finally(() => { setLoading(false); }); } return { isLoggedIn, item, isLoading, setLoading, fields, editItem }; }
// @flow import type { StandardTx, SwapFuncParams } from './checkSwapService.js' const js = require('jsonfile') const fetch = require('node-fetch') const { checkSwapService } = require('./checkSwapService.js') const confFileName = './config.json' const config = js.readFileSync(confFileName) const CACHE_FILE = './cache/wyrRaw.json' const isConfigValid = (typeof config.wyre !== 'undefined' && config.wyre.periscopeClientKey !== 'undefined') let WYRE_PERSICOPE_CLIENT_KEY if (isConfigValid) { WYRE_PERSICOPE_CLIENT_KEY = config.wyre.periscopeClientKey } async function doWyre (swapFuncParams: SwapFuncParams) { return checkSwapService(fetchWyre, CACHE_FILE, 'WYR', swapFuncParams ) } function parseTxStr (txStr) { const txItems = txStr.split(',') return { id: txItems[0], owner: txItems[1], status: txItems[2], createdAt: txItems[3], completedAt: txItems[4], sourceAmount: txItems[5], sourceCurrency: txItems[6], usdFeeEquiv: txItems[7], destAmount: txItems[8], destCurrency: txItems[9], usdEquiv: txItems[10] } } async function fetchWyre (swapFuncParams: SwapFuncParams) { if (!swapFuncParams.useCache) { console.log('Fetching Wyre...') } let diskCache = { txs: [] } try { diskCache = js.readFileSync(CACHE_FILE) } catch (e) {} const ssFormatTxs: Array<StandardTx> = [] if (!swapFuncParams.useCache && isConfigValid) { const url = `https://app.periscopedata.com/api/sendwyre/chart/csv/${WYRE_PERSICOPE_CLIENT_KEY}` const result = await fetch(url, { method: 'GET' }) const csvResults = await result.text() const txs = csvResults.split('\n') txs.shift() for (const txStr of txs) { const tx = parseTxStr(txStr) if ( tx.status === 'COMPLETED' && tx.sourceCurrency !== tx.destCurrency ) { const date = new Date(tx.createdAt) const timestamp = date.getTime() / 1000 const ssTx: StandardTx = { status: 'complete', inputTXID: tx.id, inputAddress: '', inputCurrency: tx.sourceCurrency, inputAmount: tx.sourceAmount, outputAddress: '', outputCurrency: tx.destCurrency, outputAmount: tx.destAmount, timestamp } ssFormatTxs.push(ssTx) } } } const out = { diskCache, newTransactions: ssFormatTxs } return out } module.exports = { doWyre }
//grid and clicking function inspired by https://www.javaer101.com/en/article/39601632.html let arr = []; var onea = false; var oneb, onec, twoa, twob, twoc, threea, threeb, threec = false; var zerow = 0; var onew = 0.66; var fourw = 0.33; var goalnum = 100; function setup() { canvas = createCanvas(300, 300); for (var j = 0; j < 3; j++) { var inArr = []; for (var i = 0; i < 3; i++) { var rect = new Rect(i, j); inArr.push(rect); } arr.push(inArr) } } function draw() { background(255); for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { arr[i][j].show() } } } function mousePressed() { arr.forEach(function(e, index) { e.forEach(function(d, index2) { arr[index][index2].clicked() }); }); } function Rect(i, j) { this.fill = 'pink' this.i = i; this.j = j; this.x = i * 100 this.y = j * 100 this.clickcheck = false; this.clicked = function() { let x1 = this.x, x2 = x1 + 100, y1 = this.y, y2 = y1 + 100; if (mouseX > x1 && mouseX < x2 && mouseY > y1 && mouseY < y2) { if (this.clickcheck) { this.clickcheck = false; this.fill = 'pink'; if (this.x == 0) { if (this.y == 0) { onea = false; } else if (this.y == 100) { twoa = false; } else { threea = false; } } else if (this.x == 100) { if (this.y == 0) { oneb = false; } else if (this.y == 100) { twob = false; } else { threeb = false; } } else { if (this.y == 0) { onec = false; } else if (this.y == 100) { twoc = false; } else { threec = false; } } numberRecognize(); } else { this.clickcheck = true; this.fill = 'black' if (this.x == 0) { if (this.y == 0) { onea = true; console.log("onea click"); } else if (this.y == 100) { twoa = true; } else { threea = true; } } else if (this.x == 100) { if (this.y == 0) { oneb = true; } else if (this.y == 100) { twob = true; } else if (this.y == 200) { threeb = true; } } else { if (this.y == 0) { onec = true; } else if (this.y == 100) { twoc = true; } else { threec = true; } } console.log(onea, oneb, onec); numberRecognize(); } } } this.show = function() { fill(this.fill) stroke('black') rect(this.x, this.y, 100, 100) } } function numberRecognize() { zerow = document.getElementById("zerow").value; onew = document.getElementById("onew").value; fourw = document.getElementById("fourw").value; print(zerow, onew, fourw); var zero = 0; var one = 0; var four = 0; if (onea){ zero += 0.45; four += 0.45; one += 0.1; } if (oneb){ one += 0.66; zero += 0.33; } if (onec){ zero +=0.5; four += 0.5; } if (twoa){ zero +=0.5; four +=0.5; } if (twob){ one += onew; four += fourw; zero += zerow; } if(twoc){ zero +=0.5; four +=0.5; } if (threea){ zero += 1; } if (threeb){ one +=0.66; zero += 0.33; } if (threec){ zero +=0.5; four +=0.5; } if (zero > four && zero > one){ finalnum = 0; } else if (one > zero && one > four){ finalnum = 1; } else { finalnum = 4; } console.log(zero, one, four); document.getElementById("result").innerHTML = finalnum; }
 idleMax = 30; // Logout after 30 minutes of IDLE idleTime = 0; function checkpage() { console.log("InIN"); setInterval(timerIncrement, 60000); $(this).mousemove(function (e) { idleTime = 0; }); $(this).keypress(function (e) { idleTime = 0; }); } function timerIncrement() { console.log("123"); idleTime = idleTime + 1; if (idleTime > idleMax) { window.location.href = 'Account/KillSession'; } }
import React from 'react'; import { shallow, mount } from 'enzyme'; import SOCIAL_PROFILES from './../data/socialProfiles'; import SocialProfile from './../components/SocialProfiles' const renderProjects = (props, isDeep) => isDeep ? mount(<SocialProfile {...props} />) : shallow(<SocialProfile {...props} />); describe('Component: Projects', () => { const getMinimimProps = (newProps) => Object.assign({}, { },newProps); it('Renders basic component', () => { const props = getMinimimProps(); const wrapper = renderProjects(props, true); expect(wrapper.length).toEqual(1); }); it('first div must have projects class', () => { const props = getMinimimProps(); const wrapper = renderProjects(props); expect(wrapper.hasClass('.projects')).toBe(true); }); it('first div must have title class', () => { const props = getMinimimProps(); const wrapper = renderProjects(props); expect(wrapper.hasClass('.title')).toBe(true); }); it('should pass correct props to project component', () => { const props = getMinimimProps(); const SocialProfile ={ id: 1, link: 'mailto:rvara002@fiu.edu', image: emailIcon }, const wrapper = renderProjects(props); const expectedProps = { className :'project', key: SocialProfile.id, SocialProfile: SocialProfile }; expect(wrapper.find('.SocialProfile').props().toMatchObject(expectedProps)); }); });
/** * Sample React Native App * https://github.com/facebook/react-native * @flow*/ import Home from '../home/Home' import LoginUser from '../login/Login' import Gas from '../gas/Gas' import Hum from '../hum/Hum' import Press from '../press/Press' import Temp from '../temp/Temp' import React, { Component } from 'react'; import { AppRegistry, Platform, StyleSheet, Text, View } from 'react-native'; import {StackNavigator} from 'react-navigation'; const Navigation = StackNavigator({ LoginUser : {screen: LoginUser}, Home : {screen: Home}, Gas : {screen: Gas}, Hum : {screen: Hum}, Press : {screen: Press}, Temp : {screen: Temp}, }); import { Provider } from 'react-redux'; import store from '../store'; export default class App extends Component { render() { return ( <Provider store={store}> <Navigation /> </Provider> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); /*import React, { Component } from 'react'; import { AppRegistry, Navigator, Text, View } from 'react-native'; import MyScene from './MyScene'; class SimpleNavigationApp extends Component { render() { return ( <Navigator initialRoute={{ title: 'My Initial Scene', index: 0 }} renderScene={(route, navigator) => <MyScene title={route.title} // Function to call when a new scene should be displayed onForward={ () => { const nextIndex = route.index + 1; navigator.push({ title: 'Scene ' + nextIndex, index: nextIndex, }); }} // Function to call to go back to the previous scene onBack={() => { if (route.index > 0) { navigator.pop(); } }} /> } /> ) } }*/
import React from 'react'; const FaceRecognition = (props) => { return( <div className="FaceRecognition pt3 flex justify-center"> <div className="absolute"> <img id="faceImg" alt=" " src={props.imgUrl} height="auto" width="500px" /> <div className="bounding-box" style={{ top: props.box.topRow, bottom: props.box.bottomRow, left: props.box.leftColumn, right: props.box.rightColumn }}> </div> </div> </div> ) } export default FaceRecognition;
import React, { Component } from "react" export default class ViewStatus extends Component { render() { const { bgcolor, abigoID, photoURL, text } = this.props return ( <div className="ViewStatus" style={{ background: `${bgcolor}` }}> <header className="informationSection"> <div className="backButton"> <i className="material-icons" style={{ color: "#fff" }}> arrow_back_ios </i> </div> <div className="userDetailProfile"> <img src={photoURL} alt="profile " style={{ width: "40px", height: "40px", borderRadius: "50%" }} /> </div> <div className="userDetails" style={{ color: "#fff" }}> {abigoID} </div> </header> <article className="tex_status"> <p>{text}</p> </article> </div> ) } }
import axios from 'axios' import React, { Component } from 'react' import '../src/style.css' import {connect} from 'react-redux' import {deleteStudentData} from '../src/actions/index' class DeleteStudent extends Component{ constructor(){ super() this.deleteCurrentStudent= this.deleteCurrentStudent.bind(this) } deleteCurrentStudent(data){ data.deleteStudent(data.props.id) } render(){ return( <div> <button onClick={()=>{this.deleteCurrentStudent(this.props)}} className='deleteButton'>X</button> </div> ) } } const mapDispatchToProps=(dispatch)=>{ return{ deleteStudent: (id)=>{ dispatch(deleteStudentData(id)) } } } export default connect(null, mapDispatchToProps)(DeleteStudent)
import tabs from './modules/tabs'; import modal from './modules/modal'; import data from './modules/data'; import cards from './modules/cards'; import form from './modules/form'; import slider from './modules/slider'; import loader from './modules/loader'; import accordion from './modules/accordion'; import {openModal} from './modules/modal'; window.addEventListener("DOMContentLoaded", () => { const modalTimer = setTimeout(() => openModal('.modal', modalTimer), 50000); tabs(); modal('[data-modal]', '.modal', modalTimer); data(); cards(); form(modalTimer); slider(); loader(); accordion(); });
import React, { Component } from 'react'; import { View, Animated, Button, PanResponder } from 'react-native' export default class SildeButton extends Component { constructor(props) { super(props); this.state = { pan: new Animated.ValueXY(), isOnDuty: false } } componentWillMount() { this.state.pan.addListener(({ x, y }) => { console.log("Value ", x) // console.log("X ",this.state.pan.x) this._valueX = x // this._valueY = y; }) this.panResponder = PanResponder.create({ onMoveShouldSetResponderCapture: () => true, onMoveShouldSetPanResponderCapture: () => true, // Initially, set the value of x and y to 0 (the center of the screen) onPanResponderGrant: (e, gestureState) => { this.state.pan.setOffset({ x: this.state.pan.x._value, y: this.state.pan.y._value }); this.state.pan.setValue({ x: 0, y: 0 }); }, onPanResponderMove: Animated.event([ null, { dx: (this.state.pan.x._value >= 0) ? this.state.pan.x : 0, dy: 0 }, ]), onPanResponderRelease: (e, { vx, vy }) => { console.log("vx", vx) this.state.pan.flattenOffset(); if (this._valueX < 125) { this.setState({ isOnDuty: false }) Animated.spring( //Step 1 this.state.pan, //Step 2 { toValue: { x: 0, y: 0 } } //Step 3 ).start(); } else if (this._valueX > 125) { this.setState({ isOnDuty: true }) Animated.spring( //Step 1 this.state.pan, //Step 2 { toValue: { x: 250, y: 0 } } //Step 3 ).start(() => { // this.setState({ isOnDuty: true }) }); } /* let currentPosition = height - peekHeight + this._valueY console.log("Y ", currentPosition) if (this._valueY <= -100) { Animated.spring( //Step 1 this.state.pan, //Step 2 { toValue: { x: 0, y: -300 } } //Step 3 ).start(); } else { Animated.spring( //Step 1 this.state.pan, //Step 2 { toValue: { x: 0, y: 0 } } //Step 3 ).start(); }*/ // Animated.spring( //Step 1 // this.state.pan, //Step 2 // { toValue: { x: 0, y: 0 } } //Step 3 // ).start(); } }) } render() { return ( <View style={{ flex: 1, justifyContent: 'center' }} > <View style={{ marginHorizontal: 30, height: 50, elevation: 10, backgroundColor: this.state.isOnDuty ? 'green' : 'red', borderRadius: 25, overflow: 'hidden' }} > <Animated.View {...this.panResponder.panHandlers} style={[this.state.pan.getLayout(), { height: 50, width: 50, borderRadius: 25, backgroundColor: 'white', elevation: 5 }]} /> </View> <Button title='Close' onPress={() => this.props.navigation.navigate('Ripple')} /> </View > ) } }
/* ;(function() { 'use strict'; angular .module('corporateDash') .factory('issuesService', function($http) { var getIssues = function() { // then() returns a new promise. We return that new promise. // that new promise is resolved via response.data return $http.get('../../data/issues.json').then(function(response) { return response.data; }); }; }); })(); */
// ********************************************* // * mongodb connection // ********************************************* var path = require("path"); module.exports = (function(module){ // read module var serialport = require('serialport'); var portName = module.options.serialport; var port = module.options.baudRate; var fs = require('fs'); try { fs.statSync(portName); var sp = new serialport.SerialPort(portName, { baudRate: port, dataBits: 8, stopBits: 1 }); return sp; } catch (e) { } return null; });