text
stringlengths
7
3.69M
import React from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import configureStore from './state/store'; import Views from './views'; import './main.scss' const reduxStore = configureStore(window.REDUX_INITIAL_STATE); // for SSR function Main() { return ( <ReduxProvider store = {reduxStore}> <Views/> </ReduxProvider> ); } export default Main;
//定义多个属性 Object.defineProperties()函数 var book={}; Object.defineProperties(book,{ _yaer:{ writable:true, value:2004 }, edition:{ writable:true, value:1 }, year:{ get:function(){ return this._yaer; }, set:function(newValue){ if(newValue>2004){ this._yaer=newValue; this.edition+=newValue-2004; } } } });
$(document).ready(function () { $(".attachment a").each(function () { var text = $(this).text(); var symbol = "\\"; $(this).text(text.substring(text.lastIndexOf(symbol) +1)).append("<i class='fa fa-file-word-o'></i>"); /* $(this).text($(this).text().substring(0, 497) + "...");*/ }); })
import registerUser from './register-user' import authenticateUser from './authenticate-user' import isUserLoggedIn from './is-user-logged-in' import logUserOut from './log-user-out' import retrieveUser from './retrieve-user' import search from './search' import registerDog from './register-dog' import retrieveFavorites from './retrieve-favorites' import retrieveAllDogs from './retrieve-all-dogs' import retrieveDog from './retrieve-dog' import toggleFavorite from './toggle-favorite' import unregisterDog from './unregister-dog' import createChat from './create-chat' import updateChat from './update-chat' import retrieveChat from './retrieve-chat' import retrieveAllChats from './retrieve-all-chats' import getUserId from './geUserID' import upload from './upload' export default { set __token__(token) { sessionStorage.token = token }, get __token__() { return sessionStorage.token }, registerUser, authenticateUser, isUserLoggedIn, logUserOut, retrieveUser, search, registerDog, retrieveFavorites, retrieveAllDogs, retrieveDog, toggleFavorite, unregisterDog, createChat, updateChat, retrieveChat, retrieveAllChats, getUserId, upload }
import React from "react"; import PropTypes from "prop-types"; import preloader from "image-preloader"; import { cssTimeToMs } from "../../util"; import defaults from "../../defaults"; import VisibilitySensor from "react-visibility-sensor"; export class ImageLoader extends React.Component { static propTypes = { src: PropTypes.string.isRequired, transitionTime: PropTypes.string, lazyLoad: PropTypes.bool, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, PropTypes.func, ]), }; state = { hasLoaded: false, hasFailed: false, shouldShowLoader: true, visibilitySensorIsActive: true, }; componentDidMount() { this._isMounted = true; if (!this.props.lazyLoad) { this.preloadImage(); } } componentDidUpdate(prevProps) { if (prevProps.src !== this.props.src) { if (!this.props.lazyLoad) { this.preloadImage(); } else { this.setState({ visibilitySensorIsActive: true }); } } } componentWillUnmount() { this._isMounted = false; } render() { const { src, children, lazyLoad } = this.props; const { hasLoaded, hasFailed, shouldShowLoader, visibilitySensorIsActive, } = this.state; /* * When using ImageLoader the children prop should be a function. * Render calls this function with the props it requires to * fade in an image. * See https://reactjs.org/docs/render-props.html */ const childElement = children({ hasLoaded, shouldShowLoader, hasFailed, src, }); /* * Wrap element in react visibility sensor when lazyLoad is true */ return lazyLoad ? ( <VisibilitySensor active={visibilitySensorIsActive} onChange={this.handleVisibilityChange} partialVisibility > {childElement} </VisibilitySensor> ) : ( childElement ); } preloadImage() { const { src } = this.props; preloader .simplePreload(src) .then(this.handleImageLoaderLoaded) .catch(this.handleImageLoaderFailed); } /* * Once the image is loaded successfully this handler will be * called, this will change the `hasLoaded` attribute to true * then the `shouldShowLoader` attribute to false after * the transition has completed. The reason we do this on a * timeout is to ensure the loader is not hidden as soon as the * image has loaded resulting in a 'flash' */ handleImageLoaderLoaded = () => { const { transitionTime } = this.props; const hideLoaderDelay = cssTimeToMs(transitionTime); this.setState({ hasLoaded: true }, () => { setTimeout(() => { if (!this._isMounted) return; this.setState({ shouldShowLoader: false, }); }, hideLoaderDelay); }); }; handleImageLoaderFailed = () => { this.setState({ hasFailed: true }); }; handleVisibilityChange = isVisible => { if (!isVisible) return; this.setState({ visibilitySensorIsActive: false }); this.preloadImage(); }; } ImageLoader.defaultProps = { transitionTime: defaults.transitionTime, }; export default ImageLoader;
/////////////// Geoserver中发布的 House 信息 /////////////// var House = new ol.layer.Image({ source:new ol.source.ImageWMS({ // http://localhost:8080/geoserver/WebGIS/wms url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:House'}, serverType: 'geoserver', visible: false }) }); /////////////// Geoserver中发布的 Hospital 信息 /////////////// var Hospital = new ol.layer.Image({ source:new ol.source.ImageWMS({ url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:Hospital'}, serverType: 'geoserver', visible: false }) }); /////////////// Geoserver中发布的 School 信息 /////////////// var School = new ol.layer.Image({ source:new ol.source.ImageWMS({ url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:School'}, serverType: 'geoserver', visible: false }) }); /////////////// Geoserver中发布的 Environment 信息 /////////////// var Environment = new ol.layer.Image({ source:new ol.source.ImageWMS({ url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:Environment'}, serverType: 'geoserver', visible: false }) }); /////////////// Geoserver中发布的 Subway 信息 /////////////// var Subway = new ol.layer.Image({ source:new ol.source.ImageWMS({ url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:Sub'}, serverType: 'geoserver', visible: false }) }); /////////////// Geoserver中发布的 Bus_station 信息 /////////////// var Bus_station = new ol.layer.Image({ source:new ol.source.ImageWMS({ url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:BusStops'}, serverType: 'geoserver', visible: false }) }); /////////////// Geoserver中发布的 Shopping 信息 /////////////// var Shopping = new ol.layer.Image({ source:new ol.source.ImageWMS({ url:'http://localhost:8080/geoserver/GIS/wms', params:{'LAYERS':'class:Shopping'}, serverType: 'geoserver', visible: false }) });
import React from 'react'; import { Button, Form, Grid, Header, Image, Message, Segment, Checkbox, Confirm } from 'semantic-ui-react'; import { GraphQLClient } from 'graphql-request'; class SignUpForm extends React.Component { constructor(props) { super(props); this.state = { email: '', password1: '', password2: '', data: '', userexist: false }; } handleEmailChange = (e) => { if (!e.target.value.trim()) { return } this.setState({ email: e.target.value }); }; handlePasswordChange1 = (e) => { if (!e.target.value.trim()) { return } this.setState({ password1: e.target.value }); }; handlePasswordChange2 = (e) => { if (!e.target.value.trim()) { return } this.setState({ password2: e.target.value }); }; handleSignUp = (e) => { e.preventDefault(); console.log("EMail: " + this.state.email); console.log("Password1: " + this.state.password1); console.log("Password2: " + this.state.password2); if((this.state.password1 !== '' || this.state.password1 !== '' ) && (this.state.password1 === this.state.password2)) { const client = new GraphQLClient('http://localhost:4005/graphql', { // credentials: 'include', mode: 'cors' }) const query = `query findUser($userEmail:String!){ userloginDetails(userEmail:$userEmail) { userEmail userPassword } }`; const queryvariables = { "userEmail":`${this.state.email}` } client.request(query,queryvariables).then(data => { if(data !== null) { this.setState({ userexist: true }) }; }) const mutation = `mutation saveUser($InputDoL: logindetails) { login(InputDoL: $InputDoL) { userEmail userPassword } }`; const variables = { InputDoL: { "userEmail":`${this.state.email}`, "userPassword":`${this.state.password1}` } } // Request for Data to Graphql Server... if(this.state.userexist) { client.request(mutation,variables).then(signupdata => { this.setState({ data: signupdata }) }) if( this.state.data !== 'undefined' || this.state.data !== '' ) { this.setState({email: '',password1: '',password2: '', data: ''}); window.location.href = "http://localhost:3000/signupsuccess"; } } else { this.setState({ email: '', password1: '', password2: '', data: '', userexist:false }); console.log('Already Exist!!! '); } } else { window.location.href = "http://localhost:3000/signuperror"; } }; open = () => this.setState({ userexist: true }) close = () => this.setState({ userexist: false }) render() { return ( <div className='login-form'> <style>{` body > div, body > div > div, body > div > div > div.login-form { height: 100%; } `}</style> <Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'> <Grid.Column style={{ maxWidth: 450 }}> <Header as='h2' color='teal' textAlign='center'> <Image src='/logo.png' /> Log-in to your account </Header> <Form size='large' > <Segment stacked> <Form.Input fluid icon='user' iconPosition='left' placeholder='E-mail address' value={this.state.email} onChange={e => this.handleEmailChange(e)} /> <Form.Input fluid icon='lock' iconPosition='left' placeholder='Password' value={this.state.password1} onChange={e => this.handlePasswordChange1(e)} /> <Form.Input fluid icon='lock' iconPosition='left' placeholder='Re-Enter Password' type='password' value={this.state.password2} onChange={e => this.handlePasswordChange2(e)} /> {/* <Form.Field fluid size='large'> <Checkbox fluid label='I agree to the Terms and Conditions' /> </Form.Field> <Form.Field fluid control={Checkbox} label={{ children: 'I agree to the Terms and Conditions' }} /> */} <Button color='teal' fluid size='large' onClick={(e) => this.handleSignUp(e)} > SignUp </Button> {/* <Confirm open={this.state.userexist} header='This User Already Exist' onCancel={this.close} onConfirm={this.close} /> */} </Segment> </Form> <Message> Register Users? <a href='http://localhost:3000/login'>Login</a> </Message> </Grid.Column> </Grid> </div> ); } } export default SignUpForm
require('./header'); require('./mainbar'); require('./form');
import React, {useState,useEffect} from 'react'; import { Audio } from "expo-av"; import { FlatList, View, StyleSheet, TouchableOpacity } from 'react-native'; const defaultSound = [ require('../../assets/DefaultAudio/cymbal.wav'), require('../../assets/DefaultAudio/daibyoshi.wav'), require('../../assets/DefaultAudio/med_taiko.wav'), require('../../assets/DefaultAudio/miyadaiko.wav'), require('../../assets/DefaultAudio/taiko.wav'), require('../../assets/DefaultAudio/tsuzumi.wav'), ]; const SamplerComponent = ({navigation}) =>{ const generateGrid = () =>{ const pads = []; let id = 0; for(let i=0;i<defaultSound.length;i++){ for(let j=0;j<defaultSound.length;j++){ pads.push({index:j,id:id}); id++; } } return pads; } const [sound, setSound] = useState(); const [grid, setGrid] = useState(generateGrid()); const playSound = async (index) => { const { sound } = await Audio.Sound.createAsync(defaultSound[index]); setSound(sound); await sound.playAsync(); console.log(defaultSound); }; const handleLongPress = (item) =>{ navigation.navigate("Edit sampler",{props: item}) } useEffect(() => { return () => { if (sound) { sound.unloadAsync(); } }; }, [sound]); return( <View style={styles.container}> <FlatList data={grid} numColumns={defaultSound.length} keyExtractor={(item)=>item.id.toString()} renderItem={({item})=> <TouchableOpacity style={styles.button} onPress={()=>{playSound(item.index)}} onLongPress={()=>handleLongPress(item)} > </TouchableOpacity> } /> </View> ); } const styles = StyleSheet.create({ container:{ flex: 1, justifyContent:'center', //alignContent:'center', marginTop:15 }, button:{ width:50, height:50, padding:50, margin:2, backgroundColor:'tomato' } }); export default SamplerComponent;
import { firebaseRef, checkLogin } from './auth'; const date = new Date(); const dateString = `${date.getDate()}-${date.getMonth()+1}-${date.getYear()+1900}`; const dateStringYest = `${date.getDate()}-${date.getMonth()+1}-${date.getYear()+1900}`; // var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com"); // import { secret } from '../../secret.js'; // const SHOWUSERS = true; // // function getData(date1) { // let email = []; // let users = 0; // let sessions = 0; // return new Promise((res, rej) => { // firebaseRef.child('users').once('value', snap => { // snap.forEach(dat => { // const x = dat.val(); // if (x[date1]) { // users++; // sessions+= (x[date1] || 0); // email.push({ email: x.email, count: x[date1] }); // } // }); // email = email.sort((a, b) => b.count - a.count); // console.log(email); // console.log(`${date1} users = ${users},sessions ${sessions}`); // res(users, sessions, email); // }); // }); // } // function getFreq() { // const freq = []; // const freqMost = []; // let count = 0; // return new Promise((res, rej) => { // firebaseRef.child('users').once('value', snap => { // // const value = snap.val(); // // console.log(value.length, val ue); // snap.forEach(dat => { // const value = dat.val(); // // console.log(Object.keys(value).length, value); // freq[Object.keys(value).length-1] = (freq[Object.keys(value).length-1] + 1 || 0); // if (Object.keys(value).length-1 >= 4) { // freqMost.push({ email: value.email }); // // if (value.email.indexOf('201501') > -1) { // count++; // // console.log(`https://ecampus.daiict.ac.in/webapp/intranet/StudentPhotos/${value.email.slice(0, 9)}.jpg`); // // } // } // }); // // email = email.sort((a, b) => b.count - a.count); // // console.log(email); // // console.log(`${date1} users = ${users},sessions ${sessions}`); // // res(users, sessions, email); // console.log(count, freq); // }); // }); // } // // if (SHOWUSERS) { // firebaseRef.auth(secret, function(error, result) { // if (error) { // console.log("Authentication Failed!", error); // } else { // console.log(getData()); // console.log("Authenticated successfully with payload:", result.auth); // console.log("Auth expires at:", new Date(result.expires * 1000)); // } // }); // getData('7-1-2016'); // getData('8-1-2016'); // getData('9-1-2016'); // getData('10-1-2016'); // getData('11-1-2016'); // getData('12-1-2016'); // getData('13-1-2016'); // getData('14-1-2016'); // getData('15-1-2016'); // getData('16-1-2016'); // getData('17-1-2016'); // getData('18-1-2016'); // getData('19-1-2016'); // getData('20-1-2016'); // getData('21-1-2016'); // getData('22-1-2016'); // getData('23-1-2016'); // getData('24-1-2016'); // // // // getFreq(); // // // getFreq(); // } function toHash(str) { let hash = 0; let i; let chr; let len; if (str.length === 0) return hash; for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; } export function readTopFolders(user) { return checkLogin(user) .then(() => { console.log('hshshsh'); return new Promise((resolve, reject) => { const obj = {}; firebaseRef .child('file').child(dateString).child(user.id.slice(0, 6)) .orderByValue().limitToLast(10).once('value', snap => { snap.forEach(dat => { obj[dat.key()] = (obj[dat.key()] || 0) + dat.val(); }); if (date.getDate() === 1) { resolve(obj); } }, (errorObject) => { console.log("The read failed: " + errorObject.code); reject(errorObject); return; }); if (date.getDate() >= 2) { const yesterday = `${date.getDate() - 1}-${date.getMonth()+1}-${date.getYear()+1900}`; firebaseRef .child('file').child(yesterday).child(user.id.slice(0, 6)) .orderByValue().limitToLast(10).once('value', snap => { snap.forEach(dat => { obj[dat.key()] = (obj[dat.key()] || 0) + dat.val(); }); resolve(obj); }); } }); }); } export function increment(path, user, isFile) { // console.log('incrementing'); console.log(path); const target = firebaseRef.child('file').child(dateString).child(user.id.slice(0, 6)).child(path); target.transaction((currentData) => { return (currentData || 0) + 1; }, (e) => { if (e) { console.error('hero', e); } }); } export function loginIncrement() { const auth = firebaseRef.getAuth(); const target = firebaseRef.child('users').child(auth.uid); target.child('email').transaction(currentData => { return (currentData || auth.password.email); }); target.child(dateString).transaction((currentData) => { return (currentData || 0) + 1; }, (e) => { if (e) { console.error('loginincrement', e); } }); } export function emailIncrement(subject) { // const auth = firebaseRef.getAuth(); if (!subject) { return; } firebaseRef.child('email').child(toHash(subject)) .transaction((currentData) => { if (!currentData) { return { subject, count: 1, }; } return { subject, count: currentData.count + 1, }; }, (e) => { if (e) { console.error('hero', e); } }); }
const { expect } = require('chai') const nullAddress = '0x0000000000000000000000000000000000000000' describe('Gift contract', function () { let gift, admin1, hippyKing1, hippyKing2, user1 before(async () => { [admin1, hippyKing1, hippyKing2, user1] = await ethers.getSigners() const Gift = await ethers.getContractFactory('GiftV1') gift = await Gift.deploy(admin1.address) }) describe('hippy tests', function () { it('should not have a hippy king', async function () { await expect(await gift.hippyKing()).to.equal(nullAddress) }) it('only bidder with enough salt can be hippy king, and only when not paused', async function () { const hippyFee = await gift.hippyFee() await expect(gift.connect(hippyKing1).crownMyself()).to.be.revertedWith('Invalid fee') await expect(gift.connect(admin1).pause()).to.emit(gift, 'Paused') await expect( gift.connect(hippyKing1).crownMyself({ value: hippyFee.add(ethers.utils.parseEther(String(5))) }) ).to.be.revertedWith('Pausable: paused') await expect(gift.connect(admin1).unpause()).to.emit(gift, 'Unpaused') await expect( gift.connect(hippyKing1).crownMyself({ value: hippyFee.add(ethers.utils.parseEther(String(5))) }) ).to.emit(gift, 'NewKing') await expect(await gift.hippyKing()).to.equal(hippyKing1.address) }) it('only hippy king can loose their mind', async function () { await expect(gift.connect(user1).decree()).to.be.revertedWith('Not king') await expect(gift.connect(hippyKing1).decree()).to.be.emit(gift, 'Hippy') await expect(await gift.hippy()).to.equal(true) }) it('only hippy king can regain their mind', async function () { await expect(gift.connect(user1).decree()).to.be.reverted // With(...) await expect(gift.connect(hippyKing1).decree()).to.be.emit(gift, 'Hippy') await expect(await gift.hippy()).to.equal(false) }) it('only hippy king can abdicate, and only when not paused', async function () { await expect(gift.connect(user1).abdicateCrown('I AM A COWARD')).to.be.revertedWith('Not king') await expect(gift.connect(admin1).pause()).to.emit(gift, 'Paused') await expect( gift.connect(hippyKing1).abdicateCrown('I AM A COWARD') ).to.be.revertedWith('Pausable: paused') await expect(gift.connect(admin1).unpause()).to.emit(gift, 'Unpaused') await expect(gift.connect(hippyKing1).abdicateCrown('I AM A COWARD')).to.emit(gift, 'Shame') }) it('only admins can change hippy fee', async function () { const hippyFee = await gift.hippyFee() const newFee = hippyFee.add(ethers.utils.parseEther(String(5))) await expect(gift.connect(user1).setHippyFee(newFee)).to.be.revertedWith('Not authorized') await expect(gift.connect(admin1).setHippyFee(newFee)).to.be.emit(gift, 'NewHippyFee') await expect((await gift.hippyFee())).to.equal(newFee) }) it('other bidders too can become hippy king', async function () { const hippyFee = await gift.hippyFee() await expect( gift.connect(hippyKing2).crownMyself({ value: hippyFee.add(ethers.utils.parseEther(String(5))) }) ).to.emit(gift, 'NewKing') await expect(gift.connect(hippyKing2).decree()).to.be.emit(gift, 'Hippy') }) it('only admins can mutiny', async function () { await expect(await gift.hippyKing()).to.equal(hippyKing2.address) await expect(await gift.hippy()).to.equal(true) await expect(gift.connect(user1).mutiny()).to.be.reverted // With(...) await expect(gift.connect(admin1).mutiny()).to.be.emit(gift, 'Mutiny') await expect((await gift.hippyKing())).to.equal(gift.address) await expect((await gift.hippy())).to.equal(false) }) }) })
// We are adding a function called Ctrl1 // to the module we got in the line above export default function loginController($scope, $window, Store, $http, $routeParams, $base64, restService) { // $scope.text = "Zurück zum login"; //$scope.folders = restService.getFolders(); $scope.login = () => { $scope.Alpha = Store; $scope.Alpha.Name = $scope.userName; $window.location.href = "/#!/player"; }; }
// const mongoose = require("mongoose") // const schema = new mongoose.schema({ // firstName:{type:String}, // children: [{type: Schema.Types.ObjectId, ref: 'User'}], // partner: {type: Schema.Types.ObjectId, ref: 'Partner'} // }); // const model = mongoose.model("Parent" , schema); // module.exports = model;
import Vue from 'vue' import Router from 'vue-router' import movie from '../pages/movie'; import book from '../pages/book'; import boardcast from '../pages/boardcast'; import group from '../pages/group'; import index from '../pages/index'; import register from '../pages/register'; import login from '../pages/login'; import change from '../pages/change'; import detail from '../pages/detail'; Vue.use(Router) export default new Router({ routes: [ { path: '/detail', name: 'detail', component: detail }, { path: '/movie', name: 'movie', component: movie }, { path: '/book', name: 'book', component: book }, { path: '/boardcast', name: 'boardcast', component: boardcast }, { path: '/group', name: 'group', component: group }, { path: '/index', name: 'index', component: index }, { path: '/register', name: 'register', component: register }, { path: '/login', name: 'login', component: login }, { path: '/change', name: 'change', component: change },{ path:"/*", redirect:"/index" } ] })
var express = require('express'); var router = express.Router(); var userService = require('../../services/user'); /* CREATE USER */ router.post('/', userService.createUser); module.exports = router;
$('#myModal').on('hide.bs.modal', function () { $(this).removeData('bs.modal'); let toopit = $('#tooltip'); toopit.css("display", "none"); }); function registerin() { let formData = new FormData(); let img_file = document.getElementById("ipc"); let fileObj = img_file.files[0]; let uname = $('#uname').val(); let password = $('#password1').val(); let repassword = $('#repassword').val(); let gender = $("input[name = 'gender']:checked").val(); let birthdate = $('#birthdate').val(); let email = $('#email').val(); let toopit = $('#tooltip'); msg = ''; if (uname == '') { msg += "用户名为必填字段\n"; } if (password == '' && repassword == '') { msg += "密码应为必填字段\n"; } if (birthdate == '') { msg += "生日应为必填字段\n"; } if (email == '') { msg += "email应为必填字段\n"; } if (img_file.files.length == 0) { msg += "请上传头像\n"; } if (password != repassword ? true : false) { $('#repassword').attr("class", "alert alert-danger"); } if (msg != '') { toopit.css("display", "inline"); toopit.html(msg); return; } formData.append('uname', uname); formData.append('password', password); formData.append('repassword', repassword); formData.append('gender', gender); formData.append('pic', fileObj); formData.append('birthdate', birthdate); formData.append('email', email); $.ajax({ url: 'doUserRegister.php', type: 'post', data: formData, dataType: 'text', async: false, processData: false, contentType: false, success: function (result) { console.log(result); if (result == "success") { alert(result); $('#myModal').modal('hide'); $('#uname').val(''); $('#password1').val(''); $('#repassword').val(''); $("input[name = 'gender']:checked").val('0'); $('#birthdate').val(''); $('#email').val(''); } }, error: function (msg) { alert(msg); } }) }
const gulp = require('gulp'); const sass = require('gulp-sass'); const browserSync = require('browser-sync').create(); const webpack = require('webpack'); const webpackStream = require('webpack-stream'); const wait = require('gulp-wait2'); const eslint = require('gulp-eslint'); gulp.task('browserSync', function() { browserSync.init({ server: { baseDir: 'dist' }, notify: false }) }); gulp.task('html', function () { gulp.src('./src/*.html') .pipe(gulp.dest('./dist')); }); gulp.task('image', function () { gulp.src('./src/images/*') .pipe(gulp.dest('./dist/images')); }); gulp.task('script', function () { gulp.src('src/scripts/*.js',) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()) .pipe(webpackStream({ mode: 'production', output: { filename: 'app.js', }, module: { rules: [{ test: /\.(js|jsx)$/, exclude: /(node_modules)/, loader: 'babel-loader', query: { presets: [ ['latest', { modules: false }], ], }, }], } }), webpack) .pipe(gulp.dest('./dist/js')); }); gulp.task('sass', function() { return gulp.src('./src/sass/style.scss') .pipe(wait(300)) .pipe(sass({ includePaths: ['./src/sass/'], outputStyle: 'compressed' }) .on('error', sass.logError)) .pipe(gulp.dest('./dist/css')) .pipe(browserSync.reload({ stream: true })); }); gulp.task('watch', ['script', 'sass', 'html', 'image'], function() { gulp.watch('./src/sass/**/*', ['sass']); gulp.watch('./src/scripts/**/*.js', ['script']).on('change', browserSync.reload); gulp.watch('./src/*.html', ['html']).on('change', browserSync.reload); }); gulp.task('default', ['browserSync', 'watch']); gulp.task('build', ['script', 'sass', 'html', 'image']);
/** * Example result: * { * type: 'number', * value: '6', * startIndex: 8 * endIndex: 9 * } */ export const getSymbol = (program, index, context) => { }
import React, { Component } from 'react'; import './../App.css'; import $ from 'jquery'; import Slider from 'react-slick'; export default class Slickslider extends Component { render() { const settings = { dots: true, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, }; console.log($); return( <div className="Hero-slider-section"> <div className="container"> <div className="slider"> <Slider> <div className="slider-content"> <h2 className="text-center text-sans"> Hi there! We are the new kids on the block and we build awesome websites and mobile apps. </h2> <div className="text-center mb-145"> <a href="/" className="theme-btn orange "> Work with us! </a> </div> </div> <div className="col-md-10 slider-content"> <h2 className="text-center text-sans"> Hi there! We are the new kids on the block and we build awesome websites and mobile apps. </h2> <div className="text-center mb-145"> <a href="/" className="theme-btn orange "> Work with us! </a> </div> </div> </Slider> </div> </div> </div> ) } }
import {fbDatabase} from "fbase"; class FirebaseDatabase { saveGoods(userId, item) { fbDatabase.ref(`${userId}/goods/${item.id}`).set(item); } deleteGoods(userId, item) { console.log(1); fbDatabase.ref(`${userId}/goods/${item.id}`).remove(); } syncGoods(userId, onUpdate){ const ref = fbDatabase.ref(`${userId}/goods`); ref.on("value", snapshot => { const value = snapshot.val(); value && onUpdate(value); }) return () => ref.off(); } } export default FirebaseDatabase;
const express = require('express'); const router = express.Router(); const aws = require('aws-sdk'); const pool = require('../database'); const { isLoggedIn, isNotLoggedIn } = require('../lib/auth'); router.get('/upload', isLoggedIn, (req, res) => { res.render('files/upload'); }); router.get('/uploads/:ext', isLoggedIn, async(req,res) => { console.log(req.params.ext); aws.config.update({ accessKeyId: '', secretAccessKey: '', region: 'us-east-2', signatureVersion: 'v4', }) const s3 = new aws.S3(); const post = await s3.createPresignedPost({ Bucket: 'revision-tesis-bucket', Fields: { key: Date.now() + "."+ req.params.ext, }, ACL : 'public-read-write', Expires: 60, // seconds Conditions: [ ['content-length-range', 0, 1048576], // up to 1 MB ], }); const newDoc = { NombreDoc: post.fields.key, url: post.url + "/" + post.fields.key, id_alumno: req.user.ID }; await pool.query('INSERT INTO documentos set ?', [newDoc] ); res.json(post); }); router.get('/files/list', isLoggedIn, async (req,res) =>{ const documentos = await pool.query ('SELECT * FROM documentos WHERE id_alumno = ?', [req.user.ID]); res.render('files/list', {documentos}); }); router.get('/files/delete/:id', isLoggedIn, async (req,res) => { const {id} = req.params; await pool.query('DELETE FROM documentos WHERE DocID = ?', [id]); req.flash('success', 'Documento eliminado correctamente'); res.redirect('/files/list'); }); module.exports = router;
const { DataTypes } = require('sequelize'); module.exports = (sequelize) => { sequelize.define('order', { total: { type: DataTypes.INTEGER, //allowNull: false, }, state: { type: DataTypes.ENUM('cart', 'created', 'processing', 'canceled', 'completed'), allowNull: false, } }) }
export const serverUrl = 'http://192.168.0.108:3000/';
var ColorPicker = (function() { var WIDTH = '100px'; var HEIGHT = '20px'; return function(onValueChanged) { var controlDescriptions = COLORS.map(function(colorEntry) { return { title: colorEntry.name, color: Color.toCss(colorEntry.value), width: WIDTH, height: HEIGHT, onClick: function() { onValueChanged(colorEntry.value); } }; }); controlDescriptions.push({ title: 'Erase', color: null, width: WIDTH, height: HEIGHT, onClick: function() { onValueChanged(null); } }); var SELECTED = 2; controlDescriptions[SELECTED].onClick(); return RadioBar(controlDescriptions, SELECTED); }; })();
// // // var init = function() { // chance(); // } document.querySelector('#showContent').addEventListener('click', function() { var chance = Math.floor(Math.random() * 9) + 1; var chanceDOM = document.querySelector('.chance'); // chanceDOM.style.display = 'block'; chanceDOM.src = 'img/chance-' + chance + '.jpg'; }); // document.querySelector("#moveContent").addEventListener('click', function() { function flipImg() { var element = document.getElementById('moveMe'); element.classList.toggle('flip'); } // document.querySelector('#moveMe').addEventListener('click', function() { // var flip = document.getElementById('flip'); // flip.classList.toggle('anispin'); // // }); // function ani(){ // document.getElementById('moveMe').style.keyframes = "aniset"; // }
const Joi = require('joi') module.exports.create = function createMessage(req, res, next) { let schema = Joi.object().keys({ userName: Joi.string().regex(/^[a-zA-Z0-9]+$/g).required().description('user name'), body: Joi.string().min(200).max(65535).required().description('message body') }) let body = Joi.validate(req.body, schema, (err, value)=>{ return err ? err.details[0] : false }) let query = Joi.validate(req.body, schema, (err, value)=>{ return err ? err.details[0] : false }) let error = whereError(body, query) error ? res.status(400).json(error) : next() } module.exports.getMessages = function getMessages(req, res, next) { let schema = Joi.object().keys({ page: Joi.number().default(1).description("page number"), limit: Joi.number().default(20).description("how many posts per page") }) let body = Joi.validate(req.body, schema, (err, value)=>{ return err ? err.details[0] : false }) let query = Joi.validate(req.body, schema, (err, value)=>{ return err ? err.details[0] : false }) let error = whereError(body, query) error ? res.status(400).json(error) : next() } function whereError(body, query, params){ if (body) { body.where = "body params" return body }else if (query){ query.where = "query params" return query }else { return false } }
../dist/zabo.js
import React from "react"; import { Slide, Text } from "spectacle"; const notes = ` `; export default function() { return ( <Slide bgColor="primary" textAlign="left" notes={notes}> <Text bold textColor="dark"> What happens when React needs to rerender </Text> <div style={{ marginTop: 40 }}> <img src={require("../media/react-rendering.svg")} alt="Rendering tree" /> </div> </Slide> ); }
const mongoose = require('mongoose'), bcrypt = require('bcrypt'); var UserSchema = new mongoose.Schema({ username: { type: String, unique: true, }, email: { type: String, unique: true, }, isAdmin:{ type:Boolean, default:false }, isVerified:{ type:Boolean, default:false }, status:{ type:String, default:'active' }, role:{ type:String, default:'user' }, passwordVerif: String, cover: { type:String, default:'/public/img/coverDefault.jpeg' } , avatarImg: String, avatarName: String, like:[ { article_id:String, title : String }], verif:[ { article_id:String, }] }); // chiffrée le mot de passe UserSchema.pre('save', function (next) { const user = this bcrypt.hash(user.passwordVerif, 10, (error, encrypted) => { user.passwordVerif = encrypted next() }) }) const User = mongoose.model('User', UserSchema); module.exports = User
var assert = require('assert'); var nodeunit = require('nodeunit'); var format = require('url').format; var parse = require('url').parse; var resolve = require('url').resolve; var resolveObject = require('url').resolveObject; /** * nodeunit test cases */ module.exports.testObject = function(test) { console.log("-- testObject --"); try { var url = parse('http://foo.com/a/b/../../file/?one=two'); //console.dir(url); console.log("formatted : " + format(url)); var ret = resolveObject(url, url); console.dir(ret); } catch(err) { console.log("caught exception : " + err); test.fail(); } test.done(); }; module.exports.testString = function(test) { console.log("-- testString --"); try { var url = parse('http://foo.com/a/b/../../file/?one=two'); //console.dir(url); console.log("formatted : " + format(url)); console.log("-- testString base URL provided --"); var ret = resolve('http://foo.com/', 'http://foo.com/a/b/../../file/?one=two'); console.dir(ret); console.log("-- testString base URL not provided --"); var ret = resolve('http://bar.com/a', 'http://foo.com/a/b/../file/?one=two'); console.dir(ret); } catch(err) { console.log("caught exception : " + err); test.fail(); } test.done(); };
import React, {Component} from 'react'; import * as d3 from "d3"; import * as d3scale from "d3-scale"; class RadialBarChart extends Component { constructor(props) { super(props); this.state = { width: (window.innerWidth > 500 ? 500 : window.innerWidth) } this.chartDiv = React.createRef(); } componentDidMount() { this.drawChart(); } componentDidUpdate(){ this.drawChart(); } drawChart() { var margin = {top: 150, right: 0, bottom: 100, left: 0}, width = this.state.width - margin.left - margin.right, height = this.state.width - margin.top - margin.bottom, innerRadius = 80, outerRadius = Math.min(width, height) / 2; var data = this.props.data var svg = d3.select(this.chartDiv.current).html(null) .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + (width / 2 + margin.left) + "," + (height / 2 + margin.top) + ")"); // Scales var x = d3.scaleBand() .range([0, 2 * Math.PI]) // X axis goes from 0 to 2pi = all around the circle. If I stop at 1Pi, it will be around a half circle .align(0) .domain(data.map(function(d) {return Object.keys(d)[0];})); var y = d3scale.scaleRadial() .range([innerRadius, outerRadius]) .domain([0, 20]); // Bars svg.append("g") .selectAll("path") .data(data) .enter() .append("path") .attr('fill', function(d){ if (Object.keys(d)[0] === "Blaue WST"){ return "#0000ff" } else if (Object.keys(d)[0] === "Orange WST"){ return "#ffa500" } else if (Object.keys(d)[0] === "Kreis"){ return "#34AEEB" } else if (Object.keys(d)[0] === "Quadrat"){ return "#31a4de" } else if (Object.keys(d)[0] === "Dreieck"){ return "#2B91C4" } else if (Object.keys(d)[0] === "Geprüfte WST"){ return "#31a4de" } else if (Object.keys(d)[0] === "Fehlerhafte WST"){ return "#2680AD" } }) .attr("d", d3.arc() .innerRadius(innerRadius) .outerRadius(function(d) { return y(d[Object.keys(d)[0]]); }) .startAngle(function(d) { return x(Object.keys(d)[0]); }) .endAngle(function(d) { return x(Object.keys(d)[0]) + x.bandwidth(); }) .padAngle(0.01) .padRadius(innerRadius)) // Labels - Names svg.append("g") .selectAll("g") .data(data) .enter() .append("g") .attr("text-anchor", function(d) { return (x(Object.keys(d)[0]) + x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "end" : "start"; }) .attr("transform", function(d) { return "rotate(" + ((x(Object.keys(d)[0]) + x.bandwidth() / 2) * 180 / Math.PI - 90) + ") translate(" + (y(d[Object.keys(d)[0]])+20) + ",0)"; }) .append("text") .text(function(d){return(Object.keys(d)[0])}) .attr("transform", function(d) { return (x(Object.keys(d)[0]) + x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "rotate(180)" : "rotate(0)"; }) .style("font-size", "13px") .attr("font-family", "Open Sans") .attr("alignment-baseline", "middle") // Labels - Numbers svg.append("g") .selectAll("g") .data(data) .enter() .append("g") .attr("text-anchor", function(d) { return (x(Object.keys(d)[0]) + x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "end" : "start"; }) .attr("transform", function(d) { return "rotate(" + ((x(Object.keys(d)[0]) + x.bandwidth() / 2) * 180 / Math.PI - 90) + ") translate(62,0)"; }) .append("text") .text(function(d){return(d[Object.keys(d)[0]])}) .attr("transform", function(d) { return (x(Object.keys(d)[0]) + x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "rotate(180)" : "rotate(0)"; }) .style("font-size", "13px") .attr("font-family", "Open Sans") .attr("alignment-baseline", "middle") } render(){ return <div ref={this.chartDiv}></div> } } export default RadialBarChart;
/** * Created by Max on 4/26/2018. */ let mongoose = require('mongoose'), Schema = mongoose.Schema; let messageSchema = new Schema({ userName: {type: String, required: true}, message: {type: String, required: true}, timeStamp: {type: Number, required: true}, likes: {type: Number}, favorites: {type: Number} }); module.exports = mongoose.model('message', messageSchema);
import VueFetch, { $fetch } from '../../plugins/fetch' export function getCategories() { return $fetch('category/') .then(res => res) .catch(err => { console.log(err); throw err; }); } export function getSubcategories() { return $fetch('subcategory/') .then(res => res) .catch(err => { console.log(err); throw err; }); }
function FindWord(text) { let builder = ""; let remaining = text; let result = FindWord2(builder, remaining); return result; } function CheckIfExists(text) { if (text.indexOf("car") > -1) { console.log("Text found in", text); return true; } return false; } function FindWord2(builder, remaining) { if (remaining.length == 0) { let result = CheckIfExists(builder); return result; } else { for (let i = 0; i < remaining.length; i++) { let rem = remaining.substring(0, i) + remaining.substring(i + 1); let result = FindWord2(builder + remaining[i], rem); if (result) { return result; } } } return false; } let result = FindWord("cxrza"); console.log(result);
////Como exportar de um módulo Node para outro arquivo (forma mais comum) module.exports = { bomDia: 'Bom dia', boaNoite(){ return 'Boa noite' } }
const Manager = require("./lib/Manager"); const Engineer = require("./lib/Engineer"); const Intern = require("./lib/Intern"); const inquirer = require("inquirer"); const path = require("path"); const fs = require("fs"); const OUTPUT_DIR = path.resolve(__dirname, "output") const outputPath = path.join(OUTPUT_DIR, "team.html"); const render = require("./lib/htmlRenderer"); // Write code to use inquirer to gather information about the development team members, // and to create objects for each team member (using the correct classes as blueprints!) const employees = []; const getEmployeeType = () => { inquirer .prompt([{ name: 'employeeType', type: 'list', message: 'Employee type?', choices: ['Manager', 'Engineer', 'Intern'], }] ).then((answers) => { if (answers.employeeType === 'Manager') { var managerExists = employees.some((e) => e instanceof Manager); if (managerExists) { console.log('\n\nManager already exists\n\n'); getEmployeeType(); } else { getEmployeeInfo(answers.employeeType); } } else { getEmployeeInfo(answers.employeeType); } }) .catch((err) => { console.log(err); }); } const getEmployeeInfo = (type) => { var e = {}; var answers = {}; const commonInfo = [{ name: 'employeeName', message: 'Employee Name?', }, { name: 'employeeId', message: 'Employee ID?', }, { name: 'employeeEmail', message: 'Employee Email?', }]; const engineerInfo = [{ name: 'gitHub', message: 'GitHub?', }]; const managerInfo = [{ name: 'officeNo', message: 'Office number?', }]; const internInfo = [{ name: 'school', message: 'School?', }]; const goBack = [{ name: 'back', type: 'list', message: 'Go again?', choices: ['Yes', 'No'], }]; switch (type) { case 'Manager': commonInfo.push(managerInfo[0]); commonInfo.push(goBack[0]); inquirer.prompt(commonInfo).then((a) => { answers = a; //console.log(answers); e = new Manager(answers.employeeName, answers.employeeId, answers.employeeEmail, answers.officeNo); employees.push(e); if (answers.back === 'Yes') { commonInfo.pop(); commonInfo.pop(); getEmployeeType(); } else { renderOutput(render(employees)); } }) .catch((err) => { console.log(err); }); break; case 'Engineer': commonInfo.push(engineerInfo[0]); commonInfo.push(goBack[0]); inquirer.prompt(commonInfo).then((a) => { answers = a; e = new Engineer(answers.employeeName, answers.employeeId, answers.employeeEmail, answers.gitHub); employees.push(e); if (answers.back === 'Yes') { commonInfo.pop(); commonInfo.pop(); getEmployeeType(); } else { renderOutput(render(employees)); } }) .catch((err) => { console.log(err); }); break; case 'Intern': commonInfo.push(internInfo[0]); commonInfo.push(goBack[0]); inquirer.prompt(commonInfo).then((a) => { answers = a; e = new Intern(answers.employeeName, answers.employeeId, answers.employeeEmail, answers.school); employees.push(e); if (answers.back === 'Yes') { commonInfo.pop(); commonInfo.pop(); getEmployeeType(); } else { renderOutput(render(employees)); } }) .catch((err) => { console.log(err); }); break; } } const renderOutput = (output) => { if (!fs.existsSync(OUTPUT_DIR)){ fs.mkdirSync(OUTPUT_DIR); } fs.writeFile(outputPath, output, function (err) { if (err) return console.log(err); console.log('\n\n\nRender complete !!!'); }); } getEmployeeType(); // After the user has input all employees desired, call the `render` function (required // above) and pass in an array containing all employee objects; the `render` function will // generate and return a block of HTML including templated divs for each employee! // After you have your html, you're now ready to create an HTML file using the HTML // returned from the `render` function. Now write it to a file named `team.html` in the // `output` folder. You can use the variable `outputPath` above target this location. // Hint: you may need to check if the `output` folder exists and create it if it // does not. // HINT: each employee type (manager, engineer, or intern) has slightly different // information; write your code to ask different questions via inquirer depending on // employee type. // HINT: make sure to build out your classes first! Remember that your Manager, Engineer, // and Intern classes should all extend from a class named Employee; see the directions // for further information. Be sure to test out each class and verify it generates an // object with the correct structure and methods. This structure will be crucial in order // for the provided `render` function to work!```
var globals________vars____8js__8js_8js = [ [ "globals____vars__8js_8js", "globals________vars____8js__8js_8js.html#a3855473d838853dc775c812564d7c5ca", null ] ];
import React from 'react'; import api from '../utils/api'; function Card(props) { console.log(props); const handleSave = ()=>{ console.log(props.book) const bookData ={ title:props.book.volumeInfo.title, authors: props.book.volumeInfo.authors.join(', '), description: props.book.volumeInfo.description, thumbnail: props.book.volumeInfo.imageLinks.thumbnail, link: props.book.volumeInfo.canonicalVolumeLink } api.saveBook(bookData).then(res => console.log('saved')) } return ( <div className='card m-4'> <div className='row'> <div className='col-3'> </div> <div className='col-6'> <h3>{props.book.volumeInfo.title}</h3> <h5>By: {props.book.volumeInfo.authors.join(', ')}</h5> </div> <div className='col-3'> <button className='m-1' onClick={handleSave}>Save</button> <button className='m-1'> <a href={props.book.volumeInfo.canonicalVolumeLink} target='_blank'> View </a> </button> </div> </div> <div className='row'> <div className='col-3'> <img className='m-4' src={ props.book.volumeInfo.imageLinks && props.book.volumeInfo.imageLinks.thumbnail } /> </div> <div className='col-9'> <p className='text-start'>{props.book.volumeInfo.description}</p> </div> </div> </div> ); } export default Card;
//*************** Hello import {SUCCESS, FAIL} from './src/redux/action/actionType'; import axios from 'axios'; import React, {useEffect} from 'react'; import {Text, View} from 'react-native'; var kk = SUCCESS + '_' + FAIL; const HelloWorldApp = () => { useEffect(() => { try { const users = axios.get('https://api.covid19api.com/'); console.log('aaaa', users); } catch (err) { return console.error(err); } }); return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }}> <Text>Hello, world! {kk}</Text> </View> ); }; export default HelloWorldApp;
import { Button, Grid, Typography } from "@material-ui/core"; import FormControl from "@material-ui/core/FormControl"; import IconButton from "@material-ui/core/IconButton"; import InputAdornment from "@material-ui/core/InputAdornment"; import InputLabel from "@material-ui/core/InputLabel"; import OutlinedInput from "@material-ui/core/OutlinedInput"; import { makeStyles, withStyles } from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import HomeIcon from "@material-ui/icons/Home"; import Visibility from "@material-ui/icons/Visibility"; import VisibilityOff from "@material-ui/icons/VisibilityOff"; import Alert from "@material-ui/lab/Alert"; import clsx from "clsx"; import React, { useState } from "react"; import { useDispatch } from "react-redux"; import { useHistory } from "react-router-dom"; import signInServiceApi from "../../api/signInServiceApi"; import logo from "../../images/logo_satsi.png"; import { signInVerifyEmail } from "./sigInSlice"; import "./SignIn.scss"; const useStyles = makeStyles((theme) => ({ textField: { width: "35ch", }, spaceTop: { marginTop: "1rem", }, })); const CssTextField = withStyles({ root: { "& label.Mui-focused": { color: "#fff", }, "& .MuiInput-underline:after": { borderBottomColor: "#fff", }, "& .MuiOutlinedInput-root": { "& fieldset": { borderColor: "#d4d4d4", }, "&:hover fieldset": { borderColor: "#d4d4d4", }, "&.Mui-focused fieldset": { borderColor: "#fff", }, }, }, })(TextField); const SignIn = () => { const classes = useStyles(); const dispatch = useDispatch(); const history = useHistory(); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [phone, setPhone] = useState(""); const [password, setPassword] = useState(""); const [passwordAgain, setPasswordAgain] = useState(""); const [showPassword, setShowPassword] = useState(false); const [showPasswordAgain, setShowPasswordAgain] = useState(false); const [success, setSuccess] = useState(false); const [error, setError] = useState(false); const [errorMessage, setErrorMessage] = useState(""); const [errorPasswordAgain, setErrorPasswordAgain] = useState(false); const handleClickShowPassword = () => { setShowPassword(!showPassword); }; const handleClickShowPasswordAgain = () => { setShowPasswordAgain(!showPasswordAgain); }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; const handleMouseDownPasswordAgain = (event) => { event.preventDefault(); }; const handleSubmitSignIn = (e) => { e.preventDefault(); const dataSignIn = { name: name, email: email, phone: phone, password: password, }; if (password === passwordAgain) { const fetchSignIn = () => { try { signInServiceApi .postSignIn(dataSignIn) .then(function (response) { if (response.data.email === dataSignIn.email) { setSuccess(true); const action = signInVerifyEmail(dataSignIn.email); dispatch(action); setTimeout(() => { setSuccess(false); history.push("/xac-thuc-email"); }, 1500); } else { throw "SĐT hoặc email đã được đăng ký trước"; } }) .catch(function (error) { setErrorMessage(error); setError(true); setTimeout(() => { setError(false); }, 1500); }); } catch (error) { console.log("failed to fetch product list: ", error); } }; fetchSignIn(); } else { setErrorPasswordAgain(true); setTimeout(() => { setErrorPasswordAgain(false); }, 1500); } }; return ( <div className='login-wrapper'> <div className='loginCover'> <div className='container-fluid'> <div className='contentLogin'> <Typography variant='h4' component='h1' align='center'> <Grid container> <Grid item xs={12}> {" "} <Button href='/'> <img src={logo} alt='logo' /> </Button> </Grid> <Grid item xs={12}> <Typography variant='h3' component='h1' align='center' style={{ margin: "1rem 0" }}> Minh triết nhân sinh </Typography> </Grid> <Grid item xs={12}> <Typography variant='subtitle1' align='center' style={{ fontStyle: "italic" }}> Đăng ký tài khoản </Typography> </Grid> </Grid> </Typography> <div className='loginFiled'> <form className={classes.root} onSubmit={handleSubmitSignIn}> {success && ( <Alert variant='filled' severity='success' style={{ marginTop: "1rem", justifyContent: "center" }}> Đăng ký thành công </Alert> )} {error && ( <Alert variant='filled' severity='error' style={{ marginTop: "1rem", justifyContent: "center" }}> {errorMessage} </Alert> )} {errorPasswordAgain && ( <Alert variant='filled' severity='error' style={{ marginTop: "1rem", justifyContent: "center" }}> Nhập lại mật khẩu không chính xác </Alert> )} <Grid container direction='column'> <Grid item> <CssTextField size='medium' variant='outlined' margin='normal' label='Họ và tên' className={clsx(classes.textField)} required type='text' value={name} onChange={(e) => setName(e.target.value)} // id='custom-css-outlined-input' color='secondary' /> </Grid> <Grid item> <CssTextField size='medium' variant='outlined' type='email' margin='normal' label='Email' className={clsx(classes.textField)} required value={email} onChange={(e) => setEmail(e.target.value)} // id='custom-css-outlined-input' color='secondary' /> </Grid> <Grid item> <CssTextField size='medium' variant='outlined' margin='normal' type='number' label='Số điện thoại đăng nhập' className={clsx(classes.textField)} required value={phone} onChange={(e) => setPhone(e.target.value)} color='secondary' /> </Grid> <Grid item> <FormControl className={clsx(classes.textField, classes.spaceTop)} variant='outlined' size='medium' color='secondary'> <InputLabel htmlFor='outlined-adornment-password-2'> Mật khẩu </InputLabel> <OutlinedInput id='outlined-adornment-password-2' type={showPassword ? "text" : "password"} value={password} onChange={(e) => setPassword(e.target.value)} required endAdornment={ <InputAdornment position='end'> <IconButton aria-label='toggle password visibility' onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge='end'> {showPassword ? ( <Visibility /> ) : ( <VisibilityOff /> )} </IconButton> </InputAdornment> } labelWidth={70} /> </FormControl> </Grid> <Grid item> <FormControl className={clsx(classes.textField, classes.spaceTop)} variant='outlined' size='medium' color='secondary'> <InputLabel htmlFor='outlined-adornment-password-1'> Nhập lại mật khẩu </InputLabel> <OutlinedInput id='outlined-adornment-password-1' type={showPasswordAgain ? "text" : "password"} value={passwordAgain} onChange={(e) => setPasswordAgain(e.target.value)} required endAdornment={ <InputAdornment position='end'> <IconButton aria-label='toggle password visibility' onClick={handleClickShowPasswordAgain} onMouseDown={handleMouseDownPasswordAgain} edge='end'> {showPasswordAgain ? ( <Visibility /> ) : ( <VisibilityOff /> )} </IconButton> </InputAdornment> } labelWidth={70} /> </FormControl> </Grid> </Grid> <Button size='large' color='primary' variant='contained' type='submit' style={{ marginTop: "2rem" }}> Đăng Ký </Button> <div className='navigateBlock signInBlock'> <a className='login' href='/dang-nhap'> Đã có tài khoản? </a> </div> </form> <Button href='/' startIcon={<HomeIcon />} color='primary'> Quay Về Trang Chủ </Button> </div> </div> </div> </div> </div> ); }; export default SignIn;
/* * Use this script to easily load a sprite file in a canvas and have it play as animation. * Made by Christiaan de Die le Clercq, licensed under GPL v2 or higher. */ var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var image = new Image(); var imageWidth, imageHeight; var numberOnARow, numberOfRows, numberOfImages, startPos, endPos, speed; var sx, sy, n, timeout; //Set config values here function setOrgValues() { numberOnARow = 3; // How many images on a single row? numberOfRows = 4; // How many rows in total? numberOfImages = numberOnARow * numberOfRows; // How many images in total? startPos = 0; // Starting position endPos = 3; // Ending position speed = 300; // Speed in mili seconds to move to next frame image.src = "img/tech-walk.png"; // Set image location // Stop editing :) n = startPos; image.src = "img/tech.png"; // Set image location numberOnARow = 9; // How many images on a single row? numberOfRows = 6; // How many rows in total? numberOfImages = 54; // How many images in total? startPos = 52; // Starting position endPos = 53; // Ending position speed = 100; // Speed in mili seconds to move to next frame n = startPos; } setOrgValues(); var sx, sy; image.addEventListener("load", function() { imageWidth = image.width/numberOnARow; imageHeight = image.height/numberOfRows; animate(); }); //Set on click values here canvas.addEventListener("click", function() { numberOnARow = 3; // How many images on a single row? numberOfRows = 4; // How many rows in total? numberOfImages = numberOnARow * numberOfRows; // How many images in total? startPos = 0; // Starting position endPos = 3; // Ending position speed = 300; // Speed in mili seconds to move to next frame image.src = "img/tech-walk.png"; // Set image location n = startPos; setTimeout(function(){ setOrgValues(); animate(); }, 30000); }); function animate() { window.clearTimeout(timeout); context.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight); sx = (n%numberOnARow) * imageWidth; sy = Math.floor(n/numberOnARow) * imageHeight; context.drawImage(image, sx, sy, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight); n++; if(n > endPos - 1){ n = startPos; } timeout = setTimeout(animate, speed); }
var http=require('http'); var fs=require('fs'); var url=require('url'); http.createServer(function(request,response){ var pathname=url.parse(request.url).pathname; console.log('Request for:'+pathname); fs.readFile(pathname.substr(1),function(err,data){ //路径去掉第一个目录分隔符 if(err){ console.log(err); response.writeHead(404,{'Content-Type':'text/html'}); }else{ response.writeHead(200,{'Content-Type':'text/html'}); response.write(data.toString()); } response.end(); }) }).listen(8008); console.log('Server is Listening http://127.0.0.1:8008') //访问同级目录下的127.0.0.1:8008/index.html即可
import { Router, browserHistory } from 'react-router'; import { ReduxAsyncConnect, asyncConnect, reducer as reduxAsyncConnect } from 'redux-connect' import React from 'react' import { hydrate } from 'react-dom' import { createStore, combineReducers } from 'redux'; // 1. Connect your data, similar to react-redux @connect @asyncConnect([{ key: 'lunch', promise: ({ params, helpers }) => Promise.resolve({ id: 1, name: 'Borsch' }) }]) class App extends React.Component { render() { // 2. access data as props const lunch = this.props.lunch return ( <div>{lunch.name}</div> } } };
/** * Speed Component Module * @module Speed/Component * @requires react * @requires prop-types * @requires material-ui * @requires react-amap * @requires react-amap-plugin-heatmap * @requires {@link module:Speed/Components/Echarts} * @requires {@link module:Speed/Components/SpeedBoard} */ import React from 'react'; import {object, func, string, number, shape, arrayOf} from 'prop-types'; import {withStyles} from 'material-ui/styles'; import {Map as ReactAMap} from 'react-amap'; import Heatmap from 'react-amap-plugin-heatmap'; import Echarts from './components/echarts'; import SpeedBoard from './components/speedBoard'; import movingPictures from './movingPictures.gif'; const styles = (theme) => ({ root: { position: 'relative', width: '100vw', height: '100vh', }, mapContainer: { width: '100vw', height: '100vh', }, gif: { position: 'absolute', top: '100px', left: '50px', width: '200px', height: '200px', }, statisticsBoard: { position: 'absolute', right: '100px', bottom: '300px', color: 'white', textAlign: 'right', }, echarts: { position: 'absolute', right: '100px', bottom: 0, width: '450px', height: '300px', }, }); /** * Speed Component * @extends {Component} * @param {Object} props */ @withStyles(styles) class Component extends React.Component { /** * Props validation * Declares props validation as high as possible, * since they serve as documentation. * We’re able to do this because of JavaScript function hoisting. */ static propTypes = { classes: object.isRequired, cityCode: string.isRequired, heatmapOptions: object.isRequired, morningPeakSpeed: number.isRequired, eveningPeakSpeed: number.isRequired, dayAvgSpeed: number.isRequired, speedTrend: arrayOf(shape({ time: number, speed: number, })), fetchAllLocationsSpeedRequest: func.isRequired, zoomEndHandler: func.isRequired, fetchAllStatisticsRequest: func.isRequired, }; /** * Constructor * @param {Object} props */ constructor(props) { super(props); this.props = props; this.AMapOptions = { // AMap init options amapkey: 'dfba0f951c70f029a888263a3e931d0a', mapStyle: 'amap://styles/47cf2cc474c7ad6c92072f0b267adff0?isPublic=true', center: [120.182217, 30.25316], zoom: 13, zooms: [10, 16], features: ['bg', 'road'], showIndoorMap: false, events: { created: (ins) => { // Save amap instance this.AMapInstance = ins; }, zoomend: this.zoomEndHandler.bind(this), }, }; // Call saga to fetch heat map data api this.props.fetchAllLocationsSpeedRequest({ cityCode: this.props.cityCode, }); // Call saga to fetch statistics api this.props.fetchAllStatisticsRequest({ cityCode: this.props.cityCode, }); // Auto refresh every 30 seconds this.timer = window.setInterval(() => { // Call saga to fetch heat map data api this.props.fetchAllLocationsSpeedRequest({ cityCode: this.props.cityCode, }); // Call saga to fetch statistics api this.props.fetchAllStatisticsRequest({ cityCode: this.props.cityCode, }); }, 60000); } /** * Clear auto refresh process */ componentWillUnmount() { window.clearInterval(this.timer); } /** * Fire redux action to update heat map radius and data-max value */ zoomEndHandler() { const zoom = this.AMapInstance.getZoom(); this.props.zoomEndHandler({zoom}); } /** * Return react tree of Speed page * @return {Component} */ render() { const { classes, heatmapOptions, morningPeakSpeed, eveningPeakSpeed, dayAvgSpeed, speedTrend, } = this.props; return ( <div className={classes.root}> <div className={classes.mapContainer}> <ReactAMap {...this.AMapOptions} > <Heatmap {...heatmapOptions} /> </ReactAMap> </div> <img className={classes.gif} src={movingPictures} /> <div className={classes.statisticsBoard}> <SpeedBoard title='早高峰运送速度' value={morningPeakSpeed} /> <SpeedBoard title='晚高峰运送速度' value={eveningPeakSpeed} /> <SpeedBoard title='当前平均运送速度' value={dayAvgSpeed} color='#13d5e8' /> </div> <div className={classes.echarts}> <Echarts speedTrend={speedTrend} /> </div> </div> ); } } export default Component;
var AM = new AssetManager(); //Basketball AM.queueDownload("./img/basketball.png"); AM.queueDownload("./img/Bubble.png"); AM.queueDownload("./img/Bubble Pop.png"); AM.queueDownload("./img/Tennis Ball.png"); AM.queueDownload("./img/Bowling Ball.png"); var gameEngine; var myManager; AM.downloadAll(function () { var canvas = document.getElementById("gameWorld"); var ctx = canvas.getContext("2d"); var loadedGame = false; console.log("Loaded Game?: "+AM.isDone()); if (AM.isDone()){ gameEngine = new GameEngine(); gameEngine.init(ctx); gameEngine.start(); myManager = new BallManager(gameEngine); gameEngine.addEntity(myManager); //create new classes here } console.log("All Done!"); }); window.onload = function () { var socket = io.connect("http://24.16.255.56:8888"); socket.on("load", function (data) { console.log("here"); //console.log(data.size); for (var i = 0; i < randomBalls.length; i++){ randomBalls[i].x = data.data.arrayX[i]; randomBalls[i].y = data.data.arrayY[i]; console.log("new x:" + randomBalls[i].x + "new y: " + randomBalls[i].y); } }); var text = document.getElementById("text"); var saveButton = document.getElementById("save"); var loadButton = document.getElementById("load"); saveButton.onclick = function () { console.log("save"); text.innerHTML = "Saved." var tempArrayX = []; var tempArrayY = []; for (i = 0; i < randomBalls.length; i++){ tempArrayX.push(randomBalls[i].x); tempArrayY.push(randomBalls[i].y); console.log("old x:" + tempArrayX[i] + "old y: " + tempArrayY[i]) } socket.emit("save", { studentname: "Ashlyn Weeks", statename: "Ball's Previous Place", data: {arrayX: tempArrayX, arrayY: tempArrayY}}); }; loadButton.onclick = function () { console.log("load"); text.innerHTML = "Loaded." socket.emit("load", { studentname: "Ashlyn Weeks", statename: "Ball's Previous Place" }); }; };
const express = require("express"); const LimpController = require("../../Controllers/Sistema/LimpiezaHigiene"); const api = express.Router(); api.post("/agregar-LimpiezaHigiene", LimpController.guardarLimpieza); api.get("/limpieza", LimpController.getLimpieza); api.put("/updateLimpieza/:id", LimpController.updateLimpieza); api.delete("/deleteLimpieza/:id", LimpController.deleteLimpieza); module.exports = api;
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ 'use strict'; const Abstract = require('./../Abstract'); const BC = require('@pascalcoin-sbx/common').BC; const mipherAES = require('mipher/dist/aes'); const mipherRandom = require('mipher/dist/random'); const KDF = require('./KDF'); /** * A class that can en-/decrypt values just the way payloads are encrypted * using a password in pascalcoin. */ class Password extends Abstract { /** * Encrypts the given value with the given password the PascalCoin way. * * @param {Buffer|Uint8Array|BC|String} value * @param {Object} options * @return {BC} */ static encrypt(value, options = {password: ''}) { value = BC.from(value); let aes = new mipherAES.AES_CBC_PKCS7(); const randomGenerator = new mipherRandom.Random(); const salt = new BC(Buffer.from(randomGenerator.get(8))); // mocha sees an open setinterval and won't exit without this change randomGenerator.stop(); const keyInfo = KDF.PascalCoin(options.password, salt); return BC.concat( BC.fromString('Salted__'), salt, new BC(aes.encrypt(keyInfo.key.buffer, value.buffer, keyInfo.iv.buffer)) ); } /** * Decrypts the given encrypted value with the given password the * PascalCoin way. * * @param {Buffer|Uint8Array|BC|String} encrypted * @param {Object} options * @return {BC|false} */ static decrypt(encrypted, options = {password: ''}) { encrypted = BC.from(encrypted); let aes = new mipherAES.AES_CBC_PKCS7(); const salt = encrypted.slice(8, 16); const rest = encrypted.slice(16); const keyInfo = KDF.PascalCoin(options.password, salt); let result = aes.decrypt(keyInfo.key.buffer, rest.buffer, keyInfo.iv.buffer); if (result.length === 0) { throw new Error('Unable to decrypt value.'); } return new BC(result); } } module.exports = Password;
import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import { getStoryCharacters } from '../../../services/stories.service' import CharacterCard from '../../characters/characters-card' import Spinner from '../../spinner' import NoContent from '../../no-content' import { getThumbnailURL } from '../../../utils/thumbnails' function StoryCharacters(props) { const { storyId } = props const [characters, setCharacter] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { const getData = async () => { setLoading(true) const { data } = await getStoryCharacters(storyId) setCharacter(data?.data.results) setLoading(false) } getData() }, [storyId]) console.log(characters) const renderSpinner = () => (loading ? <Spinner /> : null) const renderNoContent = () => !loading && !characters?.length ? <NoContent /> : null const renderCharacterCards = () => characters.map((character, index) => ( <CharacterCard key={'comic-character-' + index} id={character.id} name={character.name} thumbnail={getThumbnailURL(character.thumbnail)} scrollContainer="" /> )) return ( <div className="ContentRow"> {renderSpinner()} {renderCharacterCards()} {renderNoContent()} </div> ) } StoryCharacters.propTypes = { storyId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), } export default StoryCharacters
var searchData= [ ['back',['back',['../structbullet__t.html#ad0e6b6213a172f1d71e8738bb156e7ea',1,'bullet_t']]], ['back_5fbutton',['back_button',['../structgame__t.html#ac8452ffa9f2e211cbbf2b822914ca2cf',1,'game_t']]], ['background',['background',['../structgame__t.html#a69a7242ee147decd9b827b0c721a728c',1,'game_t']]], ['background_5finsts',['background_insts',['../structgame__t.html#a7cb91f6203c728437f25dd58ebfa0313',1,'game_t']]], ['bcd',['bcd',['../group__timer.html#gaa2444cde256beeae6fb06bb7a5ebd0c9',1,'timer_status_field_val']]], ['blue_5fammo',['blue_ammo',['../structbullet__t.html#adfd73240ad859dd657762c13351c689b',1,'bullet_t']]], ['blue_5fbullets',['blue_bullets',['../structgame__t.html#ac472cf2f0c318ec3fc28b36c43e83fae',1,'game_t']]], ['blue_5fspaceships',['blue_spaceships',['../structships__t.html#a9682dbcd2761da0c0cee0e99d4d6c59a',1,'ships_t']]], ['bullet_5fback',['bullet_back',['../structgame__t.html#acb1b6ebf7492c56e0391c8d65aa02a1b',1,'game_t']]], ['bullet_5fcolor',['bullet_color',['../structbullet__t.html#a77b64094e3e594aedfeb34d74046b789',1,'bullet_t']]], ['bullet_5frefresh',['bullet_refresh',['../structgame__t.html#aad1f06d37d69618ab0d33b00fbb1153b',1,'game_t']]], ['bullets',['bullets',['../structgame__t.html#a73e687a9b2c9d5a4017eccb5ac547e22',1,'game_t']]], ['bullets_5flimit',['bullets_limit',['../structgame__t.html#a3f38db44b09634f709b0682cf63a6356',1,'game_t']]], ['bullets_5fsize',['bullets_size',['../structgame__t.html#a312fe77be81d6058f134e08ecce022d1',1,'game_t']]], ['byte',['byte',['../group__timer.html#ga96f44d20f1dbf1c8785a7bc99a46164c',1,'timer_status_field_val']]] ];
import React from "react"; import { Input, Label } from "semantic-ui-react"; import PropTypes from "prop-types"; import styles from "./RenderedField.module.scss"; export const RenderedInputField = ({ meta: { error, touched }, ...rest }) => ( <div className={styles.renderedFieldContainer}> <Input {...rest} size="small" /> {error && touched && ( <Label basic pointing="left" color="red" className={styles.error}> {error} </Label> )} </div> ); RenderedInputField.propTypes = { meta: PropTypes.object };
import React from 'react'; import ReactDOM, { render } from 'react-dom'; import './index.css'; import registerServiceWorker from './registerServiceWorker'; import { BrowserRouter as Router, Switch, Route} from 'react-router-dom'; import Play from './pages/Play'; import Login from './pages/Login'; import Games from './pages/Games'; import GameWait from './pages/GameWait'; import Leaderboard from './pages/Leaderboard'; render(( <Router> <Switch> <Route exact path='/' component={Login} /> <Route path='/games' component={Games} /> {/* <Route path='/login' component={Login} /> */} <Route path='/gamewait' component={GameWait} /> <Route path='/play' component={Play} /> <Route path='/leaderboard' component={Leaderboard} /> </Switch> </Router>), document.getElementById('root')); registerServiceWorker();
function vector(x,y){ this.x = x; this.y = y; } function add(v1,v2){ v1.x = v1.x + v2.x; v1.y = v1.y + v2.y; } function sub(v1,v2){ v1.x = v1.x - v2.x; v1.y = v1.y - v2.y } function mult(v1,v2){ v1.x = v1.x * v2.x; v1.y = v1.y * v2.y } function div(v1,v2){ v1.x = v1.x / v2.x; v1.y = v1.y / v2.y } function scalar(v1,num){ v1.x = v1.x * num; v1.y = v1.y * num; }
/*! * Start Bootstrap - New Age v5.0.1 (https://startbootstrap.com/template-overviews/new-age) * Copyright 2013-2021 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-new-age/blob/master/LICENSE) */ AOS.init();
var mongoose = require('../lib/mongoose'); var Schema = mongoose.Schema; var User = require('./user').User; var eventSchema = new Schema({ title: { type : String, max : 30, required : true }, details: { type : String, max : 500 }, cover: { url : String, info: { type : Object } }, location: { type : String, max : 200 }, time: { type : String, max : 20 }, date: { type : String, max : 20 }, actualTime: { type : Date }, invited: [ { type : Schema.Types.ObjectId, ref : User.modelName } ], going: { count: { type : Number, default : 0 }, ppl: [ { type : Schema.Types.ObjectId, ref : User.modelName } ] }, createdAt: { type : Date, default : Date.now }, createdBy: { type : Schema.Types.ObjectId, ref : User.modelName } }); eventSchema.methods.verifyEvent = require('./methods/event/verify'); eventSchema.methods.saveEvent = require('./methods/event/save'); eventSchema.methods.deleteEvent = require('./methods/event/delete'); eventSchema.methods.goingToEvent = require('./methods/event/going'); exports.Event = mongoose.model('Event', eventSchema);
export filter from './filter' export data from './data'
var mergeTwoLists = function (l1, l2) { function merge(left, right) { if (!left) return right; if (!right) return left; if (left.val < right.val) { left.next = merge(left.next, right); return left; } else { right.next = merge(left, right.next); return right; } } return merge(l1, l2); };
import React, { useState, useEffect } from 'react' import { Checkbox, Grid, Header, Icon, Image, Menu, Segment, Sidebar, Button, Container, Popup, } from 'semantic-ui-react' import {estadoInicialComentario} from '../../estadosIniciales/estadoInicial-comentario'; import {agregarComentarios, obtenerComentarios} from '../../servicios/comentarios.srv'; import { cerrarSesion } from '../../servicios/autenticarUsuario.srv'; import {useDispatch} from 'react-redux' import FormularioComentarios from '../formularios/formulario.comentarios'; import ModalMensaje from '../../components/modales/modalMensaje'; import bg from '../../assets/69.jpg' import TarjetaComentario from '../tarjetas/tarjeta-comentario'; const SideBar = ({ sideBar, setSideBar }) => { const [ modalMensajeEstatus, setModalMensajeEstatus ] = useState({ activo: false, mensaje: '' }) const [ modalComentarios, setModalComentarios ] = useState(false) const [ comentario, setComentario ] = useState(Object.assign({}, estadoInicialComentario)) const [ comentarios, setComentarios ] = useState([]) const [ filtro, setFiltro ] = useState({ activo: true }) useEffect(() => { consultar() }, [filtro]) const dispatch = useDispatch() const salir = () => { dispatch(cerrarSesion()) } const consultar = async() => { const respuesta = await obtenerComentarios() console.log(respuesta) if(respuesta.data.estatus){ setComentarios(respuesta.data.data.comentarios) } else { setModalMensajeEstatus({ ...modalMensajeEstatus, activo:true, mensaje: respuesta.data.resultadoOperacion }) } } const comentarioNuevo = async() => { const respuesta = await agregarComentarios(comentario) if(respuesta.data.estatus){ setModalMensajeEstatus({ ...modalMensajeEstatus, activo:true, mensaje: respuesta.data.resultadoOperacion }) setComentario(Object.assign({}, estadoInicialComentario)) consultar() } else { setModalMensajeEstatus({ ...modalMensajeEstatus, activo:true, mensaje: respuesta.data.resultadoOperacion }) } consultar() } return ( <Grid columns={1}> <Grid.Column> <Sidebar.Pushable as={Segment}> <Sidebar as={Menu} animation="push" icon='labeled' onHide={() => setSideBar(false)} vertical visible={sideBar} width='thin' > <Menu.Item> <Icon name='home' /> OPCIONES </Menu.Item> <Menu.Item onClick={() => salir()} as='a'> <Icon name='log out' /> CERRAR SESION </Menu.Item> <Menu.Item> <Icon name='info circle' /> <p> Para Estefita </p> <p> De su crush </p> </Menu.Item> </Sidebar> <Sidebar.Pusher dimmed={sideBar}> <Grid columns={3} container style={{ backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', marginTop:65, marginBottom:50, marginLeft:50, marginRight:50, minHeight:'72vh' }} > <Grid.Row> <Container fluid> <Header as="h1" style={{marginBottom:20 }}> COMENTARIOS <Popup content="Aquí apareceran nuestros comentarios:3" trigger={ <label> <Icon name="info circle" color="purple" /> </label> } /> <span> <Button size="tiny" onClick={() => setModalComentarios(true)} style={{backgroundImage: `url(${bg})`, color: 'white'}} floated='right'> <Icon name="add"/> AGREGAR COMENTARIOS </Button> </span> </Header> <Grid columns={4}> {comentarios !== undefined && comentarios.length>0 ? comentarios.map(i => ( <TarjetaComentario item={i} /> )) :null} </Grid> <FormularioComentarios comentario={comentario} modalComentarios={modalComentarios} guardar={comentarioNuevo} setModalComentarios={setModalComentarios} setComentario={setComentario} /> <ModalMensaje estatus={modalMensajeEstatus} setModalMensajeEstatus={setModalMensajeEstatus} /> </Container> </Grid.Row> </Grid> </Sidebar.Pusher> </Sidebar.Pushable> </Grid.Column> </Grid> ) } export default SideBar
function dosomething() { if (confirm("do you want to proceed to youtube?") == true) {window.open('https://www.youtube.com/watch?v=U66dciR-fCY')} else {} } function MOWYPINW() { if (confirm("do you want to proceed to youtube?") == true) {window.open('http://www.huffingtonpost.com/2015/05/06/bsl-map_n_7216190.html')} else {} } function HTA() { if (confirm("do you want to proceed to youtube?") == true) {window.open('https://www.youtube.com/watch?v=06T-_y1RMiQ')} else {} } function APBT() { if (confirm("do you want to proceed to youtube?") == true) {window.open('http://www.globalanimal.org/2015/07/10/pit-bull-discrimination-a-people-problem/?gclid=CLD9693O_NICFQa5wAodfMILLA')} else {} } document.getElementById("luciusdefaultID").addEventListener("click", displayLucius); function displayLucius() { document.getElementById("imageholder").src='images/lucius.jpg' } document.getElementById("luciusballID").addEventListener("click", displayLuciusball); function displayLuciusball() { document.getElementById("imageholder").src='images/luciusball.jpeg' } document.getElementById("luciuscaliID").addEventListener("click", displayLuciuscali); function displayLuciuscali() { document.getElementById("imageholder").src='images/luciuscali.jpeg' }
import { getBeers } from "../../../utils/api.js"; import handleServerResponseOnLoadMore from "./ServerReponseOnLoadMore.js"; export default async ({ store, actionCreators }) => { const { toggleLoading, handleError, handleDelete } = actionCreators; try { store.dispatch(toggleLoading(true)); const { searchQuery, currentPage } = store.getState(); const receivedBeerItems = await getBeers(searchQuery, currentPage); const dataToHandleLoadMore = { store, actionCreators, receivedBeerItems, }; handleServerResponseOnLoadMore(dataToHandleLoadMore); } catch (error) { store.dispatch( handleError({ emptyResponse: "Oops... Something went wrong" }) ); store.dispatch(handleDelete([])); } finally { store.dispatch(toggleLoading(false)); } };
let obj={ x:10, y:20, z:30 } console.log(obj.x) console.log(obj['y']) //Update property obj.x=100 obj.y=200 obj.z=300 console.log(obj) let withString='x' console.log(obj[withString])
const express = require("express"); const router = express.Router(); const Test = require("../models/test"); // Getting all router.get("/", async (req, res) => { try { const testsBelongingToOwner = await Test.find({ owner: req.body.owner }); res.json(testsBelongingToOwner); } catch (err) { res.status(500).json({ message: err.message }); } }); /* // Getting One router.get('/:id', getTest, (req, res, next) => { res.json(res.test) }) */ // get all tests by ownerID router.get("/id", async (req, res) => { try { //console.log(req.query); const tests = await Test.find({ owner: req.query.id }); res.status(200).json(tests); if (tests == null) { return res.status(404).json({ message: "Cannot find test" }); } } catch (err) { console.log(err); return res.status(500).json({ message: err.message }); } }); // Creating one router.post("/", async function (req, res) { const testToSave = new Test({ title: req.body.title, owner: req.body.owner, numberOfQuestions: req.body.numberOfQuestions, typeOfTest: req.body.typeOfTest, questions: req.body.questions, }); console.log(testToSave); try { const newTest = await testToSave.save(); //console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); //console.log(newTest); res.status(201).json(newTest); } catch (err) { console.log(err); res.status(400).json({ message: err.message }); } }); //delete by test ID router.post("/deletebyid", async (req, res) => { try { const deleted = await Test.findByIdAndDelete(req.body.id); console.log(deleted); res.json({ message: "Deleted Test", deleted: deleted }); } catch (err) { res.status(500).json({ message: err.message }); } }); // Updating One //router.patch('/:id', getSubscriber, async (req, res) => { //if (req.body.name != null) { //res.subscriber.name = req.body.name // } // if (req.body.subscribedToChannel != null) { // res.subscriber.subscribedToChannel = req.body.subscribedToChannel // } //try { // const updatedSubscriber = await res.subscriber.save() // res.json(updatedSubscriber) // } catch (err) { // res.status(400).json({ message: err.message }) //} //}) // Deleting One /* router.delete('/:id', getTest, async (req, res) => { try { await res.test.remove() res.json({ message: 'Deleted Test' }) } catch (err) { res.status(500).json({ message: err.message }) } }) */ async function getTest(req, res, next) { let test; try { test = await Test.findById(req.params.id); if (test == null) { return res.status(404).json({ message: "Cannot find test" }); } } catch (err) { return res.status(500).json({ message: err.message }); } res.test = test; next(); } module.exports = router;
var NOTIFICATIONS_CENTER; var NOTIFICATIONS_URL = buildUrlWithContextPath("notifications"); var LOGOUT_URL = buildUrlWithContextPath("logout"); $(function () { setInterval(refreshNotifications, 2000); }); function refreshNotifications() { ajaxRefreshNotifications( function (notificationsCenter) { NOTIFICATIONS_CENTER = notificationsCenter; createNotificationsHTML(); }); } function ajaxRefreshNotifications(callback) { $.ajax({ url: NOTIFICATIONS_URL, dataType: "json", data: { notificationsAction: "get" }, success: function (notificationsCenter) { callback(notificationsCenter); } }); } function seenNotifications() { ajaxSeenNotifications(() => { refreshNotifications(); }); } function ajaxSeenNotifications(callback) { $.ajax({ url: NOTIFICATIONS_URL, dataType: "json", data: { notificationsAction: "see" }, success: function () { callback(); } }); } function createNotificationsHTML() { $("#notificationsList").empty(); $.each(NOTIFICATIONS_CENTER.notifications || [], addSingleNotification); updateNotificationsBadge(); } function addSingleNotification(index, notificationData) { let notification = createSingleNotificationHTML(notificationData); $("#notificationsList").append(notification); } function createSingleNotificationHTML(notificationData) { let notification; switch(notificationData.type) { case "pr": notification = '<a class="d-flex align-items-center dropdown-item" href="#">'+ ' <div class="mr-3">'+ ' <div class="bg-primary icon-circle">'+ ' <i class="far fa-window-restore text-white"></i>'+ ' </div>'+ ' </div>'+ ' <div><span class="small text-gray-500">' + notificationData.date + '</span>'+ ' <p>' + notificationData.content + '</p>'+ ' </div>'+ '</a>'; break; case "fork": notification = '<a class="d-flex align-items-center dropdown-item" href="#">'+ ' <div class="mr-3">'+ ' <div class="bg-success icon-circle">'+ ' <i class="fas fa-code-branch text-white"></i>'+ ' </div>'+ ' </div>'+ ' <div><span class="small text-gray-500">' + notificationData.date + '</span>'+ ' <p>' + notificationData.content + '</p>'+ ' </div>'+ '</a>'; ; break; case "alert": notification = '<a class="d-flex align-items-center dropdown-item" href="#">'+ ' <div class="mr-3">'+ ' <div class="bg-warning icon-circle">'+ ' <i class="fas fa-eraser text-white"></i>'+ ' </div>'+ ' </div>'+ ' <div><span class="small text-gray-500">' + notificationData.date + '</span>'+ ' <p>' + notificationData.content + '</p>'+ ' </div>'+ '</a>'; break; } return notification; } function updateNotificationsBadge() { var unseenNotifications = NOTIFICATIONS_CENTER.unseen; if (unseenNotifications === 0) { $('#notificationsBadge').hide(); } else { $('#notificationsBadge').show(); } $('#notificationsBadge').text(unseenNotifications); } function ShowModal(response) { var json = (response.success === undefined)? JSON.parse(response) : response; if (json.success) { document.getElementById("modal-success-content").textContent = json.message; $('#successModal').modal('show'); } else { document.getElementById("modal-failure-content").textContent = json.message; $('#failureModal').modal('show'); } } function ShowYesNoModal(title, content, branchName, yesDanger) { document.getElementById("modal-yesno-title").textContent = title; document.getElementById("modal-yesno-content").textContent = content; let yesBtn = document.getElementById("modal-yes-btn"); // yesBtn.click(yesFunctionCallback); $(yesBtn).on("click", function() { deleteBranch(branchName); $('#yesNoModal').modal('hide'); }); if (yesDanger) { yesBtn.className = 'btn btn-danger'; } else { yesBtn.className = 'btn btn-success'; } $('#yesNoModal').modal('show'); } function logout() { $.ajax({ url: LOGOUT_URL, dataType: "json", success: function(message) { console.log("Logout Success"); } }); window.location = "login.html"; }
const modelProduct =require('../model/Products.js'); const bodyParser = require('body-parser'); const Product = require('../model/Products.js'); const session = require('express-session'); exports.findAll= (req, res) => { var sess sess=req.session; if(sess.role!=1){ res.redirect("error") return -1; } modelProduct.findAll().then(data=>{ var id_product=[] var len=0; while(true){ if (data[len]==undefined){ break; } else{ len++; } } for(var i=0;i<len;i++){ id_product.push(data[i].dataValues) } res.render('product',{title:"tmp",product:id_product}) }) }; exports.serach_product= async (req, res) => { var sess sess=req.session; if(sess.role!=1){ res.redirect("error") return -1; } const {str_search,type_search_item}=req.body if(type_search_item=='id_product') modelProduct.findAll( { where: { id_product: str_search } }).then(data=>{ var prod=[] prod.push(data[0].dataValues) console.log(prod) res.render('product',{title:"tmp",product:prod}) } ) if(type_search_item=='model') modelProduct.findAll( { where: { model: str_search } }).then(data=>{ var prod=[] prod.push(data[0].dataValues) console.log(prod) res.render('product',{title:"tmp",product:prod}) } ) if(type_search_item=='customer') modelProduct.findAll( { where: { name_company: str_search } }).then(data=>{ var prod=[] prod.push(data[0].dataValues) console.log(prod) res.render('product',{title:"tmp",product:prod}) } ) } exports.AddProduct= async (req, res) => { var sess sess=req.session; if(sess.role!=1){ res.redirect("error") return -1; } const { model, id_order, data_start} = req.body console.log("model"+model+ " custom"+id_order+" data"+ data_start) const cut= await Product.create({model:model,id_order:id_order,data_start:data_start}).then(gig => res.redirect('product')) }; exports.DeleteProduct= async (req, res) => { var sess sess=req.session; if(sess.role!=1){ res.redirect("error") return -1; } var id_delUser=JSON.stringify(req.body.id); var id_del=id_delUser.slice(1,(id_delUser.length-1)) console.log('body: ' + id_del); const delUser= await Product.destroy({ where: { id_product: id_del } }).then(gig => res.render('product')).catch(gig => console.log("error")); }; exports.AddComments= async (req, res) => { var sess sess=req.session; if(sess.role!=1){ res.redirect("error") return -1; } const {id_product,comments} = req.body console.log("id"+id_product) console.log("coments"+comments) const cut= await Product.update({comments:comments},{where:{id_product:id_product}}).then(gig => res.render('comments',{mess:"Add comments"})) }; exports.PutProduct=async (req, res) => { const {id,model,id_order,data_start}=req.body await Product.update({ model:model,id_order:id_order,data_start:data_start }, { where: { id_product:id } }).then(data=> {res.render('product')}).catch(err=>{console.log("error")}); }
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: crm/person/picture // ================================================================================ { var i; var str = ""; var ivalues = { schema : 'mne_crm', table : 'personpicture' }; weblet.initDefaults(ivalues); weblet.loadview(); var attr = { hinput : false, sendframe : { weblet : weblet }, }; weblet.findIO(attr); weblet.showLabel(); weblet.delbuttons('add'); weblet.showids = new Array("personpictureid"); weblet.titleString.add = weblet.txtGetText("#mne_lang#Bild hinzufügen"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#Bild bearbeiten"); weblet.defvalues = {}; weblet.sendready = function() { var e; this.obj.sendform = this.frame.sendframe.contentDocument.getElementById("sendform"); this.obj.sendform.dataInput.weblet = this; this.obj.sendform.dataInput.name = "pictureInput"; var body = this.frame.sendframe.contentDocument.body; this.frame.sendframe.style.width = body.scrollWidth + "px"; this.frame.sendframe.style.height = body.scrollHeight + "px"; this.frame.sendframe.style.overflow = "hidden"; if ( typeof this.popup != 'undefined' ) this.popup.resize(true,false); this.obj.sendform.action = "/db/utils/table/modify.html"; e = this.doc.createElement('input'); e.name = "schema"; e.type = "hidden"; e.value = this.initpar.schema; this.obj.sendform.appendChild(e); e = this.doc.createElement('input'); e.name = "table"; e.type = "hidden"; e.value = this.initpar.table; this.obj.sendform.appendChild(e); this.obj.fileid = e = this.doc.createElement('input'); e.name = "personpictureidInput.old"; e.type = "hidden"; e.value = this.obj.inputs.personpictureid.value; this.obj.sendform.appendChild(e); e = this.doc.createElement('input'); e.name = "sqlend"; e.type = "hidden"; e.value = '1'; }; weblet.dataready = function() { try { if ( this.frame.sendframe.contentDocument.body.innerHTML == 'ok' ) { var obj = {}; obj.act_values = this.act_values; if ( typeof this.onbtnobj != 'undefined') this.onbtnobj.onbtnclick('ok', this.obj.buttons.ok); this.popup.hidden(); } else { this.html(this.frame.sendframe.contentDocument.getElementsByTagName("body")[0].innerHTML); this.frame.sendframe.src = "/weblet/allg/file/send/view.html"; } } catch(e) { this.exception("MneSupportFile::dataread:", e); } }; weblet.enable_buttons = function(enable) { var i = null; for ( i in this.obj.buttons ) this.obj.buttons[i].disabled = enable != true; }; weblet.showValue = function(weblet, param) { var retval = true; if ( weblet == this ) return; if ( typeof param != 'undefined' && param.popup == true ) this.obj.nochange = true; if ( weblet == null || typeof weblet.act_values.personid == 'undefined' || weblet.act_values.personid == null || weblet.act_values.personid == '################') { this.enable_buttons(false); this.frame.sendframe.src = "/weblet/allg/file/send/view.html"; retval = false; } else { MneAjaxWeblet.prototype.showValue.call(this, { act_values : { personpictureid : weblet.act_values.personid }}, { ignore_notfound : true } ); if ( this.values.length == 0 ) this.add(); this.showInput("personpictureid", weblet.act_values.personid ); this.enable_buttons(true); this.frame.sendframe.src = "/weblet/allg/file/send/view.html"; } return retval; }; weblet.add = function(setdepend) { this.obj.nochange = false; var result = MneAjaxWeblet.prototype.add.call(this,setdepend); return result; }; weblet.cancel = function() { if ( typeof this.popup != 'undefined' ) this.popup.hidden(); } weblet.ok = function(setdepend) { if ( this.obj.sendform.pictureInput.value == '' ) { this.error("#mne_lang#Bitte eine Datei auswählen"); return true; } var result = MneAjaxWeblet.prototype.ok.call(this, false, true, false); if ( result == false ) { this.obj.fileid.value = this.act_values.personpictureid; this.obj.sendform.submit(); return false; } }; }
import React, { useState, useEffect } from "react"; import Update from "./Update"; function ToDo({ task, done, id, entries, setEntries }) { const [show, setShow] = useState(false); const [entry, setEntry] = useState(task); const [color, setColor] = useState("darkblue"); useEffect(() => { let updatedEntries = []; entries.forEach((task) => { if (task.id === id) { task.entry = entry; } updatedEntries.push(task); }); setEntries(updatedEntries); }, [entry]); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const checked = { class: "far fa-check-square", color: "green", }; const unChecked = { class: "far fa-square", color: "rgb(187, 31, 31)", }; const [checkbox, setCheckbox] = useState(done ? checked : unChecked); const handleCheckbox = () => { if (checkbox.color === unChecked.color) { setCheckbox(checked); } else { setCheckbox(unChecked); } let updatedEntries = []; entries.forEach((task) => { if (task.id === id) { task.done = !task.done; } updatedEntries.push(task); }); setEntries(updatedEntries); }; const handleDelete = () => { const remainingEntries = entries.filter((entry) => entry.id !== id); setEntries(remainingEntries); }; const changeColor = () => { setColor("white"); }; const changeBack = () => { setColor("darkblue"); }; const styles = { toDo: { border: "1px solid black", width: "75vw", minHeight: "60px", margin: "0 auto", marginTop: "2vh", backgroundColor: `${checkbox.color}`, color: "darkblue", paddingTop: "17px", boxShadow: "1px 1px 15px -3px black", borderRadius: "15px" }, checkbox: { fontSize: "25px", cursor: "pointer", }, entry: { cursor: "pointer", color: `${color}`, }, }; return ( <div style={styles.toDo} className="row"> <div className="col-2 col-md-1"> <span className="far fa-trash-alt" style={styles.checkbox} onClick={handleDelete} /> </div> <div className="col-8 col-md-10"> <p className="text-center" onClick={handleShow} style={styles.entry} onMouseOver={changeColor} onMouseLeave={changeBack} > {entry} </p> </div> <div className="col-2 col-md-1 text-right"> <span className={checkbox.class} style={styles.checkbox} onClick={handleCheckbox} /> </div> <Update task={entry} show={show} handleClose={handleClose} setEntry={setEntry} /> </div> ); } export default ToDo;
import React, { useState } from 'react'; import ReactDOM from 'react-dom'; import 'react-responsive-modal/styles.css'; import { Modal } from 'react-responsive-modal'; const ModalEvent = (props) => { console.log(props) // console.log(props.modal_trigger_value) const [open, setOpen] = useState(props.modal_trigger_value); const onOpenModal = () => setOpen(true); const onCloseModal = () => setOpen(false); return ( <div> <button onClick={onOpenModal}>Open modal</button> <Modal open={open} onClose={onCloseModal} center> <h2>Simple centered modal</h2> </Modal> </div> ); }; export default ModalEvent
/* * @lc app=leetcode.cn id=135 lang=javascript * * [135] 分发糖果 */ // @lc code=start /** * @param {number[]} ratings * @return {number} */ var candy = function(ratings) { const len = ratings.length; let left = new Array(len).fill(0); for (let i = 0; i < len; i++) { if (i > 0 && ratings[i - 1] < ratings[i]) { left[i] = left[i - 1] + 1; } else { left[i] = 1; } } let right = 0, ret = 0; for (let i = len - 1; i > -1; i--) { if (i < len - 1 && ratings[i] > ratings[i + 1]) { right++ } else { right = 1; } ret += Math.max(left[i], right); } return ret; }; // @lc code=end
import React from 'react' import { StyleSheet, Text, View } from 'react-native'; import {Avatar} from "react-native-paper" const AvatarComponent = ({size, source, avatarStyle}) => { return ( <Avatar.Image size={size} source={{uri:source}} style={avatarStyle}/> ) } export default AvatarComponent
import React from "react"; import styled from "styled-components"; import { useDispatch, useSelector } from "react-redux"; import { actionsClientes } from "../../store/actions/clientes"; const AccordionWrapper = styled.div` width: 80%; display: flex; justify-content: center; ul { li { list-style-type: none; } } `; const ClientesAdminAccordion = () => { const dispatch = useDispatch(); //const [data, setData] = React.useState({}); const clientes = useSelector(state => state.clientes); React.useEffect(() => { async function fetchClientes() { dispatch(actionsClientes.getClientes()); } fetchClientes(); }, [clientes.result]); return ( <AccordionWrapper> <ul> {clientes.result.map(data => ( <li key={data._key}> <p>{data.email}</p> </li> ))} </ul> </AccordionWrapper> ); }; export default ClientesAdminAccordion;
import React from 'react'; import { Link } from 'react-router-dom'; import logo from '../../assets/images/logo.svg'; const Hero = () => { return ( <section className="hero"> <div className="hero__header"> <img src={logo} alt="logo"></img> </div> <div className="hero__claim"> <div> <h1> <span>Hey!</span> Could you fill this form for us? </h1> <Link to="/submissions"> <p className="hero__link">Show all submissions</p> </Link> </div> <div className="hero__decoration"></div> </div> </section> ); }; export default Hero;
// every and some will look at conditions and returning true and false const users = [ { name: "Mike", isActive: true, createdAt: 1601234512420, socialProfiles: [ { site: "twitter", username: "mzetlow", }, { site: "facebook", username: "fbmikezetlow", profilePhoto: { sm: "small.jpg", lg: "large.jpg", }, }, ], }, { name: "John", isActive: true, createdAt: 1601234512430, socialProfiles: [ { site: "facebook", username: "fbjsmith", profilePhoto: { sm: "small.jpg", lg: "large.jpg", }, }, ], }, { name: "Michelle", isActive: false, createdAt: 1601234512450, socialProfiles: [ { site: "twitter", username: "michelledoe", }, ], }, ]; //EVERY (looking for the first false) // everything that pass this condition will return true, if it doesnt pass = false const isEveryUserOnFb = users.every((user) => { // go through all the social profiles const siteNames = user.socialProfiles.map((profile) => { return profile.site; // turning obj to str }); return siteNames.includes(`facebook`); // if site === facebook, // if (siteNames.includes(`facebook`)) { // return true; // } else { // return false; // } // this user is on facebook, so return true // else return false }); console.log(`Is every user on fb?`, isEveryUserOnFb); //SOME (looking for the first true) const hasGithubUsers = users.some((user) => { const siteNames = user.socialProfiles.map((profile) => { return profile.site; }); return siteNames.includes(`github`); }); console.log(`Do we have any Github users?`, hasGithubUsers);
import initialState from './initialState'; import * as Action from '../actions/types'; // Reducer for currentGame store section export default function gameReducers(state = initialState.currentGame, action) { switch(action.type) { // The user starts a new game case Action.START_GAME: return { ...state, status: 1, playing: true, score: 0 } // Round state changes case Action.UPDATE_CURRENT_GAME_SCORE: return { ...state, score: action.score }; case Action.UPDATE_GAME_STATUS: return { ...state, status: action.status, twitterUsername: action.twitterUsername, profile: action.profile || 'DEFAULT', }; case Action.END_CURRENT_GAME: return { ...state, playing: false, score: action.finalScore, status: 2, }; default: return state; } }
function createRoleFromArray(roleNameArray) { return new Promise((resolve, reject) => { const saveRoles = roleNameArray.map((roleName) => { const newRole = new Parse.Object("_Role"); newRole.set("name", roleName); const aclObj = new Parse.ACL(); aclObj.setRoleWriteAccess("admin", true); aclObj.setRoleReadAccess("admin", true); newRole.setACL(aclObj); return newRole; }); Parse.Object.saveAll(saveRoles).then((savedRoles) => { resolve(savedRoles); }, (err) => { reject(err); }); }); } function addUserToRoles(userData, roleArray) { return new Promise((resolve, reject) => { const promises = []; const Role = new Parse.Query(Parse.Role); Role.containedIn("name", roleArray); Role.find({useMasterKey: true}).then(function (roles) { roles.forEach((role) => { role.getUsers().add(userData); promises.push(role.save(null, {useMasterKey: true})); }); Promise.all(promises) .then(result => { resolve(promises) }) .catch(error => { reject(error); }); }); }); } // const Role = new Parse.Query(Parse.Role); // Role.containedIn("name", roleArray); // Role.find({useMasterKey: true}).then(function (roles) { // return new Promise((resolve, reject) => { // const saveRoles = []; // roles.forEach((role) => { // const newRole = role.getUsers().add(userData); // return newRole; // }); // Parse.Object.saveAll(saveRoles).then((savedRoles) => { // resolve(savedRoles); // }, (err) => { // reject(err); // }); // }); // }); // const Role = new Parse.Query(Parse.Role); // Role.containedIn("name", roleArray); // Role.find({useMasterKey: true}).then(function (roles) { // const promises = []; // const promises = roles.map((result) => { // // Start this delete immediately and add its promise to the list. // role.getUsers().add(userData); // return role.save(); // }); // // Return a new promise that is resolved when all of the deletes are finished. // return Promise.all(promises); // // }).then(function() { // return true; // }); // const promises = []; // const Role = new Parse.Query(Parse.Role); // Role.containedIn("name", roleArray); // Role.find({useMasterKey: true}).then(function (roles) { // // const promises = roles.forEach((role) => { // role.getUsers().add(userData); // return role.save(null, {useMasterKey: true}); // }); // Promise.all(promises) // .then(result => { // console.log(result); // }) // .catch(error => { // console.log(error); // }); // }); module.exports = { createRoleFromArray: createRoleFromArray, addUserToRoles: addUserToRoles };
var searchData= [ ['velocity',['velocity',['../class_m_d___r_encoder.html#a3f8a093ef5da74530daab77c066f5b18',1,'MD_REncoder']]] ];
import React from "react"; import { shallow, mount } from "enzyme"; import GuessSection from "./guess-section"; describe("Renders Guess Section", () => { it("Shallow renders Guess Section", () => { shallow(<GuessSection />); }); });
import React, { useEffect } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import styled from 'styled-components'; import { PropTypes } from 'prop-types'; import StyledSection from '../../components/LandSection'; import DarkOverlay from '../../components/Dark-overlay'; import { profileActions } from '../../actions/profileAction'; import Spinner from '../Spinner'; const LandingInner = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; height: 100%; width: 80%; color: #fff; margin: auto; `; const Landing = () => { return ( <StyledSection className="nav"> <DarkOverlay> <LandingInner> <h1 className="x-large">Developer Connector</h1> <p className="lead"> Create a developer profile/portfolio, share posts and get help from other developers </p> <div className="buttons"> <Link to="/register" className="btn btn-primary"> Sign Up </Link> <Link to="/login" className="btn btn-light"> Login </Link> </div> </LandingInner> </DarkOverlay> </StyledSection> ); }; export default Landing;
const express = require('express'); const router = express.Router(); const cartController = require('../controllers/cartController'); // Hiển thị trang giỏ hàng router.get('/', cartController.renderCart); // Xoá sản phẩm trong giỏ hàng router.get('/remove/:id', cartController.remove); // Thêm số lượng 1 cho sản phẩm trong giỏ hàng theo id sản phẩm router.get('/add/:id', cartController.add); // Xoá số lượng 1 cho sản phẩm trong giỏ hàng theo id sản phầm router.get('/minus/:id', cartController.minus); // Hiển thị trang điền thông tin giao hàng router.get('/checkout', cartController.renderCheckout); // Check out router.post('/checkout', cartController.checkout); module.exports = router;
var utils = require('utils') var Message = require(__dirname+'/message') var PrivateKey = require(__dirname+'/private_key') class Signature { constructor(message, privateKey) { utils.assert(message instanceof Message) utils.assert(privateKey instanceof PrivateKey) // generate signature! throw new Error('Signature generation not implemented') } } module.exports = Signature
var pdaInitID = []; var pdaFinalID = []; var pdaCheck = false; var pdaId; var pdaStack = ''; var testCaseList3 = [] function findAlledgesFromOneNodePDA(xmlDoc, id) { var packagelist = []; // var list = $(xmlDoc).find('transition').children() var counter = 0; while ($(xmlDoc).find('transition').children()[counter] != undefined) { var from = $(xmlDoc).find('transition').children()[counter].innerHTML; var to = $(xmlDoc).find('transition').children()[counter + 1].innerHTML; var read = $(xmlDoc).find('transition').children()[counter + 2].innerHTML; var pop = $(xmlDoc).find('transition').children()[counter + 3].innerHTML; var push = $(xmlDoc).find('transition').children()[counter + 4].innerHTML; if (from == id) { packagelist.push(from); packagelist.push(to); packagelist.push(read); packagelist.push(pop); packagelist.push(push); } counter = counter + 5; } return packagelist; } /** * add string to testCases * * @param testCase * tastcases * @param result * true/false for the current string * @param str * string */ function pdaAdd(testCase, result, str) { if (testCase.testCases.indexOf(str) == -1) { if (result) { if (trueCounter < trueStringLimit && !loopkey(testCaseList3,str)) { testCaseList3.push(str); addtoTestCase(str, testCase, 1); trueCounter++; } } else { if (falseCounter < falseStringLimit && !loopkey(testCaseList3,str)) { testCaseList3.push(str); addtoTestCase(str, testCase, 0); falseCounter++; } } } } function reverseString(str) { return str.split("").reverse().join(""); } function helpPop(Stack, popStr){ popStr = reverseString(popStr); var pos = Stack.lastIndexOf(popStr); if(pos == -1 || Stack.length != (pos + popStr.length)){return false;} else{ pdaStack = Stack.substring(0, pos ); return true; } } function travnPda(xmlDoc, id, len) { var str = ''; for (var pos = 0; pos < len; pos++) { var package = findAlledgesFromOneNodePDA(xmlDoc, id); if(package.length ==0) { break; } var pick = Math.floor(Math.random() * (package.length / 5)); //check pop if(helpPop(pdaStack,package[pick * 5 + 3])){ //to id = package[pick * 5 + 1]; //read str = str + package[pick * 5 + 2]; //push var pushStr = reverseString(package[pick * 5 + 4]) pdaStack = pdaStack+pushStr; } } // Current node is a final nore if (finalID.includes(id)|| checkLambda(xmlDoc, id)) { pdaCheck = true; } else { pdaCheck = false; } return str; } function checkLambda(xmlDoc, id){ var checkend= false; var package = findAlledgesFromOneNodePDA(xmlDoc, id); for (var pos = 0; pos < package.length/5 ; pos++) { var to = package[pos * 5 + 1]; var read = package[pos * 5 + 2]; var pop = package[pos * 5 + 3]; var push = package[pos * 5 + 4]; if(read == "" && push==""){ if((pdaStack == "" && pop == "") ||(pdaStack == "Z" && (pop == ""||pop == "Z" ))|| (pdaStack == "z" && (pop == ""||pop == "z" ))){ if(finalID.includes(to)){ checkend = true; return checkend; } else{ checkLambda(xmlDoc, to); break; } } } } return checkend; } function pdaHelper(testCase, len) { var nfaURL = testCase.solution; var machine = $.ajax({ url: nfaURL, async: false, }) var xmltext = machine.responseText; var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xmltext, 'text/xml'); initID = findbytag(xmlDoc, 'initial'); finalID = findbytag(xmlDoc, 'final'); str = travnPda(xmlDoc, initID[0], len); pdaAdd(testCase, pdaCheck, str); } function pdaHandler(obj) { var min = randomStringLength[0]; var max = randomStringLength[1]; var stringLength = Math.round(Math.random() * (max - min)) + min; testCaseList3 = obj.testCases; pdaCheck = false; pdaStack = 'Z'; pdaHelper(obj, stringLength); }
// TODO: // Variables const PLAYER1 = 0; const PLAYER2 = 1; const OPEN_SPACE = -1; const UNPLAYABLE = -2; const PLAYER1_COLOR = "black"; const PLAYER2_COLOR = "white"; const PLAYER1_FILE = "img/pieceDark.png"; const PLAYER2_FILE = "img/pieceLight.png"; const PLAYER1_SHADE_FILE = "img/pieceDarkPossibleMove.png"; const PLAYER2_SHADE_FILE = "img/pieceLightPossibleMove.png"; const OPEN_FILE = "img/greenSquare.png"; const DK_SCORE = document.getElementById("dkScr"); const LT_SCORE = document.getElementById("ltScr"); const TXT_INPUT = document.querySelector("#input"); var board = [ [], [], [], [], [], [], [], [] ]; var player = PLAYER1; // 0 for player 1, 1 for player 2 var boxesTaken = 0; var won = false; var displayMessage = false; var twoNoMovesInARow = 0; function initializeBoard() { for (y = 0; y < 8; y++) for (x = 0; x < 8; x++) { board[y][x] = UNPLAYABLE; let strID = "i" + y + "" + x; document.getElementById(strID).src = OPEN_FILE; } board[3][3] = PLAYER1; document.getElementById("i33").src = PLAYER1_FILE; board[3][4] = PLAYER2; document.getElementById("i34").src = PLAYER2_FILE; board[4][3] = PLAYER2; document.getElementById("i43").src = PLAYER2_FILE; board[4][4] = PLAYER1; document.getElementById("i44").src = PLAYER1_FILE; boxesTaken = 4; shadeBoxes(player); winner(); } jQuery(document).ready(function($) { initializeBoard(); // create the event handlers for each box of the game for (y = 0; y < 8; y++) for (x = 0; x < 8; x++) { let eleID = "#" + y + "" + x; let tempEle = $(eleID); $(eleID).on("click", function(event) { let y = this.id.substring(0, 1); let x = this.id.substring(1); let id = y + "" + x; makeMove(id); if (displayMessage) PopUpMessage(outputMessage); displayMessage = false; }); // end of creating click function } // end of for x }); // end document ready function /******************************************************************************* ** Make Move *******************************************************************************/ function makeMove(strId) { // get game ( remove first two charageters) console.log("makeMove(\"" + strId + "\");"); let y = parseInt(strId.substring(0, 1)); let x = parseInt(strId.substring(1)); if (boxesTaken > 63) { // game over PopUpMessage("Please start another game"); return; } // if you are not clicking in an OPEN_SPACE square. exit function if (board[y][x] != OPEN_SPACE) { PopUpMessage("Please a valid move \n(Click one of the shaded squares)"); return; } // the square is OPEN_SPACE let colorFile = (player == PLAYER1) ? PLAYER1_FILE : PLAYER2_FILE; document.getElementById("i" + strId).src = colorFile; // paint it player one's color //document.getElementById(strId).style.backgroundColor = url(colorFile); // paint it player one's color board[y][x] = player; // put this square's id in the array boxesTaken++; clearShadeBoxes(); flipSquares(x, y, colorFile); if (winner()) { PopUpMessage("press reset to Play again"); return; } player = (player ^ PLAYER1) ? PLAYER1 : PLAYER2; // change player shadeBoxes(player); // sahde the next player's available moves if (twoNoMovesInARow == 2) { PopUpMessage("Now More Valid moves"); /* if (p1Count > p2Count) PopUpMessage("Dark Player won"); if (p1Count < p2Count) PopUpMessage("Light Player won"); if (p1Count == p2Count) PopUpMessage("It's a tie!"); */ return; } // set next turn color let color = (player == PLAYER1) ? PLAYER1_COLOR : PLAYER2_COLOR; document.getElementById("turnbox").style.backgroundColor = color; //document.getElementById('Undo').disabled = false; } // end clicked function /******************************************************************************* ** Do we have a winner ?? *******************************************************************************/ function winner() { let p1Count = 0; let p2Count = 0; let retVal = false; for (y = 0; y < 8; y++) for (x = 0; x < 8; x++) { if (board[y][x] == PLAYER1) p1Count++; if (board[y][x] == PLAYER2) p2Count++; } DK_SCORE.value = p1Count; LT_SCORE.value = p2Count; if (boxesTaken > 63) { if (p1Count > p2Count) PopUpMessage("Dark Player won"); if (p1Count < p2Count) PopUpMessage("Light Player won"); if (p1Count == p2Count) PopUpMessage("It's a tie!"); retVal = true; } return retVal; } /******************************************************************************* ** Clear the Shadeboxes *******************************************************************************/ function clearShadeBoxes() { // change the available spaces to be just a green space for (y = 0; y < 8; y++) for (x = 0; x < 8; x++) if (board[y][x] == OPEN_SPACE) { board[y][x] = UNPLAYABLE; let tmpID = "i" + y + "" + x; document.getElementById(tmpID).src = OPEN_FILE; } } /******************************************************************************* ** Shadeboxes *******************************************************************************/ function shadeBoxes(player) { /* Valid Moves Dark must place a piece with the dark side up on the board, in such a position that there exists at least one straight (horizontal, vertical, or diagonal) occupied line between the new piece and another dark piece, with one or more contiguous light pieces between them. */ /* find a black, move in a direction while the square is white. do this until the suare is free. this is a valid move. - set teh array to -1, - increment blackValidMove do this for all black pieces in all directions */ const otherPlayer = (player ^ PLAYER1) ? PLAYER1 : PLAYER2; const colorFile = (player == PLAYER1) ? PLAYER1_SHADE_FILE : PLAYER2_SHADE_FILE; let totShadedCount = 0; // the number of valid moves let count = 0; let x = 0; let y = 0; let i = 0; let j = 0; for (y = 0; y < 8; y++) for (x = 0; x < 8; x++) { if (board[y][x] == player) { // check in each direction for other player and open spot // left if (x != 0) { i = x - 1; count = 0; while (i >= 0 && board[y][i] == otherPlayer) { i--; count++; } if (i >= 0 && count && board[y][i] == UNPLAYABLE) { let tmpID = "i" + y + "" + i; board[y][i] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // right if (x != 7) { i = x + 1; count = 0; while (i < 8 && board[y][i] == otherPlayer) { i++; count++; } if (i < 8 && count && board[y][i] == UNPLAYABLE) { let tmpID = "i" + y + "" + i; board[y][i] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // up if (y != 0) { j = y - 1; count = 0; while (j >= 0 && board[j][x] == otherPlayer) { j--; count++; } if (j >= 0 && count && board[j][x] == UNPLAYABLE) { let tmpID = "i" + j + "" + x; board[j][x] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // down if (y != 7) { j = y + 1; count = 0; while (j < 8 && board[j][x] == otherPlayer) { j++; count++; } if (j < 8 && count && board[j][x] == UNPLAYABLE) { let tmpID = "i" + j + "" + x; board[j][x] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // upper left if (x != 0 && y != 0) { i = x - 1; j = y - 1; count = 0; while (j >= 0 && i >= 0 && board[j][i] == otherPlayer) { j--; i--; count++; } if (j >= 0 && i >= 0 && count && board[j][i] == UNPLAYABLE) { let tmpID = "i" + j + "" + i; board[j][i] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // upper right if (x != 7 && y != 0) { i = x + 1; j = y - 1; count = 0; while (j >= 0 && i < 8 && board[j][i] == otherPlayer) { j--; i++; count++; } if (j >= 0 && i < 8 && count && board[j][i] == UNPLAYABLE) { let tmpID = "i" + j + "" + i; board[j][i] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // lower left if (x != 0 && y != 7) { i = x - 1; j = y + 1; count = 0; while (j < 8 && i >= 0 && board[j][i] == otherPlayer) { j++; i--; count++; } if (j < 8 && i >= 0 && count && board[j][i] == UNPLAYABLE) { let tmpID = "i" + j + "" + i; board[j][i] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } // lower right if (x != 7 && y != 7) { i = x + 1; j = y + 1; count = 0; while (j < 8 && i < 8 && board[j][i] == otherPlayer) { j++; i++; count++; } if (j < 8 && i < 8 && count && board[j][i] == UNPLAYABLE) { let tmpID = "i" + j + "" + i; board[j][i] = OPEN_SPACE; document.getElementById(tmpID).src = colorFile; totShadedCount++; } } } // end if player } if (totShadedCount == 0) { twoNoMovesInARow++ if (twoNoMovesInARow == 1) { PopUpMessage("Now More Valid moves for Player: " + (player+1)); player = (player ^ PLAYER1) ? PLAYER1 : PLAYER2; shadeBoxes(player); } } else twoNoMovesInARow = 0; } //end shade Boxes /******************************************************************************* ** Reset *******************************************************************************/ function Reset() { boxesTaken = 0; won = false; displayMessage = false; twoNoMovesInARow = 0; initializeBoard(); } /******************************************************************************* ** flipSquares *******************************************************************************/ function flipSquare(y, x, color) { board[y][x] = player; let tmpStrID = "i" + y + "" + x; document.getElementById(tmpStrID).src = color; } function flipSquares(x, y, color) { // check to see if we need to switch colors //check left let i = x - 1; // the test x variable let j = y; // the test y variable let found = false; let opCount = 0; // the number of oponent squares inbetween mine while (i >= 0 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; i--; } if (found) { i += 2; // remove the decrement from above and move one more to the right if (x - i == opCount) for (i; i <= x; i++) { flipSquare(j, i, color); /* board[j][i] = player; let tmpStrID = "i" + j + "" + i; document.getElementById(tmpStrID).src = color; */ } } //check right i = x + 1; // the test x variable j = y; // the test y variable found = false; opCount = 0; while (i < 8 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; i++; } if (found) { i -= 2; // remove the increment from above and move one more to the left if (i - x == opCount) for (i; i > x; i--) { flipSquare(j, i, color); } } //check up i = x; // the test x variable j = y - 1; // the test y variable found = false; opCount = 0; while (j >= 0 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; j--; } if (found) { j += 2; // remove the decrement from above and move one more down if (y - j == opCount) for (j; j < y; j++) { flipSquare(j, i, color); } } //check down i = x; // the test x variable j = y + 1; // the test y variable found = false; opCount = 0; while (j < 8 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; j++; } if (found) { j -= 2; // remove the increment from above and move one more up if (j - y == opCount) for (j; j > y; j--) { flipSquare(j, i, color); } } // check diagonal up / left - both minus i = x - 1; j = y - 1; found = false; opCount = 0; // the number of oponent squares inbetween mine while (j >= 0 && i >= 0 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; j--; i--; } if (found) { i += 2; // remove the decrement from above and move one more to the right j += 2; // remove the decrement from above and move one more to the down if (y - j == opCount) for (j, i; j < y && i < x; j++, i++) { flipSquare(j, i, color); } } // check diagonal up / right - y minus / x plus i = x + 1; j = y - 1; found = false; opCount = 0; // the number of oponent squares inbetween mine while (j >= 0 && i < 8 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; j--; i++; } if (found) { i -= 2; // remove the increment from above and move one more to the left j += 2; // remove the decrement from above and move one more to the down if (y - j == opCount) for (j, i; j < y && i > x; j++, i--) { flipSquare(j, i, color); } } // check diagonal down / left - y plus / x minus i = x - 1; j = y + 1; found = false; opCount = 0; // the number of oponent squares inbetween mine while (j < 8 && i >= 0 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; j++; i--; } if (found) { i += 2; // remove the increment from above and move one more to the right j -= 2; // remove the decrement from above and move one more up if (j - y == opCount) for (j, i; j > y && i < x; j--, i++) { flipSquare(j, i, color); } } // check diagonal down / right - both plus i = x + 1; j = y + 1; found = false; opCount = 0; // the number of oponent squares inbetween mine while (j < 8 && i < 8 && !found) { if (board[j][i] == player) found = true; else if (board[j][i] == !player) opCount++; j++; i++; } if (found) { i -= 2; // remove the increment from above and move one more to the left j -= 2; // remove the decrement from above and move one more up if (j - y == opCount) for (j, i; j > y && i > x; j--, i--) { flipSquare(j, i, color); } } } /******************************************************************************* ** Undo *******************************************************************************/ function Undo() { var previousID = previousIDs.pop(); var previousGame = previousID.substring(0, 1) - 1; var strP_Box = previousID.slice(2); var previousBox = parseFloat(strP_Box); var previousPlayer = (player ^ PLAYER1) ? PLAYER1 : PLAYER2; // need to figure out if the sub gane was just won player1WinBox = playerScore[PLAYER1][OUTERGAME].indexOf(gameLocation[previousGame]); if (player1WinBox != -1) { // if so, remove winning game from OUTERGAME playerScore[PLAYER1][OUTERGAME].splice(playerScore[player][previousGame].indexOf(previousBox), 1); } player2WinBox = playerScore[PLAYER2][OUTERGAME].indexOf(gameLocation[previousGame]); if (player2WinBox != -1) { // if so, remove winning game from OUTERGAME playerScore[PLAYER2][OUTERGAME].splice(playerScore[PLAYER2][OUTERGAME].indexOf(gameLocation[previousGame]), 1); } // clear the board for (g = 0; g < 9; g++) // game for (y = 1; y <= 3; y++) for (x = 1; x <= 3; x++) { myIndex = g + 1 + "." + y + "." + x; if ((document.getElementById(myIndex).style.backgroundColor == PLAYER2_SHADE) || (document.getElementById(myIndex).style.backgroundColor == PLAYER1_SHADE)) document.getElementById(myIndex).style.backgroundColor = "" } // end for y // remove the move from the array playerScore[previousPlayer][previousGame].splice(playerScore[player][previousGame].indexOf(previousBox), 1); // put board back the way it was for (y = 1; y <= 3; y++) for (x = 1; x <= 3; x++) { myIndex = previousGame + 1 + "." + y + "." + x; thisBox = parseFloat(y + "." + x);; document.getElementById(myIndex).style.backgroundColor = ""; inPlayer1Array = playerScore[PLAYER1][previousGame].indexOf(thisBox); inPlayer2Array = playerScore[PLAYER2][previousGame].indexOf(thisBox); if (inPlayer1Array != -1) document.getElementById(myIndex).style.backgroundColor = PLAYER1_COLOR if (inPlayer2Array != -1) document.getElementById(myIndex).style.backgroundColor = PLAYER2_COLOR } var lastshade = (player != PLAYER1) ? PLAYER1_SHADE : PLAYER2_SHADE; player = (player ^ PLAYER1) ? PLAYER1 : PLAYER2; var lastcolor = (player == PLAYER1) ? PLAYER1_COLOR : PLAYER2_COLOR; // shade the game for posible moves if (1 != boxesTaken) { shadeBoxes(previousGame, lastshade); } document.getElementById("turnbox").style.backgroundColor = lastcolor; boxesTaken--; currentGameNumber = previousGame; playerScore[player][previousGame].indexOf(previousBox); document.getElementById('Undo').disabled = true; } // got the modal code form: // https://www.w3schools.com/howto/howto_css_modals.asp function PopUpMessage(message) { alert(message); }
// The number 3797 has an interesting property. Being prime itself, it is possible // to continuously remove digits from left to right, and remain prime at each // stage: 3797, 797, 97, and 7. Similarly we can work from right to // left: 3797, 379, 37, and 3. // Find the sum of the only eleven primes that are both truncatable from left to // right and right to left. // NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. (function () { 'use strict'; var memoize = { 1: false }; function isPrime(n) { if (typeof memoize[n] !== 'undefined') { return memoize[n]; } n = (n < 0) ? -n : n; for (var i = 2; i * i <= n; i++) { if (n % i === 0) { memoize[n] = false; return false; } } memoize[n] = true; return true; } function isTruncatablePrime(n) { var truncatablePrime = true; var nL = n; var nR = n; var nStrL = n + ''; var nStrR = n + ''; for (var i = 0, l = nStrL.length; i < l; i++) { truncatablePrime = truncatablePrime && isPrime(nL) && isPrime(nR); if (!truncatablePrime) { break; } nStrL = nStrL.substring(1); nStrR = nStrR.substring(0, nStrR.length - 1); nL = parseInt(nStrL, 10); nR = parseInt(nStrR, 10); } return truncatablePrime; } var count = 0; var sum = 0; for (var i = 10; count < 11; i++) { if (isTruncatablePrime(i)) { count++; sum = sum + i; } } console.log(sum); })();
import { app } from '../../server.js' import { RootController } from '../../controllers/root/index.js' import {validationResult} from 'express-validator/check'; import _root_validator_ajouter_action from '../../validators/root/index.js' import { sanitizeBody } from 'express-validator/filter'; app.get('/', (req, res) => { RootController.getRoot(res); }); app.post('/ajouter',_root_validator_ajouter_action, (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ errors: errors.array() }); } RootController.ajouterAction(req,res); }); app.post('/envoyerCommande', (req,res) => { RootController.envoyerCommande(req,res); }); app.post('/supprimer', sanitizeBody('code').customSanitizer(value => { console.log(value); let _o = [], retour = []; if(typeof value !== "object"){ _o = [value]; } else { value.forEach(e => { _o.push(e); }); } _o.forEach(e =>{ let _s = e.split("$"); retour.push({topic : _s[1], code: _s[0]}); }); return retour; }), (req,res) => { console.log(req.body); RootController.supprimerAction(req,res); });
/*global ODSA */ "use strict"; // Remove slideshow $(document).ready(function () { var av_name = "BSTremoveCON"; var config = ODSA.UTILS.loadConfig({"av_name": av_name}), interpret = config.interpreter, // get the interpreter code = config.code; // get the code object var av = new JSAV(av_name); var pseudo = av.code(code[0]); var temp1; var bstTop = 410; var bt = av.ds.binarytree({visible: true, nodegap: 15, top: bstTop, left: 275}); bt.root(37); var rt = bt.root(); rt.left(24); rt.left().left(7); rt.left().left().left(2); rt.left().right(32); rt.left().right().left(30); rt.right(42); rt.right().left(42); rt.right().left().left(40); rt.right().right(120); bt.layout(); var rt1 = av.pointer("rt", bt.root(), {anchor: "left top"}); // Slide 1 av.umsg("Let's look a few examples for removehelp. We will start with an easy case. Let's see what happens when we delete 30 from this tree."); pseudo.setCurrentLine("sig"); av.displayInit(); // Slide 2 av.umsg("As always, the first thing that we do is check if the root is null. Since it is not, we are going to be recursively descending the tree until we find the value that we are looking for (if it exists)."); pseudo.setCurrentLine("checknull"); av.step(); // Slide 3 av.umsg("Compare the root value of 37 to the value that we want to delete (30). Since 37 is greater, we will left."); pseudo.setCurrentLine("visitleft"); av.step(); // Slide 4 rt.addClass("processing"); rt1.target(rt.left()); av.umsg("Now we start the recursive call on removehelp with 24 as the root."); pseudo.setCurrentLine("sig"); av.step(); // Slide 5 av.umsg("The subtree is not null"); pseudo.setCurrentLine("checknull"); av.step(); // Slide 6 av.umsg("Compare rt's value of 24 against the search key value of 32. 24 is not greater than 32."); pseudo.setCurrentLine("checkless"); av.step(); // Slide 7 av.umsg("So check whether 24 is less than the search key of 32."); pseudo.setCurrentLine("checkgreater"); av.step(); // Slide 8 av.umsg("Since 24 is less than the value we want to delete (30), we wil make a recursive call on the right subtree."); pseudo.setCurrentLine("visitright"); av.step(); // Slide 9 rt.left().addClass("processing"); rt1.target(rt.left().right(), {anchor: "right top"}); av.umsg("Now we start the recursive call on removehelp with 32 as the root."); pseudo.setCurrentLine("sig"); av.step(); // Slide 10 av.umsg("The subtree is not null"); pseudo.setCurrentLine("checknull"); av.step(); // Slide 11 av.umsg("Since 32 is greater than the value we want to delete (30), we will go left."); pseudo.setCurrentLine("visitleft"); av.step(); // Slide 12 rt.left().right().addClass("processing"); rt1.target(rt.left().right().left(), {anchor: "left top"}); pseudo.setCurrentLine("sig"); av.umsg("Start the recursive call again. As usual, we are going to check if the root is null, then if its value is greater or less than what we want to delete"); av.step(); // Slide 13 av.umsg("This time, we have found the value that we want to delete."); pseudo.setCurrentLine("found"); av.step(); // Slide 14 av.umsg("Since the value of the left child of 30 is null, we can just return that node's right pointer back to the parent. Since the node with value 30 is a leaf node, that right pointer also happens to be null."); pseudo.setCurrentLine("checkleft"); av.step(); // Slide 15 av.umsg("Unwind the recursion, and set the left pointer of the node with value of 32"); rt.left().right().removeClass("processing"); rt1.target(rt.left().right(), {anchor: "right top"}); rt.left().right().left(null); pseudo.setCurrentLine("visitleft"); av.step(); // Slide 16 av.umsg("Unwind the recursion, and set the right pointer of the node with value of 24"); var temp = rt.left().edgeToRight(); temp.addClass("rededge"); rt.left().removeClass("processing"); rt1.target(rt.left(), {anchor: "left top"}); pseudo.setCurrentLine("visitright"); av.step(); // Slide 17 av.umsg("Unwind the recursion, and set the left pointer of the node with value of 37"); temp1 = rt.edgeToLeft(); temp1.addClass("rededge"); rt.removeClass("processing"); rt1.target(rt); pseudo.setCurrentLine("visitleft"); av.step(); // Slide 18 av.umsg("Now we return from the initial call to removehelp, setting the root of the tree to the result"); rt1.arrow.addClass("thinredline"); // This line should not be needed, but it is here to fix Raphael bug with arrows rt1.arrow.css({"stroke": "red"}); pseudo.setCurrentLine("end"); av.step(); // Slide 19 av.umsg("Now let's try something a little bit harder. We will see what happens when we remove 32. We won't show all of the details of direction tests and the multiple recursive calls this time."); pseudo.setCurrentLine("sig"); pseudo.unhighlight("end"); rt1.arrow.removeClass("thinredline"); // This line should not be needed, but it is here to fix Raphael bug with arrows rt1.arrow.css({"stroke": "black"}); temp.removeClass("rededge"); temp1.removeClass("rededge"); rt.left().right().left(30); bt.layout(); av.step(); // Slide 20 av.umsg("As always, the first thing that we do is check if the root is null. Since it is not, we are going to be recursively descending the tree until we find the value that we are looking for (if it exists)."); pseudo.setCurrentLine("checknull"); av.step(); // Slide 21 av.umsg("Since 37 is greater than the value we want to delete (32), we go left."); pseudo.setCurrentLine("visitleft"); rt.addClass("processing"); rt1.target(rt.left()); av.step(); // Slide 22 av.umsg("Since 24 is less than the value we want to delete (32), we go right."); pseudo.setCurrentLine("visitright"); rt.left().addClass("processing"); rt1.target(rt.left().right(), {anchor: "right top"}); av.step(); // Slide 23 av.umsg("Now we have found the value that we want to delete."); pseudo.setCurrentLine("found"); av.step(); // Slide 17 av.umsg("We check, and the left child is not null."); pseudo.setCurrentLine("checkleft"); av.step(); // Slide 18 av.umsg("We check and find that the right child is null. So we can just return a pointer to the left child."); pseudo.setCurrentLine("checkright"); av.step(); // Slide 19 av.umsg("Unwind the recursion, and set the right pointer of the node with value of 24"); rt.left().removeClass("processing"); rt1.target(rt.left(), {anchor: "left top"}); rt.left().right(rt.left().right().left()); temp = rt.left().edgeToRight(); pseudo.setCurrentLine("visitright"); temp.addClass("rededge"); bt.layout(); av.step(); // Slide 18 av.umsg("Unwind the recursion, and set the left pointer of the node with value of 37"); temp1 = rt.edgeToLeft(); temp1.addClass("rededge"); rt.removeClass("processing"); rt1.target(rt); pseudo.setCurrentLine("visitleft"); av.step(); // Slide 19 av.umsg("Now we return from the initial call to removehelp, setting the root of the tree to the result"); rt1.arrow.addClass("thinredline"); // This line should not be needed, but it is here to fix Raphael bug with arrows rt1.arrow.css({"stroke": "red"}); pseudo.setCurrentLine("end"); av.step(); // Slide 20 av.umsg("Finally, let's see what happens when we delete the root node."); pseudo.unhighlight("end"); pseudo.setCurrentLine("sig"); rt1.arrow.removeClass("thinredline"); // This line should not be needed, but it is here to fix Raphael bug with arrows rt1.arrow.css({"stroke": "black"}); temp.removeClass("rededge"); temp1.removeClass("rededge"); rt.left().right().left(30); rt.left().right().value(32); bt.layout(); av.step(); // Slide 21 av.umsg("First we find that the root pointer is not null."); pseudo.setCurrentLine("checknull"); av.step(); // Slide 22 av.umsg("Then we find that the root value is not less than what we want to delete."); pseudo.setCurrentLine("checkless"); av.step(); // Slide 23 av.umsg("Then we find that the root value is not greater than what we want to delete."); pseudo.setCurrentLine("checkgreater"); av.step(); // Slide 24 av.umsg("So the root node contains the value that we want to delete."); pseudo.setCurrentLine("found"); av.step(); // Slide 25 av.umsg("The left child is not null."); pseudo.setCurrentLine("checkleft"); av.step(); // Slide 26 av.umsg("The right child is not null."); pseudo.setCurrentLine("checkright"); av.step(); // Slide 27 av.umsg("So now we know that we have the hard case to deal with."); pseudo.setCurrentLine("twochildren"); av.step(); // Slide 28 av.umsg("Call getmax to set a temporary variable to point to the node with the greatest value in the left subtree."); pseudo.setCurrentLine("getmax"); var tnode = rt.left().right(); tnode.addClass("processing"); var rt2 = av.pointer("temp", tnode, {anchor: "right top", top: -10}); av.step(); // Slide 29 av.umsg("Now set the root value to what was returned by getmax."); pseudo.setCurrentLine("setelement"); av.effects.moveValue(tnode, rt); rt.addClass("rednode"); av.step(); // Slide 30 av.umsg("Now call deletemax to remove the node with the maximum value in the left subtree. Set the root node's left pointer to point to the resulting subtree."); pseudo.setCurrentLine("setleft"); rt.left().right(rt.left().right().left()); temp = rt.left().edgeToRight(); temp.addClass("rededge"); temp1 = rt.edgeToLeft(); temp1.addClass("rededge"); rt2.hide(); bt.layout(); av.step(); // Slide 31 av.umsg("We are now done deleting the old root node. Removehelp will return a pointer to this tree. The calling function will then set the BST root to point to this new tree."); pseudo.setCurrentLine("return"); rt1.arrow.addClass("thinredline"); // This line should not be needed, but it is here to fix Raphael bug with arrows rt1.arrow.css({"stroke": "red"}); av.recorded(); });
module.exports = { recno: 10, order_no: 10, code: 20, description: 50, actions: 10, }
const mongoose = require('mongoose'); // Direccion del cluster de la base de datos en MongoDB mongoose.connect('mongodb+srv://albertopacheco23:becks2323@pachecocluster-gyot5.mongodb.net/Presupuesto', { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true }) .then(db =>console.log('La base de datos esta conectada')) .catch(err =>console.error(err));
const Jiji = require("jiji-js"); module.exports = { title: "Home", command: "$ npm install -g jiji-cli", constructor: function (callback) { /* before mount */ callback(); }, mounted: function () { const controller = this; const canvas = document.querySelector('canvas'), context = canvas.getContext( '2d' ); canvas.style.backgroundColor = 'black'; canvas.height = document.body.clientHeight - 61; canvas.width = (window.innerWidth); // canvas.style.zIndex = -100; const STAR_COUNT = ( window.innerWidth + window.innerHeight ) / 8, STAR_SIZE = 3, STAR_MIN_SCALE = 0.2, OVERFLOW_THRESHOLD = 50; let scale = 1, // device pixel ratio width, height; let stars = []; let pointerX, pointerY; let velocity = { x: 0, y: 0, tx: 0, ty: 0, z: 0.0005 }; let touchInput = false; function generate() { const words = ['ji build', 'ji debug', 'ji new', 'ji g controller xyz', 'ji g index xyz']; const randHexColor = () => { const randomColor = Math.floor(Math.random()*16777215).toString(16); return "#" + randomColor; }; const randColor = () => { const randomColor = () => Math.floor(Math.random()*256); return `${randomColor()},${randomColor()},${randomColor()}`; }; for( let i = 0; i < STAR_COUNT; i++ ) { if (Math.floor(Math.random() * 2) == 1) { var word = words[Math.floor(Math.random() * words.length)]; stars.push({ x: 0, y: 0, z: STAR_MIN_SCALE + Math.random() * ( 1 - STAR_MIN_SCALE ), text: word }); } else { stars.push({ x: 0, y: 0, z: STAR_MIN_SCALE + Math.random() * ( 1 - STAR_MIN_SCALE ), shape: true, color: randColor() }); } } } function placeStar( star ) { star.x = Math.random() * width; star.y = Math.random() * height; } function recycleStar( star ) { let direction = 'z'; let vx = Math.abs( velocity.x ), vy = Math.abs( velocity.y ); if( vx > 1 || vy > 1 ) { let axis; if( vx > vy ) { axis = Math.random() < vx / ( vx + vy ) ? 'h' : 'v'; } else { axis = Math.random() < vy / ( vx + vy ) ? 'v' : 'h'; } if( axis === 'h' ) { direction = velocity.x > 0 ? 'l' : 'r'; } else { direction = velocity.y > 0 ? 't' : 'b'; } } star.z = STAR_MIN_SCALE + Math.random() * ( 1 - STAR_MIN_SCALE ); if( direction === 'z' ) { star.z = 0.1; star.x = Math.random() * width; star.y = Math.random() * height; } else if( direction === 'l' ) { star.x = -OVERFLOW_THRESHOLD; star.y = height * Math.random(); } else if( direction === 'r' ) { star.x = width + OVERFLOW_THRESHOLD; star.y = height * Math.random(); } else if( direction === 't' ) { star.x = width * Math.random(); star.y = -OVERFLOW_THRESHOLD; } else if( direction === 'b' ) { star.x = width * Math.random(); star.y = height + OVERFLOW_THRESHOLD; } } function resize() { scale = window.devicePixelRatio || 1; width = window.innerWidth * scale; height = window.innerHeight * scale; canvas.width = document.body.clientWidth; canvas.height = document.body.clientHeight - 61; stars.forEach(placeStar); } function step() { context.clearRect( 0, 0, width, height ); update(); render(); controller.requestAnimationFrameId = requestAnimationFrame( step ); } function update() { velocity.tx *= 0.96; velocity.ty *= 0.96; velocity.x += ( velocity.tx - velocity.x ) * 0.8; velocity.y += ( velocity.ty - velocity.y ) * 0.8; stars.forEach(( star ) => { star.x += velocity.x * star.z; star.y += velocity.y * star.z; star.x += ( star.x - width/2 ) * velocity.z * star.z; star.y += ( star.y - height/2 ) * velocity.z * star.z; star.z += velocity.z; // recycle when out of bounds if( star.x < -OVERFLOW_THRESHOLD || star.x > width + OVERFLOW_THRESHOLD || star.y < -OVERFLOW_THRESHOLD || star.y > height + OVERFLOW_THRESHOLD ) { recycleStar( star ); } }); } function render() { stars.forEach( ( star ) => { if (star.shape) { context.beginPath(); context.lineCap = 'round'; context.lineWidth = STAR_SIZE * star.z * scale; context.strokeStyle = star.color ? `rgba(${star.color},${(0.5 + 0.5*Math.random())}` : `rgba(255,255,255,${(0.5 + 0.5*Math.random())}`; context.beginPath(); context.moveTo( star.x, star.y ); var tailX = velocity.x * 2, tailY = velocity.y * 2; // stroke() wont work on an invisible line if( Math.abs( tailX ) < 0.1 ) tailX = 0.5; if( Math.abs( tailY ) < 0.1 ) tailY = 0.5; context.lineTo( star.x + tailX, star.y + tailY ); context.stroke(); } else { context.beginPath(); context.fillStyle = "#ffffff"; context.font = Math.round((STAR_SIZE * star.z * scale) * 2) + "px Arial"; var tailX = velocity.x * 2, tailY = velocity.y * 2; if( Math.abs( tailX ) < 0.1 ) tailX = 0.5; if( Math.abs( tailY ) < 0.1 ) tailY = 0.5; context.fillText(star.text, star.x + tailX, star.y + tailY); } }); } function movePointer( x, y ) { if ( typeof pointerX === 'number' && typeof pointerY === 'number' ) { let ox = x - pointerX, oy = y - pointerY; velocity.tx = velocity.tx + ( ox / 8 * scale ) * ( touchInput ? 1 : -1 ); velocity.ty = velocity.ty + ( oy / 8 * scale ) * ( touchInput ? 1 : -1 ); } pointerX = x; pointerY = y; } function onMouseMove( event ) { touchInput = false; movePointer( event.clientX, event.clientY ); } function onMouseLeave() { pointerX = null; pointerY = null; } generate(); resize(); step(); window.onresize = resize; canvas.onmousemove = onMouseMove; canvas.ontouchend = onMouseLeave; document.onmouseleave = onMouseLeave; }, destroy: function () { const canvas = document.querySelector('canvas'), context = canvas.getContext( '2d' ) canvas.onmousemove = undefined; canvas.ontouchend = undefined; context.clearRect( 0, 0, canvas.width, canvas.height ); document.onmouseleave = undefined; window.cancelAnimationFrame(this.requestAnimationFrameId); document.getElementsByTagName("canvas")[0].style.backgroundColor = 'transparent'; }, innerHTML: require("./home.html") };
"use strict"; let area = document.querySelector('.area') let areaW, areaH, startPosX, startPosY; document.querySelector('.area__toggle').addEventListener('mousedown', function (e) { startPosX = e.screenX; startPosY = e.screenY; areaW = area.clientWidth; areaH = area.clientHeight; document.querySelector('body').addEventListener('mousemove', move) }) document.querySelector('body').addEventListener('mouseup', function (e) { document.querySelector('body').removeEventListener('mousemove', move) }) function move(e) { let newPosX = e.screenX; let newPosY = e.screenY; area.style.width = areaW + newPosX - startPosX + 'px'; area.style.height = areaH + newPosY - startPosY + 'px'; } let windowHeight = window.innerHeight; window.addEventListener('resize', function () { windowHeight = window.innerHeight; }) window.addEventListener('scroll', function (e) { let blocks = document.querySelectorAll('.block') for (let block of blocks) { let position = block.getBoundingClientRect(); let posTop = position.top; let posHeight = position.height; if (posTop < windowHeight - posHeight && posTop > - posHeight) { block.classList.add('block__anim') } else { block.classList.remove('block__anim') } } }) activeScrollLink(); function activeScrollLink() { for (let link of document.getElementsByClassName('link')) { let sectionId = link.getAttribute('href'); window.addEventListener('scroll', function (e) { let pos = document.querySelector(sectionId).getBoundingClientRect(); if (pos.top < windowHeight / 2 && pos.top > pos.height * -1 + windowHeight / 2) { link.classList.add('link__active') } else { link.classList.remove('link__active') } }) } } for (let link of document.getElementsByClassName('link')) { link.addEventListener('click', function (e) { e.preventDefault(); let idSection = this.getAttribute('href'); let pos = document.querySelector(idSection).getBoundingClientRect(); window.scrollTo({ top: pos.y, left: 0, behavior: 'smooth', }) }) }
const express = require("express"); const app = express(); const PORT = process.env.PORT || 5000; const logger = require("morgan"); const mongoose = require("mongoose"); require("dotenv").config(); // middleware for logging incoming requests app.use(logger("dev")); // middleware for parse JSON data app.use(express.json()); app.listen(PORT, () => { console.log(`Listening to port <${PORT}>`); }); const Test = require("./model/Test"); app.get("/", async function (req, res) { const allTest = await Test.find({}); res.status(200).send(allTest); }); app.put("/", async function (req, res) { const name = req.body.name; const resp = await Test.findOneAndUpdate( { _id: "60d2a1362dab5d5933d8c2c6" }, { $set: { testName: name }, } ); res.status(200).send(resp); }); app.post("/", async function (req, res) { const { testName, testId, testDescription, testTags } = req.body; const test = new Test({ testName, testId, testDescription }); test.testTags.push(testTags); const newTest = await test.save(); res.status(201).send(newTest); }); // MongoDB connection mongoose.connect( process.env.MONGO_URI, { useCreateIndex: true, useUnifiedTopology: true, useNewUrlParser: true, }, (err) => { if (!err) { console.log("DB Connected"); return; } console.log(err); process.exit(0); } );
var express = require("express"); var router = express.Router(); let {users} = require("../db/arrayData") //display registration form router.get("/adduser", function(req, res, next) { res.render("adduser", { response: "" }); }); router.post("/adduser", function(req, res, next) { let user = { id: users.length, first: req.body.first, last: req.body.last, password: req.body.last, email: req.body.email }; users.push(user); res.render("adduser", { response: "User Added" }); }); //display login form router.get("/login", function(req, res, next) { res.render("login", { response: "" }); }); router.post("/login", function(req, res, next) { let response = "invalid login"; let foundUser = users.find(user => { let rtnVal = false; if (req.body.email.toLowerCase() == user.email.toLowerCase()) { rtnVal = true; } return rtnVal; }); if (foundUser !== undefined) { if (foundUser.password === req.body.password) response = `${foundUser.first} ${foundUser.last}`; } res.render("login", { response }); }); //update user router.get("/update", function(req, res, next) { res.render("update", { users, user: "" }); }); router.post("/update", function(req, res, next) { let index = req.body.id; let user = users[index]; for (key in user) { if (req.body[key] !== "") { user[key] = req.body[key]; } } users[index] = user; res.render("update", { users, user: JSON.stringify(user) }); }); // delete user router.get("/delete", function(req, res, next) { res.render("delete", { users, response: "" }); //what is in the brackets is just shorthand. both users and response have the : }); router.post("/delete", function(req, res, next) { let response = "User not found."; let foundUserIndex = users.findIndex(user => { let rtnVal = false; if (req.body.email.toLowerCase() == user.email.toLowerCase()) { rtnVal = true; } return rtnVal; }); if (foundUserIndex != -1) { if (users[foundUserIndex].password == req.body.password) { response = `${users[foundUserIndex].first} ${users[foundUserIndex].last} Successfully Deleted`; users.splice(foundUserIndex, 1); } } res.render("delete", { users, response }); }); //forgot password router.get("/password", function(req, res, next) { res.render("password", { users, response: "" }); }); router.post("/password", function(req, res, next) { let response = ""; let foundUserIndex = users.findIndex(user => { let rtnVal = false; if (req.body.email.toLowerCase() == user.email.toLowerCase()) { rtnVal = true; } return rtnVal; }); if (foundUserIndex != -1) { response = users[foundUserIndex].password; } res.render("password", { users, response }); }); module.exports = router;
var settings = { gamename: "0", version: "LD-0", DEBUG: window.location.href.indexOf("DEBUG") > -1, silent: window.location.href.indexOf("SILENT") > -1, ghostv: 32, Dmin: 0.5, } var beaten = {} function getlevels() { var ret = ["north", "south"] if (beaten.north) { ret.push("northwest") ret.push("northeast") } if (beaten.south) { ret.push("southwest") ret.push("southeast") } if (beaten.southwest && beaten.northwest) { ret.push("west") } if (beaten.southeast && beaten.northeast) { ret.push("east") } if (beaten.east && beaten.west) { ret.push("0") } var unbeaten = function (lname) { return !beaten[lname] } return ret.filter(unbeaten) }
angular .module('Home') .factory('HomeService', HomeService); HomeService.$inject = [ '$log', '$http' ]; function HomeService ( $log, $http ) { /// HomeService var service = { /// constants NEAR_ME_MOBIDULE : 0, ALL_MOBIDULE : 1, MY_MOBIDULE : 2, DEFAULT_SEARCH_TYPE : 1, /// vars lastSearchType : 0, /// services getMobiduls : getMobiduls }; /// services function getMobiduls (path) { return $http.get(path); } return service; }
/* eslint-env node */ 'use strict'; module.exports = function (body) { return '<html><title>test template</title><body>' + body + '</body></html>'; };
$(document).ready(function() { /* Every time the window is scrolled ... */ $(window).scroll( function(){ /* Check the location of each desired element */ $('.hideme').each( function(i){ var bottom_of_object = $(this).offset().top + $(this).outerHeight(); var bottom_of_window = $(window).scrollTop() + $(window).height(); /* If the object is completely visible in the window, fade it it */ if( bottom_of_window > bottom_of_object - 400 ){ if ( $(this).hasClass('hide-left') ){ $(this).animate({'left':'0px'},500); }else if ( $(this).hasClass('hide-right') ){ $(this).animate({'right':'0px'},500); } } }); }); $(window).trigger('scroll'); }); $(window).scroll(function() { if ($(document).scrollTop() > 315) { $('nav').addClass('shrink'); $('.navbar-brand .useravatar').removeAttr('hidden'); } else { $('nav').removeClass('shrink'); $('.navbar-brand .useravatar').attr('hidden', 'hidden'); } }); $(function(){ var navMain = $("#nav-main"); navMain.on("click", "a", null, function () { navMain.collapse('hide'); }); });
module.exports = { options: { connection: 'postgres://api_user:api_password@localhost:5432/api_development', schema: ['myApp', 'myAppPrivate'], // Command line comma separated options must be entered as arrays jwtSecret: 'myJwtSecret', defaultRole: 'myapp_anonymous', token: 'myApp.jwt_token', }, };
'use strict'; angular.module('UserProfileApp', [ 'ngRoute', 'ui.bootstrap' ]). config(function($routeProvider,$locationProvider) { $routeProvider. otherwise({redirectTo: '/userList'}); $locationProvider.html5Mode(true); });
import React, { useState, useEffect, memo } from 'react'; import { oneOfType, string, number, func } from 'prop-types'; import useModalView from '../hooks/useModalView'; import Popup from './Popup'; import PointPopupPhoto from './PointPopupPhoto'; import PointPopupLegend from './PointPopupLegend'; const propTypes = { id: oneOfType([number, string]).isRequired, humanLevel: string.isRequired, name: string.isRequired, source: string, photo: string, updatedAt: string.isRequired, canUpdateUntil: string, onUpdate: func, }; const defaultProps = { photo: null, source: null, canUpdateUntil: null, onUpdate: undefined, }; const isUpdatable = canUpdateUntil => !!canUpdateUntil && new Date(canUpdateUntil).getTime() > Date.now(); const PointPopup = ({ id, humanLevel, name, photo, source, updatedAt, canUpdateUntil, onUpdate, ...popupProps }) => { const [canUpdate, setCanUpdate] = useState(isUpdatable(canUpdateUntil)); const [isFullScreen, setIsFullScreen] = useState(false); const createModalView = useModalView(`/reports/${id}`); useEffect(createModalView, [id]); useEffect(() => { if (!canUpdate) return; const timer = setInterval(() => { setCanUpdate(isUpdatable(canUpdateUntil)); }, 1000); return () => clearInterval(timer); }, [canUpdate, canUpdateUntil]); const handlePhotoChange = photo => { onUpdate({ id, photo }); }; const handleExitFullScreen = () => { setIsFullScreen(false); }; const showPhoto = !!photo || canUpdate; return ( <Popup {...popupProps} title={name} isFullHeight={showPhoto} isFullScreen={isFullScreen} onExitFullScreen={handleExitFullScreen} > {showPhoto && ( <PointPopupPhoto photo={photo} canUpdate={canUpdate} onChange={handlePhotoChange} /> )} <PointPopupLegend humanLevel={humanLevel} source={source} updatedAt={updatedAt} hasPhoto={showPhoto} isFullScreen={isFullScreen} onFullScreen={setIsFullScreen} /> </Popup> ); }; export default memo(PointPopup); PointPopup.propTypes = propTypes; PointPopup.defaultProps = defaultProps;
import React, {Component} from 'react'; import { HashRouter as Router, Route, Switch } from 'react-router-dom'; import Home from '../containers/Home' export default class RouterMap extends Component { render(){ return ( <div> <Router> <Switch> {/*只有当路径为/的时候才匹配路由*/} <Route exact path="/" component={Home}/> </Switch> </Router> </div> ) } }
Ext.define('Admin.view.main.Main', { extend: 'Ext.Container', xtype: 'main', requires: [ 'Ext.button.Button', 'Ext.container.Container', 'Ext.list.Tree', 'Ext.toolbar.Fill' ], controller: 'main', viewModel: 'main', cls: 'sencha-dash-viewport', itemId: 'mainView', layout: { type: 'vbox', align: 'stretch' }, initComponent: function () { var me = this, boxData = {}, record = {}, modifyPassword = 1; Common.util.Util.doAjax({ url: Common.Config.requestPath('System', 'Users', 'info'), method: 'get', async: false }, function (data) { record = data.data; boxData.realname = record.realname; boxData.idPath = record.idPath; boxData.userId=record.userId; modifyPassword = record.modifyPassword; Common.permission.Permission.server_permcollections = record.buttonList; Common.Config.user.userid = record.userId; Common.Config.IMAGE_ADDRESS=record.dicMap.IMG_ADDRESS; /* clock.setHtml(record.nowTime); //定期更新时间 Ext.TaskMgr.start({ run: function(){ Ext.fly(clock.getEl()).update(); }, interval: 1000 });*/ }); //construct navigationTree store data if (record.resourceList.length > 0) { record.resourceList.splice(0, 0, { text: '首页', iconCls: 'x-fa fa-desktop', rowCls: 'nav-tree-badge nav-tree-badge-new', url: 'admindashboard', leaf: true }) } else { record.resourceList = [{ text: '首页', iconCls: 'x-fa fa-desktop', rowCls: 'nav-tree-badge nav-tree-badge-new', url: 'admindashboard', leaf: true }] } me.items = [{ xtype: 'toolbar', cls: 'sencha-dash-dash-headerbar shadow', height: 64, itemId: 'headerBar', items: [{ xtype: 'component', reference: 'senchaLogo', cls: 'sencha-logo', html: '<div class="main-logo" style="'+Common.Config.business_css+'"><img src="resources/images/dota2.jpg" style="'+Common.Config.business_image_css+'">' + Common.Config.business_name + '</div>', width: 250 }, { margin: '0 0 0 8', ui: 'header', iconCls: 'x-fa fa-navicon', id: 'main-navigation-btn', handler: 'onToggleNavigationSize' }, '->', { xtype: 'box', reference: 'profile', tpl: '欢迎:{realname}', data: boxData }, { xtype: 'box', reference: 'profile', tpl: '<img width="40px" height="40px" src="https://dota2cjy.oss-cn-beijing.aliyuncs.com/{idPath}">', data: boxData },{ xtype: 'button', text: '退出', handler: 'logout' }] }, { xtype: 'maincontainerwrap', id: 'main-view-detail-wrap', reference: 'mainContainerWrap', flex: 1, items: [ { xtype: 'treelist', reference: 'navigationTreeList', itemId: 'navigationTreeList', ui: 'navigation', store: { fields: [{ name: 'text' }], root: { expanded: true, children: record.resourceList } }, width: 250, expanderFirst: false, expanderOnly: false, listeners: { selectionchange: 'onNavigationTreeSelectionChange' } }, { xtype: 'container', flex: 1, reference: 'mainCardPanel', cls: 'sencha-dash-right-main-container', itemId: 'contentPanel', layout: { type: 'card', anchor: '100%' } } ] }]; //第一次登录需要修改密码 if(modifyPassword==0) { var modifyPasswordWindow = Ext.create('Ext.window.Window', { title: '首次登录修改密码', modal: true, layout: 'fit', closable:false, width: 300, height: 200, items: [ { xtype: 'form', items: [{xtype: 'hidden', name: 'userId', value: boxData.userId},{ xtype: 'box', html: '<span style="color: green;">密码必须包含大小写字母以及数字,且长度在6-18之间</span>' }, { xtype: 'textfield', reference: 'password', vtype: 'password', name: 'password', inputType: 'password', fieldLabel: '输入密码', allowBlank: false }, { xtype: 'textfield', inputType: 'password', fieldLabel: '重复密码', allowBlank: false, vtype: 'repetition', //指定repetition验证类型 repetition: { //配置repetition验证,提供目标组件(表单)name target: 'password' } }], buttons: [{ text: '确定', formBind: true, handler: function () { var me = this, form = me.up('form'); var formValues = form.getValues(); if (!form.isValid()) { return false; } Common.util.Util.doAjax({ url: Common.Config.requestPath('System', 'Users', 'modifypassword'), method: 'post', params: formValues }, function (data) { modifyPasswordWindow.close(); Ext.Msg.alert('密码修改成功,请重新登录'); Common.util.Util.doAjax({ url: Common.Config.requestPath('Security','Authentic', 'logout') }, function (data) { Common.Config.storage.removeItem(Common.Config.LOGINFLAG); window.location.href = window.location.origin+window.location.search; }); }); } }] } ] }); modifyPasswordWindow.show(); } this.callParent(arguments); } });
var isShowConsole = false; $(".console-content").hide(); $("#aside-showhide-console").click(function () { isShowConsole = !isShowConsole; if (isShowConsole) { $("#aside-showhide-console").attr("src", "images/triangle_up.png"); $(".console-content").show(); } else { $("#aside-showhide-console").attr("src", "images/triangle_right.png"); $(".console-content").hide(); } }); var showAnimeList = new Array(); var renderMulLineMode = false; $(".single-select").change(function () { renderMulLineMode = !renderMulLineMode; rerender(); }); $("#console-btn-1").click(function () { console.log(selectedPoint); if (selectedPoint < 0) { return; } if (showAnimeList.indexOf(selectedPoint) >= 0) { return; } showAnimeList.push(selectedPoint); $("#show-anime-list").append("<option>" + bangumi[selectedPoint].name + "</option>"); }); $("#console-btn-2").click(function () { for (var i = 0; i < showAnimeList.length; i++) { if (bangumi[showAnimeList[i]].name == $("#show-anime-list").val()) { showAnimeList.splice(i, 1); break; } } $('#show-anime-list option:selected').remove(); rerender(); }); $("#console-btn-3").click(function () { rerender(); }); $("#show-anime-list").change(function () { var select_id = -1; for (i in bangumi) { if (bangumi[i].name == $("#show-anime-list").val()) { select_id = parseInt(i); break; } } selectPoint(select_id); });
let bobSecretKey='f22811807eed1f2ae5b871e8dab4f5d879c708f0d0f0e4345b4eae799933d391fc4860560cec170d9e8866d889d54962ec9779bf57f7684a7a4cd0e1b28cef72'; let bobPublicKey='ak_2v7Dxo7cjwfgto3inBw9RBw7n2QXDavym4da5Ss3HMDEaDf3v9'; let bobClient=null; let generalClient=null; let bobKeyPairObj= null; function generateAccountWithExistingKeyPair(secretKey){ const hexStr = Ae.Crypto.hexStringToByte(secretKey); const keys = Ae.Crypto.generateKeyPairFromSecret(hexStr) console.log(keys); const pKey=Ae.Crypto.aeEncodeKey(keys.publicKey); console.log({publicKey:pKey}); return{publicKey:pKey,privateKey:secretKey}; } async function generateAccountWithoutKeyPair(){ let { secretKey, publicKey } = Ae.Crypto.generateKeyPair(true); console.log(secretKey); console.log(publicKey); let decodedPublicKey=Ae.Crypto.aeEncodeKey(publicKey); let decodedSecretKey=buffer.Buffer.from(secretKey).toString('hex'); return {publicKey:decodedPublicKey,privateKey:decodedSecretKey}; } async function getSdkInstance(secretKey,publicKey){ const NODE_URL = 'https://sdk-testnet.aepps.com'; const ACCOUNT = Ae.MemoryAccount({ keypair: { secretKey: secretKey, publicKey: publicKey } }); const nodeInstance = await Ae.Node({ url: NODE_URL }) const sdkInstance = await Ae.Universal({ compilerUrl: 'https://compiler.aepps.com', nodes: [ { name: 'test-net', instance: nodeInstance } ], accounts: [ ACCOUNT ] }); return sdkInstance; } async function getAccountBalance( publicKey,sdkInstance){ console.log(sdkInstance); let height=await sdkInstance.height(); try{ let balance=await sdkInstance.balance(publicKey); console.log(balance); balance=parseFloat(balance)/1000000000000000000; return balance.toFixed(2)+ 'aettos'; }catch(err){ console.log(err); return 0; } } async function sendAeToAccount(publicAddress,amount,client){ document.getElementById('bobLoader').style.display='block'; let returnValue=await client.spend(amount, publicAddress, { denomination: 'ae' }); console.log(returnValue); console.log(returnValue.hash); document.getElementById('bobLoader').style.display='block'; document.getElementById('bobBalance').innerText=await getAccountBalance(bobKeyPairObj.publicKey,bobClient); document.getElementById('bobLoader').style.display='none'; } document.getElementById('bobSendButton').addEventListener('click',function(){ let publicKey=document.getElementById('bobSendPublickey').value.trim(); let amount=parseInt(document.getElementById('bobSendAmount').value.trim()); sendAeToAccount(publicKey,amount,bobClient); }); document.getElementById('bobBalance').addEventListener('click', async function(){ if(bobKeyPairObj!==null&& bobClient!=null){ showLoader() let balance=await getAccountBalance(bobKeyPairObj.publicKey,bobClient); initializeBalanceElement(balance) hideLoader() } }) document.getElementById('bobPublicKey').addEventListener('click',function(){ const el = document.createElement('textarea'); el.value = bobKeyPairObj.publicKey; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); }); // generateAccountWithoutKeyPair() async function initializeViews(){ // bobKeyPairObj= generateAccountWithExistingKeyPair(bobSecretKey); bobKeyPairObj= await generateAccountWithoutKeyPair(); bobClient=await getSdkInstance(bobKeyPairObj.privateKey,bobKeyPairObj.publicKey); initializePublicKeyElement(bobKeyPairObj.publicKey); initializePrivateKeyElement(bobKeyPairObj.privateKey); let balance=await getAccountBalance(bobKeyPairObj.publicKey,bobClient); initializeBalanceElement(balance) hideLoader() } initializeViews(); function initializePublicKeyElement(value){ document.getElementById('bobPublicKey').innerText=value } function initializePrivateKeyElement(value){ document.getElementById('bobPrivateKey').innerText=value } function initializeBalanceElement(value){ document.getElementById('bobBalance').innerText=value } function hideLoader(){ document.getElementById('bobLoader').style.display='none'; } function showLoader(){ document.getElementById('bobLoader').style.display='block'; }