text
stringlengths
7
3.69M
#!/usr/bin/env node const axios = require("axios"); const { alicePair, bobPair } = require("../pairs.json"); const { SERVER_URL } = require("./lib/sdk"); const fundRootAccounts = async publicKeys => Promise.all( publicKeys.map( async publicKey => await axios.get("/friendbot", { baseURL: SERVER_URL, params: { addr: publicKey } }) ) ); fundRootAccounts([alicePair.publicKey, bobPair.publicKey]) .then(() => console.log("ok")) .catch(e => { console.error(e); throw e; });
import React from 'react'; import "../styles/register.css" import RegisterForm from "../components/registerForm" import Header from "../components/header.jsx" const Register = () => { return ( <div className="Register"> <Header /> <div className="Register-body"> <div id="register-title">Register Account</div> <RegisterForm /> </div> </div > ); }; export default Register;
export {DataContent} from "./DataContent" export {ContentContext} from "./DataContent"
import { renderComponent, expect } from '../test_helper' import App from '../../app/components/app' // Use 'describe' to group together similar tests describe('App', ()=> { let component beforeEach(()=> { component = renderComponent(App) }) // Use 'it' to test a single attribute of a target it('is mounted', ()=> { // Use 'expect' to make an assertion about a target expect(component.find('.app')).to.exist }) })
/** * THREE.Context * @author jeremt / https://github.com/jeremt/ */ ~function () { THREE = THREE || {}; /** * Create a new context and initialize the application. */ THREE.Context = function () { var self = this; // Inherite from eventDispatcher. THREE.EventDispatcher.call(this); this.paused = false; this.controls = null; // Create html container. var container = document.createElement('div'); container.className = "threejs-container"; document.body.appendChild(container); // Create a clock. this.clock = new THREE.Clock(); this.clock.start(); // Create camera. this.camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); // Create scene. this.scene = new THREE.Scene(); // Create the renderer. this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(window.innerWidth, window.innerHeight); container.appendChild(this.renderer.domElement); window.addEventListener('resize', function () { self.camera.aspect = window.innerWidth / window.innerHeight; self.camera.updateProjectionMatrix(); self.renderer.setSize(window.innerWidth, window.innerHeight); }, false); } /** * Inherite from THREE.EventDispatcher. */ THREE.Context.prototype = Object.create(THREE.EventDispatcher.prototype); /** * Reset the context to restart the application. */ THREE.Context.prototype.reset = function () { // TODO } /** * Pause the application. */ THREE.Context.prototype.pause = function () { this.paused = true; this.dispatchEvent({type: "pause"}); } /** * Quit the application. */ THREE.Context.prototype.quit = function () { this.paused = true; this.dispatchEvent({type: "quit"}); } /** * Play the application. */ THREE.Context.prototype.play = function () { this.paused = false; this.dispatchEvent({type: "play"}); } /** * Start the application. */ THREE.Context.prototype.start = function () { var self = this; this.dispatchEvent({type: "start"}); ~function animate() { requestAnimationFrame(animate); var delta = self.clock.getDelta(); if (self.controls) self.controls.update(delta); self.dispatchEvent({ type: "frame", deltaTime: delta }); if (!this.paused) self.renderer.render(self.scene, self.camera); }(); } }();
'use strict' /** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */ const Model = use('Model') class UserTask extends Model { static get dates () { return super.dates.concat(['answered_at', 'checked_at']) } user () { return this.belongsTo('App/Models/User') } task () { return this.belongsTo('App/Models/Task') } } module.exports = UserTask
var mongoose = require('../db').mongoose; var Schema = mongoose.Schema; var categorySchema = new Schema({ 'id' : {type : Number,index:true, unique: true,required: true }, 'name' : String }); module.exports = mongoose.model('category', categorySchema);
$('.btn-account-login').on('click',function(){ $('.modal-login').modal('show'); }) $('.cart-browse').on('click',function(){ $('.cart-modal').modal('show'); }) $('.store-categories').slick({ infinite: false, // autoplay: true, slidesToShow: 9, slidesToScroll: 6, speed: 300, arrows: true, }); $('.store-categories-inner').slick({ infinite: true, autoplay: true, slidesToShow: 10, slidesToScroll: 6, speed: 3000, arrows: true, }); $('.product-image-slider').slick({ infinite: true, autoplay: true, slidesToShow: 1, slidesToScroll: 1, speed: 500, dots: true }); $('.more-category').on('click',function(){ $('.more-category').toggleClass('show'); $('.list-more-category').toggleClass('hide'); }) $('.close-tooltip').on('click',function(){ $('.location-tooltip').css('display','none'); })
import style from './css/wordCreator.module.css'; import React from 'react'; import CloseBtn from '../../../buttons/closeBtn'; import Word from './word'; import AddWordBtn from './addWordBtn'; import SaveBtn from './saveBtn'; import { closeWordCreator, addWord, addDictionary, changeDictionary } from '../../../../actions/actions'; const WordCreator = ({ dispatch, state }) => { let word; let translate; let name; let repeat; return ( <div className={state.wordCreator.action ? style.wrapper : style.hiden}> <div className={style.creator}> <div className={style.name}> <input className={style.name_input} ref={node => name = node} placeholder='Name' /> </div> <CloseBtn onBtnClick={() => { dispatch(closeWordCreator()); }} absolute={{position: 'absolute', top: '-10px', right: 0}}> x </CloseBtn> <div className={style.words}> {state.wordCreator.list.map(word => { return <Word key={word.id} word={word.word} translate={word.translate} id={word.id} dispatch={dispatch} /> })} </div> <div className={style.wordInputs}> <input placeholder='word' className={style.wordInput} ref={node => word = node} /> <input placeholder='translate' className={style.wordInput} ref={node => translate = node} /> </div> <AddWordBtn onAddWord={(id) => { dispatch(addWord(word.value, translate.value)); word.value = ''; translate.value = ''; }} /> <SaveBtn dispatch={dispatch} action={state.wordCreator.action} state={state} onSaveClick={() => { if (state.wordCreator.action === 'CREATE') { dispatch(addDictionary(state.selectedGroup, name.value, state.wordCreator.list.length, repeat.value, state.wordCreator.list)); }else if (state.wordCreator.action === 'CHANGE') { if (!name.value) name.value = state.wordCreator.name; if (!repeat.value) repeat.value = state.wordCreator.repeat; dispatch(changeDictionary(state.wordCreator.id, state.selectedGroup, name.value, state.wordCreator.list.length, repeat.value, state.wordCreator.list)) } repeat.value = ''; name.value = ''; word.value = ''; translate.value = ''; dispatch(closeWordCreator()); }}> {state.wordCreator.action === 'CREATE' ? 'Add dictionary' : 'Save dictionary'} </SaveBtn> <div className={style.repeat}> <input placeholder="Repeat" className={style.repeat_input} ref={node => repeat = node} /> </div> </div> </div> ); }; export default WordCreator;
import * as tf from '@tensorflow/tfjs' // Some radial basis function const RBF = (phi, center, factor) => { var additional_phi_dims = phi.shape.slice(0, -1); var additional_center_dims = center.shape.slice(0, -1); additional_phi_dims.forEach(() => {center = center.expandDims(0)}); additional_center_dims.forEach(() => {phi = phi.expandDims(-2)}); return tf.sigmoid( tf.sum( phi.sub(center).square(), -1 // sum over last axis ).mul(-10) ).mul(factor); }; // Loss for each task (sum of some RBFs) export const RBFLoss = (phi, center, factor) => { var rbfs = RBF(phi, center, factor); return tf.sum(rbfs, -1); }; export const himmelblau = phi => { var [x, y] = phi.split(2, -1); x = x.mul(12).sub(6); y = y.mul(12).sub(6); return (x.square().add(y).sub(11)).square().add( (x.add(y.square()).sub(7)).square() ) } export const beale = phi => { var [x, y] = phi.split(2, -1); var x = x.mul(3.5).sub(1.5); var y = y.mul(3.5).sub(0.5); return tf.scalar(1).sub(x).square().add(y.sub(x.square()).square().mul(100)) }; export const rosenbrock = phi => { // Beale Function var [x, y] = phi.split(2, -1); var x = x.mul(9).sub(4.5); var y = y.mul(9).sub(4.5); var product = x.mul(y) var result = tf.scalar(1.5).sub(x).add(product).square(); product = product.mul(y); result = result.add( tf.scalar(2.25).sub(x).add(product).square() ).add ( tf.scalar(2.625).sub(x).add(product).mul(y).square() ) return result; };
import { screen } from '@testing-library/react'; import { renderWithContainer } from '../../Helpers/renderWithContainer'; import Register from '../Register'; it('renders register page', () => { renderWithContainer(<Register />) const registerComponents = screen.getAllByText("Register") expect(registerComponents.length).toBeTruthy() });
import React, { Component } from 'react' import styles from './index.scss' import { withRouter } from 'react-router' const menus = [ { name: '首页', icon: 'iconxiazai44', id: 'home', path: '/' }, { name: '标签', icon: 'iconbiaoqian', id: 'tag', path: '/' }, { name: '归档', icon: 'iconguidang', id: 'page', path: '/' } ] class PageHead extends Component{ constructor (props) { super(props) } jump = (item) => { console this.props.history.push(item.path) } render () { let {title} = this.props return ( <div className={styles.head}> <div className={styles.author}> <div className={styles.line} key={'line1'}></div> <div key={'title'}>{title}</div> <div className={styles.line} key={'line2'}></div> </div> <ul className={styles.menu}> { menus.map(item => { return ( <li className={styles.menuitem} onClick={this.jump.bind(this, item)} key={item.id}> <svg className={`icon ${styles.menuicon}`} aria-hidden="true"> <use xlinkHref={`#${item.icon}`} ></use> </svg> <span>{item.name}</span> </li> ) }) } </ul> </div> ) } } export default withRouter(PageHead)
angular.module('itunes_app') .controller('mainCtrl', [ 'Search', function(Search) { var vm = this; this.msg = 'Welcome to my iTunes App'; }]);
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const path = require('path'); const autoprefixer = require('autoprefixer'); const cssnano = require('cssnano'); const webpack = require('webpack'); const yargs = require('yargs'); const { argv } = yargs.boolean('disable-compression-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin'); const ImageminPlugin = require('imagemin-webpack-plugin').default; const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const StyleLintPlugin = require('stylelint-webpack-plugin'); const SvgStorePlugin = require('external-svg-sprite-loader'); const WebpackBuildNotifierPlugin = require('webpack-build-notifier'); const Fiber = require('fibers'); const config = require('./config.js'); const pugData = require('./src/templates/pugData.js'); module.exports = (env) => { const type = env.NODE_ENV; const isProd = config[type].mode === 'production'; const consoleStats = { all: false, modules: true, maxModules: 0, errors: true, warnings: true, moduleTrace: true, errorDetails: true, }; return { mode: config[type].mode, devtool: config[type].devtool, context: path.resolve(__dirname, './src'), cache: true, entry: { app: './app.js', }, output: { path: path.resolve(__dirname, config[type].outputPath), publicPath: config[type].outputPublicPath, filename: `${config[type].jsPath}/bundle.[name].js`, chunkFilename: `${config[type].jsPath}/[name].js`, }, resolve: { alias: { '@': path.resolve(__dirname, './src'), '@styles': path.resolve(__dirname, './src/assets/styles/'), '@scripts': path.resolve(__dirname, './src/assets/scripts/'), '@templates': path.resolve(__dirname, './src/templates/'), '@assets': path.resolve(__dirname, './src/assets/'), '@blocks': path.resolve(__dirname, './src/templates/blocks'), }, }, externals: { jquery: 'jQuery', }, devServer: { contentBase: path.resolve(__dirname, './src'), overlay: true, compress: true, port: 9090, stats: consoleStats, open: false, }, stats: consoleStats, performance: { hints: false, }, module: { rules: (function (argv) { const rules = [{ test: /\.(js|jsx)$/, use: [{ loader: 'babel-loader', options: { cacheDirectory: true, }, }], }, { test: /\.s?css$/, use: [ 'style-loader', MiniCssExtractPlugin.loader, 'css-loader?sourceMap', { loader: 'postcss-loader', options: { plugins: () => [autoprefixer], sourceMap: config[type].scssSourseMap, }, }, { loader: 'sass-loader', options: { sourceMap: config[type].scssSourseMap, sassOptions: { fiber: Fiber, }, }, }, ], }, { test: /\.svg$/, include: [ path.resolve(__dirname, './src/assets/images/svg-icons/'), ], use: [ { loader: SvgStorePlugin.loader, options: { name: 'assets/images/svg-sprite/sprite.svg', publicPath: config[type].publicPathInlineCSS, iconName: '[name]', }, }, { loader: 'svgo-loader', options: { plugins: [ { removeTitle: true, }, { convertColors: { shorthex: true, }, }, { convertPathData: true, }, ], }, }, ], }, { test: /\.(png|jpe?g|gif|ico|svg)(\?.*)?$/, loader: 'url-loader', include: [ path.resolve(__dirname, './src/assets/fonts/'), path.resolve(__dirname, './src/assets/images/'), ], exclude: [ path.resolve(__dirname, './src/assets/images/svg-icons/'), ], options: { emitFile: true, limit: 1, publicPath: config[type].publicPathInlineCSS, name: '[path][name].[ext]', }, }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, include: [ path.resolve(__dirname, './src/assets/fonts/'), ], loader: 'url-loader', options: { limit: 5000, publicPath: config[type].publicPathInlineCSS, name: isProd ? '[path][name].[ext]' : '../[path][name].[ext]', }, }, { test: /\.(mp4)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: 'assets/videos/[name].[hash:7].[ext]', }, }, { test: /\.pug$/, use: [ { loader: 'file-loader', options: { name: `${config[type].htmlFilesPath}[name].html`, }, }, { loader: 'pug-html-loader', options: { pretty: true, exports: false, data: { $data: pugData, bxpath: config[type].bxPugImageInlinePath }, }, }, ], }, ]; if (config[type].esLint) { rules.push({ test: /\.js$/, exclude: /node_modules/, use: [{ loader: 'eslint-loader', }], }); } return rules; }(argv)), }, optimization: { splitChunks: { cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, name: 'bundle.vendors', enforce: true, chunks: 'all', }, }, }, }, plugins: (function (argv) { const plugins = [ new webpack.HashedModuleIdsPlugin(), new SvgStorePlugin({ sprite: { startX: 0, startY: 0, deltaX: 10, deltaY: 10, iconHeight: 50, }, }), new CleanWebpackPlugin(), new CopyWebpackPlugin([{ from: 'assets/images', to: 'assets/images', }]), new MiniCssExtractPlugin({ filename: `${config[type].cssPath}/bundle.[name].css`, chunkFilename: `${config[type].cssPath}/[name].css`, }), new WebpackBuildNotifierPlugin({ title: 'RedSoft', suppressSuccess: 'initial', activateTerminalOnError: true, }), new FriendlyErrorsWebpackPlugin({ compilationSuccessInfo: { messages: [isProd ? `Build complete at folder "${config[type].outputPath.replace(/\./g, '')}"` : 'You server is running here http://localhost:9090'], }, }), new webpack.ProvidePlugin({ Swiper: path.resolve(__dirname, './node_modules/swiper/dist/js/swiper'), }), ]; if (isProd) { plugins.push( new OptimizeCssAssetsPlugin({ cssProcessor: cssnano, canPrint: true, }), new ImageminPlugin({ pngquant: { quality: '70', }, test: /\.(jpe?g|png|gif)$/i, }), ); } if (process.argv.includes('--analyze')) { plugins.push( new BundleAnalyzerPlugin(), ); } if (config.styleLint) { plugins.push(new StyleLintPlugin()); } return plugins; }(argv)), }; };
(function() { var gems = [ { name: 'SweerGem', price: 4.25, soldOut: false, canPurchase: true, description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { name: 'Dunkertons Medallion', price: 114.00, soldOut: false, canPurchase: false, description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { name: 'Donger Emerald', price: 57.17, soldOut: false, canPurchase: true, description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { name: 'Roys Our Boy', price: 63.71, soldOut: false, canPurchase: true, description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { name: 'Based Gem', price: 82.00, soldOut: true, canPurchase: true, description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { name: 'Infinite Donger', price: 79.66, soldOut: false, canPurchase: false, description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, ]; var app = angular.module('test',[]); app.controller('StoreControl',function(){ this.product = gems; }); app.controller('SelectionControl',function(){ this.count = 0; }); })();
import React from 'react'; import ReactDOM from 'react-dom'; import './semantic/dist/semantic.min.css' import './index.css'; import App from './containers/App'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import registerServiceWorker from './registerServiceWorker'; function contactlist(state = []) { return state; } const store = createStore(contactlist); console.log(store.getState()); const rootElement = document.getElementById('root'); ReactDOM.render( <Provider store = {store}> <App /> </Provider>, rootElement); registerServiceWorker();
import React, {Component} from 'react' import ReactDOM from 'react-dom' import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom' // components import Navbar from './Navbar' import Timeline from './timeline/Timeline' import Add from './timeline/AddDay' import Login from './Login' import Signup from './Signup' import Update from './timeline/update/Update' const Main = () => { return ( <div> <Router> <div> <Navbar /> <Switch> <Route exact path="/timeline" component={Timeline}/> <Route exact path="/timeline/add" component={Add}/> <Route exact path="/login" component={Login}/> <Route exact path="/signup" component={Signup}/> <Route path="/timeline/update/:id" component={Update}/> </Switch> </div> </Router> </div> ) } export default Main
import { MdSecurity } from 'react-icons/md'; import classes from './PrivacyPolicyCard.module.css'; const PrivacyPolicyCard = (props) => { return ( <div> <h1 className={classes.headline}>{props.headline}</h1> <div className="flex items-center "> {props.topic && <MdSecurity />} <p className={classes.topic}>{props.topic}</p> </div> <p className={classes.description}>{props.description}</p> </div> ); }; export default PrivacyPolicyCard;
import { isCorrect } from './isCorrect.js'; const startMyQuiz = document.getElementById('action-button'); const resultsBar = document.getElementById('results'); startMyQuiz.addEventListener('click', aboutMeQuiz); let counter = 0; function aboutMeQuiz() { alert('Hello! Welcome to my quiz!'); const userName = prompt('What\'s your name?'); confirm(userName + ', do you think you know Marco? Take a Quiz!'); const question1 = prompt('Marco has traveled the world in his own personal boat. Yes or no?'); const answer1 = question1.toLowerCase().trim(); if (isCorrect(answer1) === true) { alert('That\'s right! Marco has sailed the world in his own boat!'); counter++; } else { alert('Wrong! Marco is a very ambitious little kitty! He HAS sailed the seven seas!'); } const question2 = prompt('Did Marco meet the president of the united states?'); const answer2 = question2.toLowerCase().trim(); if (isCorrect(answer2) === true) { alert('Correct! Marco did meet the president!'); counter++; } else { alert('Incorrect! Marco met the president and they are good friends.'); } const question3 = prompt('Did Marco run 11 marathons, getting 1st place in all of them?'); const answer3 = question3.toLowerCase().trim(); if (isCorrect(answer3) === false) { alert('Congrats! You guessed right! Marco ran 12 marathons and placed first in all of them!'); counter++; } else { alert('Incorrect! Marco ran 12 marathons and placed FIRST in all of them!'); } alert('Great job, ' + userName + '! You\'ve completed the test! Your results will show at the bottom of the page.'); document.getElementById('hide-when-complete').style.display = 'none'; document.getElementById('results').textContent = counter; } resultsBar.textContent = counter; resultsBar.textContent(counter);
import express from 'express'; import * as controller from '../controllers/customer-role.controller'; import { createAuthMiddleware } from '../auth'; import { MODERATOR } from '../auth/constants'; const router = express.Router(); router.use(createAuthMiddleware(MODERATOR)); router.get('/', controller.list); router.post('/', controller.create); router.put('/:id', controller.update); router.delete('/:id', controller.destroy); export default router;
var _viewer = this; if(_viewer.opts.act == "cardAdd"){ var handler = _viewer.getParHandler(); var extWhere = handler._extWhere; if(typeof(extWhere.split("'")[1])!="undefined" && _viewer.getItem("KC_ID").getValue() == ""){ _viewer.getItem("KC_ID").setValue(extWhere.split("'")[1]); } } if (_viewer.opts.readOnly) { _viewer.readCard(); } _viewer.beforeSave= function() { if(checkScopeWrite()){ var msg = "操作IP区段格式不正确!"; Tip.showError(msg, true); return false; } if(_viewer.opts.act == "cardModify"){ var pkcode = _viewer._pkCode; var kcId = _viewer.getItem("KC_ID").getValue(); var newScope = _viewer.getChangeData().IPS_SCOPE; if(newScope != undefined){ var scope = FireFly.doAct("TS_KCGL_IPSCOPE","finds",{"_SELECT_":"IPS_SCOPE","_WHERE_":"and kc_id = '"+kcId+"' and IPS_ID != '"+pkcode+"'"})._DATA_; scope.push({"IPS_SCOPE":newScope}); var zw = FireFly.doAct("TS_KCGL_ZWDYB","finds",{"_SELECT_":"ZW_IP","_WHERE_":"and kc_id = '"+kcId+"'"})._DATA_; var flag = true; for(var j=0;j<zw.length;j++){ var tmpIp = zw[j].ZW_IP; var tmpFlag = true; for(var i=0;i<scope.length;i++){ var tmpScope = scope[i].IPS_SCOPE; if(checkScope(tmpScope,tmpIp)){ tmpFlag = false; break; } } if(tmpFlag){ flag = false; break; } } if(!flag){ var msg = "考场IP段范围变更后存在超出存在IP范围的座位IP!"; Tip.showError(msg, true); return false; } } } }; /** * IP段校验 符合要求 return false * 不符合要求 return true * @returns {Boolean} */ function checkScopeWrite(){ var scope = $("#TS_KCGL_IPSCOPE-IPS_SCOPE").val(); var sz = scope.split("-"); if(sz.length != 2){ return true; } var a = sz[0]; var b = sz[1]; if(a.split(".").length != 4 || b.split(".").length != 4){ return true; } var r1 = a.split(".")[0] != b.split(".")[0]; var r2 = a.split(".")[1] != b.split(".")[1]; var r3 = a.split(".")[2] != b.split(".")[2]; if(r1 || r2 || r3){ return true; } var sa4 = a.split(".")[3]; var sb4 = b.split(".")[3]; if(parseInt(sa4) > parseInt(sb4)){ return true; } return false; } /** * 校验ip是不是在scope范围内 * @param scope * @param ip * @returns {Boolean} */ function checkScope(scope,ip){ var sz = scope.split("-"); var a = sz[0]; var b = sz[1]; var r1 = a.split(".")[0]; var r2 = a.split(".")[1]; var r3 = a.split(".")[2]; var sa4 = a.split(".")[3]; var sb4 = b.split(".")[3]; var ip_1 = ip.split(".")[0]; var ip_2 = ip.split(".")[1]; var ip_3 = ip.split(".")[2]; var ip_4 = ip.split(".")[3]; if(parseInt(r1) != parseInt(ip_1) || parseInt(r2) != parseInt(ip_2) || parseInt(r3) != parseInt(ip_3)){ return false; } if(parseInt(ip_4) >= parseInt(sa4) && parseInt(ip_4) < parseInt(sb4)){ return true; } return false; }
require.config({ paths: { ARController: '../../utils/ARController' } }); define(['ARController'], function (ARControllerBase) { function createCubeScene() { const scene = new THREE.Scene(); const materials = [ new THREE.MeshBasicMaterial({color: 0xff0000}), new THREE.MeshBasicMaterial({color: 0x0000ff}), new THREE.MeshBasicMaterial({color: 0x00ff00}), new THREE.MeshBasicMaterial({color: 0xff00ff}), new THREE.MeshBasicMaterial({color: 0x00ffff}), new THREE.MeshBasicMaterial({color: 0xffff00}) ]; const ROW_COUNT = 4; const SPREAD = 1; const HALF = ROW_COUNT / 2; for (let i = 0; i < ROW_COUNT; i++) { for (let j = 0; j < ROW_COUNT; j++) { for (let k = 0; k < ROW_COUNT; k++) { const box = new THREE.Mesh(new THREE.BoxBufferGeometry(0.2, 0.2, 0.2), materials); box.position.set(i - HALF, j - HALF, k - HALF); box.position.multiplyScalar(SPREAD); scene.add(box); } } } return scene; } // 创建一个正方体 function createCube(width, height, deep) { //正方体 const materials = [ new THREE.MeshBasicMaterial({color: 0xff0000}), new THREE.MeshBasicMaterial({color: 0x0000ff}), new THREE.MeshBasicMaterial({color: 0x00ff00}), new THREE.MeshBasicMaterial({color: 0xff00ff}), new THREE.MeshBasicMaterial({color: 0x00ffff}), new THREE.MeshBasicMaterial({color: 0xffff00}) ]; let cubegeo = new THREE.BoxGeometry(width, height, deep); const cube = new THREE.Mesh(cubegeo, materials); return cube; } class OrientationExample extends ARControllerBase { constructor() { // super(true, true, ARControllerBase.ORIENTATIONCONTROLLER); super({ useReticle: true, useSelect: true, baseControlType: ARControllerBase.ORIENTATIONCONTROLLER, }); } initScene() { this.scene = new THREE.Scene(); this.model = createCube(2, 2, 2); this.model.position.set(0, 0, 0); this.model.position.multiplyScalar(1); this.modelSize = 2; // this.scene.add(this.model); } } class OrientationCubeSea extends ARControllerBase { constructor() { // super(false, true, ARControllerBase.ORIENTATIONCONTROLLER); super({ useReticle: false, useSelect: true, baseControlType: ARControllerBase.ORIENTATIONCONTROLLER, }); } setAREntrance(callback) { document.querySelector('#enter-ar').addEventListener('click', callback, false); } addListeners() { this.addEventListener(ARControllerBase.SESSIONSTART, function () { // 将页面样式切换至ar会话状态 document.body.classList.add('ar'); }); } initScene() { this.scene = new THREE.Scene(); } initModel() { //正方体 this.model = createCube(2, 2, 2); this.model.position.set(0, 0, 0); this.model.position.multiplyScalar(1); this.modelSize = 2; } } document.body.innerHTML = document.body.innerHTML + `<div id="enter-ar-info" class="demo-card mdl-card mdl-shadow--4dp"> <div class="mdl-card__title"> <h2 class="mdl-card__title-text">Augmented Reality with the WebXR Device API</h2> </div> <div class="mdl-card__supporting-text"> This is an experiment using augmented reality features with the WebXR Device API. Upon entering AR, you will be surrounded by a world of cubes. Learn more about these features from the <a href="https://codelabs.developers.google.com/codelabs/ar-with-webxr">Building an augmented reality application with the WebXR Device API</a> Code Lab. </div> <div class="mdl-card__actions mdl-card--border"> <a id="enter-ar" class="mdl-button mdl-button--raised mdl-button--accent"> Start augmented reality </a> </div> </div> <div id="unsupported-info" class="demo-card mdl-card mdl-shadow--4dp"> <div class="mdl-card__title"> <h2 class="mdl-card__title-text">Unsupported Browser</h2> </div> <div class="mdl-card__supporting-text"> Your browser does not support AR features with WebXR. Learn more about these features from the <a href="https://codelabs.developers.google.com/codelabs/ar-with-webxr">Building an augmented reality application with the WebXR Device API</a> Code Lab. </div> </div> ` // window.app = new ARSea(); // window.app = new ModelExample(); // window.app = new EarthExample();//图像识别控制 // window.app = new OrientationExample();//orientation控制模型 window.app = new OrientationCubeSea();//orientation控制相机 // window.app = new OrbitExample(); // window.app = new GPSExample(); })
import Ember from 'ember'; export default Ember.Route.extend({ currentUser: Ember.inject.service(), model() { return this.get('store').findAll('contactProfile'); }, actions: { newContact() { this.transitionTo('contacts.new.search'); }, selectContact(contact) { this.transitionTo('contacts.show', contact); }, search() { this.transitionTo('contacts.search'); } } });
function popCollect(obj){ function collectItems() { this.name='CollectionFolder' } collectItems.prototype.collect= function() { var targets; try{targets=app.project.selection} catch(err){alert('请选择')} if(targets!=0) { var folder=app.project.items.addFolder(this.name); var equal=true; for (i=1;i<targets.length;i++) { var flag=(targets[i].parentFolder==targets[i-1].parentFolder) equal=flag } if (equal) {folder.parentFolder=targets[0].parentFolder} } for(i=0;i<targets.length;i++) {targets[i].parentFolder=folder} } var UI=new collectItems (); obj.pnl=obj.add ('panel', {x:10,y:10,width:180,height:70}, '当前名字为:'+UI.name,{alignChildren:'fill',orientation:'column'}); //this.pnl.typeIn=this.pnl.add('EditText',{x:15,y:15,width:150,height:30},undefined,{multiline:true}) obj.pnl.btn1=obj.pnl.add('Button',{x:15,y:15,width:65,height:28},'整理项目') obj.pnl.btn2=obj.pnl.add('Button',{x:90,y:15,width:65,height:28},'更改设置') //this.pnl.typeIn.onChange=function () {UI.name=this.text} obj.pnl.btn1.onClick=function() { app.beginUndoGroup('整理') UI.collect () app.endUndoGroup() } obj.pnl.btn2.onClick=function() { UI.name=prompt (undefined, UI.name,'在此输入更改的名字') this.parent.text='当前名字为:'+UI.name } } popCollect(this)
function missionControl(id) { historyUpdate(viewServiceRecord, arguments); $.ajax({ url: '/members/' + id, method: 'get' }), $.ajax({ url: '/members/' + id + '/planits', method: 'get' }) // ,$.ajax({ // url: '/members/' + id + '/planits/', // method: 'get' // }). .done(function(members, planits) { var data = { member: members.members[0], // user: appvars.user, // deletable: appvars.user && (appvars.user.id == members.members[0].id || appvars.user.role_name == 'admin'), // bannable: appvars.user && appvars.user.role_name != 'normal' && appvars.user.id != members.members[0].id, // planits: planits.planit[0] }; displayTemplate('main', 'dashboard', data); }); }
const { promisify } = require('util'); const request = require('request'); const { LastFmNode } = require('lastfm'); const paypal = require('paypal-rest-sdk'); const yotutubeSearch = require('youtube-search'); const path = require('path'); const remove = require('remove'); const chalk = require('chalk'); const fs = require('fs'); /** * GET /api * List of API examples. */ exports.getApi = (req, res) => { res.render('api/index', { title: 'API Examples' }); }; /** * GET /api/lastfm * Last.fm API example. */ exports.getLastfm = async(req, res, next) => { const lastfm = new LastFmNode({ api_key: process.env.LASTFM_KEY, secret: process.env.LASTFM_SECRET }); const getArtistInfo = () => new Promise((resolve, reject) => { lastfm.request('artist.getInfo', { artist: 'Roniit', handlers: { success: resolve, error: reject } }); }); const getArtistTopTracks = () => new Promise((resolve, reject) => { lastfm.request('artist.getTopTracks', { artist: 'Roniit', handlers: { success: ({ toptracks }) => { resolve(toptracks.track.slice(0, 10)); }, error: reject } }); }); const getArtistTopAlbums = () => new Promise((resolve, reject) => { lastfm.request('artist.getTopAlbums', { artist: 'Roniit', handlers: { success: ({ topalbums }) => { resolve(topalbums.album.slice(0, 3)); }, error: reject } }); }); try { const { artist: artistInfo } = await getArtistInfo(); const topTracks = await getArtistTopTracks(); const topAlbums = await getArtistTopAlbums(); const artist = { name: artistInfo.name, image: artistInfo.image ? artistInfo.image.slice(-1)[0]['#text'] : null, tags: artistInfo.tags ? artistInfo.tags.tag : [], bio: artistInfo.bio ? artistInfo.bio.summary : '', stats: artistInfo.stats, similar: artistInfo.similar ? artistInfo.similar.artist : [], topTracks, topAlbums }; res.render('api/lastfm', { title: 'Last.fm API', artist }); } catch (err) { if (err.error !== undefined) { console.error(err); // see error code list: https://www.last.fm/api/errorcodes switch (err.error) { // potentially handle each code uniquely case 10: // Invalid API key res.render('api/lastfm', { error: err }); break; default: res.render('api/lastfm', { error: err }); } } else { next(err); } } }; /** * GET /api/paypal * PayPal SDK example. */ exports.getPayPal = (req, res, next) => { paypal.configure({ mode: 'sandbox', client_id: process.env.PAYPAL_ID, client_secret: process.env.PAYPAL_SECRET }); const paymentDetails = { intent: 'sale', payer: { payment_method: 'paypal' }, redirect_urls: { return_url: process.env.PAYPAL_RETURN_URL, cancel_url: process.env.PAYPAL_CANCEL_URL }, transactions: [{ description: 'Hackathon Starter', amount: { currency: 'USD', total: '1.99' } }] }; paypal.payment.create(paymentDetails, (err, payment) => { if (err) { return next(err); } const { links, id } = payment; req.session.paymentId = id; for (let i = 0; i < links.length; i++) { if (links[i].rel === 'approval_url') { res.render('api/paypal', { approvalUrl: links[i].href }); } } }); }; /** * GET /api/paypal/success * PayPal SDK example. */ exports.getPayPalSuccess = (req, res) => { const { paymentId } = req.session; const paymentDetails = { payer_id: req.query.PayerID }; paypal.payment.execute(paymentId, paymentDetails, (err) => { res.render('api/paypal', { result: true, success: !err }); }); }; /** * GET /api/paypal/cancel * PayPal SDK example. */ exports.getPayPalCancel = (req, res) => { req.session.paymentId = null; res.render('api/paypal', { result: true, canceled: true }); }; /** * GET /api/upload * File Upload API example. */ exports.getFileUpload = (req, res) => { res.render('api/upload', { title: 'File Upload' }); }; exports.postFileUpload = (req, res) => { req.flash('success', { msg: 'File was uploaded successfully.' }); res.redirect('/api/upload'); }; /** * GET /api/v1/track/yt * Youtube video search APIs */ exports.yt = (req, res) => { var opts = { maxResults: 20, key: 'AIzaSyBAQx2SuUo9IAb-kdZBmfLLmWH1gPF_xbo', type: 'video' }; yotutubeSearch(req.params.query, opts, function(err, results) { if (err) return console.log(err); res.json(results) }); } /** * GET /api/v1/track/details * iTunes metadata extraction * returns 1 result only */ exports.trackDetails = (req, res) => { if (!req.params.trackName || req.params.trackName == " ") { return res.json({ error: true, msg: "Invalid data. Missing token." }) } var iTunesAPI = "https://itunes.apple.com/search?term=" + req.params.trackName + "&media=music&limit=1"; request(iTunesAPI, function(error, response, body) { if (!error && response.statusCode == 200) { var json = JSON.parse(body); console.log("iTunes json request parsed.") //verify if json is null if (json.resultCount == 0) { return res.json({ error: true, msg: "Music not found on database. Check your search, and try again" }) } else { return res.send(json) } } }) } /** * GET /api/v1/track/search * iTunes metadata extraction * returns 1 result only */ exports.search = (req, res) => { if (!req.params.trackName || req.params.trackName == " ") { return res.json({ error: true, msg: "Invalid data. Missing token." }) } var iTunesAPI = "https://itunes.apple.com/search?term=" + req.params.trackName + "&media=music&limit=20"; request(iTunesAPI, function(error, response, body) { if (!error && response.statusCode == 200) { var json = JSON.parse(body); console.log("iTunes json request parsed.") //verify if json is null if (json.resultCount == 0) { return res.json({ error: true, msg: "Music not found on database. Check your search, and try again" }) } else { return res.send(json) } } }) } exports.downloadyt = (req, res) => { const rucws = function replaceUnknownCharactersWithoutSpace(string) { return string.replace(/[&\/\\#,+()$~%.'":*?<>{}/ /]/g, ''); }; var mp3Final = path.join(__dirname + '/../downloads/' + req.params.sessionID, req.params.videoTitle + '.mp3'); if (fs.existsSync(mp3Final)) { res.type('audio/mpeg3'); res.download(mp3Final, function(err) { if (err) { if (err.code === "ECONNABORT" && res.statusCode == 304) { // No problem, 304 means client cache hit, so no data sent. console.log('304 cache hit for ' + mp3Final); } console.log(err) } else { remove(__dirname + '/../downloads/' + req.params.sessionID, function(err) { if (err) console.error(err); else console.log(chalk.red(req.params.sessionID) + ' Deleted!'); }); } }) } else{ res.send('error'); } } exports.downloadI= (req, res) => { const rucws = function replaceUnknownCharactersWithoutSpace(string) { return string.replace(/[&\/\\#,+()$~%.'":*?<>{}/ /]/g, ''); }; var mp3Final = path.join(__dirname + '/../downloads/' + req.params.sessionID, req.params.trackName + '.mp3'); if (fs.existsSync(mp3Final)) { res.type('audio/mpeg3'); res.download(mp3Final, function(err) { if (err) { if (err.code === "ECONNABORT" && res.statusCode == 304) { // No problem, 304 means client cache hit, so no data sent. console.log('304 cache hit for ' + mp3Final); } console.log(err) } else { remove(__dirname + '/../downloads/' + req.params.sessionID, function(err) { if (err) console.error(err); else console.log(chalk.red(req.params.sessionID) + ' Deleted!'); }); } }) } else{ res.send('error'); } }
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; import { GUTTER, CHARACTER_SIZE, CHARACTER_VERTICAL_OFFSET } from "../gameConstants"; import Dumpling from "./Dumpling"; import DumplingActive from "./DumplingActive"; const Container = styled.div` position: absolute; transition: transform 0.07s ease-in-out; pointer-events: none; `; const Player = ({ isHolding, position, blockWidth }) => ( <Container style={{ left: 0, bottom: CHARACTER_VERTICAL_OFFSET(blockWidth), transform: `translate3d(${Math.round( GUTTER + position * (blockWidth + GUTTER) + (blockWidth - CHARACTER_SIZE(blockWidth)) / 2 )}px, 0, 0)` }} > {isHolding ? ( <DumplingActive width={CHARACTER_SIZE(blockWidth)} /> ) : ( <Dumpling width={CHARACTER_SIZE(blockWidth)} /> )} </Container> ); Player.propTypes = { blockWidth: PropTypes.number.isRequired, isHolding: PropTypes.bool.isRequired, position: PropTypes.number.isRequired }; export default Player;
import get from 'lodash/fp/get'; const placePhotoUrl = (googleApiKey, place) => { const photo = place.photos ? place.photos[0] : null; const photoReference = photo ? photo.photo_reference : null; const url = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=200&maxheight=160&photoreference=${photoReference}&key=${googleApiKey}`; return url; // console.log(url); // return '_'; }; const photoUrlSelector =
import React, { useState } from "react"; import LanguageIcon from "@material-ui/icons/Language"; import DehazeIcon from "@material-ui/icons/Dehaze"; import { Link } from "react-router-dom"; import AccountCircleIcon from "@material-ui/icons/AccountCircle"; import SignUpModale from "../../../Components/signup/SignUpModale"; // import { Dropdown } from "reactstrap"; function HeaderRight() { const [dropdownOpen, setDropdownOpen] = useState(false); //signup popup const [show, setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); // model bootstrap const [modalShow, setModalShow] = React.useState(false); const toggle = () => setDropdownOpen((prevState) => !prevState); return ( <> <div className="header2__right col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12"> <Link to="/become_host"> <p className="header_host_text">Become a Host</p> </Link> <div className="header2__right__currency"> <LanguageIcon /> </div> <div className="header2__right__icons"> <div className="header2__right__profileIcons" onClick={toggle}> <DehazeIcon /> <AccountCircleIcon /> </div> {dropdownOpen && ( <ul> <a href="/"> <li>Login</li> </a> <a variant="primary" onClick={() => setModalShow(true)}> <li>Signup</li> </a> <SignUpModale role="button" show={modalShow} onHide={() => setModalShow(false)} /> <a href="/"> <li>Host Your Home</li> </a> <a href="/"> {" "} <li>Help</li> </a> </ul> )} </div> </div> </> ); } export default HeaderRight;
$(document).ready(function () { //first plugin experience $.fn.power = function (x) { return x*x; } console.log($(".change").power(6)); //big and blue characters $.fn.bigBlue = function () { this.css("color", "blue"); this.css("font-size", "20"); } $(".change").bigBlue(); //bigger and red characters $.fn.bigRed = function () { this.css("color", "red"); this.css("font-size", "40"); } $(".bigger").bigRed(); });
import React, { Component } from 'react'; import GuideCard from './GuideCard' import ProfileService from '../lib/profile-service' import { Link } from 'react-router-dom' class Profile extends Component { state = { user: {}, isLoading: true, } componentDidMount() { ProfileService.getOtherUserInfo(this.props.match.params.id) .then((user) => { this.setState({ user, isLoading: false, }) }) .catch((error) => { this.setState({ isLoading: false, }) }) } render() { const { user } = this.state; if (this.state.isLoading) { return <div>Loading...</div> } return ( <section className="my-profile"> <h2>{user.username}'s profile</h2> <p>User expertise: {user.expertise}</p> <div className="my-guides"> <h3 className="my-guides-title">User guides</h3> <button>Create your own guide</button> <div class="guide-list-container"> {user.guides.map((guide, index) => { return ( <div key={index} className="guide-card-container"> <Link to={`/guides-list/${guide._id}`}><GuideCard key={guide._id} info={guide} /></Link> </div> ) } )} </div> </div> </section> ); } } export default Profile;
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, ScrollView } from 'react-native'; import Dimensions from 'Dimensions'; var width = Dimensions.get('window').width; //定义公用的网络连接 var COMMON = 'http://or6aio8tr.bkt.clouddn.com/'; var HomeShop = React.createClass({ getInitialState:function(){ return { data:[], } }, componentDidMount:function(){ var url = COMMON + 'ShopCenterShops.json'; fetch(url) .then((response)=>response.json()) .then((responseData)=>{ this.setState({ data:responseData.data, }); }); }, render:function(){ return ( <View style={styles.container}> {/*title部分*/} {this.shopTitle()} <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.svStyle} > <View style={styles.svContainer}> {this.renderShop()} </View> </ScrollView> </View> ); }, renderShop:function(){ if (this.state.data.length != 0) { var arr = []; var datas = this.state.data; for(var i=0;i<datas.length;i++){ var data = datas[i]; arr.push(<View key={i} style={styles.shopStyle}> {this.shopDetail(data.shopName,data.shopImage,data.saleCount)} </View>); } return arr; } }, shopTitle:function(){ return (<View style={styles.titleStyle}> <View style={styles.titDetailStyle}> <Image source={{uri:'gw'}} style={styles.iconStyle}/> <Text style={styles.txtLeftStyle}>购物中心</Text> </View> <View style={styles.titDetailStyle}> <Text style={styles.txtRightStyle}>全部4家</Text> <Image source={{uri:'icon_cell_rightarrow'}} style={styles.iconStyle}/> </View> </View>); }, shopDetail:function(desc,iamgeUrl,price){ return ( <View> <View> <Image source={{uri:iamgeUrl}} style={styles.imageStyle}/> <Text style={styles.priceStyle}>{price}家优惠</Text> </View> <Text style={styles.descStyle}>{desc}</Text> </View> ); } }) var styles = StyleSheet.create({ container:{ backgroundColor:"#fefefe", marginTop:15, }, titleStyle:{ flexDirection:"row", justifyContent:"space-between", alignItems:"center", height:50, marginBottom:10, }, titDetailStyle:{ flexDirection:"row", alignItems:"center", }, iconStyle:{ width:20, height:20, margin:10, }, txtLeftStyle:{ fontSize:22, color:"#333", }, txtRightStyle:{ fontSize:18, color:"#888", }, svContainer:{ flexDirection:"row", }, shopStyle:{ width:width/3, height:width/3+20, }, imageStyle:{ width:width/3-20, height:width/3-30, }, priceStyle:{ position:"absolute", bottom:15, left:0, backgroundColor:"yellow", fontSize:10, }, descStyle:{ fontSize:15, marginTop:10, color:"#333", } }); module.exports = HomeShop;
(function () { "use strict"; angular.module("YelpApp") .controller("topicsCtrl", ["$scope", "$window", "$http", "toaster", "topicsRepliesService", topicsCtrl]); function topicsCtrl($scope, $window, $http, toaster, topicsRepliesService) { $scope.data = topicsRepliesService; $scope.isBusy = false; if (topicsRepliesService.isReady() == false) { $scope.isBusy = true; topicsRepliesService.getTopics() .then(function (topics) { // success console.log(topics); }, function () { // error toaster.pop('error', "Could not load topics"); }) .then(function () { $scope.isBusy = false; }); } $scope.reply = function (id) { $window.location = "/message/" + id; }; } angular.module("YelpApp") .controller("newTopicCtrl", ["$scope", "$http", "$window", "toaster", "topicsRepliesService", function ($scope, $http, $window, toaster, topicsRepliesService) { $scope.newTopic = {}; $scope.save = function () { topicsRepliesService.addTopic($scope.newTopic) .then(function () { // success $window.location = "/topics"; }, function () { // error toaster.pop('error', "Faield to add topic", "Could not save the new topic."); }); }; }]); //-----------------------------single topic angular.module("YelpApp") .controller("singleTopicCtrl", ["$scope", "topicsRepliesService", "toaster", "$window", "$routeParams", function ($scope, topicsRepliesService, toaster, $window, $routeParams) { $scope.topic = null; $scope.newReply = {}; topicsRepliesService.getTopicById($routeParams.id) .then(function (topic) { // success $scope.topic = topic; }, function () { // error $window.location = "/"; }); $scope.addReply = function () { topicsRepliesService.saveReply($scope.topic, $scope.newReply) .then(function () { // success $scope.newReply.body = ""; }, function () { // error toaster.pop('error', "Failed:", "Could not save the new reply"); }); }; }]); })();
import React, { useState, useEffect, Component } from "react"; import { Platform, StyleSheet, View, Text, Image, Linking, } from 'react-native'; export default class News extends React.Component{ render(){ return( <View> <Text style={seperator}></Text> <Image style={styles.imageUrl} source={{ uri: this.props.urltoImage}} /> </View> ); } } const styles = StyleSheet.create({ container: { display: "flex", marginBottom: 20, borderBottomColor: "#e5e5e5", borderBottomWidth: 3, padding: 20 }, upperRow: { display: "flex", flexDirection: "row", marginBottom: 15 }, coinSymbol: { marginTop: 10, marginLeft: 20, marginRight: 5, fontWeight: "bold", }, coinName: { marginTop: 10, marginLeft: 5, marginRight: 20 }, seperator: { borderBottomColor: 'black', borderBottomWidth: 1, marginLeft: 5, marginRight: 5 }, newsline: { marginTop: 10, marginLeft: 20, marginRight: 5, fontWeight: "bold", fontSize:18 , }, coinPrice : { marginTop: 10, marginLeft: 20, marginRight: 5, fontWeight: "bold", }, image: { marginLeft: 15, width: 35, height: 35, }, imageUrl: { marginLeft: 15, marginTop: 10, width: null, flex: 1, aspectRatio:1, height:"60%" }, moneySymbol: { fontWeight: "bold", }, }) const { coinSymbol, coinPrice, seperator, newsline } = styles;
let backgroundAudio = document.getElementById("backgroundSong"), jumpAudio = document.getElementById("jumpMusic"), gameoverAudio = document.getElementById("tryAgainMusic"), canvas = document.getElementById("player"), ctx = canvas.getContext("2d"); ctx.fillStyle="#ed3833"; ctx.font = "24px helvetica"; let playerRadius= 15, lostCount=0, playerX, playerY, playSpeed=1000/60, playerMoveSpeed=4.2, jumpProcess, moveProcess, velocityTime=1000, gravity=4000, velocity=0, speed=0, time=playSpeed/1000, angle=0, isJumping = false, isStart=false, isWin=false; level=0, //map Levels levelMap=[ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0], [0, 0, 0, 0, 0, 70, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 45, 0, 0, 0, 0, 50, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 70, 0, 0, 0, 0, 70, 0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 50, 30, 0, 0, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 40, 20, 30, 0, 0, 0, 0, 0, 0, 99, 0, 0, 0, 0, 0, 60, 0, 0], [0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 90, 10, 0, 0, 0, 0, 0, 0, 80, 20, 0, 0], [0, 0, 0, 20, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 0, 0, 0], [0, 0, 0, 0, 0, 0, 90, 0, 0, 0, 0, 0, 80, 0, 0, 0, 0, 0, 90, 0, 0, 0, 0, 90, 0, 0, 0], ]; function keyDown(e){ if(!isStart&&!isWin){ start(); isStart=true; backgroundAudio.play(); } else if(!isStart&&isWin&&e.keyCode==13){ lostCount=0; level=0; start() isStart=true; } else if(isStart&&!isJumping){ if(moveProcess!=null) clearInterval(moveProcess); jump(); } } function touch (event){ var event = event || window.event; switch(event.type){ case "touchstart": keyDown() break; case "touchmove": event.preventDefault(); keyDown() break; } } //game-loop function main(){ ctx.clearRect(0,0,650,400); ctx.fillText("Press any Key to Start!", canvas.width/3, 150); addEventListener("keypress", function(e) { keyDown(e) }, false); addEventListener('touchstart',touch,false); addEventListener('touchmove',touch,false); } window.onload=function(){ main(); }
import {incrementCounter, decrementCounter} from "../Actions/actionTypes"; import { toggoleToday, updateItem, postItem, getItem, getItems, shuffleItems, deleteItem } from '../Actions/types'; import _ from 'underscore' import moment from 'moment' import {GetItems} from "../Actions/CardAction"; const fakeCardList = { list: ["guide1", "guide2", "guide3"] } const fakeCardDetail = { "guide1": { "uuid": "guide1", "title": "右侧打卡", "description": "点击详情", "history": "333", "today": "1", "start_date": "2017-12-21", "days": 9 }, "guide2": { "uuid": "guide2", "title": "左侧看天数", "description": "点击详情", "history": "333", "today": "5", "start_date": "2017-12-10", "days": 8 }, "guide3": { "uuid": "guide3", "title": "左侧天数", "description": "点击详情", "history": "333", "today": "4", "start_date": "2017-12-21", "days": 46 } } const template = { "uuid": "db062920-e0a1-11e7-bd7b-97661737f2f5", "title": "左侧天数", "description": "点击详情", "history": "000", "today": "5", "start_date": moment().format("YYYY-MM-DD"), "days": 0 } const shuffleTime = { shuffle_time: "2017-12-20" } const initialState = Object.assign({}, fakeCardList, fakeCardDetail, shuffleTime) const TODAY_STATE_LIST = [5, 4, 1, 5] function shuffle(item) { let history = item.history let today = item.today let end = moment(moment().format("YYYY-MM-DD")); let start = moment(item.start_date) let diff = end.diff(start, 'days') - item.history.length + 3 if (diff !== 0) { let new_history = history + (today == "5" ? '3' : today) console.log(today, new_history) item.update = true for (let i = 0; i < diff - 1; i++) { new_history += "3" } item.history = new_history item.today = "5" } console.log(item) return item } const cardReducer = (state = initialState, action) => { let state_copy = Object.assign({}, state) switch (action.type) { case toggoleToday: let oldToday = parseInt(state_copy[action.uuid].today) let newToday = TODAY_STATE_LIST[TODAY_STATE_LIST.indexOf(oldToday) + 1] state_copy[action.uuid].today = newToday + "" return state_copy; case updateItem: return { ...state, [action.uuid]: Object.assign(state[action.uuid], action.content) }; case postItem: return { ...state, [action.uuid]: Object.assign(template, action.content, { uuid: action.uuid, start_date: moment().format("YYYY-MM-DD") }), list: state .list .concat(action.uuid) }; case getItems: console.log("from getItems", state); return { ...state }; case deleteItem: state_copy.list = _.without(state_copy.list, action.uuid); state_copy[action.uuid].state = "delete"; return state_copy; case shuffleItems: console.log(state); state_copy = Object.assign({}, state) let today_date = moment().format("YYYY-MM-DD") let today_date_debug = moment().format("YYYY-MM-DD"); if (state_copy.shuffle_time !== today_date_debug) { console.log("need shuffle") state_copy .list .forEach((uuid) => { state_copy[uuid] = shuffle(state_copy[uuid]) }) } state_copy.shuffle_time = today_date_debug return state_copy default: return state; } }; export default cardReducer;
define(function (require, exports, module) { "use strict"; var EditorManager = brackets.getModule("editor/EditorManager"), ExtensionUtils = brackets.getModule("utils/ExtensionUtils"), Strings = brackets.getModule("strings"), DocumentManager = brackets.getModule("document/DocumentManager"), MainViewManager = brackets.getModule("view/MainViewManager"), QuickFormToolTemplate = require("text!ui/QuickFormToolTemplate.html"); var untitledhtml5index = 1; var untitledcssindex = 1; var untitledjsindex = 1; function quickFormToolProvider() { try { var $element = $(Mustache.render(QuickFormToolTemplate, Strings)); $element.find(".qft-form").click(function () { quickFormTool("form"); }); $element.find(".qft-button").click(function () { quickFormTool("button"); }); $element.find(".qft-textfield").click(function () { quickFormTool("textfield"); }); $element.find(".qft-filefield").click(function () { quickFormTool("filefield"); }); $element.find(".qft-checkbox").click(function () { quickFormTool("checkbox"); }); $element.find(".qft-radiobutton").click(function () { quickFormTool("radiobutton"); }); $element.find(".qft-hiddenfield").click(function () { quickFormTool("hiddenfield"); }); $element.find(".qft-textarea").click(function () { quickFormTool("textarea"); }); $element.find(".qft-imagefield").click(function () { quickFormTool("imagefield"); }); $element.find(".qft-imagebutton").click(function () { quickFormTool("imagebutton"); }); $element.find(".qft-listmenu").click(function () { quickFormTool("listmenu"); }); $element.find(".qft-link").click(function () { quickFormTool("link"); }); $element.find(".qft-html5audio").click(function () { quickFormTool("html5audio"); }); $element.find(".qft-html5video").click(function () { quickFormTool("html5video"); }); $element.find(".qft-embedflash").click(function () { quickFormTool("embedflash"); }); $element.find(".qft-html5file").click(function () { quickFormTool("html5file"); }); $element.find(".qft-cssfile").click(function () { quickFormTool("cssfile"); }); $element.find(".qft-jsfile").click(function () { quickFormTool("jsfile"); }); $element.find(".qftnotify").click(function () { $element.find(".qftblock").toggleClass("qftblock-exp"); $element.find(".qftnotify").toggleClass("qftnotify-exp"); }); $element.find(".qft-unpin").click(function () {$element.find(".qftblock").toggleClass("qftblock-exp"); $element.find(".qft-unpin").toggleClass("qft-pin"); }); $($element).insertBefore("#editor-holder"); } catch(e) { alert("Error: " + e); } } var loadfunction = quickFormToolProvider(); function quickFormTool(_class) { try { if (true) { switch (_class) { case "form": handleText("<form action=\"\" method=\"get\"></form>"); break; case "textfield": handleText("<input type=\"text\" name=\"textfield\" size=\"25\" value=\"TextField\">"); break; case "textarea": handleText("<textarea name=\"\" cols=\"25\" rows=\"5\">TextArea</textarea>"); break; case "button": handleText("<input type=\"button\" name=\"button\" value=\"Button\">"); break; case "checkbox": handleText("<input type=\"checkbox\" name=\"checkbox\" value=\"CheckBox\">"); break; case "radiobutton": handleText("<input type=\"radio\" name=\"radiogroup\" value=\"RadioButton\">"); break; case "listmenu": handleText("<select name=\"selectoptions\">\n\t<option value=\"option1\">Option 1</option>\n\t<option value=\"option2\">Option 2</option>\n</select>"); break; case "imagebutton": handleText("<input type=\"image\" name=\"\" src=\"\" width=\"\" height=\"\">"); break; case "imagefield": handleText("<img src=\"\" alt=\"\" width=\"\" height=\"\">"); break; case "filefield": handleText("<input type=\"file\" name=\"filefield\">"); break; case "hiddenfield": handleText("<input type=\"hidden\" name=\"hiddenfield\" value=\"hiddenfieldvalue\">"); break; case "link": handleText("<a href=\"\"></a>"); break; case "html5audio": handleText("<audio controls>\n\t<source src=\"audio.ogg\" type=\"audio/ogg\">\n\t<source src=\"audio.mp3\" type=\"audio/mpeg\">\n\tYour browser does not support the audio element.\n</audio> "); break; case "html5video": handleText("<video width=\"320\" height=\"240\" controls>\n\t<source src=\"movie.mp4\" type=\"video/mp4\">\n\t<source src=\"movie.ogg\" type=\"video/ogg\">\n\tYour browser does not support the video tag.\n</video>"); break; case "embedflash": handleText("<object data=\"flashfile.swf\" width=\"\" height=\"\"></object>"); break; case "html5file": var doc = DocumentManager.createUntitledDocument(untitledhtml5index++, ".html"); handleFileNew(doc); handleText(html5page); break; case "cssfile": makeCSSFile(); break; case "jsfile": makeJSFile(); break; } } } catch(e) { alert("Error: " + e); } }; function makeCSSFile() { var doc = DocumentManager.createUntitledDocument(untitledcssindex, ".css"); handleTextToTag("<link rel=\"stylesheet\" href=\"Untitled-" + untitledcssindex++ + ".css\">", "head"); handleFileNew(doc); handleText("html\n{\n\t\n\}\n"); } function makeJSFile() { var doc = DocumentManager.createUntitledDocument(untitledjsindex, ".js"); handleText("<script type=\"javascript\" src=\"Untitled-" + untitledjsindex++ + ".js\" />"); handleFileNew(doc); handleText(""); } function handleText(commandString) { try { var activeEditor = EditorManager.getActiveEditor(), activeDoc = activeEditor && activeEditor.document, fileFullPath = activeDoc.file.fullPath, fileFullName = fileFullPath.substring(fileFullPath.lastIndexOf("/") + 1), fileFormat = fileFullName.substring(fileFullName.lastIndexOf(".") + 1); if (fileFormat == "html" || fileFormat == "htm") { var line = activeEditor.document.getLine(activeEditor.getCursorPos().line); if (line.replace(/^\s+|\s+$/g, '').length>0) { var csIndent = line.match(/^\s{0,32}/)[0].length; if (line.substr(activeEditor.getCursorPos().ch).length==0) commandString = "\n" + new Array(csIndent+1).join(' ') +commandString; } activeEditor.document.replaceRange(commandString, activeEditor.getCursorPos()); } } catch(err){} } function handleTextToTag(text, tag) { try { var activeEditor = EditorManager.getActiveEditor(), activeDoc = activeEditor && activeEditor.document, fileFullPath = activeDoc.file.fullPath, fileFullName = fileFullPath.substring(fileFullPath.lastIndexOf("/") + 1), fileFormat = fileFullName.substring(fileFullName.lastIndexOf(".") + 1); if (fileFormat == "html" || fileFormat == "htm") { EditorManager.getFocusedEditor(); var getDocumentText_ = activeEditor.document.getText().replace("</" + tag + ">", "\t" + text + "\n</" + tag + ">"); activeEditor.document.setText(getDocumentText_); //activeEditor.document.replaceRange(text, activeEditor.getCursorPos()); } } catch(err){alert("Error: "+err);} } //make new file. function handleFileNew(docname) { try { var doc_ = docname; MainViewManager._edit(MainViewManager.ACTIVE_PANE, doc_); return new $.Deferred().resolve(doc_).promise(); } catch(err){alert("Error: "+err);} } var html5page = "<!doctype html>\n<html>\n<head>\n\t<meta charset=\"UTF-8\">\n\t<title>Untitled Document</title>\n\t\n</head>\n<body>\n\t\n\t\n\t\n</body>\n</html>"; ExtensionUtils.loadStyleSheet(module, "ui/style.css"); exports.quickFormToolProvider = quickFormToolProvider; });
/** * Created by harry on 2018/3/11. */ /** * Created by harry on 2018/3/10. */ let fs = require('fs'); let path = require('path'); /* * 概述 LOC_DIPLOMACY_INTEL_OVERVIEW_COLON_TOOLTIP * 概述内容组 LOC_PEDIA_CONCEPTS_PAGEGROUP +名称 * 内容标题 LOC_PEDIA_CONCEPTS_PAGE_ +名称 * * * 文明/领袖 LOC_MULTIPLAYER_CIV_LEADER_HEADER * * 城邦 * 区域 * 建筑 * 奇观项目 * 单位 * 单位强化 * 伟人 * 科技 * 市政 * 政体和政策 * 宗教 * 地形和地貌 * 资源 * 改良设置和路线 * 总督 * 历史时刻 * * */ let obj = [] let flag = false let state = [] let num = 0; fs.readFile(path.resolve(__dirname, 'data/data.json'), { encoding: 'utf-8' }, function(err, doc) { let res = JSON.parse(doc); console.log(res) let data = res.GameData.LocalizedText.Replace; for (let i = 0; i < data.length; i++) { let field = data[i].$.Tag; let fieldLen = data[i].$.Tag.split("_").length; if (fieldLen == 4 && field.indexOf('LOC_PEDIA_') == 0) { obj.push({ [data[i].$.Tag.split("_")[2]]: { name: data[i].Text, PAGEGROUP: Array.from(state) } }) flag = true } if (fieldLen == 6 && field.indexOf('LOC_PEDIA_CONCEPTS_PAGEGROUP') == 0) { state.push({ [data[i].$.Tag.split("_")[4]]: data[i].Text }) } if (field.indexOf('LOC_PEDIA_CONCEPTS_PAGE_WORLD_') == 0 && field.indexOf('_CHAPTER_CONTENT_TITLE') != -1) { num++ state.push({ ['WORLDCONTENTTITLE' + num]: data[i].Text }) // console.log(data[i]) } } console.log(obj[0].CONCEPTS.PAGEGROUP) })
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const autoIncrement = require('mongoose-auto-increment'); autoIncrement.initialize(mongoose.connection); const txSchema = new Schema({ id: {type: Number, unique: true}, type: {type: String, enum: ['PLAN', 'CONTRACT'], require: true}, ref: {type: Schema.Types.Mixed, require: true}, preStateHash: {type: String}, action: {type: Schema.Types.Mixed}, time: {type: Date, default: new Date()}, status: {type: Boolean, default: false} }); txSchema.plugin(autoIncrement.plugin, { model: 'tx', field: 'id', startAt: 100000, incrementBy: 1 }); module.exports = mongoose.model('tx', txSchema);
// // 获取地址栏中的字符串,并将其转化为对象 // function addr_obj() { // var search = location.search; // var obj = {}; // var keyValues = search.slice(1).split("&"); // keyValues.forEach(function(keyValue) { // var tempArr = keyValue.split("="); // var key = tempArr[0]; // // var value = tempArr[1].indexOf("|") > 0 ? tempArr[1].split("|") : tempArr[1]; // var value = tempArr[1]; // obj[key] = value; // }); // return obj; // } // var obj = addr_obj() // console.log(obj.openId) // //获取手机验证码 // // var InterValObj; //timer变量,控制时间 // // var count = 60; //间隔函数,1秒执行 // // var curCount;//当前剩余秒数 // // var phone = ""; // // function sendMessage() { // //  curCount = count; // //   //设置button效果,开始计时 // // $("#btnSendCode").attr("disabled", "true"); // // $("#btnSendCode").val("" + curCount + "秒后重新获取"); // // InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次 // // var openId = obj.openId; // // console.log(phone) // //    //向后台发送处理数据 // // $.ajax({ // //   type: "get", //用get方式传输 // //   dataType: "JSON", //数据格式:JSON // //   url: 'https://zhixianzhai.com/getSecurityCode', //目标地址 // //    data: { // // openId = openId, // // phone = phone, // // } // //    error: function (data) { }, // //   success: function (msg){ // // alert("验证码"+msg) // // } // // }); // // } // // console.log(openId,phone) // //timer处理函数 // // function SetRemainTime() { // // if (curCount == 0) { // // window.clearInterval(InterValObj);//停止计时器 // // $("#btnSendCode").removeAttr("disabled");//启用按钮 // // $("#btnSendCode").val("重新获取验证码").css({"background-color":"#0097a8"}); // // } // // else { // // curCount--; // // $("#btnSendCode").val("" + curCount + "秒后重新获取").css({"background-color":"#D1D4D3"}); // // } // // } // //*********获取语音验证码*********// // var AddInterValObj; //timer变量,控制时间 // var adcount = 60; //间隔函数,1秒执行 // var addCount;//当前剩余秒数 // var openId = obj.openId; // function sendAddmes() { // var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; // if(!myreg.test($("#add_phone").val())) // { // layertest('请输入有效的手机号码') // return false; // }else{ // addCount = adcount; //   //设置button效果,开始计时 // $("#addSendCode").attr("disabled", "true"); // $("#addSendCode").val("" + addCount + "秒后重新获取").css({"background-color":"#D1D4D3"}); // AddInterValObj = window.setInterval(SetAddnTime, 1000); //启动计时器,1秒执行一次 // var phone = $("#add_phone").val(); // console.log(phone) // // 向后台传输数据 // $.ajax({ //   type: "post", //用post方式传输 //   dataType: "JSON", //数据格式:JSON //   url: 'https://zhixianzhai.com/sms/getSecurityCode', //目标地址 //    data: { // openId : openId, // phone : phone, // }, //   success: function (res){ // alert("验证码:"+res) // }, //   error: function () { // }, // }); // } // } // function telphone(){ // var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; // if(!myreg.test($("#add_phone").val())) // { // $("#add_phone").test('请输入有效的手机号码'); // $('.login_ipt').addClass('error'); // return false; // }else{ // $('.login_ipt').removeClass('error'); // phone = $("#add_phone").val(); // } // } // $(document).on('blur','.login_ipt',function(){ // telphone(); // // console.log(telphone()) // }); // // timer处理函数 // function SetAddnTime() { // if (addCount == 0) { // window.clearInterval(AddInterValObj);//停止计时器 // $("#addSendCode").removeAttr("disabled");//启用按钮 // $("#addSendCode").val("重新获取验证码").css({"background-color":"#0097a8"}); // } // else { // addCount--; // $("#addSendCode").val("" + addCount + "秒后重新获取").css({"background-color":"#D1D4D3"}); // } // } // //code 验证 // function code_test(){ // if($('#code').val()==''){ // $('#code').test('验证码不能为空'); // $('#code').addClass('error'); // }else{ // $('#code').removeClass('error'); // } // } // $(document).on('blur','.code',function(){ // code_test(); // }); // // layer modal // // function layertest(content){ // // layer.open({ // // content: content // // ,btn: '我知道了' // // }); // // } // //layer loading // // function loading(content){ // // layer.open({ // // type: 2 // // ,content: content // // }); // // } // // update btn click // // $(document).on('click','.updateBtn',function(){ // // if($('.error').length >0){ // // test('请您填写正确的资料') // // }else{ // // loading('跳转中') // // } // // })
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Fragment} from 'react'; import {} from 'react-native'; import Path from "./page/path"; import NavigationService from "./public/NavigationService"; import {NavigationContainer} from "@react-navigation/native"; import {createStackNavigator,} from "@react-navigation/stack"; const Stack=createStackNavigator(); const App = () => { return ( <NavigationContainer ref={navigatorRef => { NavigationService.setTopLevelNavigator(navigatorRef); }}> <Path params={Stack}/> </NavigationContainer> ); }; export default App;
window.onload = function(){ var oBox = document.getElementById("box"); var oList = document.getElementsByTagName("ul")[0].getElementsByTagName("li"); var oCount = document.getElementsByTagName("ul")[1].getElementsByTagName("li"); var timer = paly = null; var index = 0; var bOrder = true; // 按钮切换 for (var i = 0; i < oCount.length; i++) { oCount[i].index = i; oCount[i].onmouseover = function() { show(this.index); } }; // 鼠标滑过清除定时器 oBox.onmouseover = function() { clearInterval(play); }; // 鼠标离开启动自动播放 oBox.onmouseout = function() { autoplay() } // 自动播放函数 function autoplay() { play = setInterval(function(){ // 判断播放顺序 bOrder?index++:index--; // 正序 index >= oList.length && (index = oList.length - 2, bOrder = false); // 倒序 index <= 0 && (index = 0,bOrder = true) // 调用函数 show(index); },2000) } autoplay(); //应用 // 图片切换,淡入淡出效果 function show(a){ var index = a; var alpha = 0; for (var i = 0; i < oCount.length; i++) { oCount[i].className = " "; }; oCount[index].className = "current"; for (var i = 0; i < oList.length; i++) { oList[i].style.opacity = 0; oList[i].style.filter = "alpha(opacity=0)" }; timer = setInterval(function(){ alpha += 2; alpha >= 100 &&(alpha= 100); oList[index].style.opacity = alpha/100; oList[index].style.filter = "alpha(opacity="+alpha+")"; alpha == 100 && clearInterval(timer); },20) } }
/** * @file demos/xui-multipicker.js * @author leeight */ import {defineComponent} from 'san'; import {Row, MultiPicker} from 'san-xui'; /* eslint-disable */ const template = `<template> <x-row label="[default]"> <xui-multipicker datasource="{{mp.datasource}}" value="{=mp.value=}" /> <strong class="large"> Value is: {{mp.value}} </strong> </x-row> <x-row label="操作系统"> <xui-multipicker datasource="{{os.datasource}}" value="{=os.value=}" /> <strong class="large"> 操作系统: {{os.value}} </strong> </x-row> <x-row label="lazy-loading,loader"> <xui-multipicker datasource="{{lazy.datasource}}" loader="{{lazy.loader}}" value="{=lazy.value=}" /> <strong class="large"> 操作系统: {{lazy.value}} </strong> </x-row> <x-row label="disabled"> <xui-multipicker disabled datasource="{{mp.datasource}}" value="{=mp.value=}" /> <strong class="large"> Value is: {{mp.value}} </strong> </x-row> </template>`; /* eslint-enable */ function getImages(osType) { switch (osType) { case 'CentOS': return [ {text: '7.1 x86_64 (64bit)', value: 'da93d591-4130-4870-81a9-d84daf9a8c4c'}, {text: '6.8 x86_64 (64bit)', value: 'b8639e78-b3e9-4fa5-b69e-32294b9f4b4b'}, {text: '6.5 x86_64 (64bit)', value: '2b366fe9-63ac-4c63-8c78-516bc5acb950'}, {text: '7.2 x86_64 (64bit)', value: 'bad85757-b6c6-4026-b34c-e7677435c149'}, {text: '6.5 i386 (32bit)', value: '60422670-4389-4026-ae22-b77f2be48210'} ]; case 'Debian': return [ {text: '8.1.0 amd64 (64bit)', value: '166df269-54b6-4841-a2c2-4672e0505b82'}, {text: '7.5.0 amd64 (64bit)', value: 'f7369fc5-9419-41c5-833f-28401d87dda3'} ]; case 'Ubuntu': return [ {text: '12.04.4 LTS amd64 (64bit)', value: 'ed97a9ef-7b1e-48ec-96ee-c8a01a13e1e5'}, {text: '14.04.1 LTS amd64 (64bit)', value: '3fa6fedb-c62a-4acb-b198-373b0d00e069'}, {text: '16.04 LTS amd64 (64bit)', value: '3c9832ea-3277-4716-926c-925489aa165d'}, {text: '16.04 LTS i386 (32bit)', value: '0cbe2924-1325-4d94-8e96-2989dd0a0aad'}, {text: '14.04.1 LTS i386 (32bit)', value: '1cce752d-fa3c-4af7-8e5d-9e7d3b603c9d'}, {text: '12.04.4 LTS i386 (32bit)', value: '37fcf765-f6fb-43b7-94c9-ee4153b58953'} ]; case 'Windows Server': return [ {text: '2008 R2 x86_64 (64bit) 中文版', value: '7beb02e6-5daf-4b5c-b7a0-e68f4bbcc916', disabled: true}, {text: '2012 R2 x86_64 (64bit) 中文版', value: '4af300d1-5dca-4fce-a919-5e25e96ec887'}, {text: '2016 x86_64 (64bit) 中文版', value: 'f30c74f2-07dc-4e1d-a5e6-2d5f03f737cf'} ]; default: return []; } } export default defineComponent({ template, components: { 'x-row': Row, 'xui-multipicker': MultiPicker }, initData() { return { lazy: { value: [], loader: values => { // eslint-disable-line return new Promise((resolve, reject) => { setTimeout(() => { if (values.length === 1) { const osType = values[0]; if (Math.random() > .8) { reject(new Error('RANDOM error happened')); return; } const children = getImages(osType); if (osType === 'CentOS') { children[0].expandable = true; } resolve(children); } else if (values.length === 2) { const imageId = values[1]; if (imageId === 'da93d591-4130-4870-81a9-d84daf9a8c4c') { resolve([ {text: 'xxx', value: 'xxx'}, {text: 'yyy', value: 'yyy'}, {text: 'zzz', value: 'zzz'} ]); } else { resolve([]); } } }, 500); }); }, datasource: [ { text: 'CentOS', value: 'CentOS', expandable: true }, { text: 'Debian', value: 'Debian', expandable: true }, { text: 'Ubuntu', value: 'Ubuntu', expandable: true, disabled: true }, { text: 'Windows Server', value: 'Windows Server', expandable: true } ] }, os: { value: ['Windows Server', 'f30c74f2-07dc-4e1d-a5e6-2d5f03f737cf'], datasource: [ { text: 'CentOS', value: 'CentOS', children: getImages('CentOS') }, { text: 'Debian', value: 'Debian', children: getImages('Debian') }, { text: 'Ubuntu', value: 'Ubuntu', disabled: true, children: getImages('Ubuntu') }, { text: 'Windows Server', value: 'Windows Server', children: getImages('Windows Server') } ] }, mp: { value: ['xyz', 'xyz1', 'xyz1_1'], datasource: [ { text: 'foo', value: 'foo', children: [ {text: 'foo1', value: 'foo1'}, {text: 'foo2', value: 'foo2'}, {text: 'foo3', value: 'foo3'}, {text: 'foo4', value: 'foo4'}, {text: 'foo5', value: 'foo5'} ] }, { text: 'bar', value: 'bar', children: [ {text: 'bar1', value: 'bar1'}, {text: 'bar2', value: 'bar2'}, {text: 'bar3', value: 'bar3'}, {text: 'bar4', value: 'bar4'}, {text: 'bar5', value: 'bar5'} ] }, { text: 'xyz', value: 'xyz', children: [ { text: 'xyz1', value: 'xyz1', children: [ {text: 'xyz1_1', value: 'xyz1_1'}, { text: 'xyz1_2', value: 'xyz1_2', children: [ {text: 'xyz1_2_1', value: 'xyz1_2_1'}, {text: 'xyz1_2_2', value: 'xyz1_2_2'}, {text: 'xyz1_2_3', value: 'xyz1_2_3'}, {text: 'xyz1_2_4', value: 'xyz1_2_4'}, {text: 'xyz1_2_5', value: 'xyz1_2_5'} ] }, {text: 'xyz1_3', value: 'xyz1_3'}, {text: 'xyz1_4', value: 'xyz1_4'}, {text: 'xyz1_5', value: 'xyz1_5'}, {text: 'xyz1_6', value: 'xyz1_6'} ] }, {text: 'xyz2', value: 'xyz2'}, {text: 'xyz3', value: 'xyz3'}, {text: 'xyz4', value: 'xyz4'}, {text: 'xyz5', value: 'xyz5'} ] } ] } }; } });
import React, { Component } from 'react' import Sketch from 'react-p5' export default class DVDLogo extends Component { constructor(props) { super(props); this.state = { song:'', art:'', nowPlaying: { name: '', artist: '', progress_ms: 0, albumArt: '', } }; } x; y; size; speed; xspeed; yspeed; r; g; b; bpm; direction; distance; img; setup = (p5, canvasParentRef) => { p5.createCanvas(window.innerWidth, window.innerHeight).parent(canvasParentRef) this.x = 300; this.y = 100; this.xspeed = 5; this.yspeed = 5; this.bpm = 75; this.r = 100; this.g = 100; this.b = 100; this.direction = "SW"; this.distance = "0"; this.img = p5.loadImage(this.props.art); this.size = window.innerWidth/8; } pickColor = () => { this.r = Math.random()*(256-100)+100; this.g = Math.random()*(256-100)+100; this.b = Math.random()*(256-100)+100; } changeDirection = () => { if((this.x===window.innerWidth-this.size && this.yspeed<0) || (this.y===window.innerHeight-this.size && this.xspeed<0)){ this.direction = "NW" } else if((this.x===window.innerWidth-this.size && this.yspeed>0) || (this.y===0 && this.xspeed<0)){ this.direction = "SW" } else if((this.y===window.innerHeight-this.size && this.xspeed>0) || (this.x===0 && this.yspeed<0)){ this.direction = "NE" } else if((this.x===0 && this.yspeed>0) || (this.y===0 && this.xspeed>0)){ this.direction = "SE" } } calcDistance = () => { if(this.direction==="NE"){ if(this.y<(window.innerWidth-this.size-this.x)){ this.distance = this.y/.70710; }else{ this.distance = (window.innerWidth-this.size-this.x)/.70710; } } else if(this.direction==="SE"){ if((window.innerWidth-this.size-this.x)<(400-this.y)){ this.distance = (window.innerWidth-this.size-this.x)/.70710; }else{ this.distance = (window.innerHeight-this.size-this.y)/.70710; } } else if(this.direction==="SW"){ if(this.x<(window.innerHeight-this.size-this.y)){ this.distance = this.x/.70710; }else{ this.distance = (window.innerHeight-this.size-this.y)/.70710; } } else if(this.direction==="NW"){ if(this.x<this.y){ this.distance = this.x/.70710; }else{ this.distance = this.y/.70710; } } } calcSpeed = () => { this.speed = ((this.distance*this.bpm)/3600); if(this.xspeed<0 && this.yspeed<0){ this.xspeed = -((this.speed/.70710*4/7)*.974/2); this.yspeed = this.xspeed; } else if(this.xspeed<0 && this.yspeed>0){ this.xspeed = -((this.speed/.70710*4/7)*.974/2); this.yspeed = -this.xspeed; } else if(this.xspeed>0 && this.yspeed<0){ this.xspeed = ((this.speed/.70710*4/7)*.974/2); this.yspeed = -this.xspeed; } else{ this.xspeed = ((this.speed/.70710*4/7)*.974/2); this.yspeed = this.xspeed; } } draw = p5 => { p5.background(2); p5.fill(0); p5.textSize(42); p5.textFont('Georgia'); //p5.text("BPM: " + this.bpm, 300, 30); //p5.text("Song: ", 300, 70); p5.textSize(window.innerHeight/7.5); p5.fill(this.r,this.g,this.b); p5.textAlign(p5.CENTER); p5.text(this.props.song,window.innerWidth/2,window.innerHeight/2); p5.image(this.img, this.x, this.y, this.size, this.size); this.x = this.x + this.xspeed; this.y = this.y + this.yspeed; if(this.x+this.size >= window.innerWidth){ this.x = window.innerWidth - this.size; this.changeDirection(); this.calcDistance(); this.pickColor(); this.calcSpeed(); this.xspeed = -this.xspeed; } else if(this.x <= 0){ this.x = 0; this.changeDirection(); this.calcDistance(); this.pickColor(); this.calcSpeed(); this.xspeed = -this.xspeed; } else if(this.y+this.size >= window.innerHeight){ this.y = window.innerHeight - this.size; this.changeDirection(); this.calcDistance(); this.pickColor(); this.calcSpeed(); this.yspeed = -this.yspeed; } else if(this.y <= 0){ this.y = 0; this.changeDirection(); this.calcDistance(); this.pickColor(); this.calcSpeed(); this.yspeed = -this.yspeed; } } render() { return ( <div class="sketch"> <a href="#" id="backButton" onClick={() => this.props.turnOffVisualizer()}>Back to Spotifam Queue</a> <Sketch setup={this.setup} draw={this.draw}/> </div> ); } }
export default { PRE_SELECT_FROM_ADDRESS: 'SEND_FUNDS/PRE_SELECT_FROM_ADDRESS', PRE_SELECT_TO_ADDRESS: 'SEND_FUNDS/PRE_SELECT_TO_ADDRESS', RESET_FIELDS: 'SEND_FUNDS/RESET_FIELDS', SET_AMOUNT: 'SEND_FUNDS/SET_AMOUNT', SET_FEE: 'SEND_FUNDS/SET_FEE', SET_FROM_ADDRESS: 'SEND_FUNDS/SET_FROM_ADDRESS', SET_MEMO: 'SEND_FUNDS/SET_MEMO', SET_TO_ADDRESS: 'SEND_FUNDS/SET_TO_ADDRESS', };
window.onload = function() { $('.menu .item').tab(); $('.special.cards .image').dimmer({ on: 'hover' }); console.log(localStorage.getItem("libro-leccion")); console.log(localStorage.getItem("libro-leccion")); new DiscipleshipContainer('get'); }
require('./Errors.scss'); const React = require('react'); const { arrayOf, string, oneOfType, object } = React.PropTypes; const MirageErrors = React.createClass({ propTypes: { errorMessages: arrayOf(oneOfType([ string, object ])).isRequired, }, render() { if (!this.props.errorMessages.length) { return null; } return ( <div className="mirage-errors"> {this.props.errorMessages.map(this.renderError)} </div> ); }, renderError(_e) { const error = typeof _e === 'string' ? { message: _e } : _e; return ( <div key={error.message} className="mirage-errors__error"> {error.message} {error.stack && ( <pre>{error.stack}</pre> )} </div> ) } }); module.exports = MirageErrors;
/*global window */ /*global chrome */ /*global X2JS */ /*jslint browser: true*/ var x2js = new X2JS(); var firstPage = document.getElementsByClassName("js-first-page")[0]; var secondPage = document.getElementsByClassName("js-second-page")[0]; var firstPage; var secondPage; //将日期格式化为2014-02-03格式 function formatDate(indate) { var now = new Date(parseInt(indate, 10)); var year = now.getFullYear(); var month = now.getMonth() + 1; if (month < 10) { month = "0" + month; } var date = now.getDate(); if (date < 10) { date = "0" + date; } var str = year + "-" + month + "-" + date; return str; //+ " " + hour + ":" + minute + ":" + second; } //隐藏下载页,显示提示信息页面 function hideFirstPage() { firstPage.style.display = "none"; secondPage.style.display = "block"; } function xdomain(par){//crossdomain function par.xpath=par.xpath==undefined?"*":par.xpath; par.type=par.type==undefined?"xml":par.type; var xmlhttp=new XMLHttpRequest(); par.url = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent('select * from html WHERE url="'+par.url+'" AND xpath="'+par.xpath+'"')+'&format='+par.type+'&callback=cb'; xmlhttp.open("GET",par.url,false); xmlhttp.onload=function(){ function cb(d){return d;}//callBack function for returning results from query par.callBack(xmlhttp.responseText); }; xmlhttp.send(); }; //隐藏提示信息页面,显示下载页 function showFirstPage() { secondPage.style.display = "none"; firstPage.style.display = "block"; } var today = new Date().getTime(); var nowDate; // Download all visible checked links. function downloadCheckedLinks(url, index) { var saveAs = false; if (1 === index) { saveAs = true; } var imgurl = url || document.getElementById('filter').value; chrome.downloads.download({ url: imgurl, method: "GET", saveAs : saveAs, conflictAction: "overwrite" }, function (downloadId) { }); } //计算两个日期的天数差 function GetDateRegion(BeginDate, EndDate) { var aDate, oDate1, oDate2, iDays; var sDate1 = BeginDate; //sDate1和sDate2是2008-12-13格式 var sDate2 = EndDate; aDate = sDate1.split("-"); oDate1 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]); //转换为12/13/2008格式 aDate = sDate2.split("-"); oDate2 = new Date(aDate[1] + '/' + aDate[2] + '/' + aDate[0]); var i = (oDate1 - oDate2) / 1000 / 60 / 60 / 24; iDays = i; //把相差的毫秒数转换为天数 return iDays; } //Download today bing's iamge of the day function downloadBingTodayImage() { var ratio = document.getElementById("js-ratio").value; var mkt = document.getElementById("js-country-choice").value; var i = 0; var choiceDate = document.getElementsByClassName("js-the-date")[0].value; if ("" === choiceDate) { choiceDate = nowDate; } var countDay = GetDateRegion(nowDate, choiceDate); var num = document.getElementsByClassName("div-day-num")[0].value; var ajaxRequest = new XMLHttpRequest(); var requestUrl = "http://global.bing.com/HPImageArchive.aspx?format=xml&idx=" + countDay + "&n=" + num + "&mkt=" + mkt; xdomain({ url:requestUrl,// url of site type:"xml",//return in xml or JSON format xpath:"*",//filter objects callBack:function(data){ console.log("data==== " +data); data = data.replace("/**/cb(","").replace(");",""); console.log(JSON.parse(data)) data = JSON.parse(data); var xml2Json = x2js.xml_str2json(data.results); console.log(xml2Json); if (null === xml2Json) { hideFirstPage(); return; } var images = xml2Json.html.body.images.image; var imageUrl = ""; if (undefined === images.length) { imageUrl = 'http://www.bing.com' + images.url; imageUrl = imageUrl.replace("1366x768", ratio); downloadCheckedLinks(imageUrl, 1); } else { for (i = 0; i < images.length; i++) { imageUrl = 'http://www.bing.com' + images[i].url; imageUrl = imageUrl.replace("1366x768", ratio); downloadCheckedLinks(imageUrl, 2); } } } }); } // Set up event handlers and inject send_links.js into all frames in the active // tab. window.onload = function () { firstPage = document.getElementsByClassName("js-first-page")[0]; secondPage = document.getElementsByClassName("js-second-page")[0]; nowDate = formatDate(today); document.getElementById("js-the-date").setAttribute("max", nowDate); document.getElementById("js-the-date").value = nowDate; document.getElementById('js-download0').onclick = downloadBingTodayImage; document.getElementById("js-cancle-button").onclick = showFirstPage; };
import React ,{ Component }from 'react'; import { Collapse,Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button } from 'reactstrap'; import './Aticle.css'; class ArticleCard extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { collapse: false }; } toggle() { this.setState({ collapse: !this.state.collapse }); } render(){ return ( <div> <Card className="col-md-4" style={{ width:"300px",margin:"auto"}}> <div><span><CardImg top width="100%" src="../assets/images/author1.png" alt="Card" /></span><span className=""></span>Author:proxima</div> <CardImg top width="100%" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180" alt="Card image cap" /> <CardBody> <CardTitle>Card title</CardTitle> <CardSubtitle>Card subtitle</CardSubtitle> <CardText>Some quick example text to build on the card title and make up the bulk of the card's content.</CardText> <Button color="primary" onClick={this.toggle} style={{ marginBottom: '1rem' }}>Read More</Button> <Collapse isOpen={this.state.collapse}> <Card> <CardBody> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. </CardBody> </Card> </Collapse> </CardBody> </Card> <Card className="col-md-4" style={{ width:"300px",margin:"auto"}}> <CardImg top width="100%" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180" alt="Card image cap" /> <CardBody> <CardTitle>Card title</CardTitle> <CardSubtitle>Card subtitle</CardSubtitle> <CardText>Some quick example text to build on the card title and make up the bulk of the card's content.</CardText> <Button>Button</Button> </CardBody> </Card> </div> ); } } export default ArticleCard;
/** * Require the necessary node modules. */ var gulp = require('gulp'), browserSync = require('browser-sync'), browserReload = browserSync.reload, browserNotify = browserSync.notify, cp = require('child_process'); /** * Load all Gulp plugins. */ var $ = require('gulp-load-plugins')({ rename: { 'gulp-less': 'less', 'gulp-util': 'utils', 'gulp-minify-css': 'cssMin', 'gulp-concat': 'concat', 'gulp-uglify': 'uglify', 'gulp-jsdoc': 'jsdoc' } }); /** * Set global configuration options. */ var config = { projectName: 'Gamma 7', port: 8080, folders: { buildFolder: '_site', assetsFolder: 'public', styleguideFolder: '_styleguide', // Needs to match the value in "kss.json" as well jsdocsFolder: '_jsdocs' }, messages: { lessCompile: 'Compiling Styles', jsConcat: 'Concatenating Javascript', jekyllBuild: '<span style="color: grey;">Running:</span> $ jekyll build', styleguide: 'The styleguide has been generated', jsdocs: 'The javascript documentation has been generated', } }, styleguideUrl = 'http://localhost:' + config.port + '/' + config.folders.styleguideFolder, jsdocsUrl = 'http://localhost:' + config.port + '/' + config.folders.jsdocsFolder; /** * Wait for less compilation and jekyll-build-dev, then launch the Server. */ gulp.task('browser-sync', ['less', 'js', 'jekyll-build-dev'], function() { browserSync({ port: config.port, server: { baseDir: './', routes: { 'site': config.folders.buildFolder, 'styleguide': config.folders.styleguideFolder, 'jsdocs': config.folders.jsdocsFolder } }, startPath: config.folders.buildFolder, ghostMode: true, logPrefix: config.projectName }, function() { $.utils.log('---------------------------------------------'); $.utils.log('Styleguide: ' + $.utils.colors.magenta(styleguideUrl)); $.utils.log('JS Docs: ' + $.utils.colors.magenta(jsdocsUrl)); $.utils.log('---------------------------------------------'); }); }); /** * Compile files from public/_less/ into public/css/. */ gulp.task('less', function () { browserNotify(config.messages.lessCompile, 3000); return gulp.src(config.folders.assetsFolder + '/_less/*.less') .pipe($.less({ paths: [ config.folders.assetsFolder + '/_less' ] })) .pipe($.cssMin()) .pipe(gulp.dest(config.folders.assetsFolder + '/css')); }); /** * Concatenate and uglify all javascript files. */ gulp.task('js', ['js:vendor', 'js:custom'], function() { browserNotify(config.messages.jsConcat, 3000); }); /** * Concatenates all vendor javascript (frameworks & libraries) */ gulp.task('js:vendor', function() { return gulp.src([ // jQuery 'bower_components/jquery/jquery.min.js', // jQuery Plugins 'bower_components/jquery-backstretch/jquery.backstretch.min.js', // Bootstrap 'bower_components/bootstrap/js/affix.js', 'bower_components/bootstrap/js/alert.js', 'bower_components/bootstrap/js/button.js', 'bower_components/bootstrap/js/carousel.js', 'bower_components/bootstrap/js/collapse.js', 'bower_components/bootstrap/js/dropdown.js', 'bower_components/bootstrap/js/modal.js', 'bower_components/bootstrap/js/tooltip.js', 'bower_components/bootstrap/js/popover.js', 'bower_components/bootstrap/js/scrollspy.js', 'bower_components/bootstrap/js/tab.js', 'bower_components/bootstrap/js/transition.js', ]) .pipe($.concat('vendor.js')) .pipe($.uglify({ mangle: false })) .pipe(gulp.dest(config.folders.buildFolder + '/' + config.folders.assetsFolder + '/js')); }); /** * Concatenates all custom javascript from public/js/ */ gulp.task('js:custom', function() { return gulp.src([ config.folders.assetsFolder + '/js/_main.js', config.folders.assetsFolder + '/js/_utils.js', config.folders.assetsFolder + '/js/pages/*.js', config.folders.assetsFolder + '/js/global/*.js', config.folders.assetsFolder + '/js/modules/*.js' ]) .pipe($.concat('scripts.js')) .pipe($.uglify({ mangle: false })) .pipe(gulp.dest(config.folders.buildFolder + '/' + config.folders.assetsFolder + '/js')); }); /** * Build the Jekyll site for local development. * Uses: _config-dev.yml */ gulp.task('jekyll-build-dev', function (cb) { browserNotify(config.messages.jekyllBuild, 3000); return cp.exec('jekyll build --config _config-dev.yml', function(err) { if (err) { return $.utils.log($.utils.colors.red(err)); } cb(); }); }); /** * Build the Jekyll site for production. * Uses: _config-prod.yml */ gulp.task('jekyll-build-prod', function (cb) { browserNotify(config.messages.jekyllBuild, 3000); return cp.exec('jekyll build --config _config-prod.yml', function(err) { if (err) { return $.utils.log($.utils.colors.red(err)); } cb(); }); }); /** * Watch files for changes & recompile. */ gulp.task('watch', function () { gulp.watch( config.folders.assetsFolder + '/_less/**/*.less', ['less', 'js', 'jekyll-build-dev', 'styleguide', function(cb) { browserReload(); }] ); gulp.watch( config.folders.assetsFolder + '/js/**/*.js', ['js', 'less', 'jekyll-build-dev', 'jsdocs', function(cb) { browserReload(); }] ); gulp.watch( ['*.html', 'pages/**/*.html', '_layouts/*.html', '_includes/**/*.html'], ['less', 'js', 'jekyll-build-dev', function(cb) { browserReload(); }] ); }); /** * Generates the project's styleguide. */ gulp.task('styleguide', function() { return cp.exec('./node_modules/kss/bin/kss-node --config kss.json', function(err) { if (err) { return $.utils.log($.utils.colors.red(err)); } browserNotify(config.messages.styleguide, 3000); }); }); /** * Generates the project's javascript documentation. */ gulp.task('jsdocs', function () { browserNotify(config.messages.jsdocs, 3000); return gulp.src(config.folders.assetsFolder + '/js/**/*.js') .pipe($.jsdoc(config.folders.jsdocsFolder)); }); /** * Main gulp tasks. */ gulp.task('default', ['serve']); gulp.task('serve', ['browser-sync', 'watch', 'styleguide', 'jsdocs']); gulp.task('build', ['less', 'js', 'jekyll-build-prod'], function() { $.utils.log($.utils.colors.magenta('Jekyll project has been built into: ' + config.folders.buildFolder)); });
import React from "react"; import './index.css'; import { Row, Col } from 'reactstrap'; import { Typography, Button } from 'components'; import _, { isNull } from 'lodash'; import { connect } from "react-redux"; import classNames from 'classnames'; import { getApp, getAppCustomization } from "../../lib/helpers"; import { CopyText } from "../../copy"; import { formatCurrency } from '../../utils/numberFormatation'; import { getCoinConversion, getCoinList } from "../../lib/api/coinGecko"; class PaymentBox extends React.Component{ constructor(props){ super(props); this.state = { checked : false, price : null, virtualTicker: null, walletImage: null, disabledFreeButton: true, minutes: 0, seconds: 0, amount: 0, secondsToCanvas: 0, isCanvasRenderer: false, convertedCurrency: {} } } async componentDidMount(){ this.projectData(this.props); this.setState({ isCanvasRenderer: true }) setInterval(() => this.parseMillisecondsIntoReadableTime() , 0) this.timerInterval = setInterval(() => { const { seconds, minutes } = this.state; if (seconds > 0) { this.setState({ seconds: seconds - 1 }); } if (seconds === 0) { if (minutes === 0) { } else { this.setState(({ minutes }) => ({ minutes: minutes - 1, seconds: 59, disabledFreeButton: true })); } } }, 1000); } componentWillReceiveProps(props){ this.setState({ isCanvasRenderer: true }) if(props !== this.props) { this.projectData(props); this.parseMillisecondsIntoReadableTime(); } } projectData = async (props) => { const { wallet, profile} = props; const { isCanvasRenderer } = this.state; const virtual = getApp().virtual; const currency = await getCoinList({ filter: wallet.currency.name }); const convertedCurrency = await getCoinConversion({ from: currency && currency.id, to: "usd", balance: wallet.playBalance }); this.setState({ isCanvasRenderer: false, convertedCurrency }); if (virtual === true) { const virtualCurrency = getApp().currencies.find(c => c.virtual === true); if(wallet.currency.virtual !== true && virtualCurrency) { const virtualWallet = getApp().wallet.find(w => w.currency._id === virtualCurrency._id); const price = virtualWallet ? virtualWallet.price.find(p => p.currency === wallet.currency._id).amount : null; this.setState({ price, virtualTicker : virtualCurrency.ticker }); } } const appWallet = getApp().wallet.find(w => w.currency._id === wallet.currency._id); this.setState({ walletImage : _.isEmpty(appWallet.image) ? wallet.currency.image : appWallet.image }); this.funcToGetValue(); this.funcVerificationCurrency(); if(isCanvasRenderer){ this.verifyTime(); } if(profile.user.email_confirmed === false){ this.setState({ disabledFreeButton: true}) } } funcVerifyUserWalletDate = async() => { const { wallet, profile } = this.props; const resultWallet = await profile.lastTimeFree(); if(resultWallet){ const walletFind = resultWallet.find(w => w.currency === wallet.currency._id) return walletFind.date }else{ return false; } } verifyTime = async() => { const { seconds, minutes, isCanvasRenderer } = this.state; const { wallet } = this.props; if(seconds === 0 && minutes === 0){ this.setState({ disabledFreeButton: false }); }else{ this.startCountdown(document.getElementById(wallet.currency.name)); this.setState({ disabledFreeButton: true }); } } funcVerification = () => { const { wallet } = this.props; const freeCurrency = getApp().addOn.freeCurrency; if(freeCurrency){ const wallets = freeCurrency.wallets; const walletFind = wallets.find(w => w.currency === wallet.currency._id) return walletFind ? walletFind.activated : false }else{ return false; } } funcVerificationTime = () => { const { wallet } = this.props; const freeCurrency = getApp().addOn.freeCurrency; if(freeCurrency){ const wallets = freeCurrency.wallets; const walletFind = wallets.find(w => w.currency === wallet.currency._id) return walletFind ? walletFind.time : 0 }else{ return false; } } funcVerificationCurrency = async () => { const { wallet } = this.props; const freeCurrency = getApp().addOn.freeCurrency; if(freeCurrency){ const wallets = freeCurrency.wallets; const walletFind = wallets.find(w => w.currency === wallet.currency._id) return walletFind ? walletFind.currency : "" }else{ return false; } } startCountdown = async(canvas) => { const { secondsToCanvas } = this.state; const { colors } = getAppCustomization(); const secondaryColor = colors.find(c => { return c.type == "secondaryColor" }); const PI_BY_180 = Math.PI / 180; const THREE_PI_BY_TWO = 3 * Math.PI / 2; const DEFAULT_VALUE = -360; const TIMER_INTERVAL = 40; const ringTimer = canvas.getContext('2d'); const { width, height } = canvas.getBoundingClientRect(); const centerX = width / 2; const centerY = height / 2; const radius = Math.min(width, height) / 2; const startTime = Date.now(); const endTime = startTime + (secondsToCanvas * 1000); const renderCountdown = (currentValue) => { const start = THREE_PI_BY_TWO; ringTimer.clearRect(0, 0, width, height); // Draw outer track ring ringTimer.beginPath(); ringTimer.moveTo(centerX, centerY); ringTimer.arc( centerX, centerY, radius, start - (360 - currentValue) * PI_BY_180, start, true // counter-clockwise ); ringTimer.closePath(); ringTimer.fillStyle = secondaryColor.hex; ringTimer.fill(); } return new Promise(resolve => { renderCountdown(0); const id = setInterval(() => { const now = Date.now(); if (now > endTime) { clearInterval(id); renderCountdown(360); return resolve(); } const elapsedTime = (Date.now() - startTime) / 1000; const currentValue = DEFAULT_VALUE * Math.max(0, secondsToCanvas - elapsedTime) / secondsToCanvas renderCountdown(currentValue); }, TIMER_INTERVAL); }); } funcToGetValue = () => { const { wallet } = this.props; const freeCurrency = getApp().addOn.freeCurrency; if(freeCurrency){ const wallets = freeCurrency.wallets; const walletTest = wallets.find(w => w.currency === wallet.currency._id) return this.setState({ amount: walletTest ? walletTest.value : 0 }) }else{ return false; } } userUpdateBalance = async () => { const { profile } = this.props; const { amount } = this.state; await profile.updateBalanceWithoutBet({ amount }); return new Promise(resolve => setTimeout(() => resolve(), 500)); }; handleSendCurrancyFree = async () => { try { const { profile, ln } = this.props; const resultCurrency = await this.funcVerificationCurrency(); await profile.sendFreeCurrencyRequest({ currency_id: resultCurrency }); this.setState({ disabledFreeButton: true }); await this.userUpdateBalance(); await profile.getAllData(true); await this.verifyTime(); } catch (err) { console.log(err); this.setState({ disabledFreeButton: false }); } } parseMillisecondsIntoReadableTime = async () => { const resultUserDate = await this.funcVerifyUserWalletDate(); const miliseconds = resultUserDate + this.funcVerificationTime() - Date.now(); const hours = miliseconds / (1000 * 60 * 60); if(hours< 0){ this.setState({ hours: 0, minutes: 0, seconds: 0, secondsToCanvas: 0 }); }else{ const secondsToCanvas = (miliseconds / 1000); const hours = miliseconds / (1000 * 60 * 60); const absoluteHours = Math.floor(hours); const h = absoluteHours > 9 ? absoluteHours : absoluteHours; const minutes = (hours - absoluteHours) * 60; const absoluteMinutes = Math.floor(minutes); const m = absoluteMinutes > 9 ? absoluteMinutes : absoluteMinutes; const seconds = (minutes - absoluteMinutes) * 60; const absoluteSeconds = Math.floor(seconds); const s = absoluteSeconds > 9 ? absoluteSeconds : absoluteSeconds; this.setState({ hours: h, minutes: m, seconds: s, secondsToCanvas: secondsToCanvas }); if(s === 0 && s === 0){ this.setState({ disabledFreeButton: false }); }else{ this.setState({ disabledFreeButton: true }); } } }; onClick = () => { const { id, onClick } = this.props; if(onClick){ onClick(id) this.setState({ isCanvasRenderer: false }); } } render(){ let { isPicked, wallet } = this.props; const { price, virtualTicker, walletImage, disabledFreeButton, convertedCurrency } = this.state; const styles = classNames("container-root", { selected: isPicked }); const hasBonus = !Number.isNaN(wallet.bonusAmount) && Number(wallet.bonusAmount) > 0; const walletValid = this.funcVerification(); return ( <button onClick={this.onClick} styleName={styles} disabled={wallet.currency.virtual}> <Col> <Row> <Col xs={4} md={4}> <div styleName='container-image'> <img src={walletImage} styleName='payment-image'/> </div> </Col> <Col xs={8} md={8}> <div styleName={'container-text'}> <Typography variant={'small-body'} color={'white'}> {`${wallet.currency.name} (${wallet.currency.ticker})`} </Typography> <div styleName='text-description'> <Typography variant={'x-small-body'} color={'white'}> {`${formatCurrency(wallet.playBalance)} ${wallet.currency.ticker}`} </Typography> </div> {!isNull(convertedCurrency) && <div styleName='text-description'> <Typography variant={'x-small-body'} color={'white'}> {convertedCurrency.amount} </Typography> </div> } {hasBonus && <div styleName='text-description bonus-amount'> <Typography variant={'x-small-body'} color={'white'}> Bonus: {formatCurrency(wallet.bonusAmount)} </Typography> </div> } {price ? <div styleName='text-description'> <Typography variant={'x-small-body'} color={'white'}> {`1 ${virtualTicker} = ${price} ${wallet.currency.ticker}`} </Typography> </div> : null} </div> </Col> </Row> { walletValid ? <div styleName="bottom-line"> <Col xs={4} md={4} styleName="button-padding"> <div styleName="border-radius"> <canvas id={wallet.currency.name} width="30" height="30"></canvas> </div> </Col> <Col xs={8} md={8} styleName="button-padding"> <Button size={'x-small'} theme={'action'} disabled={disabledFreeButton} onClick={this.handleSendCurrancyFree}> <Typography color={'white'} variant={'small-body'}>Replenish</Typography> </Button> </Col> </div> : null } </Col> </button> ) } } function mapStateToProps(state){ return { deposit : state.deposit, profile : state.profile }; } export default connect(mapStateToProps)(PaymentBox);
export const BEEP_SAVE_FORM = `athleteTests/BeepInputForm/BEEP_SAVE_FORM`; export const BEEP_SAVE_FORM_ERROR = `athleteTests/BeepInputForm/BEEP_SAVE_FORM_ERROR`; export const BEEP_SAVE_FORM_SUCCESS = `athleteTests/BeepInputForm/BEEP_SAVE_FORM_SUCCESS`;
import React, { Component } from 'react'; import './avatar.css'; class Avatar extends Component { render() { return ( <img src={this.props.imageUrl} alt={this.props.altText} className="avatar" /> ) } } export default Avatar;
module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin:vue/essential', '@vue/standard' ], parserOptions: { parser: 'babel-eslint' }, globals: { 'Log': 'readonly' }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-unreachable': 0, // 禁止在 return、throw、continue 和 break 语句之后出现不可达代码 'no-unsafe-negation': 2, // 禁止对关系运算符的左操作数使用否定操作符 'default-case': 0, // 要求 switch 语句中有 default 分支 'eqeqeq': 0, // 要求使用 === 和 !== 'no-alert': 1, // 禁用 alert、confirm 和 prompt 'no-new-wrappers': 0, // 禁止对 String,Number 和 Boolean 使用 new 操作符 'init-declarations': [0, 'always'], // 要求或禁止 var 声明中的初始化 'no-unused-vars': [2, { 'varsIgnorePattern': '[iI]go', 'args': 'none' }], // 禁止出现未使用过的变量 // "indent": [2, 2], // 强制使用一致的缩进 'line-comment-position': [0, { 'position': 'above' }], // 强制行注释的位置 'no-multiple-empty-lines': 0 // 禁止出现多行空行 } } /** * 行内 eslint 验证规则 * eslint-disable import/no-duplicates 禁用:多次引入同一模块 * eslint-disable no-unused-vars 禁用:禁止出现未使用过的变量 */
import React from 'react'; import moment from 'moment'; import classes from './Main.module.css'; import { CircularProgress } from '@material-ui/core'; const Main = ({loading, entries, handleAddEntry, handleEntryClick}) => { return <div className={classes.container}> <div className={[classes.plus_circle].concat(loading ? classes.disabled : '').join(' ')} onClick={handleAddEntry}> </div> <h1>Lastest Entries</h1> {loading ? <div className={classes.loading_container}><CircularProgress color='secondary'/></div> : <div className={classes.list_container}> {entries.map((e, i) => <div key={i} className={classes.entry_box} onClick={() => handleEntryClick(e._id)} > {moment.parseZone(e.createdAt).format('dddd, MMMM Do')} </div>)} </div> } </div> }; export default Main;
import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import configureStore from 'redux-mock-store'; import SearchBar from './SearchBar'; import { stateMock } from '../stateMock'; import * as Actions from '../actions/actions'; const mockStore = configureStore(); const store = mockStore(stateMock); describe('<SearchBar />', () => { describe('render()', () => { test('renders the component', () => { const wrapper = shallow(<SearchBar store={store} />); const component = wrapper.dive(); expect(component).toHaveLength(1); expect(toJson(component)).toMatchSnapshot(); }); test('hides autocomplete box by default', () => { const wrapper = shallow(<SearchBar store={store} />); const component = wrapper.dive(); expect(component.find('ul').getElement().props.style.visibility).toEqual('hidden'); }); }); describe('onFocus', () => { test('shows autocomplete box when search bar is in focus', () => { const wrapper = shallow(<SearchBar store={store} />); const component = wrapper.dive(); // by default expect(component.find('ul').getElement().props.style.visibility).toEqual('hidden'); component.find('input').simulate('focus'); expect(component.find('ul').getElement().props.style.visibility).toEqual('visible'); }); }); describe('onBlur', () => { test('hides autocomplete box when search bar is not in focus', () => { const wrapper = shallow(<SearchBar store={store} />); const component = wrapper.dive(); // by default expect(component.find('ul').getElement().props.style.visibility).toEqual('hidden'); component.find('input').simulate('blur'); expect(component.find('ul').getElement().props.style.visibility).toEqual('hidden'); }); test('hides autocomplete box when search bar is empty', () => { const wrapper = shallow(<SearchBar store={store} />); const component = wrapper.dive(); // by default expect(component.find('ul').getElement().props.style.visibility).toEqual('hidden'); component.find('input').simulate('focus'); expect(component.find('ul').getElement().props.style.visibility).toEqual('visible'); store.dispatch(Actions.clearSearch()); expect(wrapper.dive().find('ul').getElement().props.style.visibility).toEqual('hidden'); }); }); });
import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { actFetchAllMovie } from '../../../client/Home/module/actions.js'; import { Button, Input, Row, Col } from 'antd'; import MovieTable from './MovieTable/MovieTable.jsx'; import Loader from 'components/Loader/Loader'; import './Movie.scss' export default function Movie() { const dispatch = useDispatch(); useEffect(() => { dispatch(actFetchAllMovie()); }, []); // componentDidMount const { listMovie, loading } = useSelector(state => state.movieReducer); const [searchState, setSearchState] = useState({ keyword: null, searchList: [], }) const { Search } = Input; const filterListMovie = (filter) => { const searchList = listMovie.filter(movie => (movie.maPhim == filter) || (movie.tenPhim === filter) || (new Date(movie.ngayKhoiChieu).toLocaleDateString() === filter) ); setSearchState({ ...searchState, keyword: filter, searchList, }) } return !loading ? ( <div className="adminMovieListPage"> <h2 className="responsive-h2">Movie List</h2> <Row> <Col span={4}> <Button href='/admin/addMovie' type="dashed">+ Add a new movie</Button> </Col> <Col span={7}> </Col> <Col span={13}> <Search placeholder="find a movie" allowClear enterButton="Search" onChange={event => filterListMovie(event.target.value)} onSearch={keyword => filterListMovie(keyword)} /> </Col> </Row> <MovieTable listMovie={searchState.keyword ? searchState.searchList : listMovie} /> </div> ) : (<Loader />) }
import { EMAIL_CHANGED, LOGIN_USER_SUCCESS, LOGIN_USER_FAIL, LOGIN_USER_START } from './types'; export const emailChanged = (text) => { return { type: EMAIL_CHANGED, payload: text }; }; export const loginUser = ({ email, password }) => { // if using redux-thunk in index.ios.js // store={createStore(reducers, {}, applyMiddleware(ReduxThunk))} return (dispatch) => { dispatch({ type: LOGIN_USER_START }); Auth0Lock.stuff.signIn(email, password) .then((user) => { dispatch({ type: LOGIN_USER_SUCCESS, payload: user }); }) .catch(() => { Auth0Lock.createUser(email, password) .then(user => { dispatch({ type: LOGIN_USER_SUCCESS, payload: user }); }) .catch(() => loginUserFail(dispatch)); }); }; }; const loginUserFail = (dispatch) => { dispatch({ type: LOGIN_USER_FAIL }); };
const { response } = require("express"); const URLModel = require("../model/URLModel"); class URLController { async generateShortenedURL(request, response) { const { id_user, original_url } = request.body; const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let code = ""; for (let i = 0; i < 5; i++) { code += possible.charAt(Math.floor(Math.random() * possible.length)); } const data = { id_user, id_url: code, original_url, shortened_url: `${process.env.APP_URL}/${code}`, }; const url = new URLModel(data); await url .save() .then(() => { return response.status(200).json({ success: { originalURL: data.original_url, shortenedURL: data.shortened_url, }, }); }) .catch((error) => { return response.status(500).json({ error: error }); }); } async listGeneratedURL(request, response) { const { id } = request.params; const urls = await URLModel.findAll({ where: { id_user: id, }, }); if (urls) { return response.status(200).json({ success: urls }); } else { return response .status(500) .json({ success: "Usuário não possui URLs geradas!" }); } } async findURL(request, response) { const { id_url } = request.params; const url = await URLModel.findOne({ where: { id_url: id_url } }); if (url) { response.redirect(url.original_url); } else { return response.status(500).json({ success: "URL não localizada." }); } } } module.exports = new URLController();
$(document).ready(function() { $("#image_active").imagesActivesBasic({ optionsFile : "options.xml" }); });
import styled from '@emotion/styled' import { select } from '../../../macros' const SelectNative = styled.select(...select.styles()) SelectNative.propTypes = { ...select.propTypes(), } SelectNative.defaultProps = { ...select.defaultProps(), } export default SelectNative
"use strict"; exports.MANAGER_ID_NAME = exports.NotificationManagerStub = exports.NotificationManager = void 0; var _guid = _interopRequireDefault(require("../../core/guid")); var _renderer = _interopRequireDefault(require("../../core/renderer")); var _extend = require("../../core/utils/extend"); var _icon = require("../../core/utils/icon"); var _uiFile_managerNotification = _interopRequireDefault(require("./ui.file_manager.notification.progress_panel")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var FILE_MANAGER_PROGRESS_BOX_CLASS = 'dx-filemanager-progress-box'; var FILE_MANAGER_PROGRESS_BOX_ERROR_CLASS = "".concat(FILE_MANAGER_PROGRESS_BOX_CLASS, "-error"); var FILE_MANAGER_PROGRESS_BOX_IMAGE_CLASS = "".concat(FILE_MANAGER_PROGRESS_BOX_CLASS, "-image"); var FILE_MANAGER_PROGRESS_BOX_WRAPPER_CLASS = "".concat(FILE_MANAGER_PROGRESS_BOX_CLASS, "-wrapper"); var FILE_MANAGER_PROGRESS_BOX_COMMON_CLASS = "".concat(FILE_MANAGER_PROGRESS_BOX_CLASS, "-common"); var MANAGER_ID_NAME = '__operationInfoManager'; exports.MANAGER_ID_NAME = MANAGER_ID_NAME; var ACTION_PROGRESS_STATUS = { default: 'default', progress: 'progress', error: 'error', success: 'success' }; var NotificationManagerBase = /*#__PURE__*/function () { function NotificationManagerBase(_ref) { var onActionProgressStatusChanged = _ref.onActionProgressStatusChanged, isActual = _ref.isActual; this._id = new _guid.default().toString(); this._isActual = isActual || false; this._actionProgressStatus = ACTION_PROGRESS_STATUS.default; this._raiseActionProgress = onActionProgressStatusChanged; } var _proto = NotificationManagerBase.prototype; _proto.getId = function getId() { return this._id; }; _proto.isActual = function isActual() { return this._isActual; }; _proto.createErrorDetailsProgressBox = function createErrorDetailsProgressBox($container, item, errorText) { var detailsItem = this._createDetailsItem($container, item); this.renderError(detailsItem.$wrapper, errorText); }; _proto.renderError = function renderError($container, errorText) { (0, _renderer.default)('<div>').text(errorText).addClass(FILE_MANAGER_PROGRESS_BOX_ERROR_CLASS).appendTo($container); }; _proto.isActionProgressStatusDefault = function isActionProgressStatusDefault() { return this._actionProgressStatus === ACTION_PROGRESS_STATUS.default; }; _proto._createDetailsItem = function _createDetailsItem($container, item) { var $detailsItem = (0, _renderer.default)('<div>').appendTo($container); return this._createProgressBox($detailsItem, { commonText: item.commonText, imageUrl: item.imageUrl }); }; _proto._createProgressBox = function _createProgressBox($container, options) { $container.addClass(FILE_MANAGER_PROGRESS_BOX_CLASS); if (options.imageUrl) { (0, _icon.getImageContainer)(options.imageUrl).addClass(FILE_MANAGER_PROGRESS_BOX_IMAGE_CLASS).appendTo($container); } var $wrapper = (0, _renderer.default)('<div>').addClass(FILE_MANAGER_PROGRESS_BOX_WRAPPER_CLASS).appendTo($container); var $commonText = (0, _renderer.default)('<div>').addClass(FILE_MANAGER_PROGRESS_BOX_COMMON_CLASS).text(options.commonText).appendTo($wrapper); return { $commonText: $commonText, $element: $container, $wrapper: $wrapper }; }; return NotificationManagerBase; }(); var NotificationManagerStub = /*#__PURE__*/function (_NotificationManagerB) { _inheritsLoose(NotificationManagerStub, _NotificationManagerB); function NotificationManagerStub() { return _NotificationManagerB.apply(this, arguments) || this; } var _proto2 = NotificationManagerStub.prototype; _proto2.addOperation = function addOperation() { return _defineProperty({}, MANAGER_ID_NAME, this._id); }; _proto2.addOperationDetails = function addOperationDetails() {}; _proto2.updateOperationItemProgress = function updateOperationItemProgress() {}; _proto2.completeOperationItem = function completeOperationItem() {}; _proto2.completeOperation = function completeOperation() {}; _proto2.completeSingleOperationWithError = function completeSingleOperationWithError() {}; _proto2.addOperationDetailsError = function addOperationDetailsError() {}; _proto2.handleDimensionChanged = function handleDimensionChanged() { return false; }; _proto2.ensureProgressPanelCreated = function ensureProgressPanelCreated() {}; _proto2.tryHideActionProgress = function tryHideActionProgress() { this._updateActionProgress('', ACTION_PROGRESS_STATUS.default); }; _proto2.updateActionProgressStatus = function updateActionProgressStatus() { this._updateActionProgress('', ACTION_PROGRESS_STATUS.default); }; _proto2._updateActionProgress = function _updateActionProgress(message, status) { if (status !== ACTION_PROGRESS_STATUS.default && status !== ACTION_PROGRESS_STATUS.progress) { return; } this._actionProgressStatus = status; this._raiseActionProgress(message, status); }; _proto2.hasNoOperations = function hasNoOperations() { return true; }; _createClass(NotificationManagerStub, [{ key: "_operationInProgressCount", get: function get() { return 0; }, set: function set(value) {} }, { key: "_failedOperationCount", get: function get() { return 0; }, set: function set(value) {} }]); return NotificationManagerStub; }(NotificationManagerBase); exports.NotificationManagerStub = NotificationManagerStub; var NotificationManager = /*#__PURE__*/function (_NotificationManagerB2) { _inheritsLoose(NotificationManager, _NotificationManagerB2); function NotificationManager(options) { var _this; _this = _NotificationManagerB2.call(this, options) || this; _this._failedOperationCount = 0; _this._operationInProgressCount = 0; return _this; } var _proto3 = NotificationManager.prototype; _proto3.addOperation = function addOperation(processingMessage, allowCancel, allowProgressAutoUpdate) { this._operationInProgressCount++; var operationInfo = this._progressPanel.addOperation(processingMessage, allowCancel, allowProgressAutoUpdate); operationInfo[MANAGER_ID_NAME] = this._id; this._updateActionProgress(processingMessage, ACTION_PROGRESS_STATUS.progress); return operationInfo; }; _proto3.addOperationDetails = function addOperationDetails(operationInfo, details, showCloseButton) { this._progressPanel.addOperationDetails(operationInfo, details, showCloseButton); }; _proto3.updateOperationItemProgress = function updateOperationItemProgress(operationInfo, itemIndex, itemProgress, commonProgress) { this._progressPanel.updateOperationItemProgress(operationInfo, itemIndex, itemProgress, commonProgress); }; _proto3.completeOperationItem = function completeOperationItem(operationInfo, itemIndex, commonProgress) { this._progressPanel.completeOperationItem(operationInfo, itemIndex, commonProgress); }; _proto3.completeOperation = function completeOperation(operationInfo, commonText, isError, statusText) { this._operationInProgressCount--; if (isError) { this._failedOperationCount++; } this._progressPanel.completeOperation(operationInfo, commonText, isError, statusText); }; _proto3.completeSingleOperationWithError = function completeSingleOperationWithError(operationInfo, errorInfo) { this._progressPanel.completeSingleOperationWithError(operationInfo, errorInfo.detailErrorText); this._notifyError(errorInfo); }; _proto3.addOperationDetailsError = function addOperationDetailsError(operationInfo, errorInfo) { this._progressPanel.addOperationDetailsError(operationInfo, errorInfo.itemIndex, errorInfo.detailErrorText); this._notifyError(errorInfo); }; _proto3.handleDimensionChanged = function handleDimensionChanged() { if (this._progressPanel) { this._progressPanel.$element().detach(); } return true; }; _proto3.ensureProgressPanelCreated = function ensureProgressPanelCreated(container, options) { var _this2 = this; if (!this._progressPanel) { var $progressPanelElement = (0, _renderer.default)('<div>').appendTo(container); var ProgressPanelClass = this._getProgressPanelComponent(); this._progressPanel = new ProgressPanelClass($progressPanelElement, (0, _extend.extend)({}, options, { onOperationClosed: function onOperationClosed(_ref3) { var info = _ref3.info; return _this2._onProgressPanelOperationClosed(info); } })); } else { this._progressPanel.$element().appendTo(container); } } // needed for editingProgress.tests.js ; _proto3._getProgressPanelComponent = function _getProgressPanelComponent() { return _uiFile_managerNotification.default; }; _proto3._onProgressPanelOperationClosed = function _onProgressPanelOperationClosed(operationInfo) { if (operationInfo.hasError) { this._failedOperationCount--; this.tryHideActionProgress(); } }; _proto3.tryHideActionProgress = function tryHideActionProgress() { if (this.hasNoOperations()) { this._updateActionProgress('', ACTION_PROGRESS_STATUS.default); } }; _proto3.updateActionProgressStatus = function updateActionProgressStatus(operationInfo) { if (operationInfo) { var status = this._failedOperationCount === 0 ? ACTION_PROGRESS_STATUS.success : ACTION_PROGRESS_STATUS.error; this._updateActionProgress('', status); } }; _proto3._notifyError = function _notifyError(errorInfo) { var status = this.hasNoOperations() ? ACTION_PROGRESS_STATUS.default : ACTION_PROGRESS_STATUS.error; this._updateActionProgress(errorInfo.commonErrorText, status); }; _proto3._updateActionProgress = function _updateActionProgress(message, status) { this._actionProgressStatus = status; this._raiseActionProgress(message, status); }; _proto3.hasNoOperations = function hasNoOperations() { return this._operationInProgressCount === 0 && this._failedOperationCount === 0; }; _createClass(NotificationManager, [{ key: "_operationInProgressCount", get: function get() { return this._operationInProgressCountInternal; }, set: function set(value) { this._operationInProgressCountInternal = value; } }, { key: "_failedOperationCount", get: function get() { return this._failedOperationCountInternal; }, set: function set(value) { this._failedOperationCountInternal = value; } }]); return NotificationManager; }(NotificationManagerBase); exports.NotificationManager = NotificationManager;
const express = require('express'); const router = express.Router(); const carritoController = require('../controllers/carritoController'); router.get('/compras', carritoController.carrito); /*agregar ruta por post */ module.exports = router;
import { fun1, fun2 } from "./module1"; // fun1(11111) console.log(fun1(11111)) console.log('main')
import {RECEIVE_PICTURE, RECEIVE_USERS} from './actions'; export function fetchedUsers(state = [], action){ switch(action.type){ case RECEIVE_USERS: return Object.assign([], state, action.last_updated, action.payload); default: return state; } } export function fetchedPictures(state = [], action){ switch(action.type){ case RECEIVE_PICTURE: return Object.assign([], state, action.last_updated, action.payload.slice(0,25)); default: return state; } }
const Crypto = require('../utils/crypto'); const TX = require('./tx'); module.exports = class BlockData { constructor(txs) { this.txs = Array.isArray(txs) ? txs.map(tx => TX({sign: tx.sign, tx: tx})) : []; } get merkleRoot() { switch (this.txs.length) { case 0: return ''; case 1: return Crypto.Hash(JSON.stringify(this.txs[0])); default: let tmpArr1 = []; this.txs.forEach(tx => { tmpArr1.push(Crypto.Hash(JSON.stringify(tx))); }); do { let tmpArr2 = []; for (let i = 0; i < tmpArr1.length; i += 2) { let s1 = tmpArr1[i]; let s2 = (i + 1 < tmpArr1.length) ? tmpArr1[i + 1] : s1; tmpArr2.push(Crypto.Hash(s1 + s2)); } tmpArr1 = tmpArr2; } while (tmpArr1.length > 1); return tmpArr1[0]; } } };
import React, { useState, useEffect, useCallback} from 'react' import productApi from "../api/productApi" import {useHistory, useLocation} from 'react-router-dom' import queryString from 'query-string' export const OrderContext = React.createContext() const OrderContextProvider = (props) => { const [type, setType] = useState('our-foods') const [options, setOptions] = useState({}) const [data, setData] = useState([]) const [totalPage, setTotalPage] = useState(0) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState(null) const history = useHistory() const {pathname} = useLocation() // set pagination = 1 when change type otherwise if not change type pagination = page -1 // start index pagination = 0 let currentPage = options?._page - 1 || 0 const changeOptions = useCallback((value)=> { setOptions(prevState => { return {...prevState, ...value} }) },[]) const changeType = (value) => { setType(value) setOptions({}) } const initialContext = { type, options, data, changeOptions, changeType, isLoading, error, totalPage, currentPage } useEffect(() => { if(pathname === '/product') { const fetchProducts = async() => { const filterOptions = {...options} // set default page = 1 first load if(!filterOptions.hasOwnProperty('_page')) filterOptions['_page'] = 1 // delete params with value = null (price) // sort by price use input range -> clear default params Object.keys(filterOptions).forEach((key) => !filterOptions[key] && delete filterOptions[key] ) const params = { ...filterOptions, _limit:24 } const paramsGetTotalRows = { ...filterOptions, _page:null } setIsLoading(true) setError(null) try { const products = await productApi.getAll(type, params) const totalProducts = await productApi.getAll(type, paramsGetTotalRows) const pageNumber = Math.ceil(totalProducts.length / 24) setData(products) setIsLoading(false) setTotalPage(pageNumber) const queryStringUrl = {...params, name:type} history.push({ search:queryString.stringify(queryStringUrl) }) } catch (e) { setIsLoading(false) setError(e.message) } } fetchProducts() } },[options, type, history, pathname]) return ( <OrderContext.Provider value = {initialContext}> {props.children} </OrderContext.Provider> ) } export default OrderContextProvider
var User = require('./user'); function Api(models) { return { user: User(models.User) }; } module.exports = Api;
(function($) { // Some simple logging var $log = function() { console.log.apply(console, arguments); }; // // Models // var Dashboard = Backbone.Model.extend({ initialize: function(attrs) { _.bindAll(this, 'onAddGraph'); var graphs = this.graphs = new GraphList(); _.each(attrs.graphs || [], function(g) { graphs.add(g); }); graphs.bind('add', this.onAddGraph); }, // When a graph is added, fill in the association onAddGraph: function(m) { m.set({dashboard_id: this.get('id')}); }, // Intelligently place the graph on the dashboard. For now, just put it at the bottom left. autoPlaceGraph: function(g) { var pos = {left: 0, top: 0, width: 20, height: 7} , bottoms = []; this.graphs.each(function(gi) { var gpos = gi.get('position'); bottoms.push((gpos.top || 0) + (gpos.height || 0)); }); bottoms.sort(); pos.top = bottoms[bottoms.length - 1] || 0; g.set({position: pos}); this.graphs.add(g); } }); var Graph = Backbone.Model.extend({ defaults: { kind: 'counter' }, name: function() { var s = this.get('sources') || [] , s0 = s[0] , len = s.length ; if (s0) { return this.get('kind') + (len > 1 ? 's' : '') + ": " + s0 + (len > 1 ? ', ...' : ''); } return "No data defined yet." }, setLocation: function(position) { var pos = this.get('position'); _.extend(pos, position); this.set({position: position}); }, // Assume all sources are of the same kind here setSources: function(sources) { var kind = (sources[0] && sources[0].kind) || "counter" , sourceStrings = _.map(sources, function(r) { return r.source; }) ; this.set({kind: kind, sources: sourceStrings}); }, addSource: function(s) { var sources = this.get('sources'); if (!sources) { sources = [s]; } else { if (!_.include(sources, s)) { sources.push(s); } } this.set({sources: sources}); }, removeSource: function(source) { var sources = this.get('sources'); if (sources) { sources = _.reject(sources, function(el) { return el === source; }); this.set({sources: sources}); } } }); // // Collections // var DashboardList = Backbone.Collection.extend({ model: Dashboard, url: '/dashboards' }); var GraphList = Backbone.Collection.extend({ model: Graph, url: '/graphs' }); // // Views // var DashboardItemView = Backbone.View.extend({ tagName: 'li', className: 'dashboard-item', events: { 'click .delete': 'onClickDelete', 'keydown input': 'onKeyName', 'click button': 'onClickSave', 'click .cancel': 'onClickCancel' }, initialize: function(opts) { _.bindAll(this, 'render', 'onChangeModel', 'onRemoveModel', 'onClickDelete', 'onKeyName', 'onClickSave', 'onClickCancel', 'onChosen'); this.model.bind('change', this.onChangeModel); this.model.bind('remove', this.onRemoveModel); this.model.bind('chosen', this.onChosen); this.mode = opts.mode || 'show'; // vs 'edit' }, render: function() { if (this.mode === 'show') { this.renderShow(); } else { this.renderEdit(); } $(this.el).data('view', this); return this; }, renderShow: function() { var name = this.model.get('name') , html ; html = [ '<span class="chooser">' + name + '</span>' ]; $(this.el).html(html.join('')); }, renderEdit: function() { var name = this.model.get('name') , el = $(this.el) , html ; html = [ '<div class="dashboard-item-edit">', '<input type="text" value="' + name + '" /> <br />', '<button>Save</button> or <a href="#" class="cancel">Cancel</a>', '<a href="#" class="delete">Delete</a>', '</div>' ]; el.html(html.join('')); el.find('input').select(); }, saveEditing: function() { var newName = this.$('input').val(); if (newName.trim()) { this.mode = 'show'; this.model.set({'name': newName}); this.model.save(); } this.render(); }, onChangeModel: function() { this.render(); }, onRemoveModel: function() { $(this.el).remove(); }, onKeyName: function(evt) { if (evt && evt.which === 13) { this.saveEditing(); } }, onClickSave: function(evt) { this.saveEditing(); }, onClickCancel: function(evt) { if (this.model.isNew()) { this.model.destroy(); } else { this.mode = 'show'; this.render(); } }, onClickDelete: function(evt) { evt && evt.preventDefault(); this.model.destroy(); }, onChosen: function() { var el = $(this.el) , wasChosen = el.hasClass('selected') ; if (wasChosen) { this.mode = 'edit' this.render(); } else { $('.dashboard-item').removeClass('selected'); el.addClass('selected'); } } }); var DashboardListView = Backbone.View.extend({ events: { 'click .add-dashboard': 'onClickAddDashboard', 'click .chooser': 'onClickChooser' }, initialize: function() { _.bindAll(this, 'onClickAddDashboard', 'onAddDashboard', 'onResetDashboards', 'onClickChooser', 'onPopState'); this.collection = new DashboardList(); this.collection.bind('add', this.onAddDashboard); this.collection.bind('reset', this.onResetDashboards); this.collection.fetch(); window.onpopstate = this.onPopState; }, setTitle: function(model) { document.title = "Mouth: " + model.get("name"); }, onClickAddDashboard: function(evt) { evt && evt.preventDefault(); this.collection.add(new Dashboard({name: "New Dashboard"})); }, onClickChooser: function(evt) { var target = $(evt.target).parent('.dashboard-item') , view = target.data('view') ; this.trigger('current_change', view.model); view.model.trigger("chosen"); window.history.pushState({dashboardId: view.model.id}, null, "/dashboards/" + view.model.id); this.setTitle(view.model); }, onAddDashboard: function(m, isDynamicAdd) { var dbItemView = new DashboardItemView({model: m, mode: isDynamicAdd ? 'edit' : 'show'}); this.$('ul').append(dbItemView.render().el); if (m.isNew()) { this.trigger('current_change', m); m.trigger('chosen'); } return dbItemView; }, onResetDashboards: function(col) { var self = this , currentModel = null , currentView = null , view , path = window.location.pathname , match , targetDashboardId = null ; match = path.match(/\/dashboards\/(.+)/); targetDashboardId = match && match[1]; col.each(function(m) { currentModel = currentModel || m; view = self.onAddDashboard(m); currentView = currentView || view; if (targetDashboardId && m.id == targetDashboardId) { currentModel = m; currentView = view; } }); this.trigger('current_change', currentModel); currentModel.trigger('chosen'); window.history.replaceState({dashboardId: currentModel.id}, null, "/dashboards/" + currentModel.id); this.setTitle(currentModel); }, onPopState: function(evt) { var self = this , dashboardId = evt && evt.state && evt.state.dashboardId ; if (dashboardId) { self.collection.each(function(m) { if (dashboardId == m.id) { self.trigger('current_change', m); m.trigger('chosen'); self.setTitle(m); } }); } } }); var DashboardPane = Backbone.View.extend({ events: { 'click .add-graph': 'onClickAddGraph' }, initialize: function(opts) { _.bindAll(this, 'render', 'onCurrentChange', 'onClickAddGraph', 'onAddGraph', 'periodicUpdate'); this.dashboardList = opts.dashboardListView; this.dashboardList.bind('current_change', this.onCurrentChange); this.model = null; this.graphViews = []; this.elGrid= this.$('#grid'); this.elAddGraph = this.$('.add-graph'); key('g', this.onClickAddGraph); this.render(); setInterval(this.periodicUpdate, 60000); }, onCurrentChange: function(model) { var self = this; _.each(self.graphViews, function(gv) { gv.destroy(); }); self.graphViews = []; // Clean up if (self.model) { self.model.graphs.unbind('add', self.onAddGraph); //self.elGrid.empty(); } self.model = model; model.graphs.each(function(m) { self.onAddGraph(m); }); self.render(); model.graphs.bind('add', self.onAddGraph); }, onAddGraph: function(m) { var graphView = new GraphView({model: m}); this.graphViews.push(graphView); this.elGrid.append(graphView.render().el); }, onClickAddGraph: function(evt) { var self = this; evt && evt.preventDefault(); if (this.model) { sourceListInst.show({ callback: function(sources) { var item = new Graph(); item.setSources(sources); self.model.autoPlaceGraph(item); item.save(); } }); } }, periodicUpdate: function() { this.model.graphs.each(function(g) { g.trigger("tick"); }); } }); var graphSequence = 0 , currentGraph = null; var GraphView = Backbone.View.extend({ tagName: 'li', className: 'graph', events: { 'click .edit': 'onClickEdit', 'click .delete': 'onClickDelete', 'click .pick': 'onClickPick' }, initialize: function(opts) { _.bindAll(this, 'render', 'onDragStop', 'onClickEdit', 'onClickPick', 'onCreateModel', 'onClickDelete', 'onRemoveModel', 'onPick', 'onCancelPick', 'onDateRangeChanged', 'onTick', 'destroy'); this.mode = 'front'; this.model = opts.model; this.model.bind('change:id', this.onCreateModel); this.model.bind('remove', this.onRemoveModel); this.model.bind('tick', this.onTick); this.graphId = "graph" + graphSequence++; this.kind = ''; $(document.body).bind('date_range_changed', this.onDateRangeChanged); }, destroy: function() { this.model.unbind('change:id', this.onCreateModel); this.model.unbind('remove', this.onRemoveModel); this.model.unbind('tick', this.onTick); $(this.el).remove(); }, render: function() { var el = $(this.el) , m = this.model , pos = m.get('position') ; // Position it el.css({ top: pos.top * 30 + 'px', left: pos.left * 30 + 'px', width: pos.width * 30 + 'px', height: pos.height * 30 + 'px' }); // Construct the inner div. Only do it once if (!this.elInner) { this.elInner = $('<div class="graph-inner"></div>'); el.append(this.elInner); el.draggable({grid: [30,30], containment: 'parent', cursor: 'move', stop: this.onDragStop, handle: '.graph-header'}); el.resizable({grid: 30, containment: 'parent', stop: this.onDragStop}); el.css('position', 'absolute'); // NOTE: draggable applies position: relative, which seems completely retarded. } // Each side is a bit different if (this.mode === 'front') { this.renderFront(); } else { this.renderBack(); } // Update the name el.find('.graph-header span').text(m.name()); return this; }, renderFront: function() { var html = [ '<div class="graph-header">', '<span></span> <a href="#" class="edit">Edit</a>', '</div>', '<div class="graph-body" id="' + this.graphId + '"></div>' ]; this.elInner.html(html.join('')); this.updateData(); }, renderBack: function() { var html , m = this.model , sources = m.get('sources') , domUl , domItem ; html = [ '<div class="graph-header">', '<span></span> <a href="#" class="edit">See Graph</a>', '</div>', '<div class="graph-back">', '<div class="kind">', '<div class="kind-label">Kind:</div>', '<div class="kind-value">' + m.get('kind') + '</div>', '</div>', '<div class="graph-sources">', '<div class="graph-sources-label">Sources:</div>', '<ul></ul>', '</div>', '<a href="#" class="delete">Delete</a>', '</div>' ]; this.elInner.html(html.join('')); domUl = this.elInner.find('ul'); _.each(sources, function(s) { html = [ '<li>', '<span class="source-item">' + s + '</span>', '</li>' ]; domItem = $(html.join('')); domUl.append(domItem); }); domUl.append('<li class="pick-item"><a href="#" class="pick">Pick Sources</a></li>'); }, updateData: function() { var self = this , params = {} , range ; if (self.model.isNew()) { return; // TODO: maybe render a no data thinger } range = DateRangePicker.getCurrentRange(); params.granularity_in_minutes = range.granularityInMinutes; params.start_time = Math.floor(+range.startDate / 1000); params.end_time = Math.floor(+range.endDate / 1000); $.getJSON('/graphs/' + self.model.get('id') + '/data', params, function(data) { $('#' + self.graphId).empty().unbind(); var seven = null; _.each(data, function(d) { if (!seven) { seven = new Seven('#' + self.graphId, {start: d.start_time * 1000, granularityInMinutes: range.granularityInMinutes, points: d.data.length, kind: self.model.get('kind')}); } seven.graph({name: d.source, data: d.data}) }); }); }, onTick: function() { var range = DateRangePicker.getCurrentRange(); if (+range.endDate > (+new Date() - 60000)) { this.updateData(); } }, onDateRangeChanged: function(evt, data) { this.updateData(); }, onDragStop: function(evt, ui) { var el = $(this.el) , w = el.width() , h = el.height() , pos = el.position() ; this.model.setLocation({ top: parseInt(pos.top / 30, 10), left: parseInt(pos.left / 30, 10), width: parseInt(w / 30, 10), height: parseInt(h / 30, 10) }); this.model.save(); this.updateData(); }, onClickEdit: function(evt) { evt && evt.preventDefault(); if (this.mode === 'front') { this.mode = 'back'; } else { this.mode = 'front'; } this.render(); }, onCreateModel: function() { this.updateData(); }, onClickPick: function(evt) { var sources = this.model.get('sources') , kind = this.model.get('kind') , sourceObjs = _.map(sources, function(s) { return {kind: kind, source: s}; }) , pos = this.model.get('position') , windowWidth = $(window).width() , openDir = 'right' ; $('.graph').removeClass('highlighted').addClass('dimmed'); $(this.el).addClass('highlighted').removeClass('dimmed'); if (windowWidth / 2 < pos.left * 30) { openDir = 'left'; } sourceListInst.show({callback: this.onPick, sources: sourceObjs, cancel: this.onCancelPick, direction: openDir}); }, onPick: function(sources) { $('.graph').removeClass('highlighted dimmed'); this.model.setSources(sources); this.model.save(); this.mode = 'front'; this.render(); }, onCancelPick: function() { $('.graph').removeClass('highlighted dimmed'); }, onClickDelete: function(evt) { evt && evt.preventDefault(); this.model.destroy(); }, onRemoveModel: function() { $(this.el).remove(); } }); var sourceListInst; var SourceList = Backbone.View.extend({ tagName: 'div', className: "source-list", events: { 'click .cancel': 'onClickCancel', 'click .ok': 'onClickOk', 'click input:checkbox': 'onCheck' }, initialize: function(opts) { _.bindAll(this, 'render', 'show', 'fetch', 'onClickOk', 'onClickCancel', 'onCheck'); // Items are objects like this: {"source":"auth.inline_logged_in","kind":"counter"} this.items = []; this.callback = function() {}; this.cancel = function() {}; this.fetch(); $(document.body).append(this.render().hide().el); }, render: function() { var el = $(this.el) , html ; html = [ '<div class="head">', '<h2>Choose multiple counters, multiple gaugues, or one timer:</h2>', // '<input type="text" class="idea" />', '<a href="#" class="cancel">X</a>', '</div>', '<ul>', '</ul>', '<div class="foot">', '<button class="ok">Ok</button>', '</div>' ]; el.html(html.join('')); var list = el.find('ul'); // // Construct the DOM of each list item // _.each(this.items, function(item) { html = [ '<li class="source-item">', '<label>', '<input type="checkbox" class="' + item.kind + '" />', '<span class="source-name">' + item.kind + ": " + item.source + '</span>', '</label>', '</li>' ]; var domItem = $(html.join('')); domItem.find('input').val(JSON.stringify(item)).data('source', item); list.append(domItem); }); if (this.items.length == 0) { list.append('<li class="no-data source-item">No data detected recently</li>'); } return this; }, show: function(opts) { opts = opts || {}; var dir = opts.direction || 'right' , el = $(this.el) ; this.callback = opts.callback || function() {}; this.cancel = opts.cancel || function() {}; this.render(); el.removeClass('right left').addClass(dir); el.css({height: _.min([_.max([200, 100 + this.items.length * 26]), $(window).height()])}); if (opts.sources) { var checkboxes = el.find('input:checkbox') , sources = opts.sources ; _.each(checkboxes, function(e) { var source = $(e).data('source'); if (source) { var any = _.any(sources, function(s) { return s && source && (s.kind == source.kind) && (s.source == source.source); }); if (any) { $(e).prop('checked', true); } } }); } el.show(); }, hide: function() { $(this.el).hide(); return this; }, onClickOk: function(evt) { var el = $(this.el) , selected = el.find('input:checked') , vals = _.map(selected, function(item) { return JSON.parse($(item).val()); }) ; evt.preventDefault(); this.callback(vals); this.hide(); }, onClickCancel: function(evt) { evt.preventDefault(); this.cancel(); return this.hide(); }, onCheck: function(evt) { var el = $(this.el) , target = $(evt.target) , targetChecked = target.prop('checked') , source = JSON.parse(target.val()); ; if (targetChecked) { // If you check a timer, everything else is unchecked if (source.kind === 'timer') { el.find('input:checkbox').prop('checked', false); target.prop('checked', true); } // If you check a counter, all non-counters are unchecked if (source.kind === 'counter') { el.find('input:checkbox.timer, input:checkbox.gauge').prop('checked', false); } // If you check a gauge, all non-gauges are unchecked if (source.kind === 'gauge') { el.find('input:checkbox.timer, input:checkbox.counter').prop('checked', false); } } }, fetch: function() { var self = this; $.getJSON('/sources', {}, function(data) { self.items = data; }); } }); var DateRangePicker = Backbone.View.extend({ events: { 'click .custom-date': 'onClickCustomDate', 'click .date-reset': 'onClickReset', 'blur .date-starting-at': 'onBlurStart', 'click input[type=radio]': 'onClickTimeSpan' }, initialize: function() { _.bindAll(this, 'onClickCustomDate', 'onClickReset', 'onBlurStart', 'onClickTimeSpan'); this.isCurrent = true; this.format = d3.time.format("%Y-%m-%d %H:%M"); DateRangePicker.instance = this; }, triggerTimeChange: function() { $(document.body).trigger('date_range_changed', this.getRange()); }, getRange: function() { return {isCurrent: this.isCurrent, startDate: this.getStartDate(), endDate: this.getEndDate(), granularityInMinutes: this.getGranularityInMinutes()}; }, // Returns '2_hours', '24_hours', '7_days' getRangeDuration: function() { return $(this.el).find('input[type=radio][name=time_span]:checked').val(); }, getGranularityInMinutes: function() { var r = this.getRangeDuration(); if (r == '24_hours') { return 15; } else if (r == '7_days') { return 60; } else { return 1; } }, getRangeMilliseconds: function() { var r = this.getRangeDuration(); if (r == '24_hours') { return 24 * 60 * 60 * 1000; } else if (r == '7_days') { return 7 * 24 * 60 * 60 * 1000; } else { return 2 * 60 * 60 * 1000; // 2 hour } }, defaultStartDate: function() { var r = this.getRangeDuration() , now = +new Date() ; return new Date(now - this.getRangeMilliseconds()); }, // Get the start time as entered by the user, or the default. getStartDate: function() { var startInput = this.$('.date-starting-at') , startVal = startInput.val().trim() ; if (this.isCurrent || !startVal) { return this.defaultStartDate(); } else { return this.format.parse(startVal) || this.defaultStartDate(); } }, // Calculate the end time getEndDate: function() { return new Date(+this.getStartDate() + this.getRangeMilliseconds()); }, setCurrent: function(wantItToBeCurrent) { var el = $(this.el) , startInput ; this.isCurrent = wantItToBeCurrent; if (this.isCurrent) { el.addClass('current'); } else { startInput = this.$('.date-starting-at'); el.removeClass('current'); startInput.val(this.format(this.defaultStartDate())).focus(); } this.updateEndingAt(); }, updateEndingAt: function() { var endingEl = this.$('.ending-at span') if (this.isCurrent) { endingEl.text('Now'); } else { endingEl.text(this.format(this.getEndDate())); } this.triggerTimeChange(); }, onClickCustomDate: function(e) { e.preventDefault(); this.setCurrent(!this.isCurrent); }, onClickReset: function(e) { e.preventDefault(); this.setCurrent(!this.isCurrent); }, onBlurStart: function(e) { var el = $(this.el) , startInput = this.$('.date-starting-at') , startVal = startInput.val().trim() ; if (!startVal) { this.setCurrent(true); } else { this.updateEndingAt(); } }, onClickTimeSpan: function(e) { var el = $(this.el) , customDate = this.$('.custom-date') , range = this.getRangeDuration() ; if (range == '24_hours') { customDate.text('24 hours ago'); } else if (range == '7_days') { customDate.text('7 days ago'); } else { customDate.text('2 hours ago'); } this.updateEndingAt(); } }); DateRangePicker.instance = null; DateRangePicker.getCurrentRange = function() { return DateRangePicker.instance.getRange(); }; $(function() { var dblv = new DashboardListView({el: $('#dashboards')}); new DashboardPane({el: $('#current-dashboard'), dashboardListView: dblv}); new DateRangePicker({el: $('#date-range-picker')}); sourceListInst = new SourceList(); // TODO: refactor to use instance pattern. }); }(jQuery));
import React, { useState } from "react"; import "./options.scss"; import FullService from "./FullService" import Partial from "./Partial" import MonthOf from "./MonthOf" function Options() { const [fullexpand, setFullExpand] = useState(false); const [partialexpand, setPartialExpand] = useState(false); const [monthexpand, setMonthExpand] = useState(false); function fullClick(e) { e.preventDefault(); setFullExpand(!fullexpand); } function partialClick(e) { e.preventDefault(); setPartialExpand(!partialexpand); } function monthClick(e) { e.preventDefault(); setMonthExpand(!monthexpand); } return ( <div className="options-block"> <div className="option"> <div className={"option-inner " + fullexpand + ""}> <div className="option-image-holder" > <div className="option-image-background full-service" /> <FullService /> </div> <div className="option-text"> <h2>Full Service Planning</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <button onClick={fullClick}>LEARN MORE</button> </div> </div> </div> <div className="option"> <div className={"option-inner partial " + partialexpand + ""}> <div className="option-image-holder"> <div className="option-image-background partial-planning" /> <Partial /> </div> <div className="option-text"> <h2>Partial Planning</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <button onClick={partialClick}>LEARN MORE</button> </div> </div> </div> <div className="option"> <div className={"option-inner " + monthexpand + ""}> <div className="option-image-holder"> <div className="option-image-background month-of" /> <MonthOf /> </div> <div className="option-text"> <h2>Month of Coordination</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <button onClick={monthClick}>LEARN MORE</button> </div> </div> </div> </div > ) } export default Options
/* * Dynamic update of posts via Ajax */ /* window.setInterval(function() { var countUrl = jQuery('#postsList').data('count-url'); jQuery.get(countUrl, function(res) { var posts_num = jQuery('#postsList .post').length; // if the number of posts changed if(res > posts_num) { var loadUrl = jQuery('#postsList').data('load-url'); // load new posts jQuery("#postsList").load(loadUrl); } }); }, 5000); */
var config = require("json-loader!yaml-loader!../AppConfig/config.yml"); export const UNAUTH_BASE_URL = config.SERVER_CONFIG.SERVER_HOST + '/api/v1/'; export const AUTH_BASE_URL = config.SERVER_CONFIG.SERVER_HOST + '/api/v1/app/'; export const DEFAULT_HEADERS = { "Content-Type": "application/json", "Accept": "application/json", }; // export const CLIENT_URL = 'http://jackhammer-client-8080.stg.corp.olacabs.com'; //OWNER TYPES export const PERSONAL = "Personal"; export const TEAM = "Team"; export const CORPORATE = "Corporate"; //SCAN TYPES export const SOURCE_CODE = "Source Code"; export const WEB = "Web"; export const MOBILE = "Mobile"; export const NETWORK = "Network"; export const WORDPRESS = "Wordpress"; export const HARDCODED_SECRET = "Hardcoded Secret";
module.exports = require('./concept.processor.js');
var client = new XMLHttpRequest(); // $("#parser").hide(); // $("#option").hide(); // $("#result").hide(); // $("#preview").hide(); function check_input_file() { if($("#check_input_file").attr('checked')) $("#input_file").show() else $("#input_file").hide() } function check_option() { if($("#check_option").attr('checked')) $("#option").show() else $("#option").hide() } function check_drop_area() { if($("#check_drop_area").attr('checked')) { $("#drop_area").show() $("#preview").parent().removeClass('col-md-12') $("#preview").parent().addClass('col-md-9') } else { $("#drop_area").hide() $("#preview").parent().removeClass('col-md-9') $("#preview").parent().addClass('col-md-12') } } function check_preview() { if($("#check_preview").attr('checked')) $("#preview").show() else $("#preview").hide() } function check_result() { if($("#check_result").attr('checked')) $("#result").show() else $("#result").hide() } function upload() { $("#upload").val("uploading...") .addClass("disabled"); var file = document.getElementById("data_file"); /* Create a FormData instance */ var formData = new FormData(); /* Add the file */ //formData.append("data_file", file.files[0]); formData.append("data_file", file.files[0]) client.open("post", "option/", true); client.send(formData); /* Send to server */ } /* Check the response status */ client.onreadystatechange = function() { if(client.readyState == 4) { if(client.status == 200) { // alert(client.statusText); var responseJSON = JSON.parse(client.responseText) if(responseJSON['success'] == 0) alert(responseJSON['reason']) else { dataset = responseJSON['content'] series_names = dataset[0] x_labels = dataset.map(function(row){ return row[0]+','+row[1] }).slice(1); x_label_name = series_names[0] $("#option_data_mode").val('data_by_column') $("#option_mode").val('many_many') change_mode('many_many') alert("upload successfully!") } } else { alert("try again!") } $("#upload").val("upload").removeClass("disabled"); } } function one_one() { var data1_select = d3.select("#option_data").append("select").attr("id", "data1") data1_select.selectAll("option").data(series_names).enter() .append("option") .attr("value", function(d, i){return i; }) .text(function(d){return d; }) var data2_select = d3.select("#option_data").append("select").attr("id", "data2") data2_select.selectAll("option").data(series_names).enter() .append("option") .attr("value", function(d, i){return i; }) .text(function(d){return d; }) } function one_many() { d3.select("#option_data") .append("select") .attr("id", "data1") .selectAll("option") .data(series_names).enter() .append("option") .attr("value", function(d, i){return i; }) .text(function(d){return d; }) d3.select("#option_data") .append("select") .attr("multiple","") .attr("size", "15") .attr("id", "data2") .selectAll("option") .data(series_names).enter() .append("option") .attr("selected","") .attr("value", function(d, i){return i; }) .text(function(d){return d; }) } function many_many() { var data_select = d3.select("#option_data") .append("select") .attr("multiple","") .attr("size", 15) .attr("id", "data") .attr("class", "form-control tagdiv") .attr("ondrop", "drop(event)") .attr("ondragover", "allowDrop(event)"); data_select.selectAll("option") .data(series_names) .enter() .append("option") .attr("selected","") .attr("draggable",true) .attr("ondragstart", "drag(event)") .attr("class", "dragElement") .attr("id", function(d, i){return i+d; }) .attr("value", function(d, i){return i; }) .text(function(d){return d; }); } function change_mode(mode) { if(data=document.getElementById("data1")) data.remove() if(data=document.getElementById("data2")) data.remove() if(data=document.getElementById("data")) data.remove() if (mode=="one_one") {one_one();} else if(mode=="one_many") {one_many();} else if(mode=="many_many") {many_many();} } function change_data_mode(data_mode) { var newdataset = dataset[0].map(function(col, i) { return dataset.map(function(row) { return row[i] }) }); dataset = newdataset; series_names = dataset[0]; x_labels = dataset.map(function(row){ return row[0] }).slice(1); x_label_name = series_names[0] change_mode($('#option_mode').val()); } function calculate(drag_event) { options['option_mode'] = $('#option_mode').val(), options['option_algorithm'] = $('#option_algorithm').val(), options['option_data_mode'] = $('#option_data_mode').val(), options['time_series_analysis'] = ($('#time_series_analysis').attr('checked') == 'checked') // FOR BUTTON VERSION if(!drag_event) { if($('#option_mode').val() == 'many_many') { options['option_data'] = $('#option_data>#data').val().map(Number) selected_series_names = options['option_data'].map(function(d){return series_names[d]}) } else if(($('#option_mode').val() == 'one_many')) { options['option_data1'] = Number($('#option_data>#data1').val()) options['option_data2'] = $('#option_data>#data2').val().map(Number) selected_series_names = options['option_data2'].map(function(d){return series_names[d]}) } else { options['option_data1'] = Number($('#option_data>#data1').val()) options['option_data2'] = Number($('#option_data>#data2').val()) } } $.post( "calculate/", options, function(responseText) { result = responseText result = JSON.parse(responseText) $('#result').show(); $("#result").scrollTop; $('#result_text').remove(); $('#result_graph').remove(); if(options['option_mode'] == 'one_one') one_one_text_mode(); else if(options['option_mode'] == 'one_many') { one_many_text_mode(); one_many_graph_mode(); // checkField('graph_mode'); } else if(options['option_mode'] == 'many_many') { many_many_graph_mode(); // many_many_text_mode(); } $("#download_result").show() }); } function checkField(mode) { // $.('#result').remove(); // if(result=document.getElementById("result")) // result.remove() if (mode == "text_mode") { $('#result_text').show(); $('#result_graph').hide(); } else if(mode == "graph_mode") { $('#result_text').hide(); $('#result_graph').show(); } }
import React from 'react' import ReactDOM from 'react-dom' import {Provider} from 'react-redux' import './styles/styles.scss' import 'normalize.css/normalize.css' import "react-datepicker/dist/react-datepicker.css"; import {firebase} from "./firebase/firebase" //import './playground/promises' import AppRouter, {history} from './routers/AppRouter' import configureStore from './store/configureStore' import getVisibleExpenses from './selectors/expenses' import {addExpense, startSetExpenses} from './actions/expenses' import {login, logout} from './actions/auth' import {startSetText} from './actions/expenses' import LoadingPage from './components/LoadingPage' // if (process.env.NODE_ENV !== 'production') { // console.log('Looks like we are in development mode!'); // } const store = configureStore() //console.log('testing') // const expenseOne = store.dispatch(addExpense({description:'water Bill', amount:4500 })) // const expenseTwo = store.dispatch(addExpense({description :'Gas Bill', createdAt:1000})) // const expenseThree = store.dispatch(addExpense({description :'Rent', amount:109500})) // const state = store.getState() // const visibleExpenses = getVisibleExpenses(state.expenses, state.filter) // console.log(visibleExpenses) const jsx = ( <Provider store= {store}> <AppRouter/> </Provider> ); let hasRendered = false const renderApp = () => { if(!hasRendered){ ReactDOM.render( jsx, document.getElementById('app')) hasRendered = true } } ReactDOM.render( <LoadingPage/>, document.getElementById('app')) firebase.auth().onAuthStateChanged((user)=>{ if (user){ store.dispatch(login(user.uid)) console.log('uid', user.uid) store.dispatch(startSetExpenses()).then(()=>{ renderApp() if(history.location.pathname === '/'){ history.push('/dashboard') } }) }else{ store.dispatch(logout()) renderApp() history.push('/') } })
'use strict'; const HTMLPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: `${__dirname}/app/entry.js`, //entry points of the program output: { filename: 'bundle.js', //name of the bundle path: 'build', // }, // wrote our own template so there isn't default behavior plugins: [ new HTMLPlugin({ template: `${__dirname}/app/index.html`, }), // takes output of css loader and turn it into bundle css new ExtractTextPlugin('bundle.css'), ], sassLoader: { includePaths: [`${__dirname}/app/scss/lib`], }, module: { loaders: [ { test: /\.js$/, //$ - regex that means end of line exclude: /node_modules/, loader: 'babel', }, //if we are using html, use the html loader- turns the html into a string //takes file and turns it into plain text to put ina js variable- useful for components { test: /\.html$/, loader: 'html', }, { test: /\.scss$/, //regex to match file exression - run loader on all files that match this expression loader: ExtractTextPlugin.extract('style', 'css!resolve-url!sass?sourceMap'), //match loaders chain - goes right to left //style loader- injects style into page //style loader is backup //resolve url uses relative paths- used for font awesome which uses relative paths }, { test:/\.(eot|woff|ttf|svg).*/, //.* -> any other characters loader: 'url?limit=10000&name=fonts/[hash].[ext]', //10000 bytes // if less than 10000, put in, else put it in fonts directory }, ], }, }; //killall node turns off webpack dev-server
const firebase = require("firebase") const moment = require('moment') const { course_classifier, addCourses, courseDbName, codeName } = require('../helpers/course_classifier.js') const seo_page = require('../client_helpers/seo_page_info') //create reference for firestore database const db = firebase.firestore() const { getCourseKeyByValue, courseKeys } = require("../helpers/campaign") module.exports = { /** * create a course * params: none * data: Array of dates, String: course type and name */ addCourses: async (req, res, next) => { try{ //classify course arrays from the front end const dayClassDates = req.body.day ? req.body.day : [], eveningClassDates = req.body.evening ? req.body.evening : [], weekendClassDates = req.body.weekend ? req.body.weekend : [] //get the day classes const dayClasses = addCourses( dayClassDates, req.body.course, 'Day') //get the evening classes const eveningClasses = addCourses( eveningClassDates, req.body.course, 'Evening') //get the weekend classes const weekendClasses = addCourses( weekendClassDates, req.body.course, 'Weekend') //join all the courses together const courses = dayClasses.concat( eveningClasses, weekendClasses ) //How to prevent duplicates in firestore //https://stackoverflow.com/questions/54236388/prevent-duplicate-entries-in-firestore-rules-not-working if(courses.length > 0) { courses.forEach(async(course) => { await db.collection('courses').add(course) }) res.status(200).json({ message: "Courses have been added.", redirect: true, redirect_url: '/admin/course-schedules/enroll' }) } } catch (error){ console.log('ERROR ->', error) res.status(500).json({ message: `There has been an error adding the course.`, error }) } }, /** * get single course using id * params: course id * returns: a single course object an array of students with that course id in the payments array */ getCourseById: async ( req, res, next ) => { try { //get the parameters const { code, course_id } = req.params //get the course data details const course = await courseDbName ( code, course_id ) console.log('here is the course --> ', course) //get all course students const courseStudents = await db.collection('students').orderBy('enrolledOn').get() //convert results to array const query = courseStudents.docs //create an array to store students const studentsArray = [] //store all students in the array query.forEach( result => studentsArray.unshift({ id: result.id, data: result.data() })) const students = studentsArray.map (x => { return { 'id': x.id, 'name': x.data.first +" "+ x.data.last, 'email': x.data.email, 'tel': x.data.tel, 'payments': x.data.payments, 'status': x.data.status, 'amount': x.data.payments.reduce((sum, payment) => { return sum += payment.amount }, 0 ) } }).reduce(( course_students, doc ) => { const student = { 'student_id': doc.id, 'amount': doc.amount, 'email': doc.email, 'name': doc.name, 'status':doc.status, 'tel': doc.tel } doc.payments.filter( payment => { if(payment.course_id == req.params.course_id){ if(!course_students.includes(student)) { course_students.push(student) } } }) return course_students }, [] ) //sum up the payments made by students enrolled in this course const total = students.reduce( (sum, doc) => { return sum += doc.amount }, 0) //if course retain this data if(course){ res.render('admin/course/students', { // csrfToken: req.csrfToken(), code: code, courseId: course.id, seo_info: seo_page.admin_portal_seo_info, title: course.title, students: students, total: total, course: course } ) } } catch (error) { console.log(error) res.status(500).json({ message: "There has been an error", error }) } }, /** * get courses * @params: String: past, present or future * @params: default: future * returns: array of courses depending on start date (past of today, today or future of today) */ getCourses: async( req, res, next ) => { try{ const type = ( req.params.type !== undefined ) ? req.params.type : "" const today = moment().startOf('day').toDate() let classes = [] const results = await db.collection('courses') .orderBy('start_date') .get() const docs = results.docs switch(type){ case 'current': classes = docs.reduce((docArray, doc ) => { //convert timestamp to moment object let start = moment(doc.data().start_date.toDate() ) let end = doc.data().end_date ? moment(doc.data().end_date.toDate()) : null if(doc.data().end_date) { //c if( start.isSameOrBefore(today) && end.isSameOrAfter(today) ){ docArray.unshift( { code: getCourseKeyByValue(courseKeys, doc.data().name), name: doc.data().name, type: doc.data().type, start_date: moment(start).format("MMM DD"), end_date: moment(end).format("MMM DD"), id: doc.id } ) } } else { // console.log(''start.isSame(today) ) if (start.isSame(today) ) { docArray.unshift( { code: getCourseKeyByValue(courseKeys, doc.data().name), name: doc.data().name, type: doc.data().type, start_date: moment(start).format("MMM DD"), id: doc.id }) } } return docArray }, []) break case 'past': //start date and/or end date must be past today classes = docs.reduce((docArray, doc ) => { //convert timestamp to moment object let start = moment(doc.data().start_date.toDate() ) let end = doc.data().end_date ? moment(doc.data().end_date.toDate()) : null if(doc.data().end_date) { if( start.isBefore(today) && end.isBefore(today) ){ docArray.unshift( { code: getCourseKeyByValue(courseKeys, doc.data().name), name: doc.data().name, type: doc.data().type, start_date: moment(start).format("MMM DD"), end_date: moment(end).format("MMM DD"), id: doc.id } ) } } else { // console.log(''start.isSame(today) ) if (start.isBefore(today) ) { docArray.unshift( { code: getCourseKeyByValue(courseKeys, doc.data().name), name: doc.data().name, type: doc.data().type, start_date: moment(start).format("MMM DD"), id: doc.id }) } } return docArray }, []) break default: classes = docs.filter(doc => moment( doc.data().start_date.toDate() ).isSameOrAfter(moment(today)) ) .map(x=> { start = x.data().start_date.toDate() end = x.data().end_date ? x.data().end_date.toDate() : null return{ code: getCourseKeyByValue(courseKeys, x.data().name), end_date: end ? moment(end).format("MMM DD") : null, name: x.data().name, start_date: moment(start).format("MMM DD"), type: x.data().type, id: x.id } }) break } console.log('CLASSES---- ', classes) if( classes.length > 0 ){ res.render('admin/course/time-schedules', { courses: course_classifier ( classes ),//groups courses by name, type e.g., CPR has even, day and weekend and BLS only day choices: [ "Certified Nurse Assistant/CNA", "DSHS Home Care Aide/75 Hours", "HCA to CNA Bridging", "DSHS Core Basic", "DSHS 12 Hours Continuous Education Units", "DSHS Dementia Specialty", "DSHS Mental Health Specialty", "DSHS Safety and Orientation" ], seo_info: seo_page.schedule_page_seo_info }) } else{ res.render('admin/course/time-schedules', { courses: [],//groups courses by name, type e.g., CPR has even, day and weekend and BLS only day choices: [ "Certified Nurse Assistant/CNA", "DSHS Home Care Aide/75 Hours", "HCA to CNA Bridging", "DSHS Core Basic", "DSHS 12 Hours Continuous Education Units", "DSHS Dementia Specialty", "DSHS Mental Health Specialty", "DSHS Safety and Orientation" ], seo_info: seo_page.schedule_page_seo_info }) } }catch(error){ console.log("Is there an error? ",error) res.status(500).json({ message: `There has been an error getting the courses.`, error: error.message }) } }, /** * update an existing course * params: course id * data: String: course dates, */ updateCourse: async (req, res, next) => { try{ //get the new dates and course id const { course_id, dates } = req.body //check if the course exists const courseQuery = await db.collection('courses').doc( course_id ).get() //if no such course exists, return if(!courseQuery){ return res.status(404).json({ 'message': 'No such course exists!' }) } //get query data const course = courseQuery.data() //get present year to append to class dates const year = moment().year() //get the course code name const code = codeName( courseQuery.data().name ) console.log('CODE NAME IN UP DATE COURSE', ) //split the course dates const course_date = dates.split(' ') //construct start date const start_date = moment.tz(year + " "+ course_date[0] +" "+ course_date[1], "YYYY MMM D", "America/Los_Angeles").toDate() //construct end date const end_date = course_date.length > 2 ? moment.tz(year + " "+ course_date[3] +" "+ course_date[4], "YYYY MMM D", "America/Los_Angeles").toDate() : null //create course description to send to stripe const course_name = moment.utc(start_date).format("MMM DD") +' ' + course.name + ' ' + course.type + ' course' //How to prevent duplicates in firestore //https://stackoverflow.com/questions/54236388/prevent-duplicate-entries-in-firestore-rules-not-working await db.collection('courses').doc(course_id).update({ start_date, end_date }) //get all course students const courseStudents = await db.collection( 'students' ).orderBy( 'enrolledOn' ).get() //convert results to array const query = courseStudents.docs //create an array to store students const studentsArray = [] //store all students in the array query.forEach( result => studentsArray.unshift({ id: result.id, data: result.data() })) const students = studentsArray.map( x => { return { id: x.id, data: x.data } }).reduce( ( course_students, doc ) => { //filter to find payment objects containing the course id doc.data.payments.filter( async(payment, index ) => { //check if the object has the course id if( payment.course_id == course_id ){ // payment.name = course_name doc.data.payments[index].course_name = course_name //if(!course_students.includes(doc)) { await db.collection('students').doc( doc.id ).update({ payments : doc.data.payments }) course_students.push(doc) // } } }) return course_students }, [] ) res.status(200).json({ message: "The course has been successfully been updated.", redirect: true, redirect_url: `/courses/${code}/${course_id}`, students }) } catch (error){ res.status(500).json({ message: `There has been an error adding the course.`, error }) } } }
module.exports = { enableChangePassword: `UPDATE CW_USUARIO SET enableChangePassword = 1 WHERE Persona=@persona;`, eventCorrelativo: `SELECT (PersonaActual+1) as idPersona FROM SY_UnidadReplicacion WHERE UnidadReplicacion ='LIMA'`, eventDeleteUser: `DELETE FROM [dbo].[CW_USUARIO] WHERE Usuario = @usuario`, eventFindOne: `SELECT [Clave],[Persona] FROM CW_USUARIO WHERE Usuario =@username`, eventGetPersona: `SELECT Persona as id, RTRIM(Documento) as nroDocumento, RTRIM(ApellidoPaterno) as apellidoPaterno, RTRIM(ApellidoMaterno) as apellidoMaterno, RTRIM(Nombres) as nombres, RTRIM(Telefono) as telefono, RTRIM(Celular) as celular, RTRIM(CorreoElectronico) as correoElectronico, FechaNacimiento as fechaNacimiento , RTRIM(Direccion) as direccion, RTRIM(Sexo) as sexo FROM PersonaMast WHERE Documento =@documento`, eventRegisterMPerson: `INSERT INTO [dbo].[PersonaMast] ( [Persona], [Origen], [ApellidoPaterno], [ApellidoMaterno], [Nombres], [NombreCompleto], [Busqueda], [TipoDocumento], [Documento], [TipoPersona], [FechaNacimiento], [Sexo], [Nacionalidad], [Telefono], [CorreoElectronico], [Estado], [Celular], [Pais] ) VALUES ( @Persona, @Origen, @ApellidoPaterno, @ApellidoMaterno, @Nombres, @NombreCompleto, @Busqueda, @TipoDocumento, @Documento, @TipoPersona, @FechaNacimiento, @Sexo, @Nacionalidad, @Telefono, @CorreoElectronico, @Estado, @Celular, @Pais ) `, eventRegisterUser: `INSERT INTO [dbo].[CW_USUARIO] ( [Usuario], [Nombre], [Clave], [SQLLogin], [Estado], [UltimoUsuario], [Persona], [FechaRegistro], [isChangePassword] ) VALUES ( @username, @names, @password, @sqllogin, @state, @registerUser, @person, @FechaRegistro, @isChangePassword ) SELECT max(FechaRegistro) AS fecha FROM [CW_USUARIO]`, eventUpdateCorrelativo: `update SY_UnidadReplicacion SET SY_UnidadReplicacion.PersonaActual = @persona, SY_UnidadReplicacion.UltimoUsuario = @usuario, SY_UnidadReplicacion.UltimaFechaModif = @fechahoraregistro /*'2021-06-28 12:16:44.170'*/ WHERE SY_UnidadReplicacion.UnidadReplicacion ='LIMA'`, eventUpdatePersona: `UPDATE PersonaMast SET Celular = @celular,Telefono = @telefono,CorreoElectronico=@correo,Direccion =@direccion WHERE Persona = @persona`, eventValidatePassowordResulMail: `SELECT enableChangePassword AS enablecp FROM CW_USUARIO where usuario = @usuario`, eventValidateUser: `SELECT COUNT ( DISTINCT PersonaMast.Documento ) as existe FROM [dbo].[PersonaMast] WHERE ( ( PersonaMast.TipoDocumento ='D' AND PersonaMast.Documento =@documento AND PersonaMast.TipoDocumento IS NOT NULL AND PersonaMast.Documento IS NOT NULL ) OR ( PersonaMast.Documento =@documento AND PersonaMast.Documento IS NOT NULL )) AND PersonaMast.Persona <> -1 AND PersonaMast.Estado ='A'`, evenValidateUserCItas: `SELECT COUNT ( DISTINCT Usuario ) as existe FROM [dbo].[CW_USUARIO] WHERE Usuario = @documento`, getValidateChangePassword: `select enableChangePassword,isChangePassword from cw_usuario where persona = @persona`, isAfiliado: `SELECT DISTINCT p.IDPROGRAMA, p.IDTIPOPROGRAMA, p.ESTADODOCUMENTO, p.TipoAfiliado, p.ESTADO, Programa = tp.Descripcion, pac.CodigoHC, beneficiario = beneficiario.NombreCompleto, p.CodigoPoliza, Titular = (SELECT TOP 1 beneficiario.NombreCompleto FROM SS_PG_ProgramaBeneficiario LEFT JOIN PersonaMast AS beneficiario ON beneficiario.Persona = pb.idPacienteTitular WHERE pb.idPrograma = p.idPrograma), tp.TipoPrograma, tp.Modalidad FROM SS_PG_Programa p WITH(NOLOCK) LEFT JOIN SS_PG_ProgramaBeneficiario pb WITH(NOLOCK) ON pb.idPrograma = p.idPrograma LEFT JOIN PERSONAMAST pe WITH(NOLOCK) ON pe.PERSONA = p.idClienteFacturacion LEFT JOIN PERSONAMAST AS beneficiario WITH(NOLOCK) ON beneficiario.PERSONA = pb.idPaciente LEFT JOIN SS_GE_Paciente pac WITH(NOLOCK) ON pac.idPaciente = p.idClienteFacturacion LEFT JOIN SS_PG_TipoPrograma tp WITH(NOLOCK) ON p.idTipoPrograma = tp.idTipoPrograma WHERE p.Estado = 2 AND p.EstadoDocumento = 3 AND LTRIM(RTRIM(beneficiario.Documento)) = @Documento`, };
var form = document.querySelector('.form-input'); for (let i = 0; i < formData.length; i++) { var inputDiv = document.createElement('div'); inputDiv.classList.add('form-item'); form.appendChild(inputDiv); var currField = formData[i]; var icon = document.createElement('i'); let iconLabel = currField.icon; icon.setAttribute("class", iconLabel); inputDiv.appendChild(icon); if ((currField.type != 'textarea') && (currField.type != 'select')) { var newField = document.createElement('input'); newField.setAttribute("type", currField.type); newField.setAttribute("value", currField.label); newField.setAttribute("id", currField.id); newField.classList.add("form-input"); inputDiv.appendChild(newField); } if (currField.type === 'textarea') { var newTextArea = document.createElement('textarea'); newTextArea.setAttribute("value", currField.label); newTextArea.setAttribute("id", currField.id); newTextArea.classList.add('form-input'); inputDiv.appendChild(newTextArea); } if (currField.type === 'select') { var newSelect = document.createElement('select'); newSelect.setAttribute("value", currField.label); newSelect.setAttribute("id", currField.id); newSelect.classList.add('form-input'); for (let j = 0; j < currField.options.length; j++) { var selectOption = document.createElement('option'); selectOption.setAttribute("value", currField.options[j].value); selectOption.textContent = currField.options[j].label; newSelect.appendChild(selectOption); } inputDiv.appendChild(newSelect); } }
var myApp = angular.module('myApp',[]); myApp.factory('workerFunctionFactory', function () { 'use strict'; function workerFunction() { var self = this; self.onmessage = function(event) { var splitedString = event.data.split(','); self.postMessage(splitedString); } }; return { getWebworkerFunction: function () { return workerFunction; } } }); myApp.factory('workerFactory', function ($window) { 'use strict'; function createWorker(workerFunction) { var dataObj = '(' + workerFunction + ')();'; var blob = new $window.Blob([dataObj.replace('"use strict";', '')]); var blobURL = ($window.URL ? URL : webkitURL).createObjectURL(blob, { type: 'application/javascript; charset=utf-8' }); return new Worker(blobURL); }; return { createWorker: createWorker } }); myApp.controller('MyCtrl', function MyCtrl($timeout, workerFactory, workerFunctionFactory) { 'use strict'; var worker; var self = this; this.inputText = ''; this.data = ''; this.sendMessage = function () { worker.postMessage(self.inputText) }; function setData(data) { self.data = data; } (function init() { worker = workerFactory.createWorker(workerFunctionFactory.getWebworkerFunction()); worker.onmessage = function (message) { $timeout(function () { setData(message.data) }, 0); } }()); });
import styled from 'styled-components' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPeace } from '@fortawesome/free-solid-svg-icons' import { color } from '../styles/global-styles' import ScreenSize from '../styles/media-queries' const FooterContent = styled.div` display: flex; justify-content: center; align-items: center; background-color: ${color.nyanza}; font-family: 'Nova Mono', monospace; font-size: 1rem; color: ${color.taupeGrey}; padding: 1.5rem 0; z-index: 2; @media ${ScreenSize.desktop} { padding: 2rem 0; } ` const Footer = () => ( <FooterContent> <p>2021&nbsp;</p> <FontAwesomeIcon icon={faPeace} size="xs" /> <p>&nbsp;Isabelle Yim</p> </FooterContent> ) export default Footer
import inc from 'number/inc'; import dec from 'number/dec'; import min from 'number/min'; import max from 'number/max'; import sum from 'number/sum'; import average from 'number/average'; import neg from 'number/neg'; import div from 'number/div'; import mul from 'number/mul'; import mod from 'number/mod'; export { inc, dec, min, max, sum, average, neg, div, mul, mod }; export default { inc, dec, min, max, sum, average, neg, div, mul, mod };
import React, { Suspense, lazy } from "react"; import { Router, Route, Switch } from "react-router-dom"; import history from "../history"; import Loading from "../components/Loading"; import clsx from "clsx"; import { makeStyles, useTheme } from "@material-ui/core/styles"; import CssBaseline from "@material-ui/core/CssBaseline"; import withAuth from "../components/wrappers/withAuth"; import Header from "../components/Header"; import NotFound from "../pages/notfound"; import Negociations from "pages/negociations"; const drawerWidth = 250; const useStyles = makeStyles(theme => ({ root: { display: "flex", minHeight: '100vh' }, drawerHeader: { display: "flex", alignItems: "center", padding: "0 8px", ...theme.mixins.toolbar, justifyContent: "flex-end" }, content: { flexGrow: 1, padding: theme.spacing(3), paddingTop: '5em', transition: theme.transitions.create("margin", { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen }), marginLeft: -drawerWidth }, contentShift: { transition: theme.transitions.create("margin", { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen }), marginLeft: 0 }, colorPrimary: { color: theme.palette.primary }, main: { marginTop: "10vh" }, marginTopTitle: { marginTop: "5%" } })); const Home = lazy(() => import("../pages/home")); const Modalities = lazy(() => import("../pages/modalities")); const UserProviderLayout = () => { const classes = useStyles(); const [open, setOpened] = React.useState(false); return ( <div className={classes.root}> <CssBaseline /> <Header open={open} setOpen={setOpened} /> <main className={clsx(classes.content, { [classes.contentShift]: open })}> <Router history={history}> <Suspense fallback={<Loading />}> <Switch> <Route exact path={["/provider/home"]} component={Home} /> <Route exact path={["/provider/modalities"]} component={Modalities} /> <Route exact path={["/provider/negociations"]} component={Negociations} /> <Route component={NotFound} /> </Switch> </Suspense> </Router> </main> </div> ); }; export default withAuth(UserProviderLayout);
import { AUTHENTICATE, LOGOUT, VERIFY_TOKEN, } from '@/web-client/actions/constants'; import { cond, constant, isPlainObject, negate, stubTrue, isString, identity, isEmpty, isArray, } from 'lodash/fp'; const initialState = { name: null, permissions: [], }; const nameProcessor = cond([ [negate(isString), constant(initialState.name)], [isEmpty, constant(initialState.name)], [stubTrue, identity], ]); const permissionProcessor = cond([ [negate(isArray), constant(initialState.permissions)], [stubTrue, identity], ]); const auth = (state = initialState, {type, payload}) => { if (type === AUTHENTICATE || type === VERIFY_TOKEN) { const {name, permissions} = isPlainObject(payload) ? payload : {}; return { name: nameProcessor(name), permissions: permissionProcessor(permissions), }; } else if (type === LOGOUT) { return initialState; } return state; }; export default auth;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class MobileAuth { login(data) { return new Promise((res, rej) => { }); } logout() { } }
import uuid from 'uuid'; // Action Creator :- //Add Expense export const addExpense = ({ description = 'Not Set', notes = 'Not Set', amount = 0 , createdAt = new Date()} = {}) => ({ type : 'ADD_EXPENSE', expenses : { id : uuid(), description, notes, amount, createdAt } }); // RemoveExpenseActionCreator export const removeExpense = ( { id = '' } = {} ) => { return { type : 'REMOVE_EXPENSE', id }}; // Update Expense Action Creator export const updateExpese = ( ( id , obj ) => ({ type: 'UPDATE_EXPENSE', id, obj }) );
var httprequests = new XMLHttpRequest(); var url; var contatoretasti = 0; async function Check() { // Variabili associate ai campi del modulo var name = document.modulo.name.value; var surname = document.modulo.surname.value; var data = document.modulo.data.value; var luogo = document.modulo.luogo.value; var residenza = document.modulo.residenza.value; var cf = document.modulo.cf.value.toUpperCase(); var cell = document.modulo.cell.value; var mail = document.modulo.mail.value; var teamname = document.modulo.teamname.value; // Espressione regolare dell'email var email_reg_exp = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-]{2,})+.)+([a-zA-Z0-9]{2,})+$/; //Effettua il controllo sul campo NOME if ((name == "") || (name == "undefined")) { alert("Il campo Nome è obbligatorio."); document.modulo.name.focus(); return false; } //Effettua il controllo sul campo COGNOME else if ((surname == "") || (surname == "undefined")) { alert("Il campo Cognome è obbligatorio."); document.modulo.surname.focus(); return false; } //Effettua il controllo sul campo DATA DI NASCITA else if (document.modulo.data.value.substring(2, 3) != "/" || document.modulo.data.value.substring(5, 6) != "/" || isNaN(document.modulo.data.value.substring(0, 2)) || isNaN(document.modulo.data.value.substring(3, 5)) || isNaN(document.modulo.data.value.substring(6, 10))) { alert("Inserire la data di nascita in formato GG/MM/AAAA"); document.modulo.data.value = ""; document.modulo.data.focus(); return false; } else if (document.modulo.data.value.substring(0, 2) > 31) { alert("Impossibile utilizzare un valore superiore a 31 per i giorni"); document.modulo.data.select(); return false; } else if (document.modulo.data.value.substring(3, 5) > 12) { alert("Impossibile utilizzare un valore superiore a 12 per i mesi"); document.modulo.data.value = ""; document.modulo.data.focus(); return false; } else if (document.modulo.data.value.substring(6, 10) <= 1900) { alert("Impossibile utilizzare un valore inferiore a 1900 per l'anno"); document.modulo.data.value = ""; document.modulo.data.focus(); return false; } //Effettua il controllo sul campo Luogo di nascita' else if ((luogo == "") || (luogo == "undefined")) { alert("Il campo Luogo di Nascita è obbligatorio."); document.modulo.luogo.focus(); return false; } //Effettua il controllo sul campo Residenza else if ((residenza == "") || (residenza == "undefined")) { alert("Il campo Luogo di residenza è obbligatorio."); document.modulo.residenza.focus(); return false; } //Effettua il controllo sul campo Cellulare else if ((isNaN(cell)) || (cell == "") || (cell == "undefined")) { alert("Il campo Telefono è numerico ed obbligatorio."); document.modulo.cell.value = ""; document.modulo.cell.focus(); return false; } else if (!email_reg_exp.test(mail) || (mail == "") || (mail == "undefined")) { alert("Inserire un indirizzo email corretto."); document.modulo.mail.select(); return false; } //INVIA IL MODULO else { sendPost(); return; } } function sendPost() { try { var xhr = new XMLHttpRequest(); xhr.open('GET', "https://tournament-manage.herokuapp.com/tournament/players/number", false); xhr.send(); var n = xhr.responseText; console.log(n); url = "https://tournament-manage.herokuapp.com/tournament/players?name=" + document.modulo.name.value.replace(" ", "%20") + "&surname=" + document.modulo.surname.value.replace(" ", "%20") + "&data=" + document.modulo.data.value + "&luogo=" + document.modulo.luogo.value.replace(" ", "%20") + "&cf=" + document.modulo.cf.value.toUpperCase() + "&residenza=" + document.modulo.residenza.value.replace(" ", "%20") + "&cell=" + document.modulo.cell.value + "&mail=" + document.modulo.mail.value + "&teamname=" + document.modulo.teamname.value.replace(" ", "%20") + "&len=" + n; console.log(url); var c = confirm( "Controlla che i dati che hai inserito siano corretti, non potrai modificarli (perlomeno per ora...🤫😏)" + "\n" + "\n" + "Nome: " + "\t" + "\t" + "\t" + "\t" + document.modulo.name.value.toUpperCase() + "\n" + "Cognome: " + "\t" + "\t" + "\t" + document.modulo.surname.value.toUpperCase() + "\n" + "Data di nascita: " + "\t" + "\t" + document.modulo.data.value.toUpperCase() + "\n" + "Luogo di nascita: " + "\t" + "\t" + document.modulo.luogo.value.toUpperCase() + "\n" + "Città di residenza: " + "\t" + document.modulo.residenza.value.toUpperCase() + "\n" + "CF: " + "\t" + "\t" + "\t" + "\t" + "\t" + document.modulo.cf.value.toUpperCase() + "\n" + "Cellulare: " + "\t" + "\t" + "\t" + document.modulo.cell.value.toUpperCase() + "\n" + "e-Mail: " + "\t" + "\t" + "\t" + "\t" + document.modulo.mail.value.toUpperCase() + "\n" + "Squadra: " + "\t" + "\t" + "\t" + document.modulo.teamname.value.toUpperCase() + "\n" ); console.log(c); if (c == true) { console.log() httprequests.open('POST', url); httprequests.setRequestHeader('Authorization', 'BASIC YWRtaW46a290YzIwMjA='); httprequests.setRequestHeader('Content-Type', 'application/json'); httprequests.send(null); httprequests.onreadystatechange = async function () { if (httprequests.readyState === 4) { var serverResponse = await httprequests.responseText; console.log(serverResponse); if (serverResponse === 'Forbidden') { alert("Atleta con questo codice fiscale già presente"); return; } window.location.href = 'ins_baller2.html'; } else return; }; } else { return; } } catch (err) { return false; } }
// Simple asset manager let Images = {}; let Sounds = {}; let num_total_assets = 0; let num_assets_loaded = 0; function image_set_ready(image) { image.ready = true; num_assets_loaded++; } function sound_set_ready(sound) { if(sound.is_ready === false) { sound.is_ready = true; num_assets_loaded++; } } let Assets = { image_get(image_alias) { return Images[image_alias]; }, sound_get(sound_alias) { return Sounds[sound_alias]; }, image_load(alias, path) { let image = new Image(); image.src = path; image.ready = false; image.onload = () => { image_set_ready(image); // We bake a flipped image into the object for convenience in the Sprite class image.flipped = document.createElement('canvas'); image.flipped.width = image.width; image.flipped.height = image.height; let tctx = image.flipped.getContext('2d'); tctx.scale(-1,1); tctx.drawImage(image,-image.width,0); if(num_assets_loaded === num_total_assets) { if(Assets.onfinished) { Assets.onfinished(); } } }; num_total_assets++; Images[alias] = image; }, sound_load(alias, path) { let sound = new Audio(); sound.is_ready = false; sound.preload = "true"; sound.addEventListener("canplaythrough", () => { sound_set_ready(sound); if(num_assets_loaded === num_total_assets) { if(Assets.onfinished) { Assets.onfinished(); } } }); sound.src = path; num_total_assets++; sound.load(); Sounds[alias] = sound; }, get_total() { return num_total_assets; }, get_loaded() { return num_assets_loaded; }, ready() { return num_assets_loaded === num_total_assets; }, onfinished : null } export default Assets;
import React, { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import AppContext from 'app/AppContext'; import MenuButton from 'pages/home/content/MenuButton'; import CssCarousel from 'pages/home/content/CssCarousel'; import isFlagEnabled from 'utils/isFlagEnabled'; const Content = ({ activeModule, setActiveModule }) => { const [showAlert, setShowAlert] = useState(false); useEffect(() => { isFlagEnabled('alertsModule') .then((value) => setShowAlert(value)); }, []); const modules = [ { focusCallback: () => setActiveModule('search'), buttonStyles: `finder geo ${(activeModule === 'search') ? 'activeicon' : ''}`, idBtn: 'geobtn', firstLineContent: 'consultas', secondLineContent: 'geográficas', localLink: '/Consultas', auth: false, }, { focusCallback: () => setActiveModule('indicator'), buttonStyles: `finder ind ${(activeModule === 'indicator') ? 'activeicon' : ''}`, idBtn: 'indbtn', firstLineContent: 'indicadores de', secondLineContent: 'biodiversidad', localLink: '/Indicadores', auth: false, }, { focusCallback: () => setActiveModule('compensation'), buttonStyles: `finder com ${(activeModule === 'compensation') ? 'activeicon' : ''}`, idBtn: 'combtn', firstLineContent: 'compensación', secondLineContent: 'ambiental', localLink: '/GEB/Compensaciones', auth: true, }, { focusCallback: () => setActiveModule('portfolio'), buttonStyles: `finder port ${(activeModule === 'portfolio') ? 'activeicon' : ''}`, idBtn: 'portbtn', firstLineContent: '', secondLineContent: 'Portafolios', localLink: '/Portafolios', auth: false, }, ]; if (showAlert) { modules.push({ focusCallback: () => setActiveModule('alert'), buttonStyles: `finder ale ${(activeModule === 'alert') ? 'activeicon' : ''}`, idBtn: 'alebtn', firstLineContent: 'alertas', secondLineContent: 'tempranas', localLink: '/Alertas', auth: false, }); } modules.push({ focusCallback: () => setActiveModule('cbmdashboard'), buttonStyles: `finder mon ${(activeModule === 'cbmdashboard') ? 'activeicon' : ''}`, idBtn: 'monbtn', firstLineContent: 'Monitoreo', secondLineContent: 'comunitario', localLink: '/Monitoreo', auth: false, }); return ( <AppContext.Consumer> {({ user }) => { let modulesArray = modules; if (!user) { modulesArray = modules.filter((module) => !module.auth); } return ( <div className="finderline"> <CssCarousel itemsArray={modulesArray.map((module) => ( <MenuButton focusCallback={module.focusCallback} buttonStyles={module.buttonStyles} idBtn={module.idBtn} key={module.idBtn} firstLineContent={module.firstLineContent} secondLineContent={module.secondLineContent} localLink={module.localLink} /> ))} /> </div> ); }} </AppContext.Consumer> ); }; Content.propTypes = { activeModule: PropTypes.string, setActiveModule: PropTypes.func, }; Content.defaultProps = { activeModule: 'search', setActiveModule: null, }; export default Content;
import React from 'react'; import './App.css'; import { Route, BrowserRouter as Router, Switch, Link } from "react-router-dom"; import Home from "./Pages/Home"; import About from "./Pages/About"; import Login from "./Pages/Login"; import ToDo from "./Pages/ToDo"; function App() { return ( <Router> <div className="container"> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/login">Login</Link> </li> <li> <Link to="/todo">ToDo</Link> </li> </ul> </nav> <Switch> <Route path="/about" component={About} /> <Route path="/login" component={Login} /> <Route path="/todo" component={ToDo} /> <Route path="/" component={Home} /> </Switch> </div> </Router> ); } export default App;
'use strict'; var server = require('./lib/server'); var port = process.argv[process.argv.length - 1]; server.listen(port);
const mongoose = require('mongoose'); const promotionSchema = new mongoose.Schema({ title: String, image: String, desc: String, movie: [{type: String}], utldate: String, branch: String }); module.exports = mongoose.model('Promotion', promotionSchema);
(function($, window){ platform(function Events(__, storage){ var config= { //T7 }, store, pool= $(document) //T14 __ .api('0.1', { kick: function(events, data){ trigger(events, data); return __ }, //T5 T6 on: function(events, reactions){ event(true, events, reactions); return __ }, //T5 T6 un: function(events, reactions){ event(false, events, reactions); return __ } //T5 T6 }) function setup(){ store= storage() } function teardown(){ store= undefined } function many(subjects){ return typeof subjects=="object" && subjects || [subjects] } //T- function event(create, events, reactions){ $.each(many(events), process) //T10 function process(i, event){ $.each(many(reactions), handle) //T8 function handle(ii, reaction){ unbind() && create && bind() //T8 function unbind(){ return pool.unbind(event, reaction) } //T9 function bind(){ return pool.bind(event, reaction) } //T5 } } } function trigger(events, data){ report(); $.each(many(events), process) //T11 T12 T13 T15 function process(i,event){ pool.trigger(event, data) } //T5 function report(){ config.debug && log() function log(){ debug.log(events.length==1 && events[0] || events, data || '') } //D } } setup(); },{ }); })(jQuery, this);
const express = require('express'); const each = require('lodash/each'); const routes = require('./routes'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const sessionMiddleware = require('./middleware/session.js'); const responseMiddleware = require('./middleware/response.js'); require('./db/init.js'); const app = express(); app.use(bodyParser.json()); app.use(cookieParser()); each(routes, (route) => { const method = route.method.toLowerCase(); app[method]( route.path, sessionMiddleware.get, route.action, sessionMiddleware.set, responseMiddleware, ); console.info(`Route [${route.method.toUpperCase()}] - ${route.path} is alive`); }); app.listen(3080); console.info('----------------------------'); console.info('Listenning on 3080');
// @flow import curry from 'lodash.curry'; import * as base16 from 'base16'; import rgb2hex from 'pure-color/convert/rgb2hex'; import parse from 'pure-color/parse'; import flow from 'lodash.flow'; import { yuv2rgb, rgb2yuv } from './colorConverters'; import type { Theme, Base16Theme, GetDefaultStyling, StylingOptions } from './types'; const DEFAULT_BASE16 = base16.default; const BASE16_KEYS = Object.keys(DEFAULT_BASE16); // we need a correcting factor, so that a dark, but not black background color // converts to bright enough inversed color const flip = x => x < 0.25 ? 1 : (x < 0.5 ? (0.9 - x) : 1.1 - x); const invertColor = flow( parse, rgb2yuv, ([y, u, v]) => [flip(y), u, v], yuv2rgb, rgb2hex ); type OptStyling = { className?: string, style?: Object }; const merger = function merger(styling: OptStyling) { return (prevStyling: OptStyling) => ({ className: [prevStyling.className, styling.className].filter(Boolean).join(' '), style: { ...(prevStyling.style || {}), ...(styling.style || {}) } }); }; const mergeStyling = function mergeStyling(customStyling, defaultStyling) { if (customStyling === undefined) { return defaultStyling; } if (defaultStyling === undefined) { return customStyling; } const customType = typeof customStyling; const defaultType = typeof defaultStyling; switch (customType) { case 'string': switch (defaultType) { case 'string': return [defaultStyling, customStyling].filter(Boolean).join(' '); case 'object': return merger({ className: customStyling, style: defaultStyling }); case 'function': return (styling, ...args) => merger({ className: customStyling })(defaultStyling(styling, ...args)); } case 'object': switch (defaultType) { case 'string': return merger({ className: defaultStyling, style: customStyling }); case 'object': return { ...defaultStyling, ...customStyling }; case 'function': return (styling, ...args) => merger({ style: customStyling })(defaultStyling(styling, ...args)); } case 'function': switch (defaultType) { case 'string': return (styling, ...args) => customStyling(merger(styling)({ className: defaultStyling }), ...args); case 'object': return (styling, ...args) => customStyling(merger(styling)({ style: defaultStyling }), ...args); case 'function': return (styling, ...args) => customStyling( defaultStyling(styling, ...args), ...args ); } } }; const mergeStylings = function mergeStylings(customStylings, defaultStylings) { const keys = Object.keys(defaultStylings); for (const key in customStylings) { if (keys.indexOf(key) === -1) keys.push(key); } return keys.reduce( (mergedStyling, key) => ( mergedStyling[key] = mergeStyling(customStylings[key], defaultStylings[key]), mergedStyling ), {} ); }; const getStylingByKeys = (mergedStyling, keys, ...args) => { if (keys === null) { return mergedStyling; } if (!Array.isArray(keys)) { keys = [keys]; } const styles = keys.map(key => mergedStyling[key]).filter(Boolean); const props = styles.reduce((obj, s) => { if (typeof s === 'string') { obj.className = [obj.className, s].filter(Boolean).join(' '); } else if (typeof s === 'object') { obj.style = { ...obj.style, ...s }; } else if (typeof s === 'function') { obj = { ...obj, ...s(obj, ...args) }; } return obj; }, { className: '', style: {} }); if (!props.className) { delete props.className; } if (Object.keys(props.style).length === 0) { delete props.style; } return props; } export const invertTheme = (theme: Base16Theme): Base16Theme => Object.keys(theme).reduce((t, key) => (t[key] = /^base/.test(key) ? invertColor(theme[key]) : key === 'scheme' ? theme[key] + ':inverted' : theme[key], t), {}); export const createStyling = curry(( getStylingFromBase16: GetDefaultStyling, options: StylingOptions={}, themeOrStyling: Theme={}, ...args ) => { const { defaultBase16=DEFAULT_BASE16, base16Themes=null } = options; const base16Theme = getBase16Theme(themeOrStyling, base16Themes); if (base16Theme) { themeOrStyling = { ...base16Theme, ...themeOrStyling }; } const theme = BASE16_KEYS.reduce((t, key) => (t[key] = themeOrStyling[key] || defaultBase16[key], t), {}); const customStyling = Object.keys(themeOrStyling).reduce((s, key) => (BASE16_KEYS.indexOf(key) === -1) ? (s[key] = themeOrStyling[key], s) : s, {}); const defaultStyling = getStylingFromBase16(theme); const mergedStyling = mergeStylings(customStyling, defaultStyling); return curry(getStylingByKeys, 2)(mergedStyling, ...args); }, 3); export const getBase16Theme = (theme: Theme, base16Themes: ?Base16Theme[]): ?Base16Theme => { if (theme && theme.extend) { theme = theme.extend; } if (typeof theme === 'string') { const [themeName, modifier] = theme.split(':'); theme = (base16Themes || {})[themeName] || base16[themeName]; if (modifier === 'inverted') { theme = invertTheme(theme); } } return theme && theme.hasOwnProperty('base00') ? theme : undefined; }
import Link from "next/link"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faUser } from "@fortawesome/fontawesome-free-solid"; const BlogList = ({ posts }) => { let initials = ""; return ( <div className="blog-list"> <div className="wrap"> {posts.map((post, index) => { if (post != undefined) { if (post.author != "Guest") { let firstLetter = post.author.slice(0, 1); let secondLetter = post.author.split(" ")[1]; secondLetter = secondLetter.slice(0, 1); initials = firstLetter + secondLetter; } else initials = "G"; return ( <Link key={index} href={post.slug}> <div key={index} className="box" style={{ backgroundImage: "url(" + post.hero_image + ")" }} > <div className="date"> <h4>{post.date}</h4> </div> {/* <div className="date"> <h4>{post.date}</h4> </div> */} <h1>{post.title}</h1> {/* <div className="poster p1"> <h4>{initials}</h4> </div> */} </div> </Link> ); } })} </div> </div> ); }; export default BlogList;
import "react-native-gesture-handler"; import { StatusBar, View, Platform } from "react-native"; import Constants from "expo-constants"; import React from "react"; import { QueryClient, QueryClientProvider } from "react-query"; import { NavigationContainer } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; import Feather from "react-native-vector-icons/Feather"; import FavoriteScreen from "./src/screens/Favorites"; import MoviesScreen from "./src/screens/Movies"; import DetailsScreen from "./src/screens/Details"; import { MovieProvider } from "./src/reducers/movieReducer"; const Tab = createBottomTabNavigator(); const MovieStack = createStackNavigator(); const FavStack = createStackNavigator(); const queryClient = new QueryClient(); const MovieStackScreen = () => { return ( <MovieStack.Navigator> <MovieStack.Screen name="Movies" component={MoviesScreen} ></MovieStack.Screen> <MovieStack.Screen name="Details" component={DetailsScreen} ></MovieStack.Screen> </MovieStack.Navigator> ); }; const FavStackScreen = () => { return ( <FavStack.Navigator> <FavStack.Screen name="Favorites" component={FavoriteScreen} ></FavStack.Screen> <MovieStack.Screen name="Details" component={DetailsScreen} ></MovieStack.Screen> </FavStack.Navigator> ); }; export default function App() { const renderTabBarIcon = (focused, color, size, name) => { return <Feather name={name} color={color} size={size} />; }; return ( <QueryClientProvider client={queryClient}> <MovieProvider> <View style={{ paddingTop: Platform.OS === "ios" ? Constants.statusBarHeight : 0, flex: 1, }} > <StatusBar barStyle={Platform.OS === "ios" ? "dark-content" : "default"} /> <NavigationContainer> <Tab.Navigator> <Tab.Screen name="Movies" component={MovieStackScreen} options={{ tabBarIcon: ({ focused, color, size }) => renderTabBarIcon(focused, color, size, "list"), }} /> <Tab.Screen name="Favorites" component={FavStackScreen} options={{ tabBarIcon: ({ focused, color, size }) => renderTabBarIcon(focused, color, size, "heart"), }} /> </Tab.Navigator> </NavigationContainer> </View> </MovieProvider> </QueryClientProvider> ); }
// This isn't necessary but it keeps the editor from thinking L and carto are typos /* global L, carto */ var map = L.map('map', { center: [52.50, 13.50], zoom: 10 }); L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', { maxZoom: 18 }).addTo(map); // Initialize Carto var client = new carto.Client({ apiKey: 'default_public', username: 'surgab' }); // Initialze source data var listings = new carto.source.SQL('SELECT * FROM listings_berlin'); var districts = new carto.source.SQL('SELECT * FROM berliner_ortsteile'); // Create style for the data var style = new carto.style.CartoCSS(` #layer { marker-width: ramp([price], range(30, 5), quantiles(5)); marker-fill: #ee4d5a; marker-fill-opacity: 0.9; marker-file: url('https://s3.amazonaws.com/com.cartodb.users-assets.production/maki-icons/heart-18.svg'); marker-allow-overlap: true; marker-line-width: 1; marker-line-color: #FFFFFF; marker-line-opacity: 1; } `); var style2 = new carto.style.CartoCSS(` #layer { polygon-fill: #6dbaba; polygon-opacity: 0.47; } #layer::outline { line-width: 1; line-color: #FFFFFF; line-opacity: 0.5; } `); // Add style to the data var districtlayer = new carto.layer.Layer(districts, style2); var listingslayer = new carto.layer.Layer(listings, style); // Add the data to the map as a layer client.addLayer(districtlayer); client.addLayer(listingslayer); client.getLeafletLayer().addTo(map); // Step 1: Find the button by its class. If you are using a different class, change this. var mitteButton = document.querySelector('.mitte-button'); // Step 2: Add an event listener to the button. We will run some code whenever the button is clicked. mitteButton.addEventListener('click', function (e) { listings.setQuery("SELECT * FROM listings_berlin WHERE neighbourhood_group = 'Mitte'"); // Sometimes it helps to log messages, here we log to let us know the button was clicked. You can see this if you open developer tools and look at the console. console.log('Mitte was clicked'); }); // Step 1: Find the button by its class. If you are using a different class, change this. var neukoellnButton = document.querySelector('.neukoelln-button'); // Step 2: Add an event listener to the button. We will run some code whenever the button is clicked. mitteButton.addEventListener('click', function (e) { listings.setQuery("SELECT * FROM listings_berlin WHERE neighbourhood_group = 'Neukoelln'"); // Sometimes it helps to log messages, here we log to let us know the button was clicked. You can see this if you open developer tools and look at the console. console.log('Neukoelln was clicked'); });
import React from 'react'; import { Pagination } from 'react-bootstrap'; const { First, Prev, Item, Next, Last } = Pagination const CustomPagination = (props) => { const { numberPage, handleChangePage, maxPage, next, previous } = props; let arrItem = []; const handleClick = page => evt => { evt.preventDefault(); handleChangePage(page); } for ( let i = 1; i < maxPage + 1; i++ ) { arrItem.push(<Item key = {i} disabled = {numberPage === i ? true : false} onClick={handleClick(i)}>{i} </Item>); } return( <Pagination style={{float: 'right'}}> <First disabled = {numberPage === 1 ? true : false} onClick={handleClick(1)}/> <Prev disabled = {previous === null ? true : false} onClick={handleClick(numberPage - 1)}/> {arrItem} <Next disabled = {next === null ? true : false} onClick={handleClick(numberPage + 1)}/> <Last disabled = {numberPage === maxPage ? true : false} onClick={handleClick(maxPage)}/> </Pagination> ); } export default CustomPagination;
import Session from '../../../../../models/im/session' import { tableColumnsByDomain } from '../../../../../scripts/utils/table-utils' import AppRoutes from '../../../../../configs/AppRoutes' const width = App.options.styles.table.width const options = { 'avatar': { width: width.w_12, title: '头像', render(h, context) { const url = context.row.fromContact.avatar return <a onClick={() => { App.push(AppRoutes.Contact.id(context.row.fromContact.id, context.row.fromContact.nickname)) }}><im-avatar url={url}></im-avatar></a> } }, 'profileCustomID': { width: width.w_12, title: '运营微信号', render(h, context) { return <a onClick={() => { App.push(AppRoutes.Contact.id(context.row.fromContact.id, context.row.fromContact.nickname)) }}>{context.row.fromContact.customID}</a> } }, 'profileNickname': { width: width.w_12, title: '运营号昵称', render(h, context) { return <span>{context.row.fromContact.nickname}</span> } }, toPuid: false, customID: false, nickname: false, 'detail': { title: '会话详情', width: width.w_8, render(h, context) { const row = context.row let url if (context.row.type === 2) { url = AppRoutes.ChatSession.groupMessage(row.fromContact.id, row.toContact.id, '', row.toContact.nickname || '') } else { url = AppRoutes.ChatSession.chatMessage(row.fromContact.id, row.toContact.id, '', row.toContact.nickname || '') } return <a onClick={() => { App.push(url) }}>详情</a> } } } export default tableColumnsByDomain(Session, options)