text
stringlengths
7
3.69M
var expect = chai.expect; describe('Eskin construction module',function(){ describe('Constructor',function(){ it('should have tests'); }) })
const router = require('express').Router(); const Order = require('../db').model('order'); const Product = require('../db').model('product'); const ProductOrder = require('../db').model('product_order'); const gatekeeper = require('../utils/gatekeeper'); module.exports = router; const findOrCreateCartByCookie = (req, res, next) => { return Order.findOrCreate({ where: { status: 'created', id: req.session.order }, include: [Product] }) .spread((order) => { req.session.order = order.id; return order; }) .then(order => { res.json(order); }) .catch(next); } const findOrCreateCartByUser = (req, res, next) => { Order.findOrCreate({ where: { status: 'created', userId: req.user.id }, include: [Product] }) .spread((order) => { req.session.order = order.id; return order; }) .then((order) => { return order.setUser(req.user) .then(setOrder => { res.json(setOrder); return null; }) }) .catch(next); } router.get('/', (req, res, next) => { if (req.user) { findOrCreateCartByUser(req, res, next) } else { findOrCreateCartByCookie(req, res, next); } }); router.get('/', (req, res, next) => { if (req.user) { findOrCreateCartByUser(req, res, next) } else { findOrCreateCartByCookie(req, res, next); } }); router.get('/:userId', gatekeeper.isAdminOrSelf, (req, res, next) => { findOrCreateCartByUser(req, res, next); }); router.post('/:orderId/:productId', gatekeeper.isAdminOrHasOrder, (req, res, next) => { Product.findById(req.params.productId) .then(selectedProduct => { const product = selectedProduct; return Order.findById(req.params.orderId) .then(order => { return order.addProduct(product, {unit_quantity: req.body.quantity, unit_price: product.price}); }) }) .then(result => { console.log(result) res.status(201).json(result) }) .catch(next); }); router.put('/:orderId/:productId', gatekeeper.isAdminOrHasOrder, (req, res, next) => { ProductOrder.update({ unit_quantity: req.body.quantity }, { where: { orderId: +req.params.orderId, productId: +req.params.productId }, returning: true }) .then(([rowCount, updatedObj]) => { res.status(201).json(updatedObj) }) .catch(next); }); router.delete('/:orderId/:productId', gatekeeper.isAdminOrHasOrder, (req, res, next) => { ProductOrder.destroy({ where: { orderId: req.params.orderId, productId: req.params.productId } }) .then(() => { res.sendStatus(204) }) .catch(next); });
import React from 'react'; export default function Header (props) { return(<h1>ReactJS Table</h1>) }
var config = {}; // Used only if https is disabled config.pep_port = 7000; // Set this var to undefined if you don't want the server to listen on HTTPS config.https = { enabled: false, cert_file: 'cert/cert.crt', key_file: 'cert/key.key', port: 443 }; config.idm = { version: '', host: '', port: '', ssl: false } config.app_host = ''; config.app_port = ''; // Use true if the app server listens in https config.app_ssl = false; // Credentials obtained when registering PEP Proxy in app_id in Account Portal config.pep = { app_id: '', username: '', password: '', trusted_apps : [] } // in seconds config.cache_time = 300; // if enabled PEP checks permissions of NGSIv2 request with a Role Based Access Control // roles have to be provided according to the following scheme: // fiware-service|operation|entityType|entityID|attribute // e.g., tenantRZ1|GET|AirQualityObserved|| // the above example will grant GET permission for each entity of type AirQualityObserved under the Fiware-Service tenantRZ1 config.rbac = false; //if enabled PEP logs access requests and responses on mongoDb config.logging = false; // if enabled PEP checks permissions with AuthZForce GE. // only compatible with oauth2 tokens engine // // you can use custom policy checks by including programatic scripts // in policies folder. An script template is included there config.azf = { enabled: false, protocol: 'http', host: 'pdp.docker', port: 8080, custom_policy: undefined // use undefined to default policy checks (HTTP verb + path). }; // list of paths that will not check authentication/authorization // example: ['/public/*', '/static/css/'] config.public_paths = []; config.magic_key = '123456789'; // MongoDB config.mongoDb = { server: 'mongoPep', port: 27017, user: '', password: '', db: 'pep' }; module.exports = config;
const express = require("express"); const MarcaController = require("../Controllers/Marcas"); const api = express.Router(); api.post("/agregar-Marca", MarcaController.guardarMarca); api.get("/marcas", MarcaController.getMarcas); api.put("/updateMarca/:id", MarcaController.updateMarca); api.delete("/deleteMarca/:id", MarcaController.deleteMarca); api.get("/nameMarca", MarcaController.getMarcaName); module.exports = api;
import React from 'react'; const Credit = () => { return ( <div className="credit"> <div className="credit__container"> <p className="credit__title">Лига Банк выдает кредиты под любые цели</p> <ul className="credit__list"> <li className="credit__item">Ипотечный кредит</li> <li className="credit__item">Автокредит</li> <li className="credit__item">Потребительский кредит</li> </ul> <p className="credit__text">Рассчитайте ежемесячный платеж и ставку по кредиту воспользовавшись нашим <a className="credit__link" href="/#credit">кредитным калькулятором</a> </p> </div> </div> ); }; export default Credit;
$(document).ready(function(){ $('#search-movies').on('keyup', searchMovies); }) function searchMovies(event) { var searchText = $('#search-movies').val().toUpperCase(); $('.movie').each(function(index) { var movieTitle = $(this).find('.movie-title').text().split(': ')[1].toUpperCase(); var movieNote = $(this).find('.movie-note').text().split(': ')[1].toUpperCase(); if (movieTitle.includes(searchText) || movieNote.includes(searchText)) { $(this).show() } else { $(this).hide() } }) }
import "./box.css"; const Box = ({boxWidth, boxHeight}) => { return <div className="box" style={{width: boxWidth, height: boxHeight}}></div> } export default Box
import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import InnerToolTip from './InnerToolTip' import TooltipOverlay from './TooltipOverlay' const noop = () => {} // eslint-disable-line no-empty-function class Tooltip extends PureComponent { static propTypes = { children: PropTypes.node, size: PropTypes.oneOf(['small', 'medium', 'large']), placement: PropTypes.oneOf(['top', 'left', 'right', 'bottom']), style: PropTypes.shape({ border: PropTypes.string, padding: PropTypes.string, boxShadow: PropTypes.string, }), // phasing in a new style override prop to avoid using native react prop customStyle: PropTypes.shape({ border: PropTypes.string, padding: PropTypes.string, boxShadow: PropTypes.string, backgroundColor: PropTypes.string, }), overlayStyle: PropTypes.shape({}), arrowStyle: PropTypes.shape({ border: PropTypes.string, boxShadowRight: PropTypes.string, boxShadowBottom: PropTypes.string, boxShadowLeft: PropTypes.string, boxShadowTop: PropTypes.string, }), target: PropTypes.node.isRequired, snacksStyle: PropTypes.oneOf(['primary', 'secondary', 'dark']), onDismiss: PropTypes.func, onShow: PropTypes.func, isVisible: PropTypes.bool, delayCalculatePosition: PropTypes.bool, } static defaultProps = { snacksStyle: 'dark', placement: 'bottom', size: 'small', onShow: noop, onDismiss: noop, } state = { show: false, } handleToggle = () => { const { onDismiss, onShow } = this.props this.setState( prevState => ({ show: !prevState.show }), () => { if (this.state.show) { onShow() } else { onDismiss() } } ) } handleHideToolTip = () => { const { onDismiss } = this.props this.setState({ show: false }) onDismiss() } renderTriggerElement() { const { target, isVisible } = this.props const { show } = this.state if (!target) { return } const extraProps = isVisible == null ? { onClick: this.handleToggle.bind(this) } : {} return React.cloneElement(target, { ref: node => { this.trigger = node }, 'aria-haspopup': true, 'aria-expanded': isVisible || show, ...extraProps, }) } render() { const { children, placement, size, style, customStyle, arrowStyle, snacksStyle, isVisible, overlayStyle, delayCalculatePosition, } = this.props return ( <div> {this.renderTriggerElement()} <TooltipOverlay placement={placement} target={() => this.trigger} show={isVisible || this.state.show} onRootClose={this.handleHideToolTip} style={overlayStyle} delayCalculatePosition={delayCalculatePosition} > <InnerToolTip size={size} // @todo(JP): kill references to style customStyle={customStyle || style} arrowStyle={arrowStyle} snacksStyle={snacksStyle} > {children} </InnerToolTip> </TooltipOverlay> </div> ) } } export default Tooltip
var searchData= [ ['pause',['PAUSE',['../Io_8h.html#a5666ac5930c9f903698073ab1fa694f7',1,'Io.h']]], ['pg_5fdw',['PG_DW',['../Io_8h.html#a060b53752df66df685746c2710da7f07',1,'Io.h']]], ['pg_5fup',['PG_UP',['../Io_8h.html#affe3eeca643bb9ec9355c12c1d99e473',1,'Io.h']]], ['porta',['PORTA',['../Fat_8cpp.html#a7c8a7f98a98d8cb125dd57a66720ab30',1,'Fat.cpp']]], ['pos_5finicial_5fkernel',['POS_INICIAL_KERNEL',['../Memoria_8h.html#a14a210fd4b5031eb2c4dc9492ff722dc',1,'Memoria.h']]], ['pos_5finicial_5fkernel_5fheap',['POS_INICIAL_KERNEL_HEAP',['../Memoria_8h.html#a19eccf2658c44dfb33998d75b22f073a',1,'Memoria.h']]], ['prim_5fcoluna',['PRIM_COLUNA',['../Video_8cpp.html#ad3e6c95faeb7d8375737c9d0b125e849',1,'Video.cpp']]], ['prim_5flinha',['PRIM_LINHA',['../Video_8cpp.html#a8123f20ca6418b3516bb8f27f7d8864f',1,'Video.cpp']]], ['proc_5fcriado',['PROC_CRIADO',['../Mensagem_8h.html#ab4a3dbb21706369ede715f9cba4f57f1',1,'Mensagem.h']]], ['proc_5fdestruido',['PROC_DESTRUIDO',['../Mensagem_8h.html#a2e262729b2bdad53785205c2e6766fb5',1,'Mensagem.h']]], ['prt_5fscr',['PRT_SCR',['../Io_8h.html#a04821408573f2b2a43438d36929a8b03',1,'Io.h']]] ];
// Stan Helsloot, 10762388 // makes a stacked barchart for each year var requestsStacked = [d3.json("../../data/data_refined/stacked_data.json")]; // main function for drawing the stacked barchart var stackedYear = function() { Promise.all(requestsStacked) .then(function(response) { var draw = stackedMakerYear(response); }); }; // creates a stacked histogram of the earthquakes function stackedMakerYear(data) { // tooltip of stacked_year var tip = d3.tip() .attr('class', 'd3-tip') .offset([-10, 0]); // setting size and margins var w = 400; var h = 400; var margin = { top: 100, right: 50, bottom: 20, left: 50 }; // creating a svg object var svg = d3.select("div#earthquakeStacked") .append("svg") .attr("id", "stackedYear") .attr("width", w + margin.left + margin.right) .attr("height", h + margin.top + margin.bottom); // collecting range data length for determining max values in yScale var rangeData = []; for (var i = 0; i < data[0].length; i++) { len = (data[0][i][0][1] + data[0][i][1][1] + data[0][i][2][1] + data[0][i] [3][1]); rangeData.push(len); } // setting the yScale var yScale = d3.scaleLinear() .domain([0, Math.max(...rangeData)]) .range([h, margin.top]); // setting color scale manually var color = { "1.5": "rgb(186,228,179)", "2.0": "rgb(116,196,118)", "2.5": "rgb(49,163,84)", "3.0": "rgb(0,109,44)" }; // adding groups for rectangle appending var groups = svg.append("g") .selectAll("g") .data(data[0]) .enter() .append("g"); // appending rectangles groups.selectAll("rect") .data(function(d) { return d; }) .enter() .append("rect") .attr("x", function(d) { return (d[0] - 1985) * (w / data[0].length); }) .attr("y", function(d) { return yScale(d[3]); }) .attr("height", function(d) { return h - yScale(d[1]); }) .attr("width", w / data[0].length) .style("fill", function(d) { return (color[d[2]]); }) .attr("transform", "translate(" + 39 + ",0)") .on('mouseover', function(d) { // make a banner with the location and magnitude of the earthquake tip.html(function() { return "<strong>Year: </strong><span class='details'>" + d[0] + "<br></span>" + "<strong>Magnitude: </strong><span class='details'>" + d[2] + "<br></span>" + "<strong>Amount of Earthquakes: </strong><span class='details'>" + d[1] + "</span>"; }); tip.show(); d3.select(this) .style("fill", "rgba(123,50,148, 0.6)"); }) .on('mouseout', function(d) { tip.hide(); d3.select(this) .style("fill", function(d) { return (color[d[2]]); }); }) .on("click", function(d) { // call function to update the map setMap(d[0]); // update slider sliderMap.value(d[0]); }); // set tip svg.call(tip); // appending title svg.append("text") .attr("class", "title") .attr("y", margin.top / 6) .style("text-anchor", "start") .text("Total amount of earthquakes per year and magnitude"); // setting xScale var xScale = d3.scaleLinear() .range([0, w]) .domain([1986, 2019]); // setting yAxis var yAxis = d3.axisLeft() .scale(yScale) .ticks(5); // setting xAxis var xAxis = d3.axisBottom() .scale(xScale); // appending yAxis svg.append("g") .attr("class", "yaxis") .attr("transform", "translate(" + margin.left + ",0)") .call(yAxis); // appending axis svg.append("g") .attr("class", "xaxis") .attr("transform", "translate(" + margin.left + "," + h + ")") .call(xAxis.tickFormat(d3.format(".4"))); // append xAxis text svg.append("text") .attr("x", (w + margin.left + margin.right) / 2) .attr("transform", "translate(0," + (h + margin.top - margin.bottom) + ")") .text("Year"); // Append yAxis text svg.append("text") .attr("transform", "rotate(-90)") .attr("x", -h / 2 + 30) .attr("y", margin.left / 3) .style("text-anchor", "end") .text("Amount of earthquakes"); // make legend for stacked_year (horizontal, located right of chart) makeLegend(data); // function for making the interactive legend function makeLegend(data) { // defining legend dimension legendPadding = 20; data = data[0][0]; // create legend var legend = svg.append("g") .attr("font-family", "sans-serif") .attr("font-size", 10) .attr("text-anchor", "end") .selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0," + i * 25 + ")"; }) .on("click", function(d) { setMapMagRange(d[2]); }); //append legend colour blocks legend.append("rect") .attr("x", w + margin.left * 1.5) .attr("y", margin.bottom) .attr("width", legendPadding) .attr("height", legendPadding) .style("fill", function(d) { return color[d[2]]; }); //append legend texts legend.append("text") .attr("x", w + margin.left * 1.4) .attr("y", margin.bottom * 1.4) .attr("dy", "0.32em") .text(function(d) { return d[2]; }); } }
module.exports = function (grunt) { var path = require('path'); //// Grunt Configuration /////////////////////////////////////////////////////// grunt.initConfig({ // access to package.json values pkg: grunt.file.readJSON('package.json'), builddate: '<%= grunt.template.today("yyyy-mm-dd") %>', buildname: '<%= pkg.name %>-<%= pkg.version %>', buildbanner: '<%= buildname %>, build: <%= builddate %>', // Servers // ------- express: { project: { options: { port: 3000, script: 'staging/server/<%= pkg.version %>/server.js' } } }, shell: { mongodb: { command: 'mongod --dbpath ./persistence/db', options: { async: true, stdout: true, stderr: true, failOnError: true, execOptions: { cwd: '.' }, } } }, wait: { mongodb: { options: { delay: 2500 } } }, // Scripts // ------- // compile jsx to javascript react: { options: { harmony: true }, project: { files: [{ expand: true, cwd: 'sources/javascript', src: [ '**/*.js' ], dest: 'staging/theme/public/javascript/jsx', ext: '.js' }] }, watchedfile: { expand: true, cwd: 'sources/javascript', src: 'modified/file.js', dest: 'staging/theme/public/javascript/jsx', ext: '.js' } }, // check javascript for nonsense jshint: { // see: http://www.jshint.com/docs/options/ options: { curly: true, // always write quirly braces eqeqeq: true, // warnings on using == eqnull: true, // supress eqeqeq warnings on "var == null" browser: true, // assume browser evil: true, // supress use of eval warnings loopfunc: true, // supress loop function error globals: { jQuery: true // assume jquery }, }, project: [ 'staging/theme/public/javascript/jsx/**/*.js' ], watchedfile: 'modified/file.js', }, // minify javascript uglify: { options: { banner: '/*! <%= buildbanner %> */\n', sourceMap: true, mangle: false, beautify: true, preserveComments: true }, project: { src: [ 'staging/theme/public/javascript/support/**/*.js', 'staging/theme/public/javascript/lib/**/*.js', 'staging/theme/public/javascript/jsx/**/*.js', ], dest: 'staging/theme/public/javascript/scripts.js' } }, // Styles // ------ // see: exec:sass imagemin: { options: { optimizationLevel: 3 }, project: { files: [{ expand: true, cwd: 'sources/images', src: [ '**/*.{png,jpg,jpeg,gif}' ], dest: 'staging/theme/public/images' }] }, watchedfile: { expand: true, cwd: 'sources/images', src: 'modified/file', dest: 'staging/theme/public/images' } }, autoprefixer: { project: { options: { browsers: ['last 2 version', 'ie 8', 'ie 9'], map: true, diff: true }, files: [{ expand: true, cwd: 'staging/theme/public/css', src: '**/*.css', dest: 'staging/theme/public/css/' }] } }, // Misc Files // ---------- rename: { server_conf: { src: 'staging/server/server.conf.json', dest: 'staging/server/server.conf.json-draft' } }, copy: { // server related server: { expand: true, cwd: 'sources/server/', src: '**/*', dest: 'staging/server/<%= pkg.version %>/' }, packageinfo: { src: 'package.json', dest: 'staging/server/<%= pkg.version %>/package.json' }, serverconf: { src: 'sources/server.conf.json', dest: 'staging/server/server.conf.json' }, // theme files theme: { files: [ { expand: true, cwd: 'sources/theme', src: '*.html', dest: 'staging/theme/' }, { src: 'sources/theme/theme.js', dest: 'staging/theme/theme.js' } ] }, watchedthemefile: { expand: true, cwd: 'sources/theme/', src: 'modified/file.html', dest: 'staging/theme/' }, publicfiles: { expand: true, cwd: 'sources/theme/public/', src: '**/*', dest: 'staging/theme/public/' }, // public files misc: { files: [ { expand: true, cwd: 'sources', src: '*.html', dest: 'staging/theme/public/' }, { expand: true, flatten: true, src: 'sources/dependencies/fontawesome/fonts/**/*', dest: 'staging/theme/public/fonts/' } ] }, sass: { files: [ { expand: true, flatten: true, cwd: 'sources/scss/', src: '**/*.scss', dest: 'staging/theme/public/css/scss/' } ] }, sass_watchedfile: { expand: true, flatten: true, cwd: 'sources/scss/', src: 'modified/file.scss', dest: 'staging/theme/public/css/scss/' }, scripts: { files: [ { expand: true, cwd: 'sources/alpha-dependencies/', src: '**/*.js', dest: 'staging/theme/public/javascript/support/' }, { expand: true, cwd: 'sources/dependencies/', src: '**/*.js', dest: 'staging/theme/public/javascript/lib/' } ] } }, // Utilities // --------- clean: { project: [ 'staging/tmp', 'staging/theme', 'staging/server' ], release: [ 'staging/theme/public/css/scss', 'staging/theme/public/css/**/*.map', 'staging/theme/public/css/**/*.patch', 'staging/theme/public/javascript/jsx', 'staging/theme/public/javascript/**/*.map' ] }, exec: { sass: { command: [ 'bundle exec sass', '--sourcemap', '--update staging/theme/public/css/scss/:staging/theme/public/css/', '--load-path sources/scss', '--style expanded', '-E utf-8' ].join(' '), stdout: true, stderr: true } }, compress: { release_theme: { options: { mode: 'zip', pretty: true, archive: 'releases/<%= buildname %>-theme.zip' }, files: [ { expand: true, cwd: 'staging/theme/', src: ['**/*'], dest: '.' } ] }, release_server: { options: { mode: 'zip', pretty: true, archive: 'releases/<%= buildname %>-server.zip' }, files: [ { expand: true, cwd: 'staging/server/', src: ['**/*'], dest: '.' } ] } }, concat: { vendorcss: { src: [ 'sources/dependencies/**/*.css' ], dest: 'staging/theme/public/css/vendor.css' } }, replace: { serverfix: { src: 'staging/server/server.conf.json', overwrite: true, // overwrite matched source files replacements: [ { // ensure draft server.conf.json can't be used as-is from: /do-not-use-these-keys-in-production/g, to: '' } ] }, removedevdeps: { src: 'staging/server/<%= pkg.version %>/package.json', overwrite: true, // overwrite matched source files replacements: [ { // ensure draft server.conf.json can't be used as-is from: /\n[\t ]+\"devDependencies\"\: \{[^}]*\},/g, to: '' } ] }, cssmapsfix: { src: ['staging/theme/public/css/**/*.map'], overwrite: true, // overwrite matched source files replacements: [ { from: /\\\\/g, to: '/' } ] }, jsmapsfix: { src: ['staging/theme/public/javascript/**/*.map'], overwrite: true, // overwrite matched source files replacements: [ { from: /\\\\/g, to: '/' } ] } }, // running `grunt watch` will have grunt run all of the following // definitions simultaniously in the same console window :) watch: { theme: { options: { spawn: false, livereload: 8000 }, files: [ 'sources/theme/**/*.html' ], tasks: [ 'copy:watchedthemefile' ], }, server_conf: { options: { spawn: false, livereload: 8000 }, files: [ 'sources/server.conf.json' ], tasks: [ 'copy:serverconf' ], }, misc: { options: { spawn: false, livereload: 8000 }, files: [ 'sources/*.html' ], tasks: [ 'copy:misc' ] }, images: { options: { spawn: false }, files: [ 'sources/images/**/*.{png,jpg,jpeg,gif}' ], tasks: [ 'imagemin:watchedfile' ] }, styles: { options: { spawn: false, livereload: 8000, }, files: [ 'sources/scss/**/*.scss' ], tasks: [ 'copy:sass_watchedfile', 'exec:sass', 'autoprefixer:project', 'replace:cssmapsfix' ] }, scripts: { options: { spawn: false, }, files: [ 'sources/javascript/**/*.js' ], tasks: [ 'react:watchedfile', 'jshint:watchedfile', 'uglify:project', 'replace:jsmapsfix' ] }, vendorjs: { options: { spawn: false, }, files: [ 'sources/alpha-dependencies/**/*.js', 'sources/dependencies/**/*.js' ], tasks: [ 'react:project', 'copy:scripts', 'jshint:project', 'uglify:project', 'replace:jsmapsfix', ] }, server: { options: { spawn: false, livereload: 8000 }, files: [ 'sources/server/**/*' ], tasks: [ 'copy:server' ] }, express: { files: [ 'sources/server/**/*' ], tasks: [ 'express:project' ], options: { spawn: false } } }, }); //// Filtering Watch Tasks ///////////////////////////////////////////////////// grunt.event.on('watch', function(action, filepath, target) { filepath = filepath.replace(/\\/g, '/'); if (target == 'styles') { var relative_filepath = filepath.replace('sources/scss/', ''); grunt.config('copy.sass_watchedfile.src', relative_filepath); } else if (target == 'scripts') { var relative_filepath = filepath.replace('sources/javascript/', ''); grunt.config('react.watchedfile.src', relative_filepath); grunt.config('jshint.watchedfile', 'staging/theme/public/javascript/jsx/' + relative_filepath); } else if (target == 'images') { var relative_filepath = filepath.replace('sources/images/', ''); grunt.config('imagemin.watchedfile.src', relative_filepath); } else if (target == 'theme') { var relative_filepath = filepath.replace('sources/theme/', ''); grunt.config('copy.watchedthemefile.src', relative_filepath); } }); //// Task Definitions ////////////////////////////////////////////////////////// // server grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-shell-spawn'); // used for mongodb instance grunt.loadNpmTasks('grunt-wait'); // utilities grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-text-replace'); grunt.loadNpmTasks('grunt-exec'); grunt.loadNpmTasks('grunt-rename'); // scripts grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-react'); // styles grunt.loadNpmTasks('grunt-contrib-imagemin'); grunt.loadNpmTasks('grunt-autoprefixer'); // default task grunt.registerTask( 'default', [ 'clean:project', // scripts tasks 'react:project', 'copy:scripts', 'jshint:project', 'uglify:project', 'replace:jsmapsfix', // style tasks 'copy:sass', 'exec:sass', 'autoprefixer', 'copy:misc', 'concat:vendorcss', 'replace:cssmapsfix', 'imagemin:project', // themes 'copy:theme', 'copy:publicfiles', // server tasks 'copy:server', 'copy:serverconf' ] ); // release task grunt.registerTask( 'stage', [ 'default', 'clean:release', 'replace:serverfix', 'copy:packageinfo', 'replace:removedevdeps', 'rename:server_conf' ] ); grunt.registerTask( 'release', [ 'stage', 'compress:release_server', 'compress:release_theme' ] ); // server task grunt.registerTask( 'server', [ 'default', 'shell:mongodb', 'wait:mongodb', 'express:project', 'watch' ] ); };
const canvas = document.querySelector('canvas'); const c = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; let rotation; let x, y; canvas.addEventListener("keydown", function(e) { console.log(e.code); });
import React, { Component } from 'react'; // import { packageJson } from '../package.json'; import { DataTable } from 'primereact/datatable'; import { Column } from 'primereact/column'; import { Panel } from 'primereact/panel'; import { InputText } from 'primereact/inputtext'; import { Checkbox } from 'primereact/checkbox'; import { Dropdown } from 'primereact/dropdown'; import { Calendar } from 'primereact/calendar'; import { Button } from 'primereact/button'; import { Toast } from 'primereact/toast'; import Flag from 'react-world-flags'; import 'primereact/resources/themes/luna-blue/theme.css'; import 'primereact/resources/primereact.css'; import 'primeicons/primeicons.css'; import './manager.css'; const packageJson = require('../package.json'); // console.log("PJ\n" + JSON.stringify(packageJson)); const APP_VERSION = packageJson.version; const REACT_VERSION = React.version; // const REACT_DOM_VERSION = packageJson.dependencies["react-dom"].substring(1); const PRIME_REACT_VERSION = packageJson.dependencies.primereact.substring(1); // const PRIME_ICONS_VERSION = packageJson.dependencies.primeicons.substring(1); // const WORLD_FLAGS_VERSION = packageJson.dependencies['react-world-flags'].substring(1); const modes = { VIEW: 'VIEW', ADD: 'ADD', EDIT: 'EDIT', REMOVE: 'REMOVE' } class PersonManager extends Component { constructor() { super(); this.state = {entities: [], selectedEntity: null, mode: null}; // row events this.onRowEdit = this.onRowEdit.bind(this); this.onRowRemove = this.onRowRemove.bind(this); this.onRowSelect = this.onRowSelect.bind(this); this.onRowUnselect = this.onRowUnselect.bind(this); // sub panel events this.onCountryChange = this.onCountryChange.bind(this); // templates this.actionsTemplate = this.actionsTemplate.bind(this); } render() { var header = "Person Manager (" + this.state.entities.length + ")" return ( <div style={{ maxWidth: 1600, marginLeft: "auto", marginRight: "auto", marginTop: 10, marginBottom: 10 }}> <Toast ref={(el) => this.toast = el} /> <div>BBStats (R) version: {APP_VERSION}</div> <div>React version: {REACT_VERSION}</div> {/* <div>React DOM version: {REACT_DOM_VERSION}</div> */} <div>PrimeReact version: {PRIME_REACT_VERSION}</div> {/* <div>PrimeIcons version: {PRIME_ICONS_VERSION}</div> */} {/* <div>World Flags version: {WORLD_FLAGS_VERSION}</div> */} <br /> <DataTable value={this.state.entities} header={header} dataKey="id" selection={this.state.selectedEntity} selectionMode="single" onSelectionChange={e => this.setState({ selectedEntity: e.value })} onRowSelect={this.onRowSelect} onRowUnselect={this.onRowUnselect} sortField='lastName' sortOrder={1} resizableColumns columnResizeMode="fit" paginator paginatorTemplate="CurrentPageReport FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown" currentPageReportTemplate="Showing {first} to {last} of {totalRecords}" rows={10} rowsPerPageOptions={[10,20,50]} className="p-datatable-striped"> <Column field="gender" header='Sal.' body={this.salutation} sortable style={{width:'5.5%'}} /> <Column field='lastName' header='Last Name' sortable style={{width:'9%'}} /> <Column field='firstName' header='First Name' sortable style={{width:'9%'}} /> <Column field='incognito' header='Anon.' body={this.incognito} sortable style={{width:'6.5%'}} /> <Column field='roles' header='Roles' body={this.roles} style={{width:'5.5%'}} /> <Column field='streetName' header='Street' body={this.street} sortable style={{width:'8%'}} /> <Column field='zipCode' header='ZIP' sortable style={{width:'5.5%'}} /> <Column field='cityName' header='City' sortable style={{width:'7%'}} /> <Column field='countryCode' header='Country' body={this.country} sortable style={{width:'7.5%'}} /> <Column field='birthDate' header='Date of Birth' body={this.formattedBirthDate} sortable style={{width:'10%'}} /> <Column field='emailAddresses' header='E-Mail Addr.' body={this.firstEmailAddress} sortable style={{width:'10.5%'}} /> <Column field='phoneNumbers' header='Mobile No.' body={this.mobilePhoneNumber} sortable style={{width:'9%'}} /> <Column field="actions" body={this.actionsTemplate} style={{width:'7%'}} /> </DataTable> {this.renderSubPanel()} </div> ); } renderSubPanel() { let subPanel = null; if ( this.state.selectedEntity ) { subPanel = <Panel style={{marginTop: 10}}> <div className="p-grid"> <div className="p-col-1"> <label htmlFor="salutation" style={{verticalAlign: -6}}>Salutation</label> </div> <div className="p-col-4"> <Dropdown value={this.state.selectedEntity.gender} required options={this.genders} optionLabel="name" optionValue="gender" onChange={(e) => {this.setState(state => (state.selectedEntity.gender = e.value))}} disabled={this.state.mode !== "EDIT"} placeholder="Please select..." /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="incognito" style={{verticalAlign: -6}}>Incognito</label> </div> <div className="p-col-4"> <Checkbox inputId="incognito" value="Incognito" checked={this.state.selectedEntity.incognito} onChange={(e) => {this.setState(state => (state.selectedEntity.incognito = e.checked))}} disabled={this.state.mode !== "EDIT"} style={{verticalAlign: -2}} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="first-name" style={{verticalAlign: -6}}>First name</label> </div> <div className="p-col-4"> <InputText id="first-name" value={this.state.selectedEntity.firstName} required onChange={(e) => {e.persist(); this.setState(state => (state.selectedEntity.firstName = e.target.value))}} disabled={this.state.mode !== "EDIT"} maxLength="50" style={{width: "100%"}} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="last-name" style={{verticalAlign: -6}}>Last name</label> </div> <div className="p-col-4"> <InputText id="last-name" value={this.state.selectedEntity.lastName} required onChange={(e) => {e.persist(); this.setState( state => (state.selectedEntity.lastName = e.target.value))}} disabled={this.state.mode !== "EDIT"} maxLength="50" style={{width: "100%"}} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="street" style={{verticalAlign: -6}}>Street</label> </div> <div className="p-col-4"> <InputText id="street" value={this.state.selectedEntity.streetName || ''} onChange={(e) => {e.persist(); this.setState(state => (state.selectedEntity.streetName = e.target.value))}} disabled={this.state.mode !== "EDIT"} maxLength="100" style={{width: "80%"}} /> <InputText id="house-nbr" value={this.state.selectedEntity.houseNbr || ''} onChange={(e) => {e.persist(); this.setState(state => (state.selectedEntity.houseNbr = e.target.value))}} disabled={this.state.mode !== "EDIT"} maxLength="10" style={{width: "20%"}} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="zip-code" style={{verticalAlign: -6}}>ZIP code</label> </div> <div className="p-col-4"> <InputText id="zip-code" value={this.state.selectedEntity.zipCode || ''} onChange={(e) => {e.persist(); this.setState(state => (state.selectedEntity.zipCode = e.target.value))}} disabled={this.state.mode !== "EDIT"} style={{width: "100%"}} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="city" style={{verticalAlign: -6}}>City</label> </div> <div className="p-col-4"> <InputText id="city" value={this.state.selectedEntity.cityName || ''} onChange={(e) => {e.persist(); this.setState(state => (state.selectedEntity.cityName = e.target.value))}} disabled={this.state.mode !== "EDIT"} style={{width: "100%"}} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="country" style={{verticalAlign: -6}}>Country</label> </div> <div className="p-col-4"> <Dropdown id="country" value={this.countries.find(c => c.isoCode === this.state.selectedEntity.countryCode) || ''} valueTemplate={this.selectedCountryDropdownTemplate} itemTemplate={this.selectableCountryDropdownTemplate} options={this.countries} optionLabel="name" onChange={(e) => {this.setState(state => (state.selectedEntity.countryCode = e.value.countryCode))}} disabled={this.state.mode !== "EDIT"} placeholder="Please select..." /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="birth-date" style={{verticalAlign: -6}}>Date of Birth</label> </div> <div className="p-col-4"> <Calendar id="birth-date" value={this.state.selectedEntity.birthDate || ''} readOnlyInput disabled={this.state.mode !== "EDIT"} onChange={(e) => this.setState(state => (state.selectedEntity.birthDate = e.value))} /> </div> <div className="p-col-1" /> <div className="p-col-1"> <label htmlFor="e-mail-address" style={{verticalAlign: -6}}>E-Mail Address</label> </div> <div className="p-col-4"> <InputText id="e-mail-address" value={this.state.selectedEntity.emailAddresses[0] || ''} onChange={(e) => {e.persist(); this.setState(state => (state.selectedEntity.emailAddresses[0] = e.target.value))}} disabled={this.state.mode !== "EDIT"} style={{width: "100%"}} /> </div> <div className="p-col-1" /> </div> </Panel>; } return subPanel; } // Called *after* render() componentDidMount() { const entityUrl = 'http://kawoolutions.com/bbstats/ws/person/findall'; fetch(entityUrl) .then(response => response.json()) .then(data => { this.setState({entities: data}); }) .catch(console.log) // all genders this.genders = [{ "gender": "MALE", "name": "Mr" }, { "gender": "FEMALE", "name": "Mrs" }]; // all countries const allCountriesUrl = 'http://kawoolutions.com/bbstats/ws/country/findall'; fetch(allCountriesUrl) .then(response => response.json()) .then(data => { this.countries = data; }) .catch(console.log) // default countries const defaultCountryUrl = 'http://kawoolutions.com/bbstats/ws/country/finddefault'; fetch(defaultCountryUrl) .then(response => response.json()) .then(data => { this.defaultCountry = data[0]; }) .catch(console.log) } actionsTemplate(rowData) { // var index = this.state.entities.indexOf( rowData ); return ( <> <div style={{textAlign: "center"}}> {/* {index} */} <Button icon="pi pi-pencil" tooltip="Edit" onClick={() => this.onRowEdit(rowData)} className="p-button-sm p-button-raised p-button-rounded p-button-outlined" /> <Button icon="pi pi-trash" tooltip="Remove" className="p-button-sm p-button-raised p-button-rounded p-button-outlined" onClick={() => this.onRowRemove(rowData)} style={{marginLeft: 5}} /> </div> </> ); } onRowEdit(rowData) { this.setState({selectedEntity: rowData, mode: modes.EDIT}, () => this.toast.show({ severity: 'info', summary: 'Editing Person', detail: 'Name: ' + this.state.selectedEntity.lastName + ", " + this.state.mode, life: 3000 })) } onRowRemove(rowData) { this.setState({selectedEntity: rowData, mode: modes.REMOVE}, () => this.toast.show({ severity: 'info', summary: 'Removing Person', detail: 'Name: ' + this.state.selectedEntity.lastName + ", " + this.state.mode, life: 3000 })) } onRowSelect(event) { this.setState({selectedEntity: event.data, mode: modes.VIEW}, () => this.toast.show({ severity: 'info', summary: 'Viewing Person', detail: 'Name: ' + this.state.selectedEntity.lastName + ", " + event.data.countryCode + ", C: " + this.countries.find(c => c.isoCode === event.data.countryCode) + ", " + this.state.mode, life: 3000 })) } onRowUnselect(event) { let previousMode = this.state.mode; this.setState({selectedEntity: null, mode: null}, () => this.toast.show({ severity: 'info', summary: 'Unselecting Person', detail: 'Name: ' + event.data.lastName + ", PREV: " + previousMode, life: 3000 })) } view() { this.setState({mode: modes.VIEW}); } add() { this.setState({mode: modes.ADD}); } edit() { this.setState({mode: modes.EDIT}); } remove() { this.setState({mode: modes.REMOVE}); } clear() { this.setState({mode: null}); } salutation(rowData) { var gender = rowData['gender']; if ( gender ) { switch( gender ) { case "MALE": return "Mr"; case "FEMALE": return "Mrs"; default: return "Error"; } } return null; } incognito(rowData) { var incognito = rowData['incognito']; // console.log(typeof val); var text = null; if ( incognito === null ) { return null; } switch( incognito ) { case true: text = "Yes"; break; case false: text = "No"; break; default: text = "Error"; break; } return ( <> <div style={{textAlign: "center"}}> <span>{text}</span> </div> </> ); } roles(rowData) { var player = rowData['player']; var coach = rowData['coach']; var referee = rowData['referee']; return ( <> <div style={{textAlign: "center"}}> {player ? ( <span title="Player" role="img" aria-label="P">⛹️</span> ) : ( "" )} {coach ? ( <span title="Coach" role="img" aria-label="P">👨‍💼</span> ) : ( "" )} { referee ? ( <img src="http://kawoolutions.com/bbstats/javax.faces.resource/images/icons/referee-border.png.xhtml?ln=bbstats" title="Referee" alt="" width="16" style={{verticalAlign: -2.5, marginLeft: 3}} /> ) : ( <></> ) } </div> </> ); } street(rowData) { var streetName = rowData['streetName']; var houseNumber = rowData['houseNbr']; return houseNumber ? streetName + " " + houseNumber : streetName; } country(rowData) { var countryCode = rowData['countryCode']; return ( <> <div style={{textAlign: "center"}}> <Flag code={ countryCode } fallback={ <span>Unknown</span> } height="16" style={{verticalAlign: -2}} /> {/* <img alt={countryCode} src="images/flag_placeholder.png" className={`flag flag-${countryCode.toLowerCase()}`} width="30" /> */} <span> ({countryCode})</span> </div> </> ); } formattedBirthDate(rowData) { var birthDateStamp = rowData['birthDate']; if ( birthDateStamp ) { var birthDate = new Date( birthDateStamp ); var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; return birthDate.toLocaleDateString( 'en-US' ) + " (" + days[ birthDate.getDay() ] + ")"; } return null; } firstEmailAddress(rowData) { var emailAddresses = rowData['emailAddresses']; if ( emailAddresses ) { return emailAddresses[0]; } return null; } mobilePhoneNumber(rowData) { // var phoneNumbers = rowData['phoneNumbers']; // if ( phoneNumbers ) // { // return " " + rowData['id']; // // var mobilePhoneNumber = phoneNumbers["MOBILE"]; // // if ( mobilePhoneNumber ) // // { // // return "+" + mobilePhoneNumber.countryCode + " (" + mobilePhoneNumber.areaCode + ") " + mobilePhoneNumber.subscriberNbr; // // } // } // return null; return rowData['id']; } selectedCountryDropdownTemplate(option, props) { if (option) { return ( <div> <Flag code={option.isoCode} fallback={<span>Unknown</span>} height="16" style={{verticalAlign: -2}} /> {/* <img alt={countryCode} src="images/flag_placeholder.png" className={`flag flag-${countryCode.toLowerCase()}`} width="30" /> */} <span> {option.name} ({option.isoCode})</span> </div> ); } return ( <span> {props.placeholder} </span> ); } selectableCountryDropdownTemplate(option) { return ( <div> <Flag code={option.isoCode} fallback={<span>Unknown</span>} height="16" style={{verticalAlign: -2}} /> {/* <img alt={countryCode} src="images/flag_placeholder.png" className={`flag flag-${countryCode.toLowerCase()}`} width="30" /> */} <span> {option.name} ({option.isoCode})</span> </div> ); } onCountryChange(event) { this.setState({ selectedCountry: event.value }); } } export default PersonManager;
export const obj = { name : "paul", description: "eleve", age: 40 } let {name,description,age} = obj; export const arr = ['basile', 'romain', 'hachim', 'moi']; export const arr1 = ['Angela', 'Dwight', 'Florian']; export const obj1 = {...obj, color: 'red'}; console.log('niiiiice, je suis le second');
import React from 'react' import {Jumbotron} from 'react-bootstrap' export default class Welcome extends React.Component { constructor(props) { super(props); } render() { return ( <Jumbotron className='jumbotron'> <span className='welcomeText'> Welcome to Tourganic</span> </Jumbotron> ) } }
import React from 'react'; import PropTypes from 'prop-types'; import MovieCard from '../Movie-card'; import { setID, basePosterURL, defaultPosterURL } from '../../helper'; const MoviesList = ({ moviesData, rateMovie }) => { const elements = moviesData.map(({ poster_path, ...movieItems }) => { return ( <MovieCard key={setID()} {...movieItems} posterURL={poster_path ? basePosterURL + poster_path : defaultPosterURL} rateMovie={rateMovie} /> ) }); return ( <ul className="film-list"> {elements} </ul> ) } MoviesList.propTypes = { moviesData: PropTypes.array } export default MoviesList;
editFunction = function (Row, store) { var content_status_num = 0; //參數表中預設數量限制 var list_status_num = 0; //列表中已啟用的數量 var keeditor = new Ext.form.TextArea({ id: 'keeditor', fieldLabel: HOMETEXT, width: 600, height: 200 }); var editFrm = Ext.create('Ext.form.Panel', { id: 'editFrm', frame: true, plain: true, layout: 'anchor', autoScroll: true, labelWidth: 45, url: '/WebContentType/SaveWebContentType4', defaults: { anchor: "95%", msgTarget: "side", labelWidth: 80 }, listeners: { 'render': function () { KE.show({ id: 'keeditor', width: 100, imageUploadJson: '../../../../WebContentType/UploadHtmlEditorPicture' }); setTimeout("KE.create('keeditor');", 1000); } }, items: [ { xtype: 'textfield', fieldLabel: 'ID', id: 'content_id', name: 'content_id', hidden: true }, { xtype: 'combobox', //網頁 allowBlank: false, editable: false, typeAhead: true, forceSelection: false, fieldLabel: PAGEID, id: 'page_id', name: 'page_id', hiddenName: 'page_id', colName: 'page_id', store: pageidStore, displayField: 'page_name', valueField: 'page_id', emptyText: SELECT, listeners: { "select": function (combo, record, index) { var area = Ext.getCmp('area_id'); var status = Ext.getCmp('content_status'); if (combo.getValue() != undefined && area.getValue() != undefined) { status.setDisabled(false); } pageid = Ext.getCmp('page_id').getValue(); area.clearValue(); areaidStore.removeAll(); } } }, { xtype: 'combobox', //區域 allowBlank: false, editable: false, typeAhead: true, forceSelection: false, fieldLabel: AREAID, id: 'area_id', name: 'area_id', hiddenName: 'area_id', colName: 'area_id', store: areaidStore, displayField: 'area_name', valueField: 'area_id', emptyText: SELECT, listeners: { beforequery: function (qe) { // delete qe.combo.lastQuery; // areaidStore.on('beforeload', function () { // Ext.apply(areaidStore.proxy.extraParams, // { // type: 'area', // pageid: pageid, // webcontenttype_page: 'web_content_type4' // }); // }); areaidStore.load(); }, "select": function (combo, record, index) { var page = Ext.getCmp('page_id'); var status = Ext.getCmp('content_status'); var area = Ext.getCmp('area_id'); var brand = Ext.getCmp('brand_id'); if (page.getValue() != undefined && combo.getValue() != undefined) { status.setDisabled(false); } if (page.getValue() != undefined && area.getValue() != undefined) { brand.setDisabled(false); } } } }, { xtype: 'combobox', //品牌 allowBlank: false, editable: false, //typeAhead: true, disabled: true, //forceSelection: false, fieldLabel: BRANDID, id: 'brand_id', name: 'brand_name', hiddenName: 'brand_id', colName: 'brand_id', store: BrandStore, displayField: 'brand_name', valueField: 'brand_id', emptyText: SELECT, listeners: { beforequery: function (qe) { BrandStore.on('beforeload', function () { Ext.apply(BrandStore.proxy.extraParams, { webcontenttype: 'web_content_type4', content_id: Row != null ? Row.data.content_id : 0 }); }); }, "select": function (combo, record, index) { var page = Ext.getCmp('page_id'); var area = Ext.getCmp('area_id'); var brand = Ext.getCmp('brand_id'); Ext.Ajax.request({ url: "/WebContentType/GetLinkUrl", method: 'post', type: 'text', params: { brandid: brand.getValue(), pageid: page.getValue(), areaid: area.getValue(), webcontenttype_page: 'web_content_type4' }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { msg = result.msg; Ext.getCmp("link_url").setValue(msg); } } }); } } }, { xtype: 'radiogroup', hidden: false, id: 'content_status', name: 'content_status', fieldLabel: ISSTATUS, colName: 'content_status', width: 400, defaults: { name: 'content_status', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: CONTENTSTATUS, id: 'isStatus', inputValue: '1', checked: true, listeners: { change: function (radio, newValue, oldValue) { var targetCol = Ext.getCmp("content_default"); if (newValue) { targetCol.setDisabled(false); } } } }, { boxLabel: NOCONTENTSTATUS, id: 'noStatus', inputValue: '0', listeners: { change: function (radio, newValue, oldValue) { var targetCol = Ext.getCmp("content_default"); var yes = Ext.getCmp("isDef"); var no = Ext.getCmp("noDef"); var noStatus = Ext.getCmp("noStatus"); if (newValue) { targetCol.setDisabled(true); } if (noStatus) { yes.setValue(false); no.setValue(true); } } } } ] }, {//0=預設(勾選啟用的才能設預設),最多1筆,非預設=1 xtype: 'radiogroup', // hidden: false, id: 'content_default', name: 'content_default', fieldLabel: ISDEFAULT, colName: 'content_default', width: 400, defaults: { name: 'content_default', margin: '0 8 0 0' }, columns: 2, vertical: true, items: [ { boxLabel: CONTENTDEFAULT, id: 'isDef', inputValue: '0' }, { boxLabel: NOCONTENTDEFAULT, id: 'noDef', inputValue: '1', checked: true } ] }, {//自行輸入(連結回吉甲地影音專區的某個影片) xtype: 'textfield', fieldLabel: LINKURL, allowBlank: false, vtype: 'url', id: 'link_url', name: 'link_url', maxLength: "255" }, // {//在那個頁面顯示(如food.php,life.php),空值代表不設限 // xtype: 'textfield', // fieldLabel: "顯示頁面", // allowBlank: false, // id: 'link_page', // name: 'link_page' // }, { xtype: 'combobox', //開新視窗 allowBlank: false, editable: false, fieldLabel: LINKMODE, id: 'link_mode', name: 'link_mode', hiddenName: 'link_mode', colName: 'link_mode', store: linkModelStore, displayField: 'link_mode_name', valueField: 'link_mode', typeAhead: true, queryMode: 'local', forceSelection: false, value: 1 }, keeditor ], buttons: [{ text: SAVE, formBind: true, disabled: true, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { var oldStatus = 0; //修改時原數據的狀態為不啟用,要修改為啟用時,並且當前啟用值大於等於限制值,並且值存在時才提示 if (Row) { oldStatus = Row.data.content_status; } Ext.Ajax.request({ url: "/WebContentType/GetDefaultLimit", method: 'post', async: false, //true為異步,false為同步 params: { storeType: "web_content_type4", site: "7", page: Ext.getCmp("page_id").getValue(), area: Ext.getCmp("area_id").getValue() }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { list_status_num = result.listNum; content_status_num = result.limitNum; } } }); if (Ext.getCmp("content_status").getValue().content_status == "1" && oldStatus == 0 && list_status_num >= content_status_num && content_status_num != 0) {//當選擇啟用並且已啟用數大於或等於最大限制值時提示是否執行 Ext.Msg.confirm(CONFIRM, Ext.String.format(STATUSTIP), function (btn) { if (btn == 'yes') { form.submit({ params: { rowid: Ext.htmlEncode(Ext.getCmp("content_id").getValue()), page_id: Ext.htmlEncode(Ext.getCmp("page_id").getValue()), area_id: Ext.htmlEncode(Ext.getCmp("area_id").getValue()), brand_id: Ext.htmlEncode(Ext.getCmp("brand_id").getValue()), content_status: Ext.htmlEncode(Ext.getCmp("content_status").getValue().content_status), content_default: Ext.htmlEncode(Ext.getCmp("content_default").getValue().content_default), link_url: Ext.htmlEncode(Ext.getCmp("link_url").getValue()), link_mode: Ext.htmlEncode(Ext.getCmp("link_mode").getValue()), home_text: $("#keeditor").val() // type_id: Ext.htmlEncode(Ext.getCmp("type_id").getValue()) }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success) { Ext.Msg.alert(INFORMATION, SUCCESS); store.load(); editWin.close(); } else { Ext.Msg.alert(INFORMATION, FAILURE); } }, failure: function () { Ext.Msg.alert(INFORMATION, FAILURE); } }); } else { return; } }); } else { form.submit({ params: { rowid: Ext.htmlEncode(Ext.getCmp("content_id").getValue()), page_id: Ext.htmlEncode(Ext.getCmp("page_id").getValue()), area_id: Ext.htmlEncode(Ext.getCmp("area_id").getValue()), brand_id: Ext.htmlEncode(Ext.getCmp("brand_id").getValue()), content_status: Ext.htmlEncode(Ext.getCmp("content_status").getValue().content_status), content_default: Ext.htmlEncode(Ext.getCmp("content_default").getValue().content_default), link_url: Ext.htmlEncode(Ext.getCmp("link_url").getValue()), link_mode: Ext.htmlEncode(Ext.getCmp("link_mode").getValue()), home_text: $("#keeditor").val() }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success) { Ext.Msg.alert(INFORMATION, SUCCESS); store.load(); editWin.close(); } else { Ext.Msg.alert(INFORMATION, FAILURE); } }, failure: function () { Ext.Msg.alert(INFORMATION, FAILURE); } }); } } } }] }); var editWin = Ext.create('Ext.window.Window', { title: WEBCONTENTTYPEFOUR, id: "editWin", iconCls: Row ? "icon-user-edit" : "icon-user-add", width: 800, height: 470, layout: 'fit', items: [editFrm], constrain: true, //束縛窗口在框架內 closeAction: 'destroy', modal: true, resizable: false, labelWidth: 60, bodyStyle: 'padding:5px 5px 5px 5px', closable: false, tools: [ { type: 'close', qtip: CLOSEFORM, handler: function (event, toolEl, panel) { Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn) { if (btn == "yes") { Ext.getCmp('editWin').destroy(); } else { return false; } }); } }], listeners: { // beforeclose: function (panel, eOpts) { // if (!confirm("是否確定關閉窗口?")) { // return false; // } // }, 'show': function () { if (Row) { editFrm.getForm().loadRecord(Row); //如果是編輯的話 initForm(Row); } else { editFrm.getForm().reset(); //如果是編輯的話 } } } }); editWin.show(); function initForm(row) { if (row.data.brand_id != 0) { Ext.getCmp("brand_id").setDisabled(false); } switch (row.data.content_status) { case 0: Ext.getCmp("noStatus").setValue(true); break; case 1: Ext.getCmp("isStatus").setValue(true); break; } switch (row.data.content_default) { case 0: Ext.getCmp("isDef").setValue(true); break; case 1: Ext.getCmp("noDef").setValue(true); break; } $("#keeditor").val(Row.data.content_html); Ext.getCmp('brand_id').setRawValue(Row.data.brand_name); // var img = row.data.content_image.toString(); // var imgUrl = img.substring(img.lastIndexOf("\/") + 1); // Ext.getCmp('content_image').setRawValue(imgUrl); } pageidStore.on('beforeload', function () { Ext.apply(pageidStore.proxy.extraParams, { type: 'page', webcontenttype_page: 'web_content_type4' }); }); pageidStore.load(); areaidStore.on('beforeload', function () { Ext.apply(areaidStore.proxy.extraParams, { type: 'area', pageid: Ext.getCmp('page_id').getValue() == null ? "0" : Ext.getCmp('page_id').getValue(), webcontenttype_page: 'web_content_type4' }); }); areaidStore.load(); }
app.controller('mainController', ['$scope', 'usersFactory', function($scope, usersFactory){ $scope.users; usersFactory.getUsers(function(users){ $scope.users = users }) var index = function(){ usersFactory.index(function(returnedData){ $scope.users = returnedData; }); }; index(); }])
//Instancia da classe boleto = new Boleto(); /* * Executa apos carregar a pagina */ $(document).ready(function () { boleto.init(); }); /* * Classe de boleto */ function Boleto() { this.init = function () { this.validaForm(); }; /** * valida o formulario */ this.validaForm = function () { $('#boleto_dtvenc').mask('99/99/9999'); //Adiciona mascara no campo valor $('#boleto_valor').maskMoney({ symbol: 'R$ ', thousands: '.', decimal: ',', symbolStay: true }); //Validação $("form").validate( { rules: { cedente_id: { required: true }, sacado_id: { required: true }, conta_id: { required: true }, boleto_valor: { required: true }, boleto_dtvenc: { required: true }, boleto_obs: { required: true }, boleto_obscaixa: { required: true } }, messages: { cedente_id: { required: 'Preenchimento Obrigatório' }, sacado_id: { required: 'Preenchimento Obrigatório' }, conta_id: { required: 'Preenchimento Obrigatório' }, boleto_valor: { required: 'Preenchimento Obrigatório' }, boleto_dtvenc: { required: 'Preenchimento Obrigatório' }, boleto_obs: { required: 'Preenchimento Obrigatório' }, boleto_obscaixa: { required: 'Preenchimento Obrigatório' } } }); }; this.popularConta = function (objCampo) { //Popula a grid de paramclientes var url_popula = baseUrl + '/boleto/listar-contas-cedente'; var objData = { cedente_id: objCampo.value }; geral.populaFiltering('conta_id', url_popula, objData, objCampo); } }
var express = require('express'); var app = express(); var PORT = process.env.PORT || 3000; var middleware = require('./middleware.js') app.get("/about", middleware.requireAuthentication, middleware.logger, function(req, res) { res.send("Another Route") }); app.use(express.static(__dirname + "/public")); app.listen(PORT);
import {ACTION_TYPE} from "../services/constants"; export const createItem = task => ({ type: ACTION_TYPE.CREATE_ITEM, payload: task }); export const deleteItem = id => ({ type: ACTION_TYPE.DELETE_ITEM, payload: id });
/** * Created by Administrator on 2016/9/5. */ Ext.define('Admin.model.historyPhoto.HistoryPhoto', { extend: 'Admin.model.Base', idProperty: 'id', fields: [ {name: 'id', type: 'int'}, {name: 'text', type: 'string'}, {name: 'brandName', type: 'string'}, {name: 'photoNumber', type: 'string'}, {name: 'condition', type: 'string'}, {name: 'specification', type: 'string'}, {name: 'versionName', type: 'string'}, {name: 'type', type: 'string'}, {name: 'model', type: 'string'}, {name: 'photoUrl', type: 'string'}, {name: 'dwgUrl', type: 'string'} ] });
window.addEventListener('DOMContentLoaded', () => { const menu = document.getElementById('header_menu'); menu.addEventListener('mouseover', (event) => { let target = event.target.closest('.header_menu-list'); if (!target) return; sliderMenuShow(target.getElementsByTagName('li')); }); menu.addEventListener('mouseout', (event) => { let target = event.target.closest('.header_menu-list'); if (!target) return; sliderMenuRemove(target.getElementsByTagName('li')); }); function sliderMenuShow(list) { console.log('sliderMenuShow'); list[0].parentNode.previousElementSibling.setAttribute('style', 'background: #aa9144; color: #EFFEF7;'); //list[0].parentNode.previousElementSibling.setAttribute('style', 'background: #8E7424'); list[0].parentNode.setAttribute('style', 'visibility: unset;'); let topAtrr = 0;//82; for (var i = 0; i < list.length; i++) { list[i].setAttribute('style', `top: ${topAtrr}px;`); topAtrr += 69; } } function sliderMenuRemove(list) { console.log('sliderMenuRemove'); for (var i = list.length-1; i >= 0; i--) { list[i].setAttribute('style', 'top: 0px;'); } list[0].parentNode.setAttribute('style', 'opacity: 0;'); list[0].parentNode.previousElementSibling.setAttribute('style', 'background: #effef7') } });
const WitnetRequestBoardProxy = artifacts.require("WitnetRequestBoardProxy") const addresses = require("./addresses.json") module.exports = function (deployer, network, accounts) { network = network.split("-")[0] if (network in addresses && addresses[network].WitnetRequestBoardProxy) { WitnetRequestBoardProxy.address = addresses[network].WitnetRequestBoardProxy } else { const WitnetRequestBoard = artifacts.require("WitnetRequestBoard") console.log(`> Migrating WitnetRequestBoard and WitnetRequestBoardProxy into ${network} network`) deployer.deploy(WitnetRequestBoard, [accounts[0]]).then(function () { return deployer.deploy(WitnetRequestBoardProxy, WitnetRequestBoard.address) }) } }
$(function() { $("#login-submit").click(function(e) { e.preventDefault(); $.post( "/api/v1/login", { email: $("#input-email").val(), password: $("#input-password").val(), }, function( data ) { $("#span-message").text("Success!"); window.location.href = "/"; }).fail(function(res) { if(res.status==403) { $("#span-message").text("Username and/or password incorrect!"); } }); $("#span-message").text("Logging in..."); }); });
const Engine = Matter.Engine; const World= Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; var engine, world; var ground1; var box1,box2,box3,box4,box5,box6,box7,box8,box9,box10,box11,box12,box13,box14,box15,box16,box17,box18,box19,box20; var backgroundImg; var box21; function preload() { //preload the images here backgroundImg = loadImage("images/GamingBackground.png"); } function setup() { createCanvas(1400,700); engine = Engine.create(); world = engine.world; // create sprites here ground = new Ground(500,500,1100,10); box1 = new Box(900,100,70,70); box2 = new Box(900,100,70,70); box3 = new Box(900,100,70,70); box4 = new Box(900,100,70,70); box5 = new Box(900,100,70,70); box6 = new Box(900,100,70,70); box7 = new Box(800,100,70,70); box8= new Box(800,100,70,70); box9 = new Box(800,100,70,70); box10 = new Box(800,100,70,70); box11= new Box(800,100,70,70); box12= new Box(800,100,70,70); box13= new Box(700,100,70,70); box14= new Box(700,100,70,70); box15= new Box(700,100,70,70); box16= new Box(700,100,70,70); box17= new Box(1000,100,70,70); box18= new Box(1000,100,70,70); box19= new Box(1000,100,70,70); box20= new Box(1000,100,70,70); block21= new Box1(1100,190,30,30); ball= new Ball(200,200,50,50); rope = new Rope(ball.body,{x:500,y:180}); } function draw() { background(backgroundImg); //drawSprites(); Engine.update(engine); ground.display(); block21.display(); box1.display(); box2.display(); box3.display(); box4.display(); box5.display(); box6.display(); box7.display(); box8.display(); box9.display(); box10.display(); box11.display(); box12.display(); box13.display(); box14.display(); box15.display(); box16.display(); box17.display(); box18.display(); box19.display(); box20.display(); ball.display(); rope.display(); } function mouseDragged(){ Matter.Body.setPosition(ball.body, {x: mouseX , y: mouseY}); }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _CreateEvent = require('./CreateEvent'); var _CreateEvent2 = _interopRequireDefault(_CreateEvent); var _UpdateEvent = require('./UpdateEvent'); var _UpdateEvent2 = _interopRequireDefault(_UpdateEvent); var _DeleteEvent = require('./DeleteEvent'); var _ReadEvent = require('./ReadEvent'); var _socket = require('../socket'); var _initialize = require('./../initialize'); var _initialize2 = _interopRequireDefault(_initialize); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EVENT_NAME = _initialize2.default.get('eventName'); /** * Run init * @param {Object} _io * @param {String} host */ var deploy = function deploy($io, host) { var io = $io.of(host); io.on(EVENT_NAME.connection, function (client) { _socket.listOnline.list[client.id] = client.id; _socket.listOnline.count++; console.log('user ' + client.id + ' connect count now == ' + _socket.listOnline.count); (0, _ReadEvent.listenerRequest)(client, EVENT_NAME.data, EVENT_NAME.message); (0, _ReadEvent.listenerFindData)(client, EVENT_NAME.find); (0, _CreateEvent2.default)(client, EVENT_NAME.create, EVENT_NAME.afterCreate); (0, _UpdateEvent2.default)(client, EVENT_NAME.update, EVENT_NAME.afterUpdate); (0, _DeleteEvent.deleteEvent)(client, EVENT_NAME.delete, EVENT_NAME.afterDelete); /** ----------------active when some people diconnect------------ */ client.on(EVENT_NAME.disconnect, function () { delete _socket.listOnline.list[client.id]; _socket.listOnline.count--; console.log(client.id + ' has left count = ' + _socket.listOnline.count); }); }); }; exports.default = deploy;
import React from 'react' import { Link } from 'react-router-dom'; import './navBar.css' import mcssLogo from '../../mcssLogo.svg'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faFacebook, faTwitter, faDiscord, faInstagram } from "@fortawesome/free-brands-svg-icons" export default class Nav extends React.Component { state = { menuActive: false } toggleMenuActive = () => { this.setState({ menuActive: !this.state.menuActive }); } render() { return ( <div className="menu-container"> <div className={this.state.menuActive ? 'menu active' : 'menu'}> <div className="blank" /> <div className="mcss-logo-container"> <img src={mcssLogo} className="mcss-logo" /> </div> <div className="content-wrap"> <ul className="extra"> <li className="nav-text"> <Link to="/"> <span> Home </span> </Link> </li> <li className="nav-text"> <Link to="/team"> <span> The Team </span> </Link> </li> <li className="nav-text"> <Link to="/announcements"> <span> Announcements </span> </Link> </li> <li className="nav-text"> <Link to="/events"> <span> Events </span> </Link> </li> <li className="nav-text"> <Link to="/partnerClubs"> <span> Partner Clubs </span> </Link> </li> <li className="nav-text"> <Link to=""> <span> Shopify </span> </Link> </li> </ul> <div className="social-media"> <a href="https://www.facebook.com/utmmcss/"> <FontAwesomeIcon icon={faFacebook} /> </a> <a href="https://discord.com/invite/5K3TuF7DkY"> <FontAwesomeIcon icon={faDiscord} /> </a> <a href="https://www.instagram.com/utmmcss/"> <FontAwesomeIcon icon={faInstagram} /> </a> <a href="https://twitter.com/utmmcss"> <FontAwesomeIcon icon={faTwitter} /> </a> </div> </div> </div> </div> ) } }
import * as BN from 'bn.js'; class SignatureDataCodec { constructor(cryptoUtils, ec) { this.cryptoUtils = cryptoUtils; this.ec = ec; } EncodePublicKey(publicKey) { return this.EncodeEllipticCurvePoint(publicKey); } DecodePublicKey(publicKeyHex) { return this.DecodeEllipticCurvePoint(publicKeyHex); } EncodeRCommitment(RCommitment) { return this.EncodeBigNum(RCommitment); } DecodeRCommitment(RCommitmentHex) { return this.DecodeBigNum(RCommitmentHex); } EncodeRPoint(RPoint) { return this.EncodeEllipticCurvePoint(RPoint); } DecodeRPoint(RPointHex) { return this.DecodeEllipticCurvePoint(RPointHex); } EncodeSignatureContribution(signatureContribution) { return this.EncodeBigNum(signatureContribution); } DecodeSignatureContribution(signatureContributionHex) { return this.DecodeBigNum(signatureContributionHex); } EncodeEllipticCurvePoint(pubKeyPoint) { return this.cryptoUtils.ByteArrayToHex(this.ec.encodePoint(pubKeyPoint)); } DecodeEllipticCurvePoint(pubKeyHex) { let byteArray = this.cryptoUtils.HexToByteArray(pubKeyHex); let jsArray = Array.from(byteArray); return this.ec.decodePoint(jsArray); } EncodeBigNum(bigNum) { return bigNum.toString(16).toUpperCase(); } DecodeBigNum(bigNumHex) { return new BN.BN(bigNumHex, 16); } } export default SignatureDataCodec;
(function($) { if (typeof($.fn.changeClass) === 'undefined') { $.fn.changeClass = function(del, add) { return this.removeClass(del).addClass(add); } }; if (typeof($.fn.slide) !== 'undefined') { return; }; $.fn.slide = function(options) { var o = $.extend({ c: 'auto', p: 3000, d: 600, move: 1, effect1: 'swing' }, options || {}); this.move = function() { o.move = 1; }; this.stop = function() { o.move = 0; }; this.kill = function() { o.move = -1; } return this.each(function() { var sld = $(this); if (!sld[0]) return; var uls = $('ul', sld), xP = uls.eq(0), nP = uls.eq(1), tP = uls.eq(2), xl = $('li', xP), nl = $('li', nP), tl = $('li', tP), i = 0, pause = null; if (o.c == 'auto') { o.c = Math.min(xl.length, nl.length, tl.length); nl.slice(o.c).hide(); } xP.add(nP).add(tP).hover(function() { o.move = o.move > -1 ? 0 : -1; }, function() { o.move = o.move > -1 ? 1 : -1; }); nl.each(function(j, e) { $(e).bind('mouseenter', function() { s_active($(e), j) }); }); function s_active(e, j) { if (i == j) return; i = j; go(); }; go(); function go() { if (pause) { clearInterval(pause); pause = null; }; xl.stop().eq(i).animate({ opacity: 1 }, { complete: function() { xl.eq(i).css({ 'z-index': 95 }).siblings().css({ 'z-index': 94 }); if (o.move < 0) { kill(); return; } pause = setInterval(function() { if (o.move > 0) { i++; if (i >= o.c) i = 0; go(); } }, o.p); }, duration: o.d, easing: o.effect1 }).siblings().animate({ opacity: 0 }, o.d, o.effect1); nl.eq(i).addClass('s_on').siblings().removeClass('s_on'); tl.eq(i).css({ display: 'block' }).siblings().css({ display: 'none' }); }; function kill() { clearInterval(pause); pause = null; } }); } })(jQuery); var $slide; $(function() { $slide = $('#slide').slide({ d: 1200, p: 2500, effect1: 'swing' }); });
import { Http } from "../utils/http"; class Coupon{ constructor(){} static async CollectCoupon(id){ const res = await Http.request({ url:`/coupon/collect/${id}`, method:"POST" }) return res } static async getMyAviableCoupons(){ const res = await Http.request({ url:'/coupon/myself/available/with_category' }) return res.data } static async getMyCouponsByStatus(status){ const res = await Http.request({ url:`/coupon/myself/by/status/${status}` }) return res.data } } export{ Coupon }
$(document).ready(function () { $('#story5').on('mouseenter', function () { $('#kings').fadeIn("4000"); $('#title').hide(); $(this).css({ "text-decoration": "underline" }); }).on('mouseleave', function () { $('#kings').fadeOut("4000"); $('#title').fadeIn("6000"); $(this).css({ "text-decoration": '' }); });; }); $(document).ready(function () { $('#story1').on('mouseenter', function () { $('#hearteater').fadeIn("4000"); $('#title').hide(); $(this).css({ "text-decoration": "underline" }); }).on('mouseleave', function () { $('#hearteater').fadeOut("4000" ); $('#title').fadeIn("6000"); $(this).css({ "text-decoration": '' }); });; }); $(document).ready(function () { $('#story2').on('mouseenter', function () { $('#elzvar').fadeIn("4000"); $('#title').hide( ); $(this).css({ "text-decoration": "underline" }); }).on('mouseleave', function () { $('#elzvar').fadeOut("4000" ); $('#title').fadeIn("6000" ); $(this).css({ "text-decoration": '' }); });; }); $(document).ready(function () { $('#story3').on('mouseenter', function () { $('#summeraftersunset').fadeIn("4000" ); $('#title').hide( ); $(this).css({ "text-decoration": "underline" }); }).on('mouseleave', function () { $('#summeraftersunset').fadeOut("4000" ); $('#title').fadeIn("6000" ); $(this).css({ "text-decoration": '' }); });; }); $(document).ready(function () { $('#story4').on('mouseenter', function () { $('#draupadi').fadeIn("4000"); $('#title').hide(); $(this).css({ "text-decoration": "underline" }); }).on('mouseleave', function () { $('#draupadi').fadeOut("4000"); $('#title').fadeIn("6000"); $(this).css({ "text-decoration": '' }); });; }); console.log("tacos")
(function ($) { //cache body element to search later window.chik.instance(new chik.app ( 'body' )); //all init stuff goes in here jQuery(document).ready(function () { //foundation init: $(document).foundation(); if($("#payment-form").length > 0){ var checkoutService = new chik.checkout({app: chik.instance(), container: chik.instance().canvas, publishedKey: 'pk_test_RnykagDpbDN2sU20PwHtY2bg'}) checkoutService.initialize(); } }); })(jQuery);
const getDOMElements = () => { return { dateInput: document.querySelector('.dateInput'), outputRes: document.querySelector(".outputRes"), container: document.querySelector(".container") } } const reverseString = (stringToReverse) => { const stringArr = stringToReverse.split(''); stringArr.reverse(); return stringArr.join(''); } const isPallindrome = (stringToCheck) => { return stringToCheck === reverseString(stringToCheck); } const convertDateToString = (date) => { const dateStr = {day: '',month: '',year: ''}; let dayString = date.day.toString(); let monthString = date.month.toString(); if(date.day < 10){ dayString = '0' + date.day.toString(); } if(date.month < 10){ monthString = '0' + date.month.toString(); } dateStr.day = dayString; dateStr.month = monthString; dateStr.year = date.year.toString(); return dateStr; } const getAllDateFormats = (date) => { const dateStrObject = convertDateToString(date); const ddmmyyyy = dateStrObject.day + dateStrObject.month + dateStrObject.year; const mmddyyyy = dateStrObject.month + dateStrObject.day + dateStrObject.year; const yyyymmdd = dateStrObject.year + dateStrObject.month + dateStrObject.day; const ddmmyy = dateStrObject.day + dateStrObject.month + dateStrObject.year.slice(-2); const mmddyy = dateStrObject.month + dateStrObject.day + dateStrObject.year.slice(-2); const yymmdd = dateStrObject.year.slice(-2) + dateStrObject.month + dateStrObject.day; return [ddmmyyyy,mmddyyyy,yyyymmdd,ddmmyy,mmddyy,yymmdd]; } const checkPallindromeForAllDateFormats = (date) => { const allDateFormats = getAllDateFormats(date); let pallindromeFound = false; allDateFormats.some(dateFormat => { if(isPallindrome(dateFormat)){ pallindromeFound = true; return true; } }); return pallindromeFound; } const isLeapYear = (year) => { if(year%400 === 0){ return true; } if(year%100 === 0){ return false; } if(year%4 === 0){ return true; } return false; } const getFuturePallindromicDate = (date) => { let gapOfFutureDays = 0; let daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; while(true){ if(checkPallindromeForAllDateFormats(date)){ break; } if(isLeapYear(date.year)){ daysInMonth[1] = 29; } else{ daysInMonth[1] = 28; } gapOfFutureDays += 1; if(date.day === daysInMonth[date.month-1]){ date.day = 1; if(date.month === 12){ date.month = 0; date.year += 1; } date.month += 1; } else{ date.day += 1; } } return [gapOfFutureDays,date]; } const getPastPallindromicDate = (date) => { let gapOfPastDays = 0; let daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; while(true){ if(checkPallindromeForAllDateFormats(date)){ break; } if(isLeapYear(date.year)){ daysInMonth[1] = 29; } else{ daysInMonth[1] = 28; } gapOfPastDays += 1; if(date.day === 1){ if(date.month === 1){ date.month = 12; date.year -= 1; } date.month -= 1; date.day = daysInMonth[date.month]; } else{ date.day -= 1; } } return [gapOfPastDays,date]; } const getNearestDate = (date) => { let currentDate1 = {...date}; const [gapOfPastDays,pastPallindromicDate] = getPastPallindromicDate(currentDate1); let currentDate2 = {...date}; const [gapOfFutureDays,futurePallindromicDate] = getFuturePallindromicDate(currentDate2); if(gapOfFutureDays < gapOfPastDays){ return ["future",gapOfFutureDays,futurePallindromicDate]; } else{ return ["past",gapOfPastDays,pastPallindromicDate]; } } const constructDate = (date) => { return date.day.toString() + "-" + date.month.toString() + "-" + date.year.toString(); } const handleClick = () => { const dateInputVal = getDOMElements().dateInput.value; if(dateInputVal){ const dateInputArr = dateInputVal.split('-'); let date = { day: parseInt(dateInputArr[2]), month: parseInt(dateInputArr[1]), year: parseInt(dateInputArr[0]) }; if(checkPallindromeForAllDateFormats(date)){ getDOMElements().outputRes.innerHTML = "Hurray! your birthday is pallindromic date"; getDOMElements().container.style.backgroundColor = "#D1FAE5"; } else{ const [timeLine,gap,pallindromicDate] = getNearestDate(date); getDOMElements().outputRes.innerHTML = "You missed by " + gap + " days from " + timeLine + " date i.e " + constructDate(pallindromicDate); getDOMElements().container.style.backgroundColor = "#FEE2E2"; } } else{ alert("enter date"); } }
import { Record } from 'immutable' import Inventory from './Inventory' const defaultValues = { id: '', location: '', name: '', age: '', gender: '', lonlat: null, latitude: null, longitude: null, created_at: null, updated_at: null, infected: false, inventory: new Inventory(), } export default class People extends Record(defaultValues, People) { constructor(values) { let location = null if (values.location && values.location.split('/')) { location = values.location.split('/') } super({ ...values, id: location ? location[location.length - 1] : defaultValues.id, }) } }
import Koa from 'koa' const consola = require('consola') const { Nuxt, Builder } = require('nuxt') var ws = require("nodejs-websocket") var port=3101; var user=0; // Create a connection var server = ws.createServer(function (conn) { console.log("Create a new connection --------"); user++; conn.nickname="anonymous" + user; var mes = {}; mes.type = "enter"; mes.data = conn.nickname + " Come in!" broadcast(JSON.stringify(mes)); //Push the message to the client conn.on("text", function (str) { console.log("reply "+str) mes.type = "message"; mes.data = conn.nickname + " said: " + str; broadcast(JSON.stringify(mes)); }); //Listen to close connection operations conn.on("close", function (code, reason) { console.log("Close the connection"); mes.type = "leave"; mes.data = conn.nickname+" left" broadcast(JSON.stringify(mes)); }); //Error handling conn.on("error", function (err) { console.log("Error detected"); console.log(err); }); }).listen(port); function broadcast(str){ server.connections.forEach(function(connection){ connection.sendText(str); }) } /*import ws from 'nodejs-websocket' console.log("开始建立连接...") var server = ws.createServer(function(conn){ conn.on("text", function (webText) { console.log("message:"+webText) conn.sendText(webText); }) conn.on("close", function (code, reason) { console.log("关闭连接") }); conn.on("error", function (code, reason) { console.log("异常关闭") }); }).listen(8001) console.log("WebSocket建立完毕") */ // 包的加载 import mongoose from 'mongoose' import bodyParser from 'koa-bodyparser' // 处理post请求 很重要 import session from 'koa-generic-session' import Redis from 'koa-redis' import json from 'koa-json' // json格式美观 import dbConfig from './dbs/config' import passport from './interface/utils/passport' import users from './interface/users' //users接口 import geo from './interface/geo' //geo接口 import search from './interface/search' //search接口 import categroy from './interface/categroy' //categroy接口 import cart from './interface/cart' //cart接口 import Order from './interface/order' //order接口 // import city from './interface/city' //city接口 const app = new Koa() // Import and Set Nuxt.js options const config = require('../nuxt.config.js') config.dev = app.env !== 'production' async function start() { // Instantiate nuxt.js const nuxt = new Nuxt(config) const { host = process.env.HOST || '127.0.0.1', port = process.env.PORT || 3000 } = nuxt.options.server app.keys = ['mt', 'keyskeys'] app.proxy = true app.use(session({ // session的配置 key: 'mt', prefix: 'mt:uid', store: new Redis() })) app.use(bodyParser({ extendTypes: ['json', 'form', 'text'] })) app.use(json()) // 连接数据库 mongoose.connect(dbConfig.dbs, { useNewUrlParser: true }) app.use(passport.initialize()) app.use(passport.session()) // Build in development if (config.dev) { const builder = new Builder(nuxt) await builder.build() } else { await nuxt.ready() } app.use(users.routes()).use(users.allowedMethods()) // 引进路由,users路由 app.use(geo.routes()).use(geo.allowedMethods()) // 引进路由,geo路由 app.use(search.routes()).use(search.allowedMethods()) // 引进路由,search路由 app.use(categroy.routes()).use(categroy.allowedMethods()) // 引进路由,categroy路由 app.use(cart.routes()).use(cart.allowedMethods()) // 引进路由,cart路由 app.use(Order.routes()).use(Order.allowedMethods()) // 引进路由,order路由 app.use((ctx) => { ctx.status = 200 ctx.respond = false // Bypass Koa's built-in response handling ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash nuxt.render(ctx.req, ctx.res) }) app.listen(port, host) consola.ready({ message: `Server listening on http://${host}:${port}`, badge: true }) } start()
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _react = _interopRequireWildcard(require("react")); var _immutabilityHelper = _interopRequireDefault(require("immutability-helper")); var _prepareSpec = _interopRequireDefault(require("./prepare-spec")); var _default = function _default(spec, onChange) { return function (C) { var _temp; return _temp = /*#__PURE__*/ function (_Component) { (0, _inherits2.default)(_temp, _Component); function _temp(props) { var _this; (0, _classCallCheck2.default)(this, _temp); _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(_temp).call(this, props)); (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleUpdate", function (path, spec) { spec = path.split('.').reverse().reduce(function (p, n) { return (0, _defineProperty2.default)({}, n, p); }, spec); var state = (0, _immutabilityHelper.default)(_this.state, spec); (0, _prepareSpec.default)(state.spec, 'spec', _this.handleUpdate); _this.setState(state, function () { return _this.onChange && _this.onChange(state.spec); }); }); (0, _prepareSpec.default)(spec, 'spec', _this.handleUpdate); _this.state = { spec: spec }; _this.onChange = onChange; return _this; } (0, _createClass2.default)(_temp, [{ key: "render", value: function render() { // console.log('[render]', this.state.spec); return _react.default.createElement(C, (0, _extends2.default)({}, this.props, { spec: this.state.spec })); } }]); return _temp; }(_react.Component), _temp; }; }; exports.default = _default;
'use strict'; var toyAsm = function() { return { defaultPc: function() { return 0x10 } }; }(); toyAsm.createError = function(name, preamble, opcode, line) { return { name: name, line: line, message: preamble + ', line ' + line + ': ' + opcode } }; toyAsm.assemble = function(code) { var check = function(opcode, regex, exception) { if(opcode.toUpperCase().match(regex) === null) { throw exception; } }; var opcodes = _.filter(code.trim().split("\n"),function(op) { return op !== "" }); opcodes = _.map(opcodes, function(o) { return o.trim(); }); _.each(opcodes, function(op,idx) { check(op,/^[0-9,A-F]+$/, toyAsm.createError("syntax", "syntax error", op, idx + 1)); check(op,/^[0-9,A-F]{4}$/, toyAsm.createError( "invalid", "invalid opcode", op, idx + 1)); }); var header = ["0",toyAsm.defaultPc().toString(16)]; return Uint16Array.from(_.map(header.concat(opcodes), function(op) { return parseInt(op,16); })); }; toyAsm.serialize = function(bytes) { return _.map(bytes, function(b) { return sprintf('%04x',b); }).join(''); }; toyAsm.deserialize = function(hex) { var chunk = function(hex) { return hex.match(/(.{4})/g); } var parse = function(vals) { return _.map(vals, function(i) { return parseInt(i,16); }); }; return Uint16Array.from(parse(chunk(hex))); };
/* eslint-disable react/prop-types */ import React from 'react'; import './index.css'; import profilePlaceholder from '../../images/event-img-placeholder.jpg'; /** * @Params * _id => id of user * username => username of user * bio => bio of user * * @summary * Displays a custom component for a user card showing the user image, * username and user bio * * @returns * Returns JSX component to display user information */ const UserCard = (props) => { const { username, bio, } = props; return ( <a href={`/user/${username}`}> <div className="user-card-container"> <img className="user-card-profile" src={profilePlaceholder} alt="User Profile" /> <div className="user-card-info"> <h4 className="user-card-username">{username}</h4> <p className="user-card-bio">{bio}</p> </div> </div> </a> ); }; export default UserCard;
let hasOwn = require('./hasOwn') let _hasDontEnumBug, _dontEnums function checkDontEnum() { _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ] _hasDontEnumBug = true for (let key in {'toString': null}) { _hasDontEnumBug = false } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj) { let key, i = 0 // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum() for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break } } if (_hasDontEnumBug) { let ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break } } } } } function exec(fn, obj, key, thisObj) { return fn.call(thisObj, obj[key], key, obj) } module.exports = forIn
/*TMODJS:{"version":13,"md5":"97aa93638471d0c78644c1df19c8cbe5"}*/ define(function(require) { return require("../template")("info/goods", function($data, $id) { var $helpers = this, $each = $helpers.$each, data = $data.data, $value = $data.$value, $index = $data.$index, $escape = $helpers.$escape, $out = ""; $each(data.likegoodslist, function($value, $index) { $out += ' <li class="mb_10 sh"> <dl> <dt><a href="'; $out += $escape($value.goods_url); $out += '"><img src="'; $out += $escape($value.goods_pic); $out += '"></a></dt> <dd class="clearfix"> <span class="fl mr_10">'; $out += $escape($value.goods_name.length > 8 ? $value.goods_name.substring(0, 8) + "..." : $value.goods_name); $out += '</span> <span class="fl pink">'; $out += $escape($value.goods_price); $out += '</span> <!-- <span class="fr" script-role="fav" target="'; $out += $escape($value.like_url); $out += '" is_like="1" gid="'; $out += $escape($value.goods_id); $out += '">取消收藏</span> --> </dd> </dl> </li> '; }); return new String($out); }); });
import { createSlice } from 'redux-starter-kit'; import { LAYOUT_TYPE_FULL, NAV_STYLE_DARK_HORIZONTAL, THEME_COLOR_SELECTION_PRESET, THEME_TYPE_DARK } from '../../../constants/ThemeSetting'; const themeSettingsSlice = createSlice({ name: 'screens', initialState: { navCollapsed: true, navStyle: NAV_STYLE_DARK_HORIZONTAL, layoutType: LAYOUT_TYPE_FULL, themeType: THEME_TYPE_DARK, colorSelection: THEME_COLOR_SELECTION_PRESET, pathname: '', width: window.innerWidth, isDirectionRTL: false, locale: { languageId: 'english', locale: 'en', name: 'English', icon: 'us' } }, reducers: { toggleCollapsedNav(state, action) { console.log(action); state.navCollapsed = action.payload; }, updateWindowWidth(state, action) { state.width = action.payload; }, setThemeType(state, action) { state.themeType = action.payload; }, setThemeColorSelection(state, action) { state.colorSelection = action.payload; }, changeNavStyle(state, action) { state.navStyle = action.payload; }, changeLayoutType(state, action) { state.layoutType = action.payload; }, switchLanguage(state, action) { state.locale = action.payload; } } }); export const { toggleCollapsedNav, updateWindowWidth, setThemeType, setThemeColorSelection, changeNavStyle, changeLayoutType, switchLanguage } = themeSettingsSlice.actions; export default themeSettingsSlice.reducer;
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var DocumentClient = require('documentdb').DocumentClient; var endpoint = 'https://doccomments.documents.azure.com:443/'; var authKey = 'yHeqan1UnL2i410PgBYzYTXalmTgKpzhVm4rzDnKNvVXWeAd9KsZx1oqFFrXTK18wa8qdErW8zpdB1emkZumyg=='; var commentsCollection = 'dbs/OfficeAddins/colls/Comments'; app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); var port = process.env.PORT || 8080; var router = express.Router(); // var helloWorldStoredProc = { // id: 'helloWorld', // body: function(){ // var context = getContext(); // var response = context.getResponse(); // response.setBody('Would you like to play a game?'); // } // }; router.get('/:url', function(req, res){ var client = new DocumentClient(endpoint, {"masterKey": authKey}); // var context = getContext(); // var collection = context.getCollection(); var query = "SELECT * FROM docs d WHERE d.url='" + req.params.url + "'"; console.log(query); client.queryDocuments(commentsCollection, query).toArray(function(err, results){ res.json(results); }); }); router.post('/createComments', function(req,res){ var client = new DocumentClient(endpoint, {"masterKey": authKey}); var doc = { url: req.body.url, identifier: req.body.identifier, comment: req.body.comment, user: req.body.user, date: req.body.date }; client.createDocument(commentsCollection, doc, function(err, document){ res.json(document); }); }); app.use('/api', router); app.listen(port); console.log('Party is on port ' + port); // var databaseDefinition = {'id':'OfficeAddins'}; // var collectionDefinition = {'id': 'Comments'}; // var documentDefinition = { // 'id':'blaap', // 'stuff':'hello world', // 'bibbidi': { // 'bobbidi': 'boo' // } // }; // client.createDatabase(databaseDefinition, function(err, database) { // client.createCollection(database._self, collectionDefinition, function(err,collection){ // client.createDocument(collection._self, documentDefinition, function(err, document){ // client.queryDocuments(collection._self, "SELECT * FROM docs d WHERE d.bibbidi.bobbidi = 'boo'").toArray(function(err, results){ // console.log('RESULTS: '); // console.log(results); // }); // }); // }); // });
import React from 'react' import Layout from '../components/layout' const AboutPage = () => { return ( <Layout> <p>Info coming soon</p> </Layout> ) } export default AboutPage
// @flow import * as React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import setStatic from 'recompose/setStatic'; import compose from 'recompose/compose'; import InputGroupAddon from './InputGroupAddon'; import InputGroupButton from './InputGroupButton'; import { prefix, withStyleProps, defaultProps } from './utils'; type Props = { className?: string, classPrefix: string, inside?: boolean, disabled?: boolean, children?: React.Node }; type State = { focus?: boolean }; class InputGroup extends React.Component<Props, State> { static childContextTypes = { inputGroup: PropTypes.object.isRequired }; constructor(props: Props) { super(props); this.state = { focus: false }; } getChildContext() { return { inputGroup: { onFocus: this.handleFocus, onBlur: this.handleBlur } }; } handleFocus = () => { this.setState({ focus: true }); }; handleBlur = () => { this.setState({ focus: false }); }; disabledChildren() { const { children } = this.props; return React.Children.map(children, item => { if (React.isValidElement(item)) { return React.cloneElement(item, { disabled: true }); } return item; }); } render() { const { className, classPrefix, disabled, inside, children, ...props } = this.props; const { focus } = this.state; const addPrefix = prefix(classPrefix); const classes = classNames(classPrefix, className, { [addPrefix('inside')]: inside, [addPrefix('focus')]: focus, [addPrefix('disabled')]: disabled }); return ( <div {...props} className={classes}> {disabled ? this.disabledChildren() : children} </div> ); } } const EnhancedInputGroup = compose( withStyleProps({ hasSize: true }), defaultProps({ classPrefix: 'input-group' }) )(InputGroup); setStatic('Addon', InputGroupAddon)(EnhancedInputGroup); setStatic('Button', InputGroupButton)(EnhancedInputGroup); export default EnhancedInputGroup;
import React from 'react' export default function User({details}) { if (!details) { return <h3>Working fetching your friend&apos;s details...</h3> } return ( <div className='user-div'> <h2>{details.first_name} {details.last_name}</h2> <h2>{details.username}</h2> <p>Email: {details.email}</p> <p>Role: {details.role}</p> <p>Password: {details.password}</p> <p></p> </div> ) }
/** * Defining Routes for the application */ // Importing Controllers let userController = require('./controllers/user.controller'); let orderController = require('./controllers/order-list.controller'); let viewController = require('./controllers/view.controller'); let productController = require('./controllers/product.controller'); //Importing Auth gaurd let auth = require('./authGaurd').auth; module.exports = (app) =>{ // Public Apis app.get('/',viewController.loginView); app.get('/register',viewController.registerView); app.get('/product',viewController.productView); app.get('/api', userController.index); app.put('/api/users/', userController.register); app.post('/api/users/', userController.login); // Protected Api app.get('/api/users/:userid',auth, userController.getUser); app.get('/api/orders', orderController.createOrder); app.get('/api/orders/list',auth, orderController.orderList); app.get('/api/product/', productController.createProduct); app.get('/api/product/list',auth, productController.getProducts); app.put('/api/product',auth, productController.buyProduct); };
import React from 'react' import {Image} from 'react-native' const color = { p1 : '#5700f9', //purple p2: '#4501c1', //darker purple p3: '#9055fc', //lighter purple b1: '#686868', //gray b2: '#3f3f3f', //darker gray b3: '#2b2b2b', //darkes gray t1: '#000000', //white t2: '#3f3f3f', //dark gray t3: '#4501c1', //darker purple cb1: 'rgba(104, 104, 104, .5)', cb2: 'rgba(63, 63, 63, .5)', cb3: 'rgba(43, 43, 43,.5)' } images = { logo: 'https://i.imgur.com/18JK6oE.jpg', background: 'https://i.imgur.com/aWKOJsf.jpg' } const header = { headerTintColor: 'white', headerStyle: { backgroundColor: color.b3, borderBottomColor: color.b2, borderBottomWidth: 3, }, headerTitleStyle: { fontSize: 18, }, headerRight: ( <Image style={{width:60,height:40}} source={{uri: 'https://i.imgur.com/18JK6oE.jpg'}}/> ), } const MyStyles = { color, header, images } export default MyStyles
const cloudbuild_utils = require('./src/cloudbuild_utils'); const config = require('./src/config') const approval = require('./src/approval') const eventToBuild = (data) => { return JSON.parse(new Buffer(data, 'base64').toString()); } function isDuplicate(req) { if (req.headers['x-slack-retry-num']) { // this is a retry, don't process. TODO: find a better solution console.log('Message was retried, ignoring'); return true; } return false; } exports.gcpCiCdSlackEvents = (event, context) => { const build = eventToBuild(event.data); console.log(JSON.stringify(build)); const repo = config.getRepo(build.substitutions.REPO_NAME) if (repo && build.substitutions.TAG_NAME) { cloudbuild_utils.handleProductionDeployment(build, repo) .then(() => {}).catch(err => console.log(err)); } else if (repo) { cloudbuild_utils.handleBranchAndPRBuilds(build, repo).then(()=>{}); } }; exports.gcpCiCdApprovalAction = (req, res) => { if (isDuplicate(req)) { res.sendStatus(200); return; } if (req.method === 'POST') { approval.processAction(req.body).then(() => {}); } res.sendStatus(200); }
const _ = require('lodash'); const { Album } = require('../models/album'); const { Song } = require('../models/song'); const { Artist } = require('../models/artist'); const { User } = require('../models/user'); exports.search = async (req, res) => { const query = new RegExp(req.query.q.trim(), 'gi'); const songs = await Song.find({ $text: { $search: query } }) .select(['_id', 'title']) .populate('album artist'); const albums = await Album.find({ $text: { $search: query } }) .select(['_id', 'title']) .populate({ path: 'songs', populate: 'album artist' }); const artists = await Artist.find({ $text: { $search: query } }) .select(['_id', 'stageName']) .populate({ path: 'songs', populate: 'album artist' }); const users = await User.find({ $text: { $search: query } }) .select(['_id', 'firstName', 'lastName']); if (_.isEmpty(songs) && _.isEmpty(albums) && _.isEmpty(artists) && _.isEmpty(users)) { return res.status(404).send({ success: false, message: 'we could not find what you are looking for' }); } const results = { songs, albums, artists, users }; res.status(200).send({ success: true, data: results }); };
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import '../App.css'; import 'react-responsive-carousel/lib/styles/carousel.min.css'; import { Carousel } from 'react-responsive-carousel'; class About extends Component { // we have used it so that when we open our page it opens from the top componentDidMount() { window.scrollTo(0, 0) } render(){ return( <div className="main"> <div className='About'> <br /> </div> <br/> <br/> <div className='subabout'> About <img src="https://imgur.com/NUVy1oN.jpg" id="hills"/></div> <div className='card cardabout'> <Carousel autoPlay="true" infiniteLoop="true" className="img1"> <img src="https://imgur.com/yXslPdG.jpg" alt="painting" /> <img src="https://imgur.com/31XyE3j.jpg" alt="painting" /> <img src="https://imgur.com/qV8uwzd.jpg" alt="painting" /> </Carousel> <p className='text'> Lorem ipsum dolor sit amet, ad his alii mandamus, at qui amet suscipit dissentiet. Errem ceteros luptatum at vim, aeque perfecto pro an. Pro eu veniam iriure, ea iriure adipiscing efficiantur duo. Putant sadipscing eum ei, noster tamquam mnesarchum ut duo. Fugit graece laoreet nam ne, causae consectetuer in eos. Vix brute veniam equidem an, et vis velit quaeque, postulant adolescens et has. <br/> Lorem ipsum dolor sit amet, ad his alii mandamus, at qui amet suscipit dissentiet. Errem ceteros luptatum at vim, aeque perfecto pro an. Pro eu veniam iriure, ea iriure adipiscing efficiantur duo. Putant sadipscing eum ei, noster tamquam mnesarchum ut duo. Fugit graece laoreet nam ne, causae consectetuer in eos. Vix brute veniam equidem an, et vis velit quaeque, postulant adolescens et has. <br/> Lorem ipsum dolor sit amet, ad his alii mandamus, at qui amet suscipit dissentiet. Errem ceteros luptatum at vim, aeque perfecto pro an. Pro eu veniam iriure, ea iriure adipiscing efficiantur duo. Putant sadipscing eum ei, noster tamquam mnesarchum ut duo. Fugit graece laoreet namne, causae consectetuer in eos. Vix brute veniam equidem an, et vis velit quaeque, postulant adolescens et has. <br/> Lorem ipsum dolor sit amet, ad his alii mandamus, at qui amet suscipit dissentiet. Errem ceteros luptatum at vim, aeque perfecto pro an. Pro eu veniam iriure, ea iriure adipiscing efficiantur duo. Putant sadipscing eum ei, noster tamquam mnesarchum ut duo. Fugit graece laoreet namne, causae consectetuer in eos. Vix brute veniam equidem an, et vis velit quaeque, postulant adolescens et has. </p> </div> </div> ); } } export default About;
var slideItem = 0; window.onload = function() { setInterval(passarSlide, 5000); var slidewidth = document.getElementById("slideshow").offsetWidth; var objs = document.getElementsByClassName("slide"); for (var i in objs) { objs[i].style.width = slidewidth; } } function passarSlide() { var slidewidth = document.getElementById("slideshow").offsetWidth; if(slideItem >= 3){ slideItem = 0; }else{ slideItem++; } document.getElementsByClassName("slideshow-area")[0].style.marginLeft = "-" + (slidewidth * slideItem)+"px"; } function mudarSlide(pos){ slideItem = pos -1 ; passarSlide(); } function toogglemenu(){ var menu = document.getElementById("menu"); if (menu.style.display == 'none' || menu.style.display == ''){ menu.style.display = 'block'; }else{ menu.style.display = 'none'; } } function hgsubmit() { if (/\S+/.test(document.hgmailer.nome.value) == false) alert ("Por favor, digite um nome."); else if (/^\S+@[a-z0-9_.-]+\.[a-z]{2,6}$/i.test(document.hgmailer.email.value) == false) alert ("Um endereço de e-mail válido é requerido."); else if (/\S+/.test(document.hgmailer.mensagem.value) == false) alert ("É necessário um conteúdo para mensagem."); else if (/\S+/.test(document.hgmailer.assunto.value) == false) alert ("É necessário um assunto para mensagem."); else { document.hgmailer.submit(); alert ('Obrigado!\nSeu e-mail foi enviado com sucesso.'); } }
import React, { Component } from "react"; import { View, StyleSheet, Text } from "react-native"; import Square from '../components/Square'; class Exo5 extends Component { render() { return( <View style={styles.container}> <Square text="Square 1" color="lightblue"/> <Square text="Square 2" color="lightgreen"/> <Square text="Square 3" color="red"/> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'space-around', alignItems: 'center', flexDirection: 'row' } }) export default Exo5;
import React from 'react'; import {Text, View, StyleSheet, ScrollView} from 'react-native'; import AntDesign from 'react-native-vector-icons/AntDesign'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import { colors } from '../constants'; import AsyncStorage from '@react-native-community/async-storage'; const Header = ({popModal, nav, refreshPage}) => { const [balance, setBalance] = React.useState(0) React.useEffect(() => { async function getMatches() { try { let bal = await AsyncStorage.getItem('@wallet_bal'); setBalance(bal); } catch (error) { console.log(error); } } getMatches(); }, []); return ( <View style={styles.headerBox}> <MaterialCommunityIcons name={'menu'} size={30} color={'#000'} onPress={() => popModal(true)} /> <View style={styles.leftBox}> <MaterialCommunityIcons name={'wallet'} size={30} color={'#000'} onPress={() => nav.push('Wallet')} /> <Text style={styles.headerText}>{balance}</Text> <MaterialCommunityIcons name={'refresh'} size={30} color={'#000'} onPress={() => refreshPage()} /> </View> </View> ); }; const styles = StyleSheet.create({ headerBox: { padding: 5, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', backgroundColor: colors.primary, paddingHorizontal: 10, width: '100%', paddingVertical: 15 }, headerText: { fontFamily: 'AveriaSansLibre-Regular', fontSize: 24, marginHorizontal: 10 }, leftBox: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }, }); export default Header;
/** * Created by 佳锐 on 2017/3/20. */ window.onload = function(){ var canvas = document.createElement("canvas"); var context = canvas.getContext('2d'); var canvasHeight = window.innerHeight; var canvasWidth = window.innerWidth; //初始化一个数组存放粒子 var particles = []; init(); function init(){ document.body.appendChild(canvas); canvas.width = canvasWidth; canvas.height = canvasHeight; } document.onclick = function(e){ var x = e.clientX; var y = e.clientY; console.log(e.clientX); console.log(e.clientY); setInterval(function(){ loop(x,y); },1000/30); }; function loop(x,y){ //清除canvas中的内容 context.fillStyle = "rgba(0,0,0,1)"; context.fillRect(0,0,canvasWidth,canvasHeight); //随机产生一个粒子 var particle = new Particle(x,y); particle.xVel = Math.random()*4-2;//给粒子一个水平位置变化量 particles.push(particle);//加入数组中 if(particles.length > 2000){ particles.shift(); } for(var i=0;i<particles.length;i++){ var particle = particles[i]; //绘制数组中的每一个粒子 particle.render(context); //更新数组中的每一个粒子 particle.update(); } } //粒子类 function Particle(x,y){ this.x = x; this.y = y; this.step = -5;//加入垂直方向的增量,负值就向上运动 this.xVel = 0; this.gravity = 0.1;//增加重力影响 this.counter = 0;//影响颜色 this.render = function(context){ //hsl(H,S,L) //H:0-360,S:饱和度0.0%-100.0%,L:亮度0.0%-100.0% context.fillStyle = "hsl("+this.counter+",100%,50%)"; context.beginPath(); context.arc(this.x,this.y,3,0,2*Math.PI,true); context.fill(); }; this.update = function(){ this.y += this.step; this.step += this.gravity; this.x += this.xVel; this.counter += 2; }; } };
import React from 'react'; import {Row, Col, Card, Table, Button} from 'react-bootstrap'; import { Link } from 'react-router-dom' import Aux from "../../../hoc/_Aux"; import Item from '../Item'; const item = new Item(); class ListItems extends React.Component { constructor(props) { super(props); this.state = { items: [], }; this.handleDelete = this.handleDelete.bind(this); } componentDidMount() { var self = this; item.getItems().then(function (result) { self.setState({ items: result}) }); } handleDelete(e,pk){ item.deleteItem({pk : pk}).then(()=>{ var newArr = this.state.items.filter(function(obj) { return obj.pk !== pk; }); this.setState({items: newArr}) }); } render() { return ( <Aux> <Row> <Col> <Card> <Card.Header> <Card.Title as="h5">Items</Card.Title> <span className="d-block m-t-5">Listado de Items</span> </Card.Header> <Card.Body> <Table responsive hover> <thead> <tr> <th>Categoria</th> <th>ID producto</th> <th>Laboratorio</th> <th>Presentación</th> <th>Nombre Medico</th> <th>Contenido</th> <th>Unidad Medida</th> <th>Descripción</th> <th>Referencia</th> <th>Proveedor</th> <th>Precio</th> <th>Proveedor</th> </tr> </thead> <tbody> {this.state.items.map( item => <tr key={item.id}> <td>{item.category}</td> <td>{item.id_product}</td> <td>{item.laboratory}</td> <td>{item.presentation}</td> <td>{item.medical_name}</td> <td>{item.quantity}</td> <td>{item.measure_unity}</td> <td>{item.description}</td> <td>{item.reference}</td> <td>{item.supplier}</td> <td>{item.price}</td> <td> <Link to={"api/item/" + item.id}> <Button variant="secondary"> Editar </Button> </Link> </td> </tr> )} </tbody> </Table> </Card.Body> </Card> </Col> </Row> </Aux> ); } } export default ListItems;
import Swiper from 'swiper/js/swiper.min.js'; var arWorkSwiper = []; $('.js-swiper--work').each(function (index) { var $el = $(this), $elPag = $el.find('.swiper-pagination--work'), $elNavLeft = $el.siblings('.swiper-controls').find('.swiper-button-next--work'), $elNavRight = $el.siblings('.swiper-controls').find('.swiper-button-prev--work'), $elFraction = $el.find('.swiper-fraction--work'), extraOptions = $el.data('slider-options') || {}; $el.addClass(`js-swiper--work-${index}`); $elPag.addClass(`swiper-pagination--work-${index}`); $elNavLeft.addClass(`swiper-button-next--work-${index}`); $elNavRight.addClass(`swiper-button-prev--work-${index}`); $elFraction.addClass(`swiper-fraction--work-${index}`); arWorkSwiper[index] = new Swiper(`.js-swiper--work-${index}`, { lazy: true, spaceBetween: 3, loop: false, slidesPerView: 4, speed: 900, autoHeight: true, simulateTouch: false, init: false, mousewheel: false, pagination: { el: `.swiper-pagination--work-${index}`, clickable: true, type: 'bullets', }, navigation: { nextEl: `.swiper-button-next--work-${index}`, prevEl: `.swiper-button-prev--work-${index}`, }, breakpoints: { 320: { slidesPerView: 1 }, 420: { slidesPerView: 2 }, 768: { slidesPerView: 4 } }, ...extraOptions, }); arWorkSwiper[index].init(); });
// Construcción de la base de datos var path = require('path'); // POSTGRES DataBase // // DATABASE_URL = postgres://user:passwd@host:port/database var url = process.env.DATABASE_URL.match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/); var DB_name = (url[6]||null); var user = (url[2]||null); var pwd = (url[3]||null); var protocol = (url[1]||null); var dialect = (url[1]||null); var port = (url[5]||null); var host = (url[4]||null); var storage = process.env.DATABASE_STORAGE; // SQLite DataBase // // DATABASE_URL = sqlite://:@:/ // // Cargar Modelo ORM var Sequelize = require('sequelize'); // Usar BBDD SQLite - // En sequelize metemos un objeto que creamos con el módulo Sequelize // Sequelize es la clase de bases de datos // sequelize será nuestro objeto con la bd genérica particularizada // para SQLite3. Y el fichero que tendrá la db es quiz.sqlite. //var sequelize = new Sequelize(null, null, null, // { dialect: "sqlite", storage: "quiz.sqlite"}); var sequelize = new Sequelize(DB_name, user, pwd, { dialect: protocol, protocol: protocol, port: port, host: host, storage: storage, // Para sqlite desde .env omitNull: true // Para Postgres } ); // Importar la definición de la tabla Quiz de quiz.js para construirla // El objeto de tipo Quiz podŕá así acceder a los elementos // de la tabla definida en quiz.js. //var quiz_path = path.join(__dirname, 'quiz'); var quiz_path = path.join(__dirname, 'quiz'); // Esto es nuevo en tema comments //var Quiz = sequelize.import(path.join(__dirname, 'quiz')); var Quiz = sequelize.import(quiz_path); // Importamos la definición de la tabla comment.js para construirla var comment_path = path.join(__dirname, 'comment'); var Comment = sequelize.import(comment_path); // Relación de tipo 1-a-N entre Quiz y Comment Comment.belongsTo(Quiz); // Parte 1 - Los comentarios pertenecen a las preguntas Quiz.hasMany(Comment); // Parte N - Una pregunta puede tener muchos comentarios // Exportar la definición de la tabla Quiz y la de Comment // Esto es para que se pueda importar en otros lugares de la aplicación exports.Quiz = Quiz; exports.Comment = Comment; // sequelize.sync() crea e inicializa la bd y, por tanto, la tabla de // preguntas de la db que es la única tabla que tenemos hasta ahora // La forma success es la forma antigua de usar sequelize. Actualmente // se usa lo que se denomina "promesas". Se verán posteriormente sequelize.sync().then(function() { // then ejecuta el manejador una vez creada la tabla // count nos da el número de filas que tiene la tabla Quiz.count().then(function(count) { // La tabla se inicializa solo si está vacía if(count === 0) { Quiz.create({ pregunta: 'Capital de Italia', respuesta: 'Roma', tema: 'Geografía' }); Quiz.create({ pregunta: 'Capital de Portugal', respuesta: 'Lisboa', tema: 'Geografía' }).then(function(){ console.log('Base de datos inicializada') }); }; }); });
import express from "express"; import controller from "../Controller/party.js"; const PartyRouter = express.Router(); PartyRouter.post("/", controller.createParty); PartyRouter.get("/", controller.getParty); PartyRouter.get("/:id", controller.getPartyById); PartyRouter.put("/", controller.updateParty); PartyRouter.delete("/:id", controller.deleteParty); export default PartyRouter;
var riot = require('riot'); var map = require('./map.tag'); var welcome = require('./welcome.tag'); var listView = require('./listView.tag'); var controls = require('./controls.tag'); var tour = require('./tour.tag'); var L = require('leaflet'); var Connector = require('./localground_connector'); var itemDetail = require('./itemDetail.tag'); var audioPlayer = require('./audioPlayer.tag'); var Controller = require('./controller'); var GeoQuerier = require('./geoQuerier.js'); var welcome = require('./welcome.tag'); // set up jquery/bootstrap var jQuery = require('jquery'); window.jQuery = jQuery; window.$ = jQuery; var bootstrap = require('bootstrap'); var blueimpgallery = require('./blueimp-gallery'); function InSite(opts){ this.opts = opts; } InSite.prototype.setup = function(){ var controller = new Controller(); controller.filter = opts.startFilter opts.controller = controller; var connector = new Connector(opts); var geoQuerier = new GeoQuerier(opts); riot.mount('*', opts); // set initial view controller.trigger('StartApp'); } // make InSite global window.InSite = InSite;
import React, { useEffect, useState } from "react"; import { Steps } from "antd"; import logo from "../../assets/logo_trans.png"; import { APP_NAME } from "../../utils/constants"; const { Step } = Steps; function About(props) { return ( <div className="content"> <img src={logo} className="hero-logo" /> <Steps current={3} size="large" className="header-steps"> <Step title="Discover" description="Discover and purchase collections listed by other individuals" /> <Step title="List" description={`Use ${APP_NAME} to list and sell rights and access to your previous NFTs.`} /> <Step title="Earn" description="Get paid for your new and existing content." /> </Steps> <hr /> </div> ); } export default About;
import React, { useState } from "react"; import { Navbar } from "../NavBar/Navbar"; export const ShowHide = () => { const [show, setShow] = useState(false); return ( <div> {show && <Navbar />} <button onClick={() => { setShow(!show); }} > click </button> </div> ); };
'use strict'; const { Client } = require('pg'); const urlConexao = require('../../config/pg_connection'); module.exports = { cadastrar_endereco: cadastrarEndereco, listar_enderecos_usuario: listarEnderecosUsuario, listar_enderecos: listarEnderecos }; async function cadastrarEndereco(req, res) { const rua = req.body.rua.trim(); const numero = req.body.numero || null; const complemento = req.body.complemento || null; const bairro = req.body.bairro; const usuario_id = req.body.usuario_id; try { const client = new Client({ connectionString: urlConexao }); await client.connect(); await client.query('INSERT INTO endereco (rua, numero, complemento, bairro, usuario_id) VALUES ($1, $2, $3, $4, $5)', [rua, numero, complemento, bairro, usuario_id]); await client.end(); res.status(201).json({ mensagem: 'Endereço cadastrado com sucesso!' }); } catch (err) { console.log(err); res.status(500).json({ mensagem: err.toString() }); } } async function listarEnderecosUsuario(req, res) { const usuario_id = req.swagger.params.usuario_id.value; try { const client = new Client({ connectionString: urlConexao }); await client.connect(); await client.query('SELECT rua, numero, complemento, bairro FROM endereco WHERE usuario_id = $1', [usuario_id], function (err, result) { if (err) { return console.error(err); } var enderecos = []; result.rows.forEach(function (endereco) { var rua = endereco.rua; var numero = endereco.numero == null ? 's/n' : endereco.numero; var complemento = endereco.complemento != null ? ' - ' + endereco.complemento : ''; var bairro = endereco.bairro; enderecos.push({ 'endereco': rua + ', ' + numero + complemento, 'bairro': bairro }); }) const lista = { 'total': result.rows.length, 'enderecos': enderecos } res.status(200).json(lista); }); await client.end(); } catch (err) { console.log(err); res.status(500).json({ mensagem: err.toString() }); } } async function listarEnderecos(req, res) { var query = ''; if (typeof req.query.bairro == 'undefined') query = 'SELECT * FROM endereco'; else query = `SELECT * FROM endereco WHERE bairro ILIKE '${req.query.bairro}'`; try { const client = new Client({ connectionString: urlConexao }); await client.connect(); await client.query(query, function (err, result) { if (err) { return console.error(err); } res.status(200).json(result.rows); }); await client.end(); } catch (err) { console.log(err); res.status(500).json({ mensagem: err.toString() }); } }
const TwoFactorAuth = artifacts.require("./TwoFactorAuth.sol"); module.exports = function (deployer) { deployer.deploy(TwoFactorAuth, 'example.com', 'Example Ltd'); };
var unirest = require('unirest'); var changeCase = require('change-case') const hashtag = require('../tokens/hashtag.json'); exports.run = function(client, message, args) { let argscmd = message.content.split(" ").slice(1); let hash = argscmd[0]; // yes, start at 0, not 1. I hate that too. if (!hash) return message.reply("Please give me a hashtag to look up."); unirest.get("https://tagdef.p.mashape.com/one." + hash + ".json") .header("X-Mashape-Key", hashtag.token) .header("Accept", "application/json") .end(function(result) { // For Debug Only //console.log(result.status, result.headers, result.body); console.log("Running Command for Hashtag | Params: Hashtag: " + hash); if (!result.body.defs.def["text"]) return message.reply("That hashtag does not exist."); message.channel.send("Hashtag: " + hash + ": " + result.body.defs.def["text"] + "\n" + "Upvotes: " + result.body.defs.def["upvotes"] + " Downvotes: " + result.body.defs.def["downvotes"]); }); }
import map from '../signals/processes/map' export default map((ev) => [ev.target.value, ev.keyCode])
function handlePowerup(context, identifier) { switch (identifier) { case "Tomato": context.$store.commit('addPointsPerSecond', 1); break; case "Peely": context.$store.commit("addPointsPerClick", 1); break; case "Fishstick": context.$store.commit('addPointsPerSecond', 5); break; case "SkullTrooper": context.$store.commit('addPointsPerSecond', 20); break; case "Victory": Victory(context); break; default: } console.log(identifier); } function startInterval(context, interval = 10) { let divider = 1000 / interval; setInterval(() => { let pointsGained = context.$store.state.pointsPerSecond / divider; console.log(pointsGained); context.$store.dispatch('addPoints', pointsGained); }, interval); } function Victory(context) { context.$store.dispatch('toggleModal') } export {handlePowerup, startInterval}
Meteor.startup(function() { if(Trees.find({}).count() < 52) { Trees.remove({}); for(var i = 0; i < TREE_DATA.length; i++) { Trees.insert(TREE_DATA[i]); } } }); var scroll = new ReactiveVar(0); Tracker.autorun(function() { console.log(scroll.get()); }); Template.TreeList.onRendered(function() { scrollTo(0, scroll.get()); }); Template.TreeList.events({ 'click .trees-back-text': function() { scroll.set(0); }, 'click .treelist a': function() { scroll.set(scrollY); } }); Template.SingleTree.onRendered(function() { scrollTo(0, 0); }); /*Template.Trees.events({ 'submit form': function(evt, tmpl) { evt.preventDefault(); var value = tmpl.find('input[type=text]').value; if(value.length > 0) { Router.go('/trees/search/' + value); } } });*/ window.Tree = function(obj) { this.combined = ""; for(i in obj) { this[i] = obj[i]; this.combined += obj[i]; } } Tree.prototype.occurrences = function(word) { var pattern = new RegExp(word, 'gi'); return (this.combined.match(pattern) || []).length; } Tree.prototype.rank = function(phrase) { phrase = phrase.toLowerCase().split(' ').sort().join(' '); var count = 0; this.rank = this.rank || {}; if(this.rank[phrase] !== undefined) { return this.rank[phrase]; } var terms = phrase.split(' '); for(i in terms) { count += this.occurrences(terms[i]); } this.rank[phrase]; return count; } Template.Dichotomous.events({ 'click .dichotomous-container .tree-item': function(evt, tmpl) { var name = $(evt.target).find('span').text(); var pattern = new RegExp(name, 'i'); var tree = Trees.findOne({name: pattern}); console.log('hi'); Session.set('treesBackUrl', window.location.pathname); console.log('hi'); if(tree) { Router.go('/trees/tree/' + tree._id); } else { Router.go('/notrees'); } } });
//temporary while not fetching from Firebase var image1 = require('../../resources/images/image1.jpeg'); var image2 = require('../../resources/images/image2.jpeg'); var image3 = require('../../resources/images/image3.jpeg'); var image4 = require('../../resources/images/image4.jpeg'); var image5 = require('../../resources/images/image5.jpeg'); var image6 = require('../../resources/images/image6.jpeg'); var image7 = require('../../resources/images/image7.jpeg'); var image8 = require('../../resources/images/image8.jpeg'); var image9 = require('../../resources/images/image9.jpeg'); var image10 = require('../../resources/images/image10.jpeg'); var image11 = require('../../resources/images/image11.jpeg'); const INITIAL_STATE = { chats: [{ "id": 1, "name": "Diane", "message": "Suspendisse accumsan tortor quis turpis.", "image" : image1 }, { "id": 2, "name": "Lois", "message": "Morbi sem mauris, laoreet ut, rhoncus aliquet, pulvinar sed, nisl.", "image" : image2 }, { "id": 3, "name": "Mary", "message": "Duis bibendum.", "image" : image3 }, { "id": 4, "name": "Susan", "message": "Praesent blandit.", "image" : image4 }, { "id": 5, "name": "Betty", "message": "Mauris enim leo, rhoncus sed, vestibulum, cursus id, turpis.", "image" : image5 }, { "id": 6, "name": "Deborah", "message": "Aliquam sit amet diam in magna bibendum imperdiet.", "image" : image6 }, { "id": 7, "name": "Frances", "message": "Phasellus sit amet erat.", "image" : image7 }, { "id": 8, "name": "Joan", "message": "Vestibulum ante ipsum bilia Curae; Duis faucibus accumsan odio.", "image" : image8 }, { "id": 9, "name": "Denise", "message": "Aliquam non mauris.", "image" : image9 }, { "id": 10, "name": "Rachel", "message": "Nulla ac enim.", "image" : image10 }], newMatches: [{ "id": 1, "first_name": "Sarah", "image" : image7 }, { "id": 2, "first_name": "Pamela", "image" : image8 }, { "id": 3, "first_name": "Diana", "image" : image9 }, { "id": 4, "first_name": "Christina", "image" : image10 }, { "id": 5, "first_name": "Rebecca", "image" : image11 }, { "id": 6, "first_name": "Wanda", "image" : image5 }, { "id": 7, "first_name": "Sara", "image" : image6 }, { "id": 8, "first_name": "Judith", "image" : image7 }, { "id": 9, "first_name": "Ruby", "image" : image1 }, { "id": 10, "first_name": "Sandra", "image" : image11 }] }; export default (state = INITIAL_STATE, action) => { switch (action.type) { default: return state; } };
function random(maxValue) { return Math.floor(Math.random() * maxValue + 1); } function pickSuit() { suit = random(4); if(suit == 1) return "红桃"; if(suit == 2) return "草花"; if(suit == 3) return "方块"; if(suit==4) return "红心"; } function cardName(card) { if(card == 1) return "Ace"; if(card == 11) return "侍从"; if(card == 12) return "皇后"; if(card == 13) return "国王"; return "" + card; } function cardValue(card) { if(card == 1) return 11; if(card > 10) return 10; return card; } function PickACard(strWho) { card = random(13); suit = pickSuit(); //alert(strWho + " picked the " + cardName(card) + " of " + suit); return cardValue(card); } function NewHand(form) { form.dealer.value = 0; form.you.value = 0; form.dealer.value = eval(form.dealer.value) + PickACard("Dealer"); form.you.value = eval(form.you.value) + PickACard("You"); } function Dealer(form) { while(form.dealer.value < 16) { form.dealer.value = eval(form.dealer.value) + PickACard("Dealer"); } } function User(form) { form.you.value = eval(form.you.value) + PickACard("You"); if(form.you.value > 21) { alert("玩家超过21点了,电脑胜了!"); form.c.value = parseInt(form.c.value) + 1; //先转换成数字 form.cm.value = parseInt(form.cm.value) + (form.you.value-form.dealer.value); //同上 form.um.value-=form.you.value-form.dealer.value; if(form.um.value<=0) //好像等于0的时候也应该判定为输吧? alert("你没有筹码了,请重新开始游戏!"); } } function LookAtHands(form) { if(form.dealer.value > 21) { alert("电脑超过21点了,玩家胜出!"); form.u.value = parseInt(form.u.value) + 1; //先转换成数字 form.cm.value-=form.dealer.value-form.you.value; form.um.value = parseInt(form.um.value) + (form.dealer.value-form.you.value); //先转换成数字 if(form.cm.value<=0) //好像等于0的时候也应该判定为玩家赢吧? alert("恭喜你成为最后的大赢家!"); } else if(form.you.value<16) { alert("点数不够16,玩家输了!"); /* 点数不够16是什么意思?是点数必须达到16否则就判为输吗?这样的话应该首先判断这一条; 或者是由于电脑的点数一定是大于16的,如果电脑没有超过21那么玩家必输,这个逻辑是成立的,但是好像alert不应该这么写。 */ form.c.value = parseInt(form.c.value) + 1; //先转换成数字 form.cm.value = parseInt(form.cm.value) + 1; //同上 form.um.value--; if(form.um.value<=0) //等于0 alert("你没有筹码了,请重新开始游戏!"); } else if(form.you.value > form.dealer.value) { alert("玩家胜出了!"); form.u.value = parseInt(form.u.value) + 1; //先转换成数字 form.cm.value-=form.you.value-form.dealer.value; form.um.value = parseInt(form.um.value) + (form.you.value-form.dealer.value); //先转换成数字 if(form.cm.value<=0) //等于0 alert("恭喜你成为最后的大赢家!"); } else if(form.dealer.value == form.you.value) { alert("平局!"); } else { alert("电脑胜了!"); form.c.value = parseInt(form.c.value) + 1; //先转换成数字 form.cm.value = parseInt(form.cm.value) + (form.dealer.value-form.you.value); //同上 form.um.value-=form.dealer.value-form.you.value; if(form.um.value<=0) //等于0 alert("你没有筹码了,请重新开始游戏!"); } } function ReStart(form){ form.c.value=0; form.u.value=0; form.cm.value=100; form.um.value=100; }
var odiv=document.getElementById('box'); odiv.onclick=function(){ odiv.style.background='orange'; } odiv.onmouseover=function(){ odiv.style.background='tomato'; } odiv.onmouseout=function(){ odiv.style.background='#ff0'; } console.log('bbb')
#!/usr/bin/node const process = require('process'); const args = process.argv; const myVar = 'C is fun'; const number = parseInt(args[2]); if (!number) { console.log('Missing number of occurrences'); } for (let i = 0; i < number; i++) { console.log(myVar); }
import styled from 'styled-components'; export const SignInContainer = styled.div` display: flex; flex-direction: column; flex-wrap: wrap; // justify-content: space-between; width: 100%; max-width: 1024px; margin: 0 auto; @media (min-width: 768px) { flex-direction: row; } > * { flex: 1; @media (min-width: 768px) { padding: 0 16px; &:first-child { padding-left: 0; } &:last-child { padding-right: 0; } } } `;
const Augur = require("augurbot"), u = require("../utils/utils"), milestone = 5000, pizza = false; const Module = new Augur.Module() .addEvent("guildMemberAdd", async (member) => { try { if (member.guild.id == Module.config.ldsg) { let guild = member.guild; let bot = member.client; let user = await Module.db.user.fetchUser(member.id); let general = guild.channels.cache.get(Module.config.ldsg); // #general let welcomeChannel = guild.channels.cache.get(Module.config.channels.welcome); // #welcome let modLogs = guild.channels.cache.get(Module.config.channels.modlogs); // #mod-logs let embed = u.embed() .setColor(0x7289da) .setDescription("Account Created:\n" + member.user.createdAt.toLocaleDateString()) .setTimestamp() .setThumbnail(member.user.displayAvatarURL({dynamic: true})); let welcomeString; if (user) { // Member is returning let toAdd = user.roles.filter(role => ( guild.roles.cache.has(role) && !guild.roles.cache.get(role).managed && !["281135201407467520", "96360253850935296", "205826273639923722", "503066022912196608", "96345401078087680", "734797110389506108", "801333875329728522", "803315372613697536"].includes(role) )); if (user.roles.length > 0) member = await member.roles.add(toAdd); let roleString = member.roles.cache.sort((a, b) => b.comparePositionTo(a)).map(role => role.name).join(", "); if (roleString.length > 1024) roleString = roleString.substr(0, roleString.indexOf(", ", 1000)) + " ..."; embed.setTitle(member.displayName + " has rejoined the server.") .addField("Roles", roleString); welcomeString = `Welcome back, ${member}! Glad to see you again.`; } else { // Member is new let welcome = [ "Welcome", "Hi there", "Glad to have you here", "Ahoy" ]; let info1 = [ "Take a look at", "Check out", "Head on over to" ]; let info2 = [ "to get started", "for some basic community rules", "and join in the chat" ]; let info3 = [ "What brings you our way?", "How'd you find us?", "What platforms/games do you play?" ]; welcomeString = `${u.rand(welcome)}, ${member}! ${u.rand(info1)} ${welcomeChannel} ${u.rand(info2)}. ${u.rand(info3)}\n\nTry \`!profile\` over in <#${Module.config.channels.botspam}> if you'd like to opt in to roles or share IGNs.`; embed.setTitle(member.displayName + " has joined the server."); Module.db.user.newUser(member.id); } if (!member.client.ignoreNotifications?.has(member.id)) modLogs.send({embed}); else member.client.ignoreNotifications.delete(member.id); if (pizza && (guild.members.size < milestone)) welcomeString += `\n*${milestone - guild.members.size} more members until we have a pizza party!*`; if (!member.roles.cache.has(Module.config.roles.muted) && !member.user.bot) general.send(welcomeString); if (guild.members.size == milestone) { general.send(`:tada: :confetti_ball: We're now at ${milestone} members! :confetti_ball: :tada:`); modLogs.send(`:tada: :confetti_ball: We're now at ${milestone} members! :confetti_ball: :tada:\n*pinging for effect: ${guild.members.cache.get("96335658997526528")} ${guild.members.cache.get("111232201848295424")}*`); } } } catch(e) { u.errorHandler(e, "New Member Add"); } }); module.exports = Module;
function cargarFondo() { fondo.cargaOK = true; dibujar(); } function cargarVacas() { vaca.cargaOK = true; dibujar(); } function cargarCerdos() { cerdo.cargaOK = true; dibujar(); } function cargarPollos() { pollo.cargaOK = true; dibujar(); } var xCerdo = 190; var yCerdo = 200; function dibujar() { if(fondo.cargaOK) { papel.drawImage(fondo.imagen, 0, 0); } if(vaca.cargaOK) { console.log(cantidad); for (var v=0; v< cantidad; v++) { var x = aleatorio(0, 4); var y = aleatorio(0, 4); var x = x * 80; var y = y * 80; papel.drawImage(vaca.imagen, x, y); } } if(pollo.cargaOK) { console.log(cantidad); for (var v=0; v< cantidad; v++) { var x = aleatorio(0, 4); var y = aleatorio(0, 4); var x = x * 100; var y = y * 100; papel.drawImage(pollo.imagen, x, y); } } if(cerdo.cargaOK) { papel.drawImage(cerdo.imagen, xCerdo, yCerdo); } } function aleatorio(min, maxi) { var resultado; resultado = Math.floor(Math.random() * (maxi - min + 1)) + min; return resultado; } function moverCerdo(evento) { var movimiento = 5; switch(evento.keyCode) { case teclas.UP: yCerdo -= movimiento; break; case teclas.DOWN: yCerdo += movimiento; break; case teclas.RIGTH: xCerdo += movimiento; break; case teclas.LEFT: xCerdo -= movimiento; break; default: console.log("Otra tecla") break; } vp.width = vp.width; papel.drawImage(cerdo.imagen, xCerdo, yCerdo) }
import axios from "axios"; import { GET_ERRORS, GET_DOCUMENTS, GET_DOCUMENT} from "./type"; export const getDocuments = () => async dispatch => { const response = await axios.get("http://localhost:8081/api/document/topics",document); dispatch({ type: GET_DOCUMENTS, payload: response.data }); }; export const getDocument = (documentId, history) => async dispatch => { const response = await axios.get(`http://localhost:8081/api/document/${documentId}`); dispatch({ type: GET_DOCUMENT, payload: response.data }); };
import * as BABYLON from '@babylonjs/core' import { STATION_SIZE, STATION_INTERACT_COEFF, STATION_MAX_HEALTH, GUN_POSITION } from './constants.js' import { getTruncatedIcosahedron, getBrokenIcosahedron } from './geometry.js' import { getGroundElevation } from './utils.js' import { handleGameOver } from './lifecycle.js' // restore one wreck export function repairOneStation(scene) { var wreck = null for (var w of scene.wreckedStations) { if (w.shell.isEnabled()) { wreck = w break } } if (wreck !== null) { // get the station info let id = wreck.id let posx = wreck.shell.position.x let posz = wreck.shell.position.z /* remove the wreckage */ wreck.shell.dispose() wreck.innerCore.dispose() wreck.particles.dispose() const hasId = (obj) => obj.id === id const idx = scene.wreckedStations.findIndex(hasId) scene.wreckedStations.splice(idx, 1) /* replace the station */ addPowerStation(scene, posx, posz, id) } } function makePowerStation(name, scene) { /* perimeter */ var rmat = scene.getMaterialByName("stationPylons_Lit") let perimeterRadius = STATION_INTERACT_COEFF * STATION_SIZE let pylons = [] let theta = 0 var CoT = new BABYLON.TransformNode(name + "_powerStationRoot"); for (var i = 0; i < 12; i++) { let pylonName = name + "_pylon_" + i pylons[i] = BABYLON.MeshBuilder.CreateCylinder(pylonName, {diameterBottom:0.2, diameterTop: 0.07, height: 0.5, tessellation: 8}, scene) pylons[i].convertToFlatShadedMesh() theta = i * (Math.PI / 6) let px = Math.cos(theta) * perimeterRadius let pz = Math.sin(theta) * perimeterRadius let py = 0 pylons[i].position = new BABYLON.Vector3(px, py, pz) pylons[i].material = rmat pylons[i].parent = CoT } /* Pedestal */ var pmat = scene.getMaterialByName("pedestalMat") var pedestal = BABYLON.MeshBuilder.CreateCylinder(name + "_pedestal", {diameterTop: 0, tessellation: 16}, scene) pedestal.scaling = new BABYLON.Vector3(0.8, 0.15, 0.8) pedestal.position = new BABYLON.Vector3(0, -.8, 0) pedestal.material = pmat pedestal.parent = CoT /* core */ var tico = getTruncatedIcosahedron() var core = BABYLON.MeshBuilder.CreatePolyhedron(name, { custom: tico }, scene); core.scaling = new BABYLON.Vector3(0.6, 0.6, 0.6); var mat = scene.getMaterialByName("powerCoreMat") core.material = mat core.parent = CoT let s = STATION_SIZE core.scaling = core.scaling.multiplyInPlace(new BABYLON.Vector3(s, s, s)) /* inner core */ let innerCore = BABYLON.MeshBuilder.CreateSphere(name + '_innerCore', scene) innerCore.scaling = new BABYLON.Vector3(1.2,1.2,1.2) innerCore.material = scene.getMaterialByName("innerPowerCoreMat") innerCore.parent = core /* animation */ var animationCore = new BABYLON.Animation(name + "_stationAnim", "material.emissiveColor", 30, BABYLON.Animation.ANIMATIONTYPE_COLOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) var keys = [] keys.push({ frame: 0, value: new BABYLON.Color3(0,0,0) }) keys.push({ frame: 30, value: new BABYLON.Color3(1,1,0) }) keys.push({ frame: 60, value: new BABYLON.Color3(0,0,0) }) animationCore.setKeys(keys); innerCore.animations = [] innerCore.animations.push(animationCore) scene.beginAnimation(innerCore, 0, 60, true) /* damage particles */ // var damageParticles = new BABYLON.GPUParticleSystem(name + "_damageparticles", { capacity: 900 }, scene); // var sphereEmitter = damageParticles.createSphereEmitter(1.2); // let damageColors = { // particles_color1: new BABYLON.Color4(.2,.45,.15, 1), // particles_color2: new BABYLON.Color4(1, 1, 1, 1.0), // particles_colorDead: new BABYLON.Color4(0, .1, 0, 0.0) // } // damageParticles.particleTexture = new BABYLON.Texture("textures/flare.png", scene); // damageParticles.emitter = innerCore; // damageParticles.minSize = 0.01; // damageParticles.maxSize = 0.2; // damageParticles.maxLifeTime = 1 // damageParticles.color1 = damageColors.particles_color1 // damageParticles.color2 = damageColors.particles_color2 // damageParticles.colorDead = damageColors.particles_colorDead // damageParticles.emitRate = 300; // damageParticles.minEmitPower = .1; // damageParticles.maxEmitPower = 9; // damageParticles.gravity = new BABYLON.Vector3(0, -20, 0); return { CoT: CoT, pylons: pylons, anim: animationCore, shell: core, innerCore: innerCore, //particles: damageParticles } } export function updatePowerStationGraphics( station, scene ) { let damagedPylonMat = scene.getMaterialByName("stationPylons_Dark") let damage = STATION_MAX_HEALTH - station.health for (var i = 0; i < damage; ++i) { station.pylons[i].material = damagedPylonMat } // initial is 1.2 (health = 12) final is 1.98 (health = 1) var s = ((0.78/11) * (damage)) + 1.2 station.innerCore.scaling = new BABYLON.Vector3(s,s,s) // if (damage > 3) { // station.particles.start() // } } export function addPowerStation(scene, x, z, id) { let name = "station_" + id let ps = makePowerStation(name, scene) let y = getGroundElevation(x, z, scene) let mesh = ps.CoT mesh.position = new BABYLON.Vector3(x, y + 0.85, z) // Put pylons on the ground for (var pylon of ps.pylons) { let pyGE = getGroundElevation( pylon.position.x + mesh.position.x, pylon.position.z + mesh.position.z, scene) pylon.position.y = pyGE - ps.CoT.position.y } let powerStation = { name: name, pos: mesh.position, mesh: ps.CoT, anim: ps.anim, pylons: ps.pylons, shell: ps.shell, interactRadius: mesh.scaling.x * STATION_INTERACT_COEFF, innerCore: ps.innerCore, particles: ps.particles, health: STATION_MAX_HEALTH, id: id } scene.powerStations.push(powerStation) addPowerStationWreckage(scene, powerStation) scene.liveStations += 1 } export function addPowerStations(scene) { addPowerStation(scene, 12, 8, 1) addPowerStation(scene, 10, 0, 2) addPowerStation(scene, 12,-8, 3) } export function placePowerStations(scene) { for ( var station of scene.powerStations ) { let x = station.mesh.position.x let z = station.mesh.position.z let y = getGroundElevation(x, z, scene) station.pos = new BABYLON.Vector3(x, y + 0.85, z) station.mesh.position = station.pos // Put pylons on the ground for (var pylon of station.pylons) { let pyGE = getGroundElevation( pylon.position.x + station.mesh.position.x, pylon.position.z + station.mesh.position.z, scene) pylon.position.y = pyGE - station.mesh.position.y } // update the wreckage location let wreck = scene.getMeshByName(station.name + "_wreck_core") wreck.position = new BABYLON.Vector3(station.pos.x, station.pos.y - .4, station.pos.z) } } function makePowerStationWreckage(name, scene) { /* core */ var tico = getBrokenIcosahedron() var core = BABYLON.MeshBuilder.CreatePolyhedron(name + "_core", { custom: tico }, scene); core.scaling = new BABYLON.Vector3(0.6, 0.6, 0.6); core.rotate(BABYLON.Axis.X, 1.7, BABYLON.Space.LOCAL) // random y rotation let rot = Math.random() core.rotate(BABYLON.Axis.Y, rot, BABYLON.Space.WORLD) var mat = scene.getMaterialByName("powerCoreBrokenMat") core.material = mat let s = STATION_SIZE core.scaling = core.scaling.multiplyInPlace(new BABYLON.Vector3(s, s, s)) /* inner core */ let innerCore = BABYLON.MeshBuilder.CreateSphere(name + '_innerCore', scene) innerCore.scaling = new BABYLON.Vector3(1.2,1.2,1.2) innerCore.material = scene.getMaterialByName("innerPowerCoreBrokenMat") innerCore.position = new BABYLON.Vector3(0, .2, .5) innerCore.rotate(BABYLON.Axis.X, -1.7) innerCore.parent = core let flareTexture = new BABYLON.Texture("textures/flare.png", scene); /* damage particles */ var damageParticles = new BABYLON.GPUParticleSystem(name + "_damageparticles", { capacity: 500 }, scene); var sphereEmitter = damageParticles.createHemisphericEmitter(1.2); let damageColors = { particles_color1: new BABYLON.Color4(.1,.5,.1, 1), particles_color2: new BABYLON.Color4(1, 1, 1, 1.0), particles_colorDead: new BABYLON.Color4(0.1, 0, 0.1, 0.0) } damageParticles.particleTexture = flareTexture damageParticles.emitter = innerCore; damageParticles.minSize = 0.01; damageParticles.maxSize = 0.15; damageParticles.maxLifeTime = 5 damageParticles.color1 = damageColors.particles_color1 damageParticles.color2 = damageColors.particles_color2 damageParticles.colorDead = damageColors.particles_colorDead damageParticles.emitRate = 100; damageParticles.minEmitPower = .1; damageParticles.maxEmitPower = 5; damageParticles.gravity = new BABYLON.Vector3(0, -5, 0); damageParticles.preWarmCycles = 100; damageParticles.preWarmStepOffset = 5; /* explosion particles */ var exploParticles = new BABYLON.GPUParticleSystem(name + "_exploParticles", { capacity: 1500 }, scene); var coneEmitter = exploParticles.createConeEmitter(2, 2) let exploColors = { particles_color1: new BABYLON.Color4(.1, 1, .2, 1), particles_color2: new BABYLON.Color4(1, .8, 1, 1.0), particles_colorDead: new BABYLON.Color4(0, .1, 0, 0.0) } exploParticles.particleTexture = flareTexture exploParticles.emitter = innerCore; exploParticles.minSize = 0.05; exploParticles.maxSize = 0.6; exploParticles.maxLifeTime = .003 exploParticles.targetStopDuration = 5 exploParticles.color1 = exploColors.particles_color1 exploParticles.color2 = exploColors.particles_color2 exploParticles.colorDead = exploColors.particles_colorDead exploParticles.emitRate = 1500; exploParticles.minEmitPower = 1; exploParticles.maxEmitPower = 15; exploParticles.gravity = new BABYLON.Vector3(0, -5, 0); exploParticles.preWarmCycles = 100; exploParticles.preWarmStepOffset = 5; exploParticles.disposeOnStop = true core.setEnabled(false) innerCore.setEnabled(false) return { shell: core, innerCore: innerCore, particles: damageParticles, exploParticles: exploParticles} } export function enableStationWreckage(scene, station) { scene.getSoundByName("station-destroyed").play() let wreckName = station.name + "_wreck" const hasName = (obj) => obj.name === wreckName const idx = scene.wreckedStations.findIndex( hasName ) if(idx > -1) { let ws = scene.wreckedStations[idx] ws.shell.setEnabled(true) ws.innerCore.setEnabled(true) ws.particles.start() ws.exploParticles.start() } scene.liveStations -= 1 } export function addPowerStationWreckage(scene, station) { let name = station.name + "_wreck" let ps = makePowerStationWreckage(name, scene) ps.shell.position = new BABYLON.Vector3(station.pos.x, station.pos.y - .4, station.pos.z) let powerStationWreck = { name: name, shell: ps.shell, innerCore: ps.innerCore, particles: ps.particles, exploParticles: ps.exploParticles, id: station.id } scene.wreckedStations.push(powerStationWreck) } export function destroyStation(station, scene, handleUpdateGUIinfo) { let destroyedStationName = station.name const hasName = (obj) => obj.name === destroyedStationName const idx = scene.powerStations.findIndex( hasName ) if(idx > -1) { scene.powerStations[idx].mesh.dispose() //scene.powerStations[idx].particles.dispose() scene.powerStations.splice(idx, 1) } } export function removeStationWreckage(scene) { for (var wreck of scene.wreckedStations) { wreck.shell.dispose() wreck.innerCore.dispose() wreck.particles.dispose() } scene.wreckedStations = [] } export function makeBase(scene) { var baseMesh = BABYLON.MeshBuilder.CreateCylinder("base", {diameter:0.5, sizeY:6.5, tessellation: 8}, scene) baseMesh.convertToFlatShadedMesh() baseMesh.position = new BABYLON.Vector3(GUN_POSITION.x - 0.4, 3.5, GUN_POSITION.z) var spireMesh = BABYLON.MeshBuilder.CreateCylinder("spire", {diameterBottom:0.4, diameterTop: 0.05, height:3.0, tessellation: 8}, scene) spireMesh.position = new BABYLON.Vector3(0, 2.0, 0) spireMesh.rotate(BABYLON.Axis.Y, 30 * (Math.PI / 180.0), BABYLON.Space.LOCAL) spireMesh.convertToFlatShadedMesh() spireMesh.parent = baseMesh var capCone = BABYLON.MeshBuilder.CreateCylinder("capCone", {diameterTop:0.25, diameterBottom: 0, height:0.5, tessellation: 12}, scene) capCone.convertToFlatShadedMesh() capCone.position = new BABYLON.Vector3(0, 1.23, 0) capCone.parent = spireMesh var capMesh = BABYLON.MeshBuilder.CreateCylinder("cap", {diameter:0.4, height:0.06, tessellation: 12}, scene) //capMesh.convertToFlatShadedMesh() capMesh.position = new BABYLON.Vector3(0, 1.4, 0) capMesh.parent = spireMesh var capMesh2 = BABYLON.MeshBuilder.CreateCylinder("cap2", {diameter:0.4, height:0.06, tessellation: 12}, scene) //capMesh.convertToFlatShadedMesh() capMesh2.position = new BABYLON.Vector3(0, 1.5, 0) capMesh2.parent = spireMesh }
import { h } from "hyperapp" import Spinner from '../components/Spinner.js' import MoviesTable from '../components/MoviesTable.js' import Pagination from '../components/Pagination.js' const Movies = module.exports = (state, actions) => <div key='movies'> <h2>Movie list</h2> <div class="columns"> <div class="column col-lg-12" oncreate={() => { console.log("Create movies"); actions.load(window.g_urls.movies) } }> {state.loading == true ? <Spinner /> : <MoviesTable movies={state} actions={actions} />} </div> </div> <Pagination page={state.page} next={state.next} previous={state.previous} actions={actions} /> </div>
config({ 'kg/autosize/index': {alias: ['kg/autosize/2.0.0/index']} });
import Item from "../models/item.model.js"; import Produto from "../models/produto.model.js"; import Contagem from "../models/contagem.model.js"; async function insertItem(item) { try { return await Item.create(item); } catch(err) { throw err; } } async function updateItem(item) { try { return await Item.update(item, { where: { itemId: item.id } }); } catch(err) { throw err; } } async function getItems() { try { return await Item.findAll({ include: [ { model: Produto }, { model: Contagem } ] }); } catch(err) { throw err; } } async function getItem(id) { try { return await Item.findByPk(id); } catch(err) { throw err; } } async function deleteItem(id) { try { await Item.destroy({ where: { itemId: id } }); } catch(err) { throw err; } } export default { insertItem, updateItem, getItems, getItem, deleteItem }
const FS = require("fs"); const isFile = require("./isFile"); module.exports = (f) => isFile(f) && FS.readFileSync(f, "utf8");
const express = require('express'); const mongoose = require('mongoose'); const Potato = require('../models/Potato'); const router = express.Router(); /* GET ALL POTATOES */ router.get('/', function(req, res, next) { Potato.find(function (err, products) { if (err) return next(err); res.json(products); }); }); /* GET SINGLE POTATO BY ID */ router.get('potato/:id', function(req, res, next) { Potato.findById(req.params.id, function (err, post) { if (err) return next(err); res.json(post); }); }); /* SAVE POTATO */ router.post('/potato', function(req, res, next) { console.log('saving potato'); Potato.create(req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); /* UPDATE POTATO */ router.put('potato/:id', function(req, res, next) { Potato.findByIdAndUpdate(req.params.id, req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); /* DELETE POTATO */ router.delete('potato/:id', function(req, res, next) { Potato.findByIdAndRemove(req.params.id, req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); module.exports = router;
const { body,validationResult } = require('express-validator/check'); const { sanitizeBody } = require('express-validator/filter'); var mongoose = require('mongoose'); var School = require('../models/highschool'); var Participant = require('../models/participant'); var async = require('async'); exports.index = function(req, res) { async.parallel({ participant_count: function(callback) { participant.countDocuments({}, callback); // Pass an empty object as match condition to find all documents of this collection }, participant_instance_count: function(callback) { participant.countDocuments({}, callback); }, participant_instance_available_count: function(callback) { participant.countDocuments({status:'Available'}, callback); }, school_count: function(callback) { School.countDocuments({}, callback); }, school_count: function(callback) { School.countDocuments({}, callback); } }, function(err, results) { res.render('index', { title: 'Local Library Home', error: err, data: results }); }); }; // Display list of all Participants. exports.participant_list = function(req, res, next) { Participant.find({}) .exec(function (err, list_participants) { if (err) { return next(err); } //Successful, so render res.render('participant_list', { title: 'Participant List', participant_list: list_participants }); }); }; // Display detail page for a specific participant. exports.participant_detail = function(req, res, next) { var id = mongoose.Types.ObjectId(req.params.id); async.parallel({ participant: function(callback) { Participant.findById(req.params.id) .exec(callback); }, participant_school: function(callback) { School.find({ 'participant': req.params.id }) .exec(callback); }, }, function(err, results) { if (err) { return next(err); } if (results.participant==null) { // No results. var err = new Error('Participant not found'); err.status = 404; return next(err); } // Successful, so render. res.render('participant_detail', { title: 'Participant Detail', participant: results.participant, participant_school: results.participant_school } ); }); }; // Display participant create form on GET. exports.participant_create_get = function(req, res, next) { // Get all Schools , which we can use for adding to our Participant. async.parallel({ schools: function(callback) { School.find(callback); }, }, function(err, results) { if (err) { return next(err); } res.render('participant_form', { title: 'Enroll', schools: results.schools, schools: results.schools }); }); }; // Handle participant create on POST. exports.participant_create_post = [ // Convert the school to an array. (req, res, next) => { if(!(req.body.school instanceof Array)){ if(typeof req.body.school==='undefined') req.body.school=[]; else req.body.school=new Array(req.body.school); } next(); }, // Validate fields. body('FirstName', 'FirstName must not be empty.').isLength({ min: 1 }).trim(), body('LastName', 'LastName must not be empty.').isLength({ min: 1 }).trim(), body('Email', 'Email must not be empty.').isLength({ min: 1 }).trim(), body('Address', 'Address must not be empty').isLength({ min: 1 }).trim(), // Sanitize fields (using wildcard). sanitizeBody('*').trim().escape(), // Process request after validation and sanitization. (req, res, next) => { // Extract the validation errors from a request. const errors = validationResult(req); // Create a Participant object with escaped and trimmed data. var participant = new Participant( { FirstName: req.body.FirstName, LastName: req.body.LastName, Email: req.body.Email, Address: req.body.Address, ParticipantType: req.body.ParticipantType }); if (!errors.isEmpty()) { // There are errors. Render form again with sanitized values/error messages. // Get all schools for form. async.parallel({ schools: function(callback) { Author.find(callback); }, }, function(err, results) { if (err) { return next(err); } // Mark our selected schools as checked. for (let i = 0; i < results.schools.length; i++) { if (participant.school.indexOf(results.schools[i]._id) > -1) { results.schools[i].checked='true'; } } res.render('participant_form', { title: 'Create Participant',participants:results.participants, schools:results.schools, participant: participant, errors: errors.array() }); }); return; } else { // Data from form is valid. Save participant. participant.save(function (err) { if (err) { return next(err); } //successful - redirect to new participant record. res.redirect(participant.url); }); } } ]; // Display Participant delete form on GET. exports.participant_delete_get = function(req, res) { res.send('NOT IMPLEMENTED: Participant delete GET'); }; // Handle Participant delete on POST. exports.participant_delete_post = function(req, res) { res.send('NOT IMPLEMENTED: Participant delete POST'); }; // Display Participant update form on GET. exports.participant_update_get = function(req, res) { res.send('NOT IMPLEMENTED: Participant update GET'); }; // Handle Participant update on POST. exports.participant_update_post = function(req, res) { res.send('NOT IMPLEMENTED: Participant update POST'); };
export default { name: 'financeOrderList', data() { let baseUrl = process.env.NODE_URL; let uploadPath = baseUrl + '/' + this.api.financeManager.importJinzuFinanceInfo.url; let downloadJinzuImportTemplate = baseUrl + '/' + this.api.financeManager.downloadJinzuImportTemplate.url; return { tableData: [], tableOption: this.getTableOption(), // table配置 intoChannels:[ { channelCode: "001", channelName: "物主微信公众号" }, { channelCode: "002", channelName: "支付宝小程序" }, { channelCode: "003", channelName: "物主京东合作渠道" }, { channelCode: "004", channelName: "支付宝生活号" }, { channelCode: "005", channelName: "IOS APP" } ], financeChannels: [ { channelCode: "001", channelName: "来组" }, { channelCode: "002", channelName: "金租" } ], searchCondition:{ intoChannel: "", financeChannel: "", category: "", orderStatus: "", orderRentTotalDays: "" }, fileList: [], importUrl: uploadPath, templateUrl: downloadJinzuImportTemplate } }, component: {}, computed: {}, methods: { getList(pageInfo, callback){ let param = { pageNum: pageInfo.pageIndex, pageSize: pageInfo.pageSize, intoChannel: this.searchCondition.intoChannel, financeChannel: this.searchCondition.financeChannel, category: this.searchCondition.category, orderStatus: this.searchCondition.orderStatus, orderRentTotalDays: this.searchCondition.orderRentTotalDays } this.$api.financeManager.queryFinanceList.send(param, { showLoading: true }).then(res => { if (res.code === '00') { this.tableData = res.data.list || []; callback(res.data.total); } }) }, // 查询数据 queryFinanceOrderList(){ this.$refs.table.refreshPaging(1); }, // 重置查询条件 resetConditions(){ this.searchCondition = {}; this.$refs.table.refreshPaging(1); }, // 下载模板 downloadTemp(){ let baseUrl = process.env.NODE_URL; let url = baseUrl + '/finance/download-jinzu-import-template'; window.open(url); }, // 导入 handleRemove(file, fileList) { console.log(file, fileList); }, handlePreview(file) { console.log(file); }, handleExceed(files, fileList) { this.$message.warning(`当前限制选择1个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`); }, handelSuccess(response, file, fileList){ if(response.code === '00'){ this.$message({ message: '数据导入成功', type: 'success' }); }else{ this.$alert(response.msg, '导入失败', { confirmButtonText: '确定', callback: action => {} }); this.fileList=[] } }, // 初始化表格列 getTableOption(){ let thisObj = this; let option = { showPage:true, autoHeight:true, showSerial:true, columns:[ { prop:'orderNo',label:'订单号',width:150 }, { prop:'intoChannelName',label:'渠道',width:120 }, { prop:'city',label:'城市',width:80 }, { prop:'commodityBand',label:'商品品牌',width:100 }, { prop:'shortName',label:'商品品类',width:120 }, { prop:'fullName',label:'商品描述',width:200 }, // { prop:'specContentList',label:'商品属性',width:100 }, { prop:'model',label:'型号',width:60 }, { prop:'memory',label:'内存',width:60 }, { prop:'color',label:'颜色',width:60 }, { prop:'commodityNo',label:'商品编号',width:100 }, { prop:'iemi',label:'商品IEMI码',width:150 }, { prop:'invoiceAmt',label:'发票金额',width:80 }, { prop:'depositAmt',label:'已冻结/支付押金',width:80 }, { prop:'repaymentPeriodAmt',label:'每期还款金额',width:80 }, { prop:'activateTimeStr',label:'激活时间',width:150 }, { prop:'expireDateStr',label:'租赁到期时间',width:120 }, { prop:'orderStatusName',label:'订单状态',width:150 }, { prop:'buyoutAmt',label:'买断价',width:80 }, { prop:'rentSolution',label:'租赁方案',width:100 }, { prop:'depreciationRatio',label:'折旧系数',width:80 }, { prop:'scrapValueAmt',label:'残值',width:80 }, { prop:'customerName',label:'客户姓名',width:80 }, { prop:'certId',label:'身份证号',width:150 }, { prop:'receiverTel',label:'收货人电话',width:100 }, { prop:'receiverAddr',label:'收货地址',width:200 }, { prop:'allRentAmt',label:'全部租金',width:80 }, // { prop:'financeTimeStr',label:'融资时间',width:150 }, // { prop:'financeAmt',label:'融资金额',width:80 }, { prop:'financeCount',label:'融资次数',width:80 }, { prop:'financeName',label:'资金方',width:100 } ] } return option; } } }
import { GraphQLServer, PubSub } from 'graphql-yoga'; import { formatError } from 'apollo-errors'; // set and load database configuration import './config/db'; import './models/User'; import './models/Category'; import './models/Receipt'; import mergeGraphql from './utils/mergeGraphql'; import middlewares from './middlewares/graphql'; const { typeDefs, resolvers } = mergeGraphql([{ dir: `${__dirname}/graphql/**/resolvers.js`, type: 'RESOLVERS' }, { dir: `${__dirname}/graphql/**/*.gql`, type: 'TYPES' }]) const port = process.env.PORT || 3000; const server = new GraphQLServer({ typeDefs, resolvers, middlewares, context: req => ({ req, pubsub: new PubSub() }) }); server.start( { port, formatError }, () => console.log(`Listening on port ${port}`) ); //https://ultimatecourses.com/blog/graphql-client-side-integration-with-apollo-hooks
import React, {useEffect,useState} from 'react' import Youtube from 'react-youtube' import axios from '../../axios' import './RowPost.css' import { imageUrl } from '../../Constants/constants' function RowPost(props) { const [movies, setMovies] =useState([]) useEffect(() => { axios.get(props.url).then(response=>{ console.log(response.data.results) setMovies(response.data.results) }) }, []) const opts = { height: '390', width: '100%', playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 1, }, }; const handleMovie =(id)=>{ } return ( <div className="row"> <h2>{props.title}</h2> <div className= "posters"> { movies.map((obj)=> <img onClick={()=>handleMovie(obj.id)} className={props.isSmall ? "smallposter" :"poster"} src={`${imageUrl+obj.backdrop_path}`} alt="poster"></img> ) } </div> <Youtube videoId="2g811Eo7K8U" opts={opts} /> </div> ) } export default RowPost
import React, {useState} from 'react'; function PostNewReportForm({currentUser, postId, addReport}){ const API = "http://localhost:3001/" const [reason, setReason] = useState("") const [reportOnce, setReportOnce] = useState(false) function handleSubmit(e){ e.preventDefault() const newPostReport = { user_id: currentUser.id, post_id: postId, reason, } fetch(`${API}postreports`,{ method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(newPostReport) }) .then(r => r.json()) .then(reportObj=>{ if (reportObj.id === null){ setReportOnce((reportOnce) => !reportOnce) } else { addReport(reportObj) } }) setReason("") } return( <div className="post-report-form-div"> {!reportOnce ? <div> <form onSubmit={handleSubmit}> <label htmlFor="Why are you reporting this post?"> Why are you reporting this post? </label> <br/> <div className="post-report-form-input-div"> <input className="report-input" type="text" name="reason" value={reason} onChange={(e)=>setReason(e.target.value)} placeholder={"Report as " + currentUser.username} required /> <button type="submit"><i class="fas fa-ban"></i></button> </div> </form> </div> : <div className="post-report-form-report-only-once-div">You can only report once!</div> } </div> ) } export default PostNewReportForm;
/** * Created by ntban_000 on 5/3/2017. */ angular.module('userServices',[]) .factory('User', ['$http', 'Conf', function($http, Conf){ const userFactory = []; //get all users userFactory.getUsers = function(){ return $http.get(Conf.auth_service.concat('/users')).then(function(data){ return data; }).catch(function(err){ return err; }) } //get user by username userFactory.getUserByUsername = function(uname){ return $http.get(Conf.auth_service.concat('/users/').concat(uname)).then(function(data){ return data; }).catch(function(err){ return err; }) } //create new user userFactory.addUser = function(data) { return $http.post(Conf.auth_service.concat('/users'),data).then(function(data){ return data; }).catch(function(err){ return err; }) } //update user userFactory.updateUser = function(uname,data){ return $http.put(Conf.auth_service.concat('/users/').concat(uname),data).then(function(data){ return data; }).catch(function(err){ return data; }) } //delete user record userFactory.deleteUser = function(username){ return $http.delete(Conf.auth_service.concat('/users/').concat(username)).then(function(data){ return data; }).catch(function(err){ return err; }) } return userFactory; }]) .factory('UserData', [function(){ const userDataFac = {}; var user_data; userDataFac.setData = function(data){ user_data = data; } userDataFac.getData = function(){ return user_data; } return userDataFac; }]) // user logs .factory('UserLogs',['$injector','Conf',function($injector,Conf){ const userLogsFactory = {}; //get all logs userLogsFactory.getAllLogs = function(){ return $injector.get('$http').get(Conf.auth_service.concat('/logs')).then(function(data){ return data; }).catch(function(err){ return err; }) } //add new log userLogsFactory.addLog = function(data){ const send = {}; send.description = data; return $injector.get('$http').post(Conf.auth_service.concat('/logs'),send).then(function(data){ return data; }).catch(function(err){ console.log(err); return err; }) } return userLogsFactory; }]) //intercept requests and send logs .factory('LogInterceptor', ['UserLogs','Conf','$rootScope', function(UserLogs,Conf,$rootScope){ const logInterceptFactory = {}; const fact = this; if($rootScope.user){ fact.uname = $rootScope.user.data.name; console.log($rootScope.user); } logInterceptFactory.request = function(req){ //auth service requests if(req.url==Conf.auth_service.concat('/authenticate')){ UserLogs.addLog("User logged into the system"); }else if(req.url==Conf.auth_service.concat('/users')&&req.method=="POST"){ UserLogs.addLog("Added the user "+req.data.username+" to the system"); }else if(req.url.startsWith(Conf.auth_service.concat('/users'))&&req.method=="PUT"){ UserLogs.addLog("Updated the user "+req.url.split('/')[4]); }else if(req.url.startsWith(Conf.auth_service.concat('/users'))&&req.method=="DELETE"){ UserLogs.addLog("Deleted the user "+req.url.split('/')[4]); } //drug service requests else if(req.url.startsWith(Conf.drug_service.concat('/drug'))&&req.method=="POST"){ UserLogs.addLog("Added a new drug to the system"); }else if(req.url.startsWith(Conf.drug_service.concat('/drug'))&&req.method=="PUT"){ UserLogs.addLog("Updated a drug in the system"); } //batch routes else if(req.url.startsWith(Conf.drug_service.concat('/batch'))&&req.method=="POST"){ UserLogs.addLog("Added a new batch to the system"); } //prescriptions else if(req.url.startsWith(Conf.prescription_service.concat('/prescription/pharmacist'))&&req.method=="POST"){ UserLogs.addLog("Pharmacist added a new prescription to the system"); } else if(req.url.startsWith(Conf.prescription_service.concat('/prescription/doctor'))&&req.method=="POST"){ UserLogs.addLog("Doctor added a new prescription to the system"); } return req; } return logInterceptFactory; }])
// Declare your function first // Write a function that adds two numbers together // * Call the function, passing `13` and `124` as parameters, and assigning the returned value to a variable `sum` function suma(a, b) { return a + b; } let sum = suma(13, 124); // Call the function and assign to a variable `sum` var sum = add(13, 124); console.log(sum);
/* * Copyright (c) 2011. * * Author: oldj <oldj.wu@gmail.com> * Blog: http://oldj.net/ * * Last Update: 2011/1/10 5:22:52 */ // _TD.a.push begin _TD.a.push(function (TD) { /** * 舞台类 * @param id {String} 舞台ID * @param cfg {Object} 配置 */ TD.Stage = function (id, cfg) { this.id = id || ("stage-" + TD.lang.rndStr()); this.cfg = cfg || {}; this.width = this.cfg.width || 640; this.height = this.cfg.height || 540; /** * mode 有以下状态: * "normal": 普通状态 * "build": 建造模式 */ this.mode = "normal"; /* * state 有以下几种状态: * 0: 等待中 * 1: 运行中 * 2: 暂停 * 3: 已结束 */ this.state = 0; this.acts = []; this.current_act = null; this._step2 = TD.lang.nullFunc; this._init(); }; TD.Stage.prototype = { _init: function () { if (typeof this.cfg.init == "function") { this.cfg.init.call(this); } if (typeof this.cfg.step2 == "function") { this._step2 = this.cfg.step2; } }, start: function () { this.state = 1; TD.lang.each(this.acts, function (obj) { obj.start(); }); }, pause: function () { this.state = 2; }, gameover: function () { //this.pause(); this.current_act.gameover(); }, /** * 清除本 stage 所有物品 */ clear: function () { this.state = 3; TD.lang.each(this.acts, function (obj) { obj.clear(); }); // delete this; }, /** * 主循环函数 */ step: function () { if (this.state != 1 || !this.current_act) return; TD.eventManager.step(); this.current_act.step(); this._step2(); }, /** * 绘制函数 */ render: function () { if (this.state == 0 || this.state == 3 || !this.current_act) return; this.current_act.render(); }, addAct: function (act) { this.acts.push(act); }, addElement: function (el, step_level, render_level) { if (this.current_act) this.current_act.addElement(el, step_level, render_level); } }; }); // _TD.a.push end // _TD.a.push begin _TD.a.push(function (TD) { TD.Act = function (stage, id) { this.stage = stage; this.id = id || ("act-" + TD.lang.rndStr()); /* * state 有以下几种状态: * 0: 等待中 * 1: 运行中 * 2: 暂停 * 3: 已结束 */ this.state = 0; this.scenes = []; this.end_queue = []; // 本 act 结束后要执行的队列,添加时请保证里面全是函数 this.current_scene = null; this._init(); }; TD.Act.prototype = { _init: function () { this.stage.addAct(this); }, /* * 开始当前 act */ start: function () { if (this.stage.current_act && this.stage.current_act.state != 3) { // queue... this.state = 0; this.stage.current_act.queue(this.start); return; } // start this.state = 1; this.stage.current_act = this; TD.lang.each(this.scenes, function (obj) { obj.start(); }); }, pause: function () { this.state = 2; }, end: function () { this.state = 3; var f; while (f = this.end_queue.shift()) { f(); } this.stage.current_act = null; }, queue: function (f) { this.end_queue.push(f); }, clear: function () { this.state = 3; TD.lang.each(this.scenes, function (obj) { obj.clear(); }); // delete this; }, step: function () { if (this.state != 1 || !this.current_scene) return; this.current_scene.step(); }, render: function () { if (this.state == 0 || this.state == 3 || !this.current_scene) return; this.current_scene.render(); }, addScene: function (scene) { this.scenes.push(scene); }, addElement: function (el, step_level, render_level) { if (this.current_scene) this.current_scene.addElement(el, step_level, render_level); }, gameover: function () { //this.is_paused = true; //this.is_gameover = true; this.current_scene.gameover(); } }; }); // _TD.a.push end // _TD.a.push begin _TD.a.push(function (TD) { TD.Scene = function (act, id) { this.act = act; this.stage = act.stage; this.is_gameover = false; this.id = id || ("scene-" + TD.lang.rndStr()); /* * state 有以下几种状态: * 0: 等待中 * 1: 运行中 * 2: 暂停 * 3: 已结束 */ this.state = 0; this.end_queue = []; // 本 scene 结束后要执行的队列,添加时请保证里面全是函数 this._step_elements = [ // step 共分为 3 层 [], // 0 [], // 1 默认 [] // 2 ]; this._render_elements = [ // 渲染共分为 10 层 [], // 0 背景 1 背景图片 [], // 1 背景 2 [], // 2 背景 3 地图、格子 [], // 3 地面 1 一般建筑 [], // 4 地面 2 人物、NPC等 [], // 5 地面 3 [], // 6 天空 1 子弹等 [], // 7 天空 2 主地图外边的遮罩,panel [], // 8 天空 3 [] // 9 系统特殊操作,如选中高亮,提示、文字遮盖等 ]; this._init(); }; TD.Scene.prototype = { _init: function () { this.act.addScene(this); this.wave = 0; // 第几波 }, start: function () { if (this.act.current_scene && this.act.current_scene != this && this.act.current_scene.state != 3) { // queue... this.state = 0; this.act.current_scene.queue(this.start); return; } // start this.state = 1; this.act.current_scene = this; }, pause: function () { this.state = 2; }, end: function () { this.state = 3; var f; while (f = this.end_queue.shift()) { f(); } this.clear(); this.act.current_scene = null; }, /** * 清空场景 */ clear: function () { // 清空本 scene 中引用的所有对象以回收内存 TD.lang.shift(this._step_elements, function (obj) { TD.lang.shift(obj, function (obj2) { // element //delete this.scene; obj2.del(); // delete this; }); // delete this; }); TD.lang.shift(this._render_elements, function (obj) { TD.lang.shift(obj, function (obj2) { // element //delete this.scene; obj2.del(); // delete this; }); // delete this; }); // delete this; }, queue: function (f) { this.end_queue.push(f); }, gameover: function () { if (this.is_gameover) return; this.pause(); this.is_gameover = true; }, step: function () { if (this.state != 1) return; if (TD.life <= 0) { TD.life = 0; this.gameover(); } var i, a; for (i = 0; i < 3; i++) { a = []; var level_elements = this._step_elements[i]; TD.lang.shift(level_elements, function (obj) { if (obj.is_valid) { if (!obj.is_paused) obj.step(); a.push(obj); } else { setTimeout(function () { obj = null; }, 500); // 一会儿之后将这个对象彻底删除以收回内存 } }); this._step_elements[i] = a; } }, render: function () { if (this.state == 0 || this.state == 3) return; var i, a, ctx = TD.ctx; ctx.clearRect(0, 0, this.stage.width, this.stage.height); for (i = 0; i < 10; i++) { a = []; var level_elements = this._render_elements[i]; TD.lang.shift(level_elements, function (obj) { if (obj.is_valid) { if (obj.is_visiable) obj.render(); a.push(obj); } }); this._render_elements[i] = a; } if (this.is_gameover) { this.panel.gameover_obj.show(); } }, addElement: function (el, step_level, render_level) { //TD.log([step_level, render_level]); step_level = step_level || el.step_level || 1; render_level = render_level || el.render_level; this._step_elements[step_level].push(el); this._render_elements[render_level].push(el); el.scene = this; el.step_level = step_level; el.render_level = render_level; } }; }); // _TD.a.push end
'use strict'; const Controller = require('./controller'); module.exports.signUp = { method: 'POST', path: '/api/v1/user/signUp', handler: Controller.signUp, options: { auth: false, tags: ['api', 'user'], description: 'Register a new user' } }; module.exports.signIn = { method: 'POST', path: '/api/v1/user/signIn', handler: Controller.signIn, options: { auth: false, tags: ['api', 'user'], description: 'Authenticate a user' } }; module.exports.getById = { method: 'GET', path: '/api/v1/user/{id}', handler: Controller.getById, options: { auth: 'default', tags: ['api', 'user'], description: 'Find a user by id' } }; module.exports.update = { method: 'PUT', path: '/api/v1/user/{id}', handler: Controller.update, options: { auth: 'default', tags: ['api', 'user'], description: 'Update a user by id' } }; module.exports.delete = { method: 'DELETE', path: '/api/v1/user/{id}', handler: Controller.delete, options: { auth: 'default', tags: ['api', 'user'], description: 'Delete a user by id' } };
import React from 'react' import Score from '../Score/Score'; import Dropdown from 'react-dropdown' const Side = ({teams, score, selected, modifyScore, _OnSelect }) => { return ( <article className='side'> <p>{teams[0].name}</p> <p>{score}</p> </article> ) } export default Side
import React, { Component } from "react"; import { View } from "react-native"; import NewCard from "./NewCard" import { useNavigation, useRoute } from '@react-navigation/native'; import { useDispatch } from 'react-redux'; class NewCardScreen extends Component { static displayName = "NewCardScreen"; static navigationOptions = { title: "New Card" }; render() { return ( <View> <NewCardShow /> </View> ); } } const NewCardShow = () => { const navigation = useNavigation(); const dispatch = useDispatch(); const route = useRoute(); const deckID = route.params.deckID; return ( <View> <NewCard deckID={deckID} navigation={navigation} dispatch={dispatch} /> </View> ); }; export default NewCardScreen;
import { getTheTvShows, getTheTrailers } from '../api'; import { TVSHOWS_FETCHED, TRAILERS_FETCHED, } from './actionTypes' export const tvShowsFetched = value => { return { type: TVSHOWS_FETCHED, payload: value } }; export const trailersFetched = value => { return { type: TRAILERS_FETCHED, payload: value } }; export const fetchTvShows = (text) => { return async (dispatch) => { try { const response = await getTheTvShows(text); dispatch(tvShowsFetched(response.data.results)) } catch (err) { console.log(err); dispatch(tvShowsFetched([])) } } }; export const getTvShowsTrailer = (id) => { return async (dispatch) => { try { const response = await getTheTrailers(id); dispatch( trailersFetched(response.data.results[0].key)) } catch (err) { console.log(err); dispatch(trailersFetched(null)) } } };
$ = function(s) { // suit for ie if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function(prefix) { return this.slice(0, prefix.length) === prefix; }; } if (s.startsWith("#")) { return document.getElementById(s.slice(1)) } else if (s.startsWith(".")) { return document.getElementsByClassName(s.slice(1)) } else if (s.startsWith(",")) { return document.getElementsByName(s.slice(1)) } else { return document.getElementsByTagName(s) } } function main() { $("#add").onclick = function() { window.location.href = 'add.html' return false } $("#join").onclick = function() { window.location.href = 'login.html' return false } Menu() } function Menu() { var e1 = $('#left') var e2 = $('#right') // e1.style.height = "0px" // e1.style.padding = "0px" $("#menu").onclick = function() { // if(e1.style.backgroundColor == "rgba(255, 255, 255, 0)" || e1.style.backgroundColor == ""){ // e1.style.display = "block" // e2.style.display = "block" // sleep(120) // for (var i = 0; i < 0.3; i+=0.001) { // e1.style.backgroundColor=' rgba(255, 255, 255, '+ i +')' // e2.style.backgroundColor=' rgba(255, 255, 255, '+ i +')' // // } // for (variable of e1.children) { // variable.children[0].style.color=' rgba(255, 255, 255, 1)' // } // for (variable of e2.children) { // variable.children[0].style.color=' rgba(255, 255, 255, 1)' // } // } // else { // e1.style.backgroundColor=' rgba(255, 255, 255, 0)' // e2.style.backgroundColor=' rgba(255, 255, 255, 0)' // for (variable of e1.children) { // variable.children[0].style.color=' rgba(255, 255, 255, 0)' // } // for (variable of e2.children) { // variable.children[0].style.color=' rgba(255, 255, 255, 0)' // } // sleep(120) // e1.style.display = "none" // e2.style.display = "none" // sleep(120) // } // if(e1.style.height == "0px"){ // e1.style.height = "auto" // e1.style.padding = "5px" // } // else { // e1.style.height = "0px" // e1.style.padding = "0px" // } if (e1.style.display == "none" || e1.style.display == "") { e1.style.display = "block" e2.style.display = "block" } else { e1.style.display = "none" e2.style.display = "none" } } drawMenu() } function drawMenu() { var canvas = $("#menu") var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgba(255,255,255,0.5)'; ctx.fillRect(0, 0, 50, 6); ctx.fillRect(0, 10, 50, 6); ctx.fillRect(0, 20, 50, 6); } function sleep(t) { var now = new Date(); var exitTime = now.getTime() + t; while (true) { now = new Date(); if (now.getTime() > exitTime) return; } }
/** * @describe canvas 绘制图表纯手写 * */ export function printBar(strength, id) { let container = document.getElementById(id); let w = container.offsetWidth; let h = container.offsetHeight; let line = 2; // 方块件的纵向距离 let size = h / 6 - line; // 方块宽高 let distance = size / 2; // 方块间的横向距离 let bgColor = '#2E333E'; // 方块的背景颜色 let boxColors = ['#059DEA', '#05ACE0', '#05BCD7', '#05CCCC', '#05e5e5']; let canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; container.appendChild(canvas); let ctx = canvas.getContext("2d"); /** * @describe 绘制纵向的一条 * params (num:第几条;x:绘制这一条的起始的横向位置) * */ let longitudinal = (num, x, isbg) => { for (let n = 1; n <= num; n++) { ctx.fillStyle = isbg ? bgColor : boxColors[n - 1]; ctx.fillRect(x, h - n * (line + size) + line, size, size); } } for (let i = 1; i <= 5; i++) { longitudinal(i, (distance + size) * (i - 1), true) } for (let i = 1; i <= strength; i++) { longitudinal(i, (distance + size) * (i - 1)) } } export function printRing(strength, id) { let container = document.getElementById(id); let w = container.offsetWidth; let h = container.offsetHeight; let bgColor = '#2E333E'; // 圆环的背景颜色 let ringColor = '#059DEA'; // 圆环渐变色 let radius = 60; // 圆环半径 let PI = Math.PI; let canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; container.appendChild(canvas); let ctx = canvas.getContext("2d"); /** * @describe 绘制圆环 * params * */ let ring = (start, end) => { ctx.beginPath(); ctx.arc(50, 70, 40, start, end, false); ctx.lineWidth = 12; ctx.stroke();//画空心圆 ctx.closePath(); } ctx.strokeStyle = bgColor; ring(PI * 3 / 4, PI * 9 / 4); let deg = (PI * 9 / 4 - PI * 3 / 4) * strength / 5; ctx.strokeStyle = ringColor; ring(PI * 3 / 4, PI * 3 / 4 + deg) }
var mongoose = require('mongoose'); var studentSchema = new mongoose.Schema({ student_id : {type: String, required: true, max: 5, unique: true}, student_name :{type : String,required : true}, student_contact : Number, student_address : {type : String, required : true,} }); var Student = mongoose.model('student', studentSchema); module.exports = Student;
import React from 'react'; import './styles/Comment.css'; const Comment = ({text, votes, id, thumbUpComment, thumbDownComment, removeComment}) => <li className="Comment"> <div className="text"> <p>{text}</p> </div> <div> <span className="votes">votes: {votes}</span> <button className="btn" onClick={() => thumbUpComment(id)}>Thumb up</button> <button className="btn" onClick={() => thumbDownComment(id)}>Thumb Down</button> <button className="btn btn--remove" onClick={() => removeComment(id)}>X</button> </div> </li>; export default Comment;
const { validateExtension } = require('./validateExtension.js'); const { validateUrls } = require('./validate.js') const { links } = require('./links.js') const { stats } = require('./stats.js') module.exports = addExp = (path, options) => { return new Promise((resolve, reject) => { if (validateExtension(path)){ links(path).then((objLinks) => { if (options.validate === true && options.stats === true) { validateUrls(objLinks).then((res)=>{ resolve(stats(res, options.validate)) }) } else if (options.validate === true) { validateUrls(objLinks).then(response => { resolve(response) }) } else if (options.stats === true) { resolve(stats(objLinks)) } else { resolve(objLinks) } }) .catch((err) => { reject(err); }) }else { reject("Extension isn't valid") } }) //return mainPromise; }