text
stringlengths
7
3.69M
function formatDate(timestamp) { let date = new Date(timestamp); let hours = date.getHours(); if (hours < 10) { hours = `0${hours}`; } let minutes = date.getMinutes(); if (minutes < 10) { minutes = `0${minutes}`; } let days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; let day = days[date.getDay()]; return `${day}, ${hours}:${minutes}`; } // -----forecast data----- // function formatDay(timestamp) { let date = new Date(timestamp * 1000); let day = date.getDay(); let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; return days[day]; } function showForecast(response) { let forecast = response.data.daily; let forecastElement = document.querySelector(".weather-forecast"); let forecastHTML = `<div class="row">`; forecast.forEach(function (forecastDay, index) { if (index < 6) { forecastHTML = forecastHTML + ` <div class="col-2"> <div class="forecast-day">${formatDay(forecastDay.dt)}</div> <img src="http://openweathermap.org/img/wn/${ forecastDay.weather[0].icon }@2x.png" alt="" width="40" /> <div class="forecast-temperature"> <span class="forecast-temp-max">${Math.round( forecastDay.temp.max )}°</span> <span class="forecast-temp-min">${Math.round( forecastDay.temp.min )}°</span> </div> </div> `; } }); forecastHTML = forecastHTML + `</div>`; forecastElement.innerHTML = forecastHTML; } // -----weather data----- // function getForecast(coordinates) { console.log(coordinates); let apiKey = "159a9f8ff294f264def02ae4cac4278a"; let apiUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${coordinates.lat}&lon=${coordinates.lon}&appid=${apiKey}&units=metric`; axios.get(apiUrl).then(showForecast); } function showTemp(response) { console.log(response.data); celsiusTemp = response.data.main.temp; document.querySelector(".city").innerHTML = response.data.name; document.querySelector(".temperature").innerHTML = Math.round(celsiusTemp); document.querySelector(".weather-description").innerHTML = response.data.weather[0].description; document.querySelector(".humidity").innerHTML = response.data.main.humidity; document.querySelector(".wind").innerHTML = Math.round( response.data.wind.speed ); document.querySelector(".date").innerHTML = formatDate( response.data.dt * 1000 ); let iconElement = document.querySelector("#icon"); iconElement.setAttribute( "src", `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png` ); getForecast(response.data.coord); } // -----search----- // function search(city) { let apiKey = "159a9f8ff294f264def02ae4cac4278a"; let apiSite = "https://api.openweathermap.org/data/2.5/weather?q="; let units = "metric"; let apiUrl = `${apiSite}${city}&appid=${apiKey}&units=${units}`; axios.get(apiUrl).then(showTemp); } function searchCity(event) { event.preventDefault(); let city = document.querySelector(".findCity").value; search(city); } let form = document.querySelector(".search"); form.addEventListener("submit", searchCity); // -----get current location----- // function showPosition(position) { let lat = position.coords.latitude; let long = position.coords.longitude; let units = "metric"; let apiKey = "159a9f8ff294f264def02ae4cac4278a"; let apiSite = "https://api.openweathermap.org/data/2.5/weather?"; let apiUrl = `${apiSite}lat=${lat}&lon=${long}&appid=${apiKey}&units=${units}`; axios.get(apiUrl).then(showTemp); } function showCurrentPosition(event) { event.preventDefault(); navigator.geolocation.getCurrentPosition(showPosition); } let button = document.querySelector(".current-location"); button.addEventListener("click", showCurrentPosition); // -------unit conversion------- // let celsiusTemp = null; function showCelsiusTemp(event) { event.preventDefault(); let temp = document.querySelector(".temperature"); temp.innerHTML = Math.round(celsiusTemp); } function showFahrenheitConversion(event) { event.preventDefault(); let temp = document.querySelector(".temperature"); let fahTemp = (celsiusTemp * 9) / 5 + 32; temp.innerHTML = Math.round(fahTemp); } let celsiusUnit = document.querySelector(".celsius"); celsiusUnit.addEventListener("click", showCelsiusTemp); let fahrenheitUnit = document.querySelector(".fah"); fahrenheitUnit.addEventListener("click", showFahrenheitConversion); search("Tokyo");
import React, { PureComponent } from 'react' import { Link } from 'gatsby' import debounce from 'lodash/debounce' import cx from 'classnames' import Icon from './Icon' import Nav from './Nav' class Header extends PureComponent { constructor(props) { super(props) this.delta = 80 this.lastScrollY = 0 this.headerHeight = 62 } state = { isBackgroundVisible: false, isHeaderUp: false, } componentDidMount() { window.addEventListener('scroll', this.handleScroll) } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll) } handleScroll = debounce(() => { this.toggleBackground() this.toggleUp() }) toggleBackground() { const scrollY = window.scrollY if (scrollY > 0) { this.setState({ isBackgroundVisible: true }) return } this.setState({ isBackgroundVisible: false }) } toggleUp() { const scrollY = window.scrollY if (Math.abs(this.lastScrollY - scrollY) <= this.delta) { return } if (scrollY > this.lastScrollY && scrollY > this.headerHeight * 2) { this.setState({ isHeaderUp: true }) } else { this.setState({ isHeaderUp: false }) } this.lastScrollY = scrollY } render() { const { isBackgroundVisible, isHeaderUp } = this.state const { onToggleMenu } = this.props return ( <header className={cx('header', { 'header--backgroundVisible': isBackgroundVisible, 'header--up': isHeaderUp, })} > <h1 className='header__title'> <Link to='/'>I.</Link> </h1> <Nav className='u-hide u-show--md' /> <div className='header__toggle u-hide--md' onClick={onToggleMenu}> <Icon icon='hamburger' /> </div> </header> ) } } export default Header
'use strict'; var React = require('react/addons'); var ReactRouter = require('react-router'); var { Router, Route } = ReactRouter; var { history } = require('react-router/lib/BrowserHistory'); var HomeOwners = require('./HomeOwners'); var Home = require('./Home'); var Routes = ( <Router history={history}> <Route path="/" component={Home}> <Route path="home-owners" component={HomeOwners} /> </Route> </Router> ); module.exports = Routes;
import axiosApi from "../components/comuns/UtilHttp"; import { URL_BACKEND, TAG_USUARIO_STORAGE } from "../constants/ConstantesInternas"; import Erro from "../components/comuns/Erro"; import { getValoresStorage } from "../components/comuns/UtilStorage"; const URI = "medico-api/son-rest/medicos"; const URI_ESPECIALIDADES = "medico-api/son-rest/especialidades"; const filtrarMedicos = async (nomeMedico, numCrmUF) => { const usuario = await recuperarDadosUsuario(); return axiosApi.get(`${URL_BACKEND}${URI}/filtrar?nomeMedico=${nomeMedico}&numCrmUF=${numCrmUF}&codUsuario=${usuario.idUsuario}`) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); }; const recuperarMedicos = async () => { const usuario = await recuperarDadosUsuario(); return axiosApi.get(`${URL_BACKEND}${URI}/filtrar?codUsuario=${usuario.idUsuario}`) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); }; const desvincularMedico = async (medico) => { const usuario = await recuperarDadosUsuario(); let obj = { codUsuario: usuario.idUsuario, codMedico: medico.idMedico }; return axiosApi.post(`${URL_BACKEND}${URI}/desvincularMedico`, JSON.stringify(obj)) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); }; const vincularMedico = async (medico) => { const usuario = await recuperarDadosUsuario(); let obj = { codUsuario: usuario.idUsuario, codMedico: medico.idMedico, mobile: true }; return axiosApi.post(`${URL_BACKEND}${URI}/vincularMedico`, JSON.stringify(obj)) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); }; const criarMedicoClone = (medico, bolAdiciona, usuario) => { let novoMedico = { idMedico: medico.idMedico, nomeMedico: medico.nomeMedico, codEspecialidade: medico.codEspecialidade, numRegistroCrm: medico.numRegistroCrm, descEmail: medico.descEmail, numCelular: medico.numCelular } if (bolAdiciona){ novoMedico.codUsuarioCadastro = usuario.idUsuario } else { novoMedico.idMedico = medico.idMedico; } console.log('clone medico', novoMedico); return novoMedico; } const salvarMedico = async (medico) => { const usuario = await recuperarDadosUsuario(); return axiosApi.post(`${URL_BACKEND}${URI}`, JSON.stringify( criarMedicoClone(medico, true, usuario) ) ) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); }; const alterarMedico = (medico) => { let novoMedico = criarMedicoClone(medico, false, null); return axiosApi.put(`${URL_BACKEND}${URI}`, JSON.stringify(novoMedico)) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); return true; }; const buscarMedico = (codMedico) => { return axiosApi.get(`${URL_BACKEND}${URI}/medico?codMedico=${codMedico}`) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); } const obterEspecialidades = async () => { return axiosApi.get(`${URL_BACKEND}${URI_ESPECIALIDADES}`) .then( result => result ) .catch(error => Erro.getDetalhesErro(error)); }; const recuperarDadosUsuario = async () => { const dadosUsuario = await getValoresStorage(TAG_USUARIO_STORAGE); let usuario = JSON.parse( dadosUsuario ); return usuario; } export default { filtrarMedicos, recuperarMedicos, desvincularMedico, vincularMedico, obterEspecialidades, salvarMedico, alterarMedico, buscarMedico }
var GPSCalculateController = require('../controllers/GPSCalculateController'); module.exports = function (app) { app.post('/gps/getGPS', function (req, res) { console.log('/gps/getGPS', req.body) GPSCalculateController.getGPS(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) }
import { BrowserRouter } from "react-router-dom"; import { ConfigProvider } from "antd"; import "moment/locale/pt-br"; import locale from "antd/es/locale/pt_BR"; import SiderBar from "./components/templates/SiderBar"; import "./themes/default.less"; function App() { return ( <ConfigProvider locale={locale} componentSize="middle"> <BrowserRouter> <SiderBar /> </BrowserRouter> </ConfigProvider> ); } export default App;
const express = require('express'); const bodyParser = require('body-parser'); const Favorites = require('../models/favorite'); const favoriteRouter = express.Router(); const cors = require('./cors'); var authenticate = require('../authenticate'); favoriteRouter.use(bodyParser.json()); function UpdateFavorites(favorite, req, res, next, dishId) { favorite.author = req.user._id; if (dishId == null) { req.body.map(favoriteDish => { var found = false; favorite.dishes.find(item => { if (item._id == favoriteDish._id) { found = true }; }); if (!found) { favorite.dishes.push(favoriteDish) } }); } else { var found = false; favorite.dishes.find(item => { if (item._id == dishId) { found = true }; }); if (!found) { favorite.dishes.push(dishId) } } favorite.save() .then((favorite) => { Favorites.findById(favorite._id) .populate('dishes.dish') .populate('author') .then((favorite) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }, (err) => next(err)) }, (err) => next(err)) .catch((err) => next(err)); } favoriteRouter.route('/') .options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); }) .get(cors.cors, (req, res, next) => { Favorites.findOne({ author: req.user._id }) .populate('dish') .populate('author') .then((Favorites) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(Favorites); }, (err) => next(err)) .catch((err) => next(err)); }) .post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { Favorites.findOne({ author: req.user._id }) .then((favorite) => { if (favorite != null) { UpdateFavorites(favorite, req, res, next, null); } else { Favorites.create(req.body) .then((favorite) => { UpdateFavorites(favorite, req, res, null); }, (err) => next(err)); } }, (err) => next(err)) .catch((err) => next(err)); }) .put(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { res.statusCode = 403; res.end('PUT operation not supported on /Favorites'); }) .delete(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { Favorites.findOne({ author: req.user._id }) .then((favorite) => { if (favorite != null) { favorite.remove() .then((favorite) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }, (err) => next(err)); } else { err = new Error('Favorite dish ' + req.params.dishId + ' not found'); err.status = 404; return next(err); } }, (err) => next(err)) .catch((err) => next(err)); }); favoriteRouter.route('/:dishId') .options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); }) .get(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { res.statusCode = 403; res.end('GET operation not supported on /favorites/' + req.params.dishId); }) .post(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { Favorites.findOne({ author: req.user._id }) .then((favorite) => { if (favorite != null) { UpdateFavorites(favorite, req, res, next, req.params.dishId); } else { Favorites.create(req.body) .then((favorite) => { UpdateFavorites(favorite, req, res, next, req.params.dishId); }, (err) => next(err)); } }, (err) => next(err)) .catch((err) => next(err)); }) .put(cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => { res.statusCode = 403; res.end('PUT operation not supported on /favorites/' + req.params.dishId); }) .delete(cors.corsWithOptions, authenticate.verifyUser, authenticate.verifyAdmin, (req, res, next) => { Favorites.findOne({ author: req.user._id }) .then((favorite) => { if (favorite != null) { for (var i = (favorite.dishes.length - 1); i >= 0; i--) { if (favorite.dishes[i]._id == req.params.dishId) { favorite.dishes.id(favorite.dishes[i]._id).remove(); } } favorite.save() .then((favorite) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }, (err) => next(err)); } else { err = new Error('Favorite dish ' + req.params.dishId + ' not found'); err.status = 404; return next(err); } }, (err) => next(err)) .catch((err) => next(err)); }); module.exports = favoriteRouter;
var Dash = Dash || {}; Dash.dashboard = (function($){ var config = { origin: {lat: 22, lng: 144}, destination: {lat: 23, lng: 145}, markers: [], callback: null, icon: { pin_a: '/assets/pin_a.png', pin_b: '/assets/pin_b.png', marker_onpath: '/assets/red_dot12x12.png', marker_offpath: '/assets/white_dot12x12.png' } }, map, view_all = function(){ var bounds = new google.maps.LatLngBounds(); bounds.extend(new google.maps.LatLng(config.origin.lat, config.origin.lng)); bounds.extend(new google.maps.LatLng(config.destination.lat, config.destination.lng)); map.fitBounds(bounds); }, zoom_in = function(marker){ map.setZoom(15); map.panTo(marker.getPosition()) }, draw_markers = function(result, tol){ var poly = new google.maps.Polyline({ path: result.overview_path }), onpath_marker_ids = []; if (typeof tol === 'undefined') { tol = 1e-3 } $.each(config.markers, function(i,m){ var point = new google.maps.LatLng(m.lat, m.lng); m.click = zoom_in; if (google.maps.geometry.poly.isLocationOnEdge(point, poly, tol)) { m.icon = config.icon.marker_onpath; onpath_marker_ids.push(m.id); } else { m.icon = config.icon.marker_offpath; } }) map.addMarkers(config.markers); return onpath_marker_ids; }, draw_endpoints = function(){ var endpoints = []; endpoints.push( $.extend({}, config.origin, { click: zoom_in, icon: config.icon.pin_a })); endpoints.push( $.extend({}, config.destination, { click: zoom_in, icon: config.icon.pin_b })); map.addMarkers(endpoints); }, initialize = function(map_div, options){ $.extend(config, options); map = new GMaps({ div: map_div, scrollwheel: false }); google.maps.event.addListener(map.map, 'click', view_all); map.addLayer('traffic'); draw_endpoints(); view_all(); }, dashboard = function(map_div, options){ initialize(map_div, options); map.drawRoute({ origin: [ config.origin.lat, config.origin.lng ], destination: [ config.destination.lat, config.destination.lng ], travelMode: 'driving', strokeColor: '#FF00FF', strokeOpacity: 0.3, strokeWeight: 16, callback: function(result){ var distance = result.legs[0].distance.value, duration = result.legs[0].duration.value, onpath_marker_ids = draw_markers(result); if (typeof config.callback === 'function') { config.callback.call(this, distance, duration, onpath_marker_ids); } } }); }; return dashboard; }(jQuery));
// 자바스크립트는 객체 확장을 이용하여 상속과 비슷한 효과를 만들 수 있다. function Parent() { this.hello = 'hello' } function Child() { this.world = 'world' this.helloWorld = this.hello + ' ' + this.world; } Child.prototype = new Parent(); Child.prototype.constructure = Child; const child = new Child(); console.log(child.helloWorld)
module.exports = function(value) { return Number((value % 1).toFixed(2).substring(2)) }
/** * Created by dcorns on 6/8/14. */ 'use strict'; var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(3000); app.get('/', function(req, res){ res.sendfile(__dirname + '/client/rooms.html'); }); io.on('connection', function(socket) { socket.on('room', function(data){ socket.join(data); socket.emit('joined', 'Joined room1'); }); }); io.sockets.in('room1').emit('message','Whats up!');
module.exports = (Sequelize, DataTypes) => { 'use strict'; const BlogPost = Sequelize.define('BlogPost', { id: { type: DataTypes.UUID, unique: true, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, title: { type: DataTypes.STRING, unique: true }, body: { type: DataTypes.TEXT } }, { classMethods: { associate: models => { BlogPost.belongsTo(models.Category, { onDelete: 'CASCADE', foreignKey: { allowNull: false } }); BlogPost.belongsTo(models.User, { onDelete: 'CASCADE', foreignKey: { allowNull: false } }); } } }); return BlogPost; };
function times(number1, number2) { let result = number1 * number2; console.log(result); return result; } let oneFactorial = times(1, 1); let twoFactorial = times(2, oneFactorial); let threeFactorial = times(3, twoFactorial);
var structSolution = [ [ "mots", "structSolution.html#ab511245410043c846351c6acf272d656", null ], [ "nbMots", "structSolution.html#a60e0881a49e593091d2210dd49f2f51a", null ] ];
import React from 'react'; import ServiceManagerContainer from './ServiceManagerContainer'; const path = '/serviceManager'; const action = () => { return { wrap: true, component: <ServiceManagerContainer /> } }; export default {path, action};
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; import RecipeCard from './RecipeCard'; class MenuComponent extends Component{ constructor(){ super(); this.state={ Italian:[], Indian:[], Chinese:[], American:[], Seafood:[], Desserts:[], menuList:[], selectedItems:[], isEmpty:true } } componentDidMount(){ var list=[]; axios({ method:"GET", url:'https://www.themealdb.com/api/json/v1/1/filter.php?a=Italian' }).then(response=>{ console.log('menu data'); console.log(response); this.setState({ Italian:response.data.meals }) }).catch(error=>{ console.log(error); }); axios({ method:"GET", url:'https://www.themealdb.com/api/json/v1/1/filter.php?a=Indian' }).then(response=>{ console.log('menu data'); console.log(response); this.setState({ Indian:response.data.meals }) }).catch(error=>{ console.log(error); }); axios({ method:"GET", url:'https://www.themealdb.com/api/json/v1/1/filter.php?a=Chinese' }).then(response=>{ console.log('menu data'); console.log(response); this.setState({ Chinese:response.data.meals }) }).catch(error=>{ console.log(error); }); axios({ method:"GET", url:'https://www.themealdb.com/api/json/v1/1/filter.php?a=American' }).then(response=>{ console.log('menu data'); console.log(response); this.setState({ American:response.data.meals }) }).catch(error=>{ console.log(error); }); axios({ method:"GET", url:'https://www.themealdb.com/api/json/v1/1/filter.php?c=Dessert' }).then(response=>{ console.log('menu data'); console.log(response); this.setState({ Desserts:response.data.meals }) }).catch(error=>{ console.log(error); }); axios({ method:"GET", url:'https://www.themealdb.com/api/json/v1/1/filter.php?c=Seafood' }).then(response=>{ console.log('menu data'); console.log(response); this.setState({ Seafood:response.data.meals }) }).catch(error=>{ console.log(error); }); console.log(list); } addItem=(item)=>{ this.setState({ selectedItems:[...this.state.selectedItems,item] }) } render(){ const { cuisine }=this.props.location.state; const answer=cuisine.split(','); console.log(answer); let i=0; var input=this.state.Indian; for(i=0;i<answer.length;i++){ console.log('in for loop'); if(answer[i].includes('Indian')){ input=this.state.Indian; } if(answer[i]==='Chinese'){ input=this.state.Chinese; } if(answer[i]==='Italian' || answer[i]==='Pizza'){ input=this.state.Italian; } if(answer[i]==='Bakery' || answer[i]==='Desserts'){ input=this.state.Desserts; } if(answer[i]==='Breakfast' || answer[i]==='Fast Food'){ input=this.state.American; } if(answer[i]==='Seafood'){ input=this.state.Seafood; } } if (input){ return( <div className='container'> <RecipeCard data={input} addFn={this.addItem}/> <div className='center-align'> <Link to={{ pathname:'/bill',state:{ elements:this.state.selectedItems }}} className='btn orange'> { !this.state.selectedItems.length>0 ? 'Select items':'Order' } </Link> </div> </div> ) }else{ return( <div className='container center white-text'> <h2>Loading</h2> </div> ) } } } export default MenuComponent;
module.exports = (sequelize, DataTypes) => { const Vendor = sequelize.define( 'Vendor', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, allowNull: false, unique: true }, slug: { type: DataTypes.STRING, allowNull: false, unique: true }, code: { type: DataTypes.STRING, allowNull: false, unique: true } }, { sequelize, underscored: true, tableName: 'vendor', createdAt: false, updatedAt: false } ); Vendor.associate = function (models) { this.hasMany(models.VendorIdentifier, { foreignKey: 'flavorId' }); this.hasMany(models.Flavor, { foreignKey: 'vendorId' }); }; return Vendor; };
'use strict '; const width=Dimensions.get('screen').width const height=Dimensions.get('screen').height import {Dimensions,PixelRatio,Platform} from 'react-native'; let backgroundcolor="#DEDEDE" let colorapp="#D22F32" const styles = { global:{ flex: 0, alignItems: 'center', justifyContent: 'center', backgroundcolor:backgroundcolor, paddingTop: ( Platform.OS === 'ios' ) ? 20 : 0, height:Dimensions.get('screen').height, width:Dimensions.get('screen').width, } } export default styles
function calculatePhoto(number) { var screenWidth = screen.width; var imageWidth = document.getElementById("image"+number).style.width; var imageHeight = document.getElementById("image"+number).style.height; if (screenWidth < imageWidth) { while(screenWidth < imageWidth) { imageHeight = imageHeight - 5; } } }
// - store products in an object literal // - export // - getCategoryNames // - getProductsByCategory // - createProduct // - deleteProduct // - updateProduct // - deleteCategory // - createCategory //looks like I have a Home, where I can make category names //I then get a tab per category //and each category gets an input field, product name, delete product button, delete category button var products = //why did products need to be in a list in tweetbank.js? will this work here? { "Foo Category": [ { "name": "foo product 1", "id": 1 }, { "name": "foo product 2", "id": 2 } ], "Bar Category": [ { "name": "bar product 1", "id": 1 }, { "name": "bar product 2", "id": 2 } ] } // - getCategoryNames // - getProductsByCategory // - createProduct // - deleteProduct // - updateProduct // - deleteCategory // - createCategory module.exports = { getCategoryNames: function(){ return Object.keys(products) }, getProductsByCategory(category){ return products[category] }, createProduct: function(category, in_product_name){ if(!in_product_name){ throw 'name is required' } var num_products = products[category].length var newProduct = { id: num_products+1, name: in_product_name } products[category].push(newProduct) }, deleteProduct: function(category, in_product_id){ var new_products_obj = products[category].filter(function(product){ console.log(product, product.id, in_product_id) if(product.id != in_product_id){ return product } }) console.log(new_products_obj, 'new arr') products[category] = new_products_obj }, //seems to not need updateProduct deleteCategory: function(category){ delete products[category] }, createCategory: function(in_cat_name){ if(!in_cat_name){ throw 'category name is required' } products[in_cat_name] = [] } }
import { put, takeLatest } from 'redux-saga/effects'; import axios from 'axios'; // payload for POST and PUT contains whole target object // on server modification values and target row if PUT are pulled from target object function* postTarget(action) { try { console.log(`post table mod`, action.payload); yield axios.post('api/process/insert', action.payload); } catch (error) { console.log('Error posting target modification', error); alert('Sorry error sending data.') } } function* putTarget(action) { try { console.log(`put table mod`, action.payload); yield axios.put('api/process/update', action.payload); } catch (error) { console.log('Error PUT target modification', error); alert('Sorry error sending data.') } } function* getTaskInfoSaga() { yield takeLatest('TARGET_POST', postTarget); yield takeLatest('TARGET_PUT', putTarget); } export default getTaskInfoSaga;
import React, { Component } from 'react'; import './App.scss'; import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; import LandingPage from './containers/LandingPage'; import Profile from './containers/Profile'; import MainPage from './containers/MainPage'; import DesignPortal from './containers/DesignPortal'; import ClothingSection from './containers/ClothingSection'; import ClothingTile from './components/ClothingTile'; class App extends Component { componentDidMount() { fetch(`${process.env.REACT_APP_APIURL}/categories`) .then(res => res.json()) .then(data => { console.log(data) data.map(d => { console.log(d.clothes) switch(d.name) { case 'hat': return this.props.loadHats(d.clothes) case 'top': return this.props.loadTops(d.clothes) case 'jacket': return this.props.loadJackets(d.clothes) case 'bottom': return this.props.loadBottoms(d.clothes) case 'shoes': return this.props.loadShoes(d.clothes) } }) }) fetch(`${process.env.REACT_APP_APIURL}/colors`) .then(res => res.json()) .then(colors => { let toBeFiltered = ['white', 'grey', 'black'] let filteredColors = colors.filter(c => !toBeFiltered.includes(c.name)) filteredColors.map(c => { this.props.setColors(c) }) }) } render() { // this.props.loggedIn === true ? this.props.logOut : null return ( <div className="App"> <Router> <> <nav className='navbar'> <Link to='/'><h1>Outfit Designr</h1></Link> <div> <Link to='/profile'>Profile</Link> <Link to='/portal'>Design Portal</Link> <Link to='main'>Catalog</Link> </div> </nav> <Route path='/' exact component={LandingPage}/> <Route path='/profile' exact component={Profile}/> <Route path='/portal' component={DesignPortal}/> <Route path='/main' component={MainPage}/> </> </Router> </div> ); } } function mapStateToProps(state) { return { user: state.user, loggedIn: state.loggedIn, hats: state.hats, tops: state.tops, jackets: state.jackets, bottoms: state.bottoms, shoes: state.shoes } } function mapDispatchToProps(dispatch) { return { // logOut: dispatch({type: 'LOG_IN', payload: false}), setColors: (data) => dispatch({type: 'SET_COLORS', payload: data}), loadHats: (data) => dispatch({type: 'LOAD_HATS', payload: data}), loadTops: (data) => dispatch({type: 'LOAD_TOPS', payload: data}), loadJackets: (data) => dispatch({type: 'LOAD_JACKETS', payload: data}), loadBottoms: (data) => dispatch({type: 'LOAD_BOTTOMS', payload: data}), loadShoes: (data) => dispatch({type: 'LOAD_SHOES', payload: data}) } } export default connect(mapStateToProps, mapDispatchToProps)(App);
var gulp = require('gulp'), // This imports the gulp node package sass = require('gulp-sass'), uglify = require('gulp-uglify'), browserSync = require('browser-sync').create(), imagemin = require('gulp-imagemin'), autoprefixer = require('gulp-autoprefixer'), rename = require('gulp-rename'); function errorLog(error) { console.error(error.message); } // Styles task // Compiles sass gulp.task('styles', function(){ gulp.src('./styles/sass/*.scss') .pipe(sass({outputStyle: 'expanded'})) // compressed. expanded. .on('error', errorLog) .pipe(autoprefixer({ browsers: ['> 5%'], cascade: false })) .pipe(gulp.dest('./styles/css')); }); // Scripts task // Uglifies gulp.task('scripts', function(){ gulp.src('./js/*.js') // loads the files .pipe(uglify()) // uglifies them .on('error', errorLog) .pipe(rename({extname: '.min.js'})) .pipe(gulp.dest('./js/')) // saves the files into minjs }); // Image task // Compresses Images gulp.task('image', function(){ gulp.src('./img/*') .pipe(imagemin()) .pipe(gulp.dest('./img')); }); // BrowserSync Auto-Reload gulp.task('serve', function() { browserSync.init({ server: "./" }); gulp.watch("*.html").on('change', browserSync.reload); gulp.watch("./styles/sass/**/*.scss", ['styles']).on('change', browserSync.reload); }); gulp.task('default', ['serve']); // sets the default task to run an array of tasks. gulp.task('build', ['image', 'scripts']);
var canvas = document.getElementById('canvas'); var gl = canvas.getContext('experimental-webgl'); //清屏幕 gl.clearColor(0.0, 1.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT);
const Computer = require('./Computer') const program = require('./input') const generateInputValues = () => { const inputValues = [] for (let a = 5; a < 10; a++) { for (let b = 5; b < 10; b++) { for (let c = 5; c < 10; c++) { for (let d = 5; d < 10; d++) { for (let e = 5; e < 10; e++) { if (isUnique(a, b, c, d, e)) inputValues.push([a,b,c,d,e]) } } } } } return inputValues } const isUnique = (a, b, c, d, e) => { return (a !== b && a !== c && a !== d && a !== e && b !== c && b !== d && b !== e && c !== d && c !== e && d !== e) } const main = async () => { const inputValues = generateInputValues() let thrust = 0 let output = {} let iteration = 0 for ([phaseA, phaseB, phaseC, phaseD, phaseE] of inputValues) { try { let compA = new Computer(program, [phaseA, 0]) let compB = new Computer(program, [phaseB]) let compC = new Computer(program, [phaseC]) let compD = new Computer(program, [phaseD]) let compE = new Computer(program, [phaseE]) compA.setOutput(compB.addInput) compB.setOutput(compC.addInput) compC.setOutput(compD.addInput) compD.setOutput(compE.addInput) compE.setOutput(compA.addInput) const result = await Promise.all([compA.compute(), compB.compute(), compC.compute(), compD.compute(), compE.compute()]) iteration++ //console.log('result', result) thrust = Math.max(thrust, result[4]) //} //console.log(thrust, output.value) } catch(error) { console.log('main error', error) } } console.log('output', thrust) } main()
import uuid from 'uuid'; import passport from 'passport'; export default function userRoute(baseRoute, db, createLogger) { const logger = createLogger('routes:saves'); baseRoute.post('/NewSaveGame', passport.authenticate('google-login-token'), (req, res) => { logger.info({ route: 'SaveGame', method: 'POST', }); const { currentSceneId, previousSceneId, gamestates, scenestate, } = req.body; const Save = db.model('Save'); const save = new Save({ playerId: req.user.id, currentSceneId, previousSceneId, gamestates, scenestate, saveId: uuid(), timestamp: Date.now(), }); save .save() .then(() => { logger.info('success'); res.status(200).send(save.toJSON()); }) .catch((err) => { logger.info('error', { err }); res.status(500).send('failed to save'); }); }); baseRoute.post('/SaveGame', passport.authenticate('google-login-token'), (req, res) => { const { saveId, gamestates, scenestate, currentSceneId, previousSceneId, } = req.body; const Save = db.model('Save'); Save .findNewest(saveId) .then((save) => { if (save) { Object.assign(save, { playerId: save.playerId, saveId, gamestates, scenestate, currentSceneId, previousSceneId, timestamp: Date.now(), }); return save.save().then(() => { logger.info('Updated save'); res.status(200).send(save.toJSON()); }); } logger.error('Could not find save to update'); res.status(404).send('not found'); return Promise.reject(new Error('No save found to update')); }) .catch((err) => { if (!res.headersSent) { logger.error('Failed to update save', { err, }); res.status(500).send('error'); } }); }); baseRoute.get('/GetAllSaveMeta', passport.authenticate('google-login-token'), (req, res) => { const Save = db.model('Save'); Save.findAllForPlayer(req.user.id) .then((saves) => { if (saves) { logger.info('Loaded saves', { playerId: req.user.id, count: saves.length, }); return res.status(200).send(saves .map(({ saveId, timestamp, currentScene, }) => ({ saveId, timestamp, currentScene, }))); } logger.error('Could not load saves?'); return res.status(500).send('failed'); }) .catch((err) => { logger.error('Failed to load all saves', { err, }); res.status(500).send('error'); }); }); baseRoute.post('/GetSaveGame', passport.authenticate('google-login-token'), (req, res) => { const Save = db.model('Save'); const { saveId, } = req.body; Save.findNewest(saveId) .then((save) => { if (save) { return res.status(200).send(save.toJSON()); } return res.status(404).send('not found'); }) .catch((err) => { logger.error('Failed to find save', { err, }); res.status(500).send('error'); }); }); }
const stripe = require('stripe')(process.env.STRIPE_SKEY); const schedule = require('node-schedule'); const User = require('../models/User'); exports.getCards = async (req, res, next) => { try { res.status(200).json({ cards: req.user.cards }); } catch (err) { next(err); } }; exports.initCron = () => { schedule.scheduleJob('* * 01 * * *', async () => { const users = await User.find({}); users.forEach((user) => { if (!user.cards.length) { user.remove(); } }); }); }; exports.postCards = async (req, res, next) => { const { user } = req; req.assert('number', 'Card number is not valid').len(16); req.assert('number', 'Card number must be numeric').isNumeric(); req.assert('exp_month', 'Exp month is not valid').len(2); req.assert('exp_month', 'Exp month must be numeric').isNumeric(); req.assert('exp_year', 'Exp year is not valid').len(4); req.assert('exp_year', 'Exp month must be numeric').isNumeric(); req.assert('cvc', 'CVC is not valid').len(3); req.assert('cvc', 'CVC month must be numeric').isNumeric(); const errors = req.validationErrors(); if (errors) { res.status(400).json({ message: errors }); return; } try { const card = { number: req.body.number, exp_month: req.body.exp_month, exp_year: req.body.exp_year, cvc: req.body.cvc, }; const token = await stripe.tokens.create({ card }); let customerId; if (!user.customer) { const customer = await stripe.customers.create({ email: user.email }); customerId = customer.id; } else { customerId = user.customer; } const newCard = await stripe.customers.createSource(customerId, { source: token.id }); await User.updateOne({ _id: user._id }, { $push: { cards: newCard.id }, $set: { customer: customerId }, }); res.status(200).json({ message: 'Card was successful added' }); } catch (err) { next(err); } }; const validateIsUserHaveCard = (req, res, next) => { const token = req.params.id; if (!req.user.cards.includes(token)) { res.status(400).json({ message: 'You have not this card' }); return; } next(); }; exports.putCard = [ validateIsUserHaveCard, async (req, res, next) => { const token = req.params.id; const customerId = req.user.customer; const { body } = req; if (Object.keys(body).length === 0) { res.status(400).json({ message: 'Body must not be empty' }); return; } try { await stripe.customers.updateCard(customerId, token, body); res.status(200).json({ message: 'Card was successful changed' }); } catch (err) { next(err); } } ]; exports.deleteCard = [ validateIsUserHaveCard, async (req, res, next) => { const token = req.params.id; const customerId = req.user.customer; const { user } = req; try { await stripe.customers.deleteCard(customerId, token); await user.cards.pull(token); await user.save(); res.status(200).json({ message: 'Card was successful deleted' }); } catch (err) { next(err); } } ];
class HtmlItems { static get menuAbout() { return 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quaerat eaque accusamus reiciendis nobis corrupti quidem dolorem, hic ducimus, minus, tenetur cupiditate tempore laudantium amet perspiciatis repellendus iusto vitae! Perferendis, harum. Quaerat, qui incidunt ex error deleniti repudiandae ducimus nulla perferendis libero laborum, consequuntur vitae doloribus eum veniam aperiam aut minima asperiores sunt.'; } static get menuAccount() { return ` <div id="menu-account"> <h3>Log In / Sign Up to save the lists and maps you create!</h3> <form id="log-or-sign-in" action=""> <div class="menu-inputs-row"> <div class="col-33"> <label for="username">Username</label> </div> <div class="col-48"> <input type="text" id="username" name="username"> </div> </div> <div class="menu-inputs-row"> <div class="col-33"> <label for="password">Password</label> </div> <div class="col-48"> <input type="text" id="password" name="password"> </div> </div> <div id="submit-row"> <button type="button" id="login" class="menu-submit-btn green">Log In</button> <button type="button" id="signup" class="menu-submit-btn green">Sign Up</button> </div> </form> </div>`; } static get menuMyAccount() { return ` <div id="menu-account"> <div id="menu-lists"></div> <div id="submit-row"> <button type="button" id="logout" class="menu-submit-btn green">Log Out</button> </div> </div>`; } static menuWelcome(username) { return ` <h3>Welcome ${username}!</h3> <p>You can access your saved lists and maps from here after you save them.</p>`; } static get menuSaveForm() { return ` <div id="menu-account"> <h3>Provide a name for this map and list</h3> <form id="add-name" action=""> <div class="menu-inputs-row"> <div class="col-20"> <label for="name">Name</label> </div> <div class="col-60"> <input type="text" id="name" name="name"> </div> </div> <div id="submit-row"> <button type="button" id="save-with-name" class="menu-submit-btn green">Save</button> </div> </form> </div>`; } static get listNoMsas() { return ` <div id="no-msas" class="list-msg"> <h1>No Matches</h1> <h2>None of the 100 most populated metropolitan areas in the USA meet the criteria you selected.</h2> </div>`; } static msaDetails(msa) { return ` <div id="msa-details"> <h3>${msa.name}</h3> <h4>${msa.states}</h4> <p><b>Time Zone: </b>${msa.timeZone()}</p> <p><b>Population: </b>${msa.pop.toLocaleString('en', { useGrouping: true })}</p> <p><b>Median Hourly Wage: </b>$${msa.wage}</p> <p><b>Unemployment Rate: </b>${msa.unemp}%</p> <p><b>Highest Summer Heat Index: </b>${msa.heat}</p> <p><b>Coldest Winter Temperature: </b>${msa.cold}&deg; F</p> <p><b>Annual Precipitation: </b>${msa.precip} inches</p> <p><b>Annual Snowfall: </b>${msa.snow} inches</p> <p><b>Air Quality Index: </b>${msa.aqi}% Good Days</p> <h6>(Climate values represent what's normal for this metro area. Other values are the annual amounts from the latest available year as of Jan 2021.) </h6> </div>`; } }
try { const workPrinciplesSliderElement = document.querySelector('.work-principles__slider'); const workPrinciplesSwiper = workPrinciplesSliderElement.querySelector('.swiper'); const workPrinciplesSwiperButton = workPrinciplesSliderElement.querySelector('.slider-button'); const swiper = new Swiper(workPrinciplesSwiper, { loop: true, navigation: { nextEl: workPrinciplesSwiperButton, }, pagination: { el: '.swiper-pagination', type: 'bullets', }, }); } catch { }
import React, { Component } from 'react'; import style from '../Login.css'; export default class VolunteerLogin extends Component { render() { return ( <div className= "login-container"> <h1 className='login-title'>VOLUNTEER LOGIN</h1> <br /> <div className='login-input-container'> <input className="user" type="text" placeholder="Username" value={this.props.volunteerUsername} onChange={this.props.updateVolunteerUsername} /> <br /> <br /> <input className="pass" type="password" placeholder="Password" value={this.props.volunteerPassword} onChange={this.props.updateVolunteerPassword} /> <br /> <br /> <button className="login-button" onClick={this.props.simpleVolunteerAuth}> Log In </button> <br /> <p className="or">-or-</p> <button className="register-button" onClick={this.props.ShowModal}>Register</button> </div> </div> ); } }
$(function () { /* Define Objects */ var Tab = function (title, primaryCategories) { var self = this; var element = $('#html-templates .tab-level-template').clone(); var titleElement = element.find('.tab-level-title').first(); var childrenContainerElement = $('#primary-category-ul'); this.render = function () { // set the title and add the element to the page titleElement.text(title).attr('data-title', title); $('#tab-ul').append(element); // setup events element.unbind('click.raildocs'); element.on('click.raildocs', self.onClick); }; this.onClick = function (event) { currentTab = self; if ($(event.target).hasClass('tab-level-title')) { currentPrimaryCategory = undefined; currentSubCategory = undefined; currentHeader = undefined; } self.select(); }; this.select = function () { $('.tab-level-title').removeClass('active'); titleElement.addClass('active'); // load in primary categories childrenContainerElement.empty(); for (var primaryCategoryIndex in primaryCategories) { if (primaryCategories.hasOwnProperty(primaryCategoryIndex)) { var primaryCategory = primaryCategories[primaryCategoryIndex]; primaryCategory.render(childrenContainerElement); } } if (currentPrimaryCategory === undefined) { primaryCategories[0].select(); } else { currentPrimaryCategory.select(); } }; }; var PrimaryCategory = function (title, subCategories) { var self = this; var element = $('#html-templates .primary-category-list-template').clone(); var titleElement = element.find('.primary-category-list-title').first(); var childrenContainerElement = element.find('.primary-category-list-ul').first(); this.render = function (containerElement) { titleElement.text(title).attr('data-title', title); containerElement.append(element); element.unbind('click.raildocs'); element.on('click.raildocs', self.onClick); // empty and insert new sub categories childrenContainerElement.find('.sub-category-list-template').detach(); for (var subCategoryIndex in subCategories) { if (subCategories.hasOwnProperty(subCategoryIndex)) { var subCategory = subCategories[subCategoryIndex]; subCategory.render(childrenContainerElement); } } }; this.displayMarkdown = function () { // insert the actual markdown content in to the pages iFrame var mdHtml = ''; var mdSplitterElement = $('#html-templates .sub-category-splitter').clone(); for (var subCategoryIndex in subCategories) { if (subCategories.hasOwnProperty(subCategoryIndex)) { var subCategory = subCategories[subCategoryIndex]; mdHtml += mdSplitterElement[0].outerHTML; mdHtml += subCategory.combinedMarkdownHtml; } } $('.content-container', frames['md-iframe'].document).empty().append($(mdHtml)); document.getElementById('md-iframe') .contentWindow .Prism .highlightAll(true, function () { }); }; this.select = function () { childrenContainerElement.show(); $('.primary-category-list-title').removeClass('active'); titleElement.addClass('active'); self.displayMarkdown(); if (currentSubCategory === undefined) { subCategories[0].select(); } else { currentSubCategory.select(); } }; this.onClick = function (event) { currentPrimaryCategory = self; if ($(event.target).hasClass('primary-category-list-title')) { currentHeader = undefined; currentSubCategory = undefined; } currentPrimaryCategory.select(); if (currentSubCategory === undefined) { subCategories[0].select(); } else { currentSubCategory.select(); } }; }; var SubCategory = function (title, mdFile) { var self = this; var element = $('#html-templates .sub-category-list-template').clone(); var titleElement = element.find('.sub-category-list-title').first(); var childrenContainerElement = element.find('.sub-category-list-ul').first(); var headers = []; var converter = new showdown.Converter(); converter.setFlavor('github'); this.combinedMarkdownHtml = ''; this.render = function (containerElement) { element.find('.sub-category-list-title').text(title).attr('data-title', title); containerElement.append(element); element.unbind('click.raildocs'); element.on('click.raildocs', self.onClick); childrenContainerElement.children().detach(); this.combinedMarkdownHtml = ''; headers = []; $.ajax({ type: 'GET', url: 'pages/' + mdFile, async: false, success: function (html) { ajaxCount--; var mdHtml = converter.makeHtml(html); var mdElement = $('<div>' + mdHtml + '</div>'); self.combinedMarkdownHtml += mdHtml; // render headers mdElement.find('h1').each(function (index, h1Element) { var headerTitle = $(h1Element).text(); var header = new Header(headerTitle); header.render(childrenContainerElement); headers.push(header); }); } }); ajaxCount++; }; this.select = function () { $('.sub-category-list-title').removeClass('active'); titleElement.addClass('active'); childrenContainerElement.show(); var interval = setInterval(function () { if (ajaxCount === 0) { var index = element .closest('.primary-category-list-template') .find('.sub-category-list-template') .index(element); var newPosition = $('body', frames['md-iframe'].document) .find('.sub-category-splitter') .eq(index) .offset().top; $('body', frames['md-iframe'].document).scrollTop(newPosition); if (currentHeader === undefined) { headers[0].select(); } else { currentHeader.select(); } clearInterval(interval); } }, 50); }; this.onClick = function (event) { currentSubCategory = self; if ($(event.target).hasClass('sub-category-list-title')) { currentHeader = undefined; } }; }; var Header = function (title) { var self = this; var element = $('#html-templates .title-list-template').clone(); var titleElement = element.find('.title-list-title').first(); this.render = function (containerElement) { element.find('.title-list-title').text(title).data('title', title); containerElement.append(element); }; this.onClick = function (event) { currentHeader = self; }; this.select = function () { var index = element .closest('.primary-category-list-template') .find('.title-list-template') .index(element); var newPosition = $('body', frames['md-iframe'].document) .find('h1') .eq(index) .offset().top; $('body', frames['md-iframe'].document).scrollTop(newPosition); $('.title-list-title').removeClass('active'); titleElement.addClass('active'); }; element.click(self.onClick); }; var TabSplitter = function () { this.render = function () { $('#tab-ul').append($('#html-templates .tab-divider-template').clone()); } }; /* Master Tree */ var masterTree = [ new Tab('Documentation', [ new PrimaryCategory('Guidelines', [ new SubCategory('Rules & Formatting', 'rules-and-guidelines.md'), new SubCategory('Syntax Reference', 'syntax.md'), new SubCategory('How To Create New Pages & Categories', 'creating-new-pages.md'), new SubCategory('Pushing Changes', 'pushing-changes.md'), ]), ]), new TabSplitter(), new Tab('Environments, Deployment, & Sysops', [ new PrimaryCategory('Local Development Environments', [ new SubCategory('Getting Started / Pre Setup', 'getting-started.md'), new SubCategory('Drumeo Setup', 'drumeo.md'), new SubCategory('Pianote Setup', 'pianote.md'), new SubCategory('Guitar Lessons Setup', 'guitarlessons.md'), new SubCategory('Static/Misc Sites Setup', 'misc-sites.md'), new SubCategory('Helper Links & Commands', 'helper-links-and-commands.md'), new SubCategory('Pulling Production Databases', 'pulling-production-databases.md'), new SubCategory('PHPStorm Debugging & PHPUnit', 'php-debugging.md'), ]), new PrimaryCategory('How To Deploy', [ new SubCategory('Drumeo', 'deploying-drumeo.md'), new SubCategory('Drumeo Forums', 'deploying-drumeo-forums.md'), new SubCategory('Pianote', 'deploying-pianote.md'), new SubCategory('Misc Sites', 'deploying-misc-sites.md'), ]), new PrimaryCategory('Production Emergency Procedure', [ new SubCategory('Drumeo Production Server Procedure', 'production-server-down.md'), new SubCategory('Infusionsoft API Down/Offline Procedure', 'infusionsoft-api-down.md'), ]), new PrimaryCategory('Sysops Guides', [ new SubCategory('Creating A Kubernetes Cluster', 'creating-a-new-kubernetes-cluster.md'), new SubCategory('Connecting To Kubernetes Cluster', 'connecting-to-existing-kubernetes-cluster.md'), new SubCategory('Using Our ELK Stack', 'elk-stack.md'), new SubCategory('Setting Up A AWS VPC', 'setting-up-a-aws-vpc.md'), new SubCategory('AWS EBS Cron Jobs', 'aws-ebs-cron-jobs.md'), ]), new PrimaryCategory('PHPStorm Guides & Reference', [ new SubCategory('Advanced Find & Replace', 'find-and-replace.md'), ]), ]), new Tab('Programming', [ new PrimaryCategory('Tutorials', [ new SubCategory('Package Development Workflow', 'package-development-workflow.md'), ]), new PrimaryCategory('Management', [ new SubCategory('Updating Drumeo Wordpress', 'updating-wordpress.md'), ]), ]), new Tab('Front End', [ new PrimaryCategory('Grid', [ new SubCategory('Float Grid', 'front-end/float-grid.md'), new SubCategory('Flex Grid', 'front-end/flex-grid.md'), new SubCategory('Responsive Ratios', 'front-end/ratios.md') ]), new PrimaryCategory('Components', [ new SubCategory('Buttons', 'front-end/buttons.md'), new SubCategory('Modal', 'front-end/modal.md'), new SubCategory('Accordion', 'front-end/accordion.md'), new SubCategory('Navigation', 'front-end/navigation.md'), new SubCategory('Loading', 'front-end/loading.md') ]), new PrimaryCategory('Form Validation', [ new SubCategory('Usage', 'front-end/forms/usage.md'), new SubCategory('Validation Rules', 'front-end/forms/rules.md'), new SubCategory('Methods', 'front-end/forms/methods.md'), new SubCategory('Events', 'front-end/forms/events.md') ]), new PrimaryCategory('Icons', [ new SubCategory('Icons', 'front-end/icons.md') ]) ]), new Tab('Misc Dev', []), new TabSplitter(), new Tab('Support (incl. Marketing and Community Managers)', [ new PrimaryCategory('Guides', [ new SubCategory('Intercom', 'intercom-guide.md') ]) ]), new Tab('Accounting', [ new PrimaryCategory('Intercom Guide', 'intercom-guide.md') ]) ]; /* App Entry Point */ var ajaxCount = 0; var currentTab; var currentPrimaryCategory; var currentSubCategory; var currentHeader; // render main tabs for (var tabIndex in masterTree) { if (masterTree.hasOwnProperty(tabIndex)) { var tab = masterTree[tabIndex]; tab.render(); } } $('iframe').on('load', function () { $('.tab-level-title').first().trigger('click.raildocs'); }); // setup iFrame auto resizing setInterval(function (event) { var iFrame = $('#md-iframe'); if (iFrame.length === 0) { return; } iFrame.height($(window).height() - iFrame.offset().top - 10); }, 50); });
import React, {useState} from 'react'; const Display = (props) => { console.log(props); return( <div className="the-display" > <div className="view-stat" >{props.strikes}</div> <div className="view-stat" >{props.balls}</div> <div className="view-stat" >{props.fouls}</div> </div> ); } export default Display;
/** * Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved. * * This software is the property of Pacific Controls Software Services LLC and its * suppliers. The intellectual and technical concepts contained herein are proprietary * to PCSS. Dissemination of this information or reproduction of this material is * strictly forbidden unless prior written permission is obtained from Pacific * Controls Software Services. * * PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * Version : 1.0 * User : pcseg306 * Function : This is creating server instance. */ // @pcseg306 - This only runs at port 8000 ; i have tried running on other ports but it does not work. I'd check later. var express = require('Express'); var app = express(); port = process.argv[2] || 8000; /** The below syntax is for version 4.0 **/ /** //all environments app.set('title', 'Galaxy 2021 - Platform of Platforms'); // development only if ('development' == app.get('env')) { app.set('app_uri', 'http://localhost/dev'); } // production only if ('production' == app.get('env')) { app.set('app_uri', 'http://localhost/prod'); } app.use("/", express.static('C:/Galaxy_workspace/galaxy-ui')); app.listen(port); console.log("Express server running at http://localhost:" + port + "/\nCTRL + C to shutdown"); **/ /** The below syntax is for version 3.4.6 - version 4 has errors with ngRoute ; i'd update when those stable code fixes are committed**/ app.configure(function () { app.use("/",express.static('C:/Users/pcscs204/workspace/galaxy-ui')); }); app.listen(port); console.log("Express server running at http://localhost:" + port + "/\nCTRL + C to shutdown");
const logger = require("../index"); let message = `hello there`; function waitFor(time = 500) { return new Promise((resolve, reject) => setTimeout(resolve, time)); } async function run() { for (let i = 0; i < 100; i++) { if (i % 5 === 0) { message = message + i; } await waitFor(); logger.info(message); } } run().catch(console.error);
var flag = false; $(function () { var h = $(".container-fluid-full").height(); var h1 = $("#content .breadcrumb").height(); $("#tree").height(h - h1 - 24); ShowViewer.init("earth"); // 加载球模型 ShowViewer.initLeftClick(globalviewer,showlabel); globalviewer.camera.setView( { destination : new FreeDo.Cartesian3(-2183570.5850746077,4471852.254049122,3990050.5935917823), orientation : { heading : 6.283061736872095, pitch : -0.7852936750535262, roll : 0.00010838690093617487 } }); var surveymanager = new SurveyManager(globalviewer,function(){}); var h = $(".container-fluid-full").height(); var h1 = $("#content .breadcrumb").height(); $("#tree").height(h - h1 - 24); $.ajax({ url: "static/page/surveystudy/show/show.json", type: "get", dataType:"json", success: function (data) { var zTreeObj; var setting = { data: { simpleData: { enable: true, idKey: "id", pIdKey: "pId", rootPId: "0" } }, check:{ enable: true, chkStyle: "checkbox", chkboxType: { "Y": "p", "N": "s" } }, callback:{ onCheck:function(event, treeId, treeNode){ $(".msgInfo").hide(); checkflag =treeNode.checked; switch (treeNode.id) { case 7: globalviewer.zoomTo(water[0]); if(checkflag){ water[0].show=true; }else{ water[0].show=false; } break; case 8: globalviewer.zoomTo(water[1]); if(checkflag){ water[1].show=true; }else{ water[1].show=false; } break; case 10: globalviewer.zoomTo(environment[0]); if(checkflag){ environment[0].show=true; }else{ environment[0].show=false; } break; case 11: globalviewer.zoomTo(environment[1]); if(checkflag){ environment[1].show=true; }else{ environment[1].show=false; } break; case 12: globalviewer.zoomTo(environment[2]); if(checkflag){ environment[2].show=true; }else{ environment[2].show=false; } break; case 13: globalviewer.zoomTo(environment[3]); if(checkflag){ environment[3].show=true; }else{ environment[3].show=false; } break; case 14: globalviewer.zoomTo(environment[4]); if(checkflag){ environment[4].show=true; }else{ environment[4].show=false; } break; default: break; } }, onClick:function(event, treeId, treeNode){ $(".msgInfo").hide(); $("#tableInfo").hide(); switch (treeNode.id) { case 3: ShowViewer.fly(globalviewer,115.999,39.001,70,function(){}); break; case 4: ShowViewer.fly(globalviewer,116.001,39,70,function(){}); break; case 5: ShowViewer.fly(globalviewer,116.002,39.002,70,function(){}); break; case 7: globalviewer.zoomTo(water[0]); break; case 8: globalviewer.zoomTo(water[1]); break; case 10: globalviewer.zoomTo(environment[0]); break; case 11: globalviewer.zoomTo(environment[1]); break; case 12: globalviewer.zoomTo(environment[2]); break; case 13: globalviewer.zoomTo(environment[3]); break; case 14: globalviewer.zoomTo(environment[4]); break; default: break; } } } }; zTreeObj = $.fn.zTree.init($("#tree"), setting, data); zTreeObj.checkAllNodes(true); zTreeObj.expandAll(true); } }); /** *工具栏按钮点击 */ $("#appendTools i").each(function(){ $(this).click(function(){ if($(this).hasClass("active")){ //设置方法为none surveymanager.setSurveyType(SurveyType.NONE); //移除原有的监听事件 ShowViewer.removeListener(); //初始化相应的监听事件 switch ($(this).attr("id")) { //统计查询 case "TJCX": $("#img").hide(); surveymanager.setSurveyType(SurveyType.QUERY) break; //距离测量 case "JLCL": $("#echartarea").hide(); $("#img").hide(); surveymanager.setSurveyType(SurveyType.LINE_DISTANCE); break; //方位测量 case "FWCL": $("#echartarea").hide(); $("#img").hide(); surveymanager.setSurveyType(SurveyType.Azimuth_DISTANCE); break; //面积测量 case "MJCL": $("#echartarea").hide(); $("#img").hide(); break; //地面刨切 case "DMPQ": $("#echartarea").hide(); surveymanager.setSurveyType(SurveyType.Geology_SLICING); break; //其他 default: break; } }else{ //隐藏echarts和img窗口 $("#echartarea").hide(); $("#img").hide(); //删除三维页面所有的线、标签 //设置方法为none surveymanager.setSurveyType(SurveyType.NONE); //初始化原有的监听事件 ShowViewer.initLeftClick(globalviewer,showlabel); } }); }); //窗口拖动 tool.drag("#tableInfo"); $("#tableInfo p span:last-of-type").click(function () { $("#tableInfo").hide(); }); }); var cartesian= null; var str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb =null; function showlabel(data,data2){ if(data!=null){ if(flag==true){ removeFollowListener(); } let name = data2.id.name; if(data2.id=="钻井柱1_0"){ $(".msgInfo").html("名称:粉质粘土<br>深度:180米<br>厚度:20米<br>标高:11米"); $(".msgInfo").show(); cartesian = transform1([115.999,39.001,15]); }else if(data2.id=="钻井柱1_1"){ $(".msgInfo").html("名称:泥岩<br>深度:-95米<br>厚度:5米<br>标高:9米"); $(".msgInfo").show(); cartesian = transform1([115.999,39.001,27.5]); }else if(data2.id=="钻井柱1_2"){ $(".msgInfo").html("名称:沙岩<br>深度:-87米<br>厚度:13米<br>标高:15米"); $(".msgInfo").show(); cartesian = transform1([115.999,39.001,36.5]); }else if(data2.id=="钻井柱1_3"){ $(".msgInfo").html("名称:素填土<br>深度:-90米<br>厚度:10米<br>标高:10米"); $(".msgInfo").show(); cartesian = transform1([115.999,39.001,48]); }else if(data2.id=="钻井柱1_4"){ $(".msgInfo").html("名称:强风华带<br>深度:198米<br>厚度:2米<br>标高:8米"); $(".msgInfo").show(); cartesian = transform1([115.999,39.001,54]); }else if(data2.id=="钻井柱2_0"){ $(".msgInfo").html("名称:粉质粘土<br>深度:-98米<br>厚度:2米<br>标高:11米"); $(".msgInfo").show(); cartesian = transform1([116.001,39,6]); }else if(data2.id=="钻井柱2_1"){ $(".msgInfo").html("名称:泥岩<br>深度:-95米<br>厚度:5米<br>标高:9米"); $(".msgInfo").show(); cartesian = transform1([116.001,39,10.5]); }else if(data2.id=="钻井柱2_2"){ $(".msgInfo").html("名称:沙岩<br>深度:-97米<br>厚度:3米<br>标高:15米"); $(".msgInfo").show(); cartesian = transform1([116.001,39,11.5]); }else if(data2.id=="钻井柱2_3"){ $(".msgInfo").html("名称:素填土<br>深度:-90米<br>厚度:10米<br>标高:10米"); $(".msgInfo").show(); cartesian = transform1([116.001,39,20]); }else if(data2.id=="钻井柱2_4"){ $(".msgInfo").html("名称:强风华带<br>深度:-98米<br>厚度:2米<br>标高:8米"); $(".msgInfo").show(); cartesian = transform1([116.001,39,26]); }else if(data2.id=="钻井柱3_0"){ $(".msgInfo").html("名称:粉质粘土<br>深度:28米<br>厚度:20米<br>标高:11米"); $(".msgInfo").show(); cartesian = transform1([116.002,39.002,15]); }else if(data2.id=="钻井柱3_1"){ $(".msgInfo").html("名称:泥岩<br>深度:13米<br>厚度:5米<br>标高:9米"); $(".msgInfo").show(); cartesian = transform1([116.002,39.002,27.5]); }else if(data2.id=="钻井柱3_2"){ $(".msgInfo").html("名称:沙岩<br>深度:21米<br>厚度:13米<br>标高:15米"); $(".msgInfo").show(); cartesian = transform1([116.002,39.002,36.5]); }else if(data2.id=="钻井柱3_3"){ $(".msgInfo").html("名称:素填土<br>深度:18米<br>厚度:10米<br>标高:10米"); $(".msgInfo").show(); cartesian = transform1([116.002,39.002,48]); }else if(data2.id=="钻井柱3_4"){ $(".msgInfo").html("名称:强风华带<br>深度:28米<br>厚度:20米<br>标高:8米"); $(".msgInfo").show(); cartesian = transform1([116.002,39.002,63]); }else if(name=="baiyangdianshuiwenbaohu"){ str_ghqmc="白洋淀水文保护区"; str_xmmc="白洋淀水文保护区"; str_bgmc="白洋淀水文保护区控制性工程规划报告书"; str_kjbj="中心村以均匀布局形式带动基层村发展的空间结构形态"; str_xzqh="河北省保定市安新县"; str_rjztmj="99.24平方米"; str_ghqmj="993公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为8350,规划近期到2010年,镇区人口为8750,规划近期2015到年,镇区人口为9750,规划近期2025到年,镇区人口为10450"; str_fzfx="旅游用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为8430,城镇人口比重为33%<br>2015年城镇人口为10452,城镇人口比重为38%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="daqingheshuiwenbaohu"){ str_ghqmc="大清河水文保护区"; str_xmmc="大清河水文保护区"; str_bgmc="大清河水文保护区控制性工程规划报告书"; str_kjbj="清河县地处环渤海经济区中心地带,北京、天津、济南、石家庄、郑州、太原等大城市拱卫辐射内外"; str_xzqh="河北省邢台市清河县"; str_rjztmj="120.24平方米"; str_ghqmj="1200公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为13020,规划近期到2010年,县区人口为13500,规划近期2015到年,县区人口为14031,规划近期2025到年,县区人口为16000"; str_fzfx="建设用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为6430,城镇人口比重为38%<br>2015年城镇人口为8552,城镇人口比重为44%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="gaoxiaowangcunchaiquanqu"){ str_ghqmc="高小王村拆迁区"; str_xmmc="高小王村拆迁区"; str_bgmc="高小王村拆迁区控制性工程规划报告书"; str_kjbj="中心村以均匀布局形式带动基层村发展的空间结构形态"; str_xzqh="河北省保定市空城县"; str_rjztmj="99.24平方米"; str_ghqmj="993公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为8350,规划近期到2010年,镇区人口为8750,规划近期2015到年,镇区人口为9750,规划近期2025到年,镇区人口为10450"; str_fzfx="旅游用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为8430,城镇人口比重为33%<br>2015年城镇人口为10452,城镇人口比重为38%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="zhangweizhuangtoucunchaiqianqu1"){ str_ghqmc="张巍庄头村拆迁区一区"; str_xmmc="张巍庄头村拆迁区一区"; str_bgmc="张巍庄头村拆迁区一区控制性工程规划报告书"; str_kjbj="中心村以均匀布局形式带动基层村发展的空间结构形态"; str_xzqh="河北省保定市安新县"; str_rjztmj="97.24平方米"; str_ghqmj="697.3公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为8350,规划近期到2010年,镇区人口为8750,规划近期2015到年,镇区人口为9750,规划近期2025到年,镇区人口为10450"; str_fzfx="旅游用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为8430,城镇人口比重为33%<br>2015年城镇人口为10452,城镇人口比重为38%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="zhangweizhuangtoucunchaiqianqu2"){ str_ghqmc="张巍庄头村拆迁区二区"; str_xmmc="张巍庄头村拆迁区二区"; str_bgmc="张巍庄头村拆迁区二区控制性工程规划报告书"; str_kjbj="中心村以均匀布局形式带动基层村发展的空间结构形态"; str_xzqh="河北省保定市安新县"; str_rjztmj="88.26平方米"; str_ghqmj="785公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为8350,规划近期到2010年,镇区人口为8750,规划近期2015到年,镇区人口为9750,规划近期2025到年,镇区人口为10450"; str_fzfx="旅游用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为8430,城镇人口比重为33%<br>2015年城镇人口为10452,城镇人口比重为38%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="xiaoyangcunchaiqianqu"){ str_ghqmc="小阳村拆迁区"; str_xmmc="小阳村拆迁区"; str_bgmc="小阳村拆迁区控制性工程规划报告书"; str_kjbj="中心村以均匀布局形式带动基层村发展的空间结构形态"; str_xzqh=" 郑州市新密市小阳村"; str_rjztmj="98.24平方米"; str_ghqmj="853公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为8350,规划近期到2010年,镇区人口为8750,规划近期2015到年,镇区人口为9750,规划近期2025到年,镇区人口为10450"; str_fzfx="旅游用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为8430,城镇人口比重为33%<br>2015年城镇人口为10452,城镇人口比重为38%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="dayangcunchaiqianqu"){ str_ghqmc="大阳村拆迁区"; str_xmmc="大阳村拆迁区"; str_bgmc="大阳村拆迁区控制性工程规划报告书"; str_kjbj="中心村以均匀布局形式带动基层村发展的空间结构形态"; str_xzqh="山东省日照市五莲县大阳村"; str_rjztmj="78.24平方米"; str_ghqmj="600公顷"; str_gdqx="2008-2025年"; str_znjg="中心镇是全镇的政治、经济、文化及交通中心,是以发展第三产业、农副产品精深加工及蔬菜等包装业和物流业为主的综合开发区,中心村是村民行政、文化娱乐中心、初级商贸中心,基层村是村民活动中心"; str_zqgm="现状人口为8350,规划近期到2010年,镇区人口为8750,规划近期2015到年,镇区人口为9750,规划近期2025到年,镇区人口为10450"; str_fzfx="旅游用地发展方向为向东发展"; str_czhfzmb="2015年城镇人口为8430,城镇人口比重为33%<br>2015年城镇人口为10452,城镇人口比重为38%"; TableAssign.setablevalue(str_ghqmc,str_xmmc,str_bgmc,str_kjbj,str_xzqh,str_rjztmj,str_ghqmj,str_gdqx,str_znjg,str_zqgm,str_fzfx,str_czhfzmb) $("#tableInfo").show(); }else if(name=="钻井柱1"){ cartesian = transform(data); $(".msgInfo").html("钻孔编号:钻井柱1<br>日期:2017-9-22<br>钻孔深度:-100<br>孔口高程:113") $(".msgInfo").show(); }else if(name=="钻井柱2"){ cartesian = transform(data); $(".msgInfo").html("钻孔编号:钻井柱2<br>日期:2017-9-23<br>钻孔深度:-100<br>孔口高程:103") $(".msgInfo").show(); }else{ cartesian = transform(data); $(".msgInfo").html("钻孔编号:钻井柱3<br>日期:2017-9-24<br>钻孔深度:8<br>孔口高程:113") $(".msgInfo").show(); } addFollowListener(); }else{ removeFollowLisener(); $(".msgInfo").hide(); $("#tableInfo").hide(); return; } } var htmlOverlay = document.getElementById('showmsg'); var addFollowListener=function(){ flag = globalviewer.scene.preRender.addEventListener(setScreenPostion); } var removeFollowLisener= function(){ if(flag==true){ globalviewer.scene.preRender.removeEventListener(setScreenPostion); } flag = false; } var setScreenPostion=function (){ var canvasPosition = globalviewer.scene.cartesianToCanvasCoordinates(cartesian); if (FreeDo.defined(canvasPosition)) { htmlOverlay.style.top = canvasPosition.y -150+ 'px'; htmlOverlay.style.left = canvasPosition.x +220+ 'px'; } } var transform = function(data){ var pick= new FreeDo.Cartesian2(data.x,data.y); var cartesian = globalviewer.scene.globe.pick(globalviewer.camera.getPickRay(pick), globalviewer.scene); return cartesian; } var transform1 = function(lonlathei){ return FreeDo.Cartesian3.fromDegrees(lonlathei[0],lonlathei[1],lonlathei[2]); }
import React, { useContext } from "react"; import { Card, Form, Container, Row, Col } from "reactstrap"; import { AppContext } from "../utilities/Context"; import { firstPageValidation } from "../utilities/validation"; import { MyDatePicker } from "../components/common/MyDatePicker"; import { ErrorMessage } from "../components/error/ErorrMessage"; import { BtnRound } from "../components/common/Buttons"; import { Select, NumInput } from "../components/common/Inputs"; import { MOVIES } from "../constants"; function First(props) { const [state, dispatch] = useContext(AppContext); const handleInput = ({ target }) => { const { value, name } = target; dispatch({ type: name, payload: value }); }; const handleSubmit = () => { if (firstPageValidation(state) === false) { return dispatch({ type: "error", payload: "All fields required!" }); } dispatch({ type: "error", payload: "" }); dispatch({ type: "createTicketArr" }); props.pushHistory("/second"); }; return ( <Container> <Row> <Col className="ml-auto mr-auto" lg="4"> <Card className="card-register ml-auto mr-auto"> <h3 className="title mx-auto">Welcome</h3> <Form className="register-form"> <label>Movie</label> <Select name="movie" value={state.movie} onChange={handleInput} options={MOVIES} /> <label>Ticket Count</label> <NumInput name="ticketAmount" value={state.ticketAmount} onChange={handleInput} /> <label>Date</label> <MyDatePicker value={state.date} onChange={(date) => dispatch({ type: "date", payload: date })} /> <ErrorMessage message={state.error} /> <BtnRound onClick={handleSubmit}>Next</BtnRound> </Form> </Card> </Col> </Row> </Container> ); } export { First };
Class("TestSession", { //LIST THE USER TEST SESSIONS has : { app : { is : 'rw' }, sessions : { is : 'rw', init : ( function () { return [] } )()}, tpl : { is : 'rw', init : ( function () { return "\ <li class='{{status}}' data-id='{{id}}'>\ <span class='icon-status'></span>\ <div class='title'>\ {{name}}\ <span class='icon-device'></span>\ </div>\ <span class='time-start'>{{created}}</span>\ <span class='duration'>{{created}}</span>\ </li>\ "; } )() }, target : { is : 'rw' }, current_session : { is : 'rw' }, }, methods : { get_sessions : function () { var _this = this; $.ajax({ url : '/v1/user/sessions', cache : false, async : true, success : function ( data ) { console.log( 'user test sessions', data ); _this.setSessions( data.sessions ); _this.render(); }, contentType : 'application/json', dataType : 'json', type : 'GET' }); }, init : function () { var _this = this; _this.app.named_instances.TestSession = _this; $(document).ready(function () { _this.setTarget( $( '.test-sessions' ) ); _this.get_sessions(); setInterval( function () { _this.get_sessions(); }, 3000 ) }); }, render : function () { var self = this; var reversed = self.sessions.reverse(); for ( var i=0,item; item = reversed[i]; i++ ) { if ( $('.test-sessions [data-id='+item.id+']').length ) { continue; } var markup = $( Mustache.render( self.tpl, item ) ); markup .click( function ( ev ) { var target = $( ev.currentTarget ); self.open( target.data('id') ); } ) .prependTo( self.target ) ; } }, show_vm_screenshot : function ( ) { var self = this; var target = $('.machine-screenshot'); var img = new Image(); img.src = '/v1/live-screenshot/'+self.current_session.id+".png?"+Math.random(); img.onload = function () { target.html(img); } }, open : function ( test_id ) { var self = this; //open a test and its details $.ajax( { url : '/v1/test/'+test_id, cache : false, async : true, success : function ( data ) { // console.log( "current session id", data ); self.setCurrent_session( data.session ); self.render_test_detail( data ); self.show_vm_screenshot( ); if ( self.current_session.status == 'initialized' ) { setTimeout( function () { self.open( self.current_session.id ) } , 2000) } }, contentType : 'application/json', dataType : 'json', type : 'GET' } ); }, render_test_detail : function ( data ) { console.log('render test detail', data); var target = $('.col-right'); target.html(''); var tpl_headers = "\ <table class='test-summary'>\ <tr>\ <td>Started</td>\ <td>{{created}}</td>\ </tr>\ <tr>\ <td>Duration</td>\ <td>{{duration}}</td>\ </tr>\ <tr>\ <td>Status</td>\ <td>{{status}}</td>\ </tr>\ <tr>\ <td>Device</td>\ <td>{{device}}</td>\ </tr>\ <tr>\ <td>Browser</td>\ <td>{{browser}}</td>\ </tr>\ <tr>\ <td>Version</td>\ <td>{{version}}</td>\ </tr>\ <tr>\ <td>Platform</td>\ <td>{{platform}}</td>\ </tr>\ </table>\ "; var markup_header = $( Mustache.render( tpl_headers, data.session ) ) .appendTo( target ); var steps = $( '<table/>' ) .addClass('test-steps') .append('<tr><td>Start</td><td>Duration</td><td>Action</td></tr>') ; var tpl_step = "\ <tr>\ <td class='created'>{{created}}</td>\ <td class='elapsed'>{{elapsed}}</td>\ <td class='action'>{{action}}</td>\ </tr>\ "; for (var i=0,item; item=data.result[i]; i++) { $( Mustache.render( tpl_step, item ) ) .appendTo( steps ) ; } steps.appendTo( target ); } }, // after : { // } })
$('.purchaseCoupon').on('click', function(e){ e.preventDefault(); var thisForm = $(this).parent(); var couponid = thisForm.data('couponid'); var quant = $(this).siblings().eq(0).val(); var data = { coupon_id: couponid, quantity: quant } //one way $.post("/coupons/users/create", data, function(response){ alert("the response from the server is: " + response + ". If 200 then that's good. If 500 then there was something wrong."); }); //another way // $.ajax({ // url: "/coupons/users/create", // method: "POST" // data: data // }, function(response){ // alert("the response from the server is: " + response + ". If 200 then that's good. If 500 then there was something wrong."); // }); });
import {CHANGE_THEME, DECREMENT, DISABLE_BUTTONS, ENABLE_BUTTONS, INCREMENT} from './types.js' import {combineReducers} from "redux"; const counterReducer = (state = 0, action) => { switch (action.type) { case INCREMENT: { return state + 1 } case DECREMENT: { return state - 1 } default: { return state } } } const initialValue = { value: 'dark', disabled: false } const themeReducer = (state = initialValue, action) => { switch (action.type) { case CHANGE_THEME: { return {...state, value: action.value} } case ENABLE_BUTTONS: { return {...state, disabled: false} } case DISABLE_BUTTONS: { return {...state, disabled: true} } default: { return state } } } export const rootReducer = combineReducers({ counter: counterReducer, theme: themeReducer })
import React from 'react'; import {Slide, Heading, List, ListItem} from 'spectacle'; export default ( <Slide transition={["fade"]} bgColor="primary"> <Heading size={5} textColor="secondary">Ключевые идеи</Heading> <List> <ListItem> Простота </ListItem> <ListItem> Читабельность </ListItem> <ListItem> Конкурентность </ListItem> </List> </Slide> );
//================================================================================ //Copyright: M.Nelson - technische Informatik //Alle Rechte vorbehalten //Das Verändern, Kopieren, Benutzen des Codes ist nur mit ausdrücklicher //Genehmigung gestattet. //================================================================================ window.MneAjaxTable = function( win, container, classname, selectRows, plain ) { MneMisc.call(this, win); this.frame = container; this.classname = classname; this.selectRows = selectRows; this.selectHead = true; this.sizeElement = false; this.ignoreUnselect = false; this.ignoreEvent = false; this.noshowActive = false; this.input = new Array(); this.inputstyle = new Array(); this.inputname = "Cell"; this.plain = plain; this.fixcols = true; this.borderclass = " border padding"; this.mouseoverclass = "mouseover"; this.tdclass = new Array(); this.invisible = new Array(); this.cellWidth = new Array(); this.cellAlign = new Array(); this.table = this.win.document.createElement("table"); this.frame.appendChild(this.table); this.table.className = this.classname + " border"; this.table.mne_table = this; this.head = null; this.body = this.win.document.createElement("tbody"); this.body.className = this.classname; this.body.sname = 'body'; this.body.data = new Array(); this.body.origdata = new Array(); this.table.appendChild(this.body); this.sections = new Array(); this.sections["head"] = this.head; this.sections["body"] = this.body; this.clickCb = new Array(); this.clickCb["head"] = null; this.clickCb["body"] = null; this.dblclickCb = new Array(); this.dblclickCb["head"] = null; this.dblclickCb["body"] = null; this.multiselect = false; this.act_event = null; this.max_rownum = 10000; this.max_rownum_step = 500; this.next_button = null; this.modify_function = null; this.mkNextbutton = function() { if ( this.next_button != null ) return; this.next_button = this.win.document.createElement("input"); this.next_button.type = "button"; this.next_button.value = "#mne_lang#weiter"; try { this.next_button.appendChild(this.win.document.createTextNode(this.next_button.value)); } catch(e) {}; this.next_button.mne_table = this; this.next_button.vtype = "button"; this.next_button.onclick = function() { this.mne_table.show_next(); }; this.frame.appendChild(this.next_button); }; this.act_rownums = new Array(); this.reset = function() { var i; for ( i=0; i< this.act_rownums.length; i++) this.set_active(this.act_rownums[i], false); this.act_section = null; this.act_row = null; this.act_cell = null; this.act_text = ""; this.act_selection = ""; this.act_rownum = -1; this.act_colnum = -1; this.act_rownums = new Array(); }; this.reset(); this.act_event = null; this.col2tab = function(col) { var tab_col; var r; for ( tab_col = col, r = 0; r < col; r++ ) if ( this.invisible[r] == true ) tab_col--; return tab_col; }; this.tab2col = function(tab_col) { var col; var r; for ( col = tab_col, r = 0; r <= col; r++ ) if ( this.invisible[r] == true ) col++; return col; }; this.set_active = function(rownum, active) { var c; var act_row = this.act_section.rows[rownum]; for ( c=0; c < act_row.cells.length; c++ ) this.eleMkClass(act_row.cells[c], 'active', active); } this.findCell = function(cell, dblclick, ignore_cb) { var r,c,s,ss; if ( cell == this.act_cell && dblclick != true && this.multiselect != true ) return; ss = null; if ( this.act_cell != null && this.act_colnum >= 0 && this.noshowActive != true ) { if ( this.selectRows == true ) { if ( this.act_section.sname == 'head' ) { for ( ss in this.sections ) for ( r=0; r < this.sections[ss].rows.length; r++ ) this.eleMkClass(this.sections[ss].rows[r].cells[this.act_colnum], 'active', false); } } else { this.act_cell.className = this.classname + this.borderclass; if ( typeof this.tdclass[this.act_cell.colnum] != 'undefined' ) this.eleMkClass(this.act_cell, this.tdclass[this.act_cell.colnum], true); } } if ( dblclick == true ) this.reset(); else if ( this.ignoreUnselect == false && this.act_section != null && ( cell == null || ( cell.section == this.act_section.sname && ( this.act_rownum == cell.rownum && this.selectRows == true && this.act_section.sname != 'head' || this.act_colnum == cell.colnum && this.selectRows == true && this.act_section.sname == 'head' || this.act_cell == cell ))) ) { s = this.act_section.sname; this.reset(); if ( ignore_cb != true && s != null && dblclick != true && this.clickCb[s] != null ) { try { this.clickCb[s](this); } catch(e) { this.error("MneAjaxTable::clickCb: " + e.message); } } return; } if ( this.multiselect == false || (this.act_event != null && this.act_event.ctrlKey == false && this.act_event.shiftKey == false )) this.reset(); if ( cell == null ) return; s = null; c = 0; r = 0; if ( cell.rownum < this.sections[cell.section].rows.length ) { if ( cell.colnum < this.sections[cell.section].rows[cell.rownum].cells.length ) if ( this.sections[cell.section].rows[cell.rownum].cells[cell.colnum] == cell ) { s = cell.section; r = cell.rownum; c = cell.colnum; } } if ( s == null ) { for ( s in this.sections ) { if ( this.sections[s] != null ) { for ( r=0; r<this.sections[s].rows.length; r++) { for ( c=0; c < this.sections[s].rows[r].cells.length; c++ ) if ( this.sections[s].rows[r].cells[c] == cell ) break; if ( c < this.sections[s].rows[r].cells.length && this.sections[s].rows[r].cells[c] == cell ) break; } if ( r < this.sections[s].rows.length && this.sections[s].rows[r].cells[c] == cell ) break; } } if ( this.multiselect == true && this.sections[s] != this.act_section ) this.reset(); } if ( this.sections[s].rows[r].cells[c] == cell ) { this.act_section = this.sections[s]; this.act_colnum = c; this.act_rownum = r; this.act_row = this.sections[s].rows[r]; this.act_cell = cell; if ( this.multiselect && s != 'head' && this.act_event != null && this.act_event.shiftKey == true && this.act_rownums.length > 0 ) { var i = this.act_rownums[this.act_rownums.length - 1]; if ( r < i ) { while ( i > r ) this.act_rownums[this.act_rownums.length] = --i; } else { while ( i < r ) this.act_rownums[this.act_rownums.length] = ++i; } } else if ( this.multiselect && s != 'head' && this.act_event != null && this.act_event.ctrlKey == true ) { var i; var act_rownums = new Array(); for ( i = 0; i<this.act_rownums.length; i++ ) { if ( this.act_rownums[i] == r ) break; act_rownums[i] = this.act_rownums[i]; } if ( i == this.act_rownums.length ) { this.act_rownum = r; this.act_rownums[this.act_rownums.length] = r; } else { this.set_active(this.act_rownums[i],false); while ( ++i < this.act_rownums.length ) { act_rownums[i-1] = this.act_rownums[i]; } if ( act_rownums.length > 0 ) { this.act_rownums = act_rownums; } else { this.reset(); } } } else { this.act_rownum = r; this.act_rownums[this.act_rownums.length] = r; } this.act_rownums.sort(); this.act_text = this.sections[s].data[r][this.tab2col(c)]; this.act_selection = this.sections[s].data[r][0]; if ( this.noshowActive != true ) { if ( this.selectRows == true ) { var i; if ( s == 'head' && this.selectHead == true ) { for ( ss in this.sections ) for ( i=0; i<this.sections[ss].rows.length; i++ ) this.eleMkClass(this.sections[ss].rows[i].cells[c], 'active', true); } else if ( s == 'body' ) { var i; for ( i = 0; i<this.act_rownums.length; i++) this.set_active(this.act_rownums[i], true); } } else { this.eleMkClass(cell, 'active', true); } } if ( ignore_cb != true && dblclick != true && this.clickCb[s] != null ) try { this.clickCb[s](this); } catch(e) { this.error("MneAjaxTable::clickCb: " + e.message); } if ( ignore_cb != true && dblclick == true && this.dblclickCb[s] != null ) try { this.dblclickCb[s](this); } catch(e) { this.error("MneAjaxTable::dblclickCb: " + e.message); } } }; this.mkContent = function(p_str, colnum, rownum) { var ityp = null; var name = null; var value = null; var limit = null; var secval = null; var minval = null; var maxval = null; var pos; var e, ee, errval; var str = p_str; errval = str; var retval; if ( this.plain == true || typeof str.substr == 'undefined' ) return this.win.document.createTextNode(str); if ( this.input.length == 0 ) { if ( str.substr(0,4) != '####' ) return this.win.document.createTextNode(str); str = str.substring(4, str.length); if ( (pos = str.indexOf('####' )) >= 0 ) { ityp = str.substring(0,pos); name = str.substring(pos + 4, str.length); } if ( name != null && (pos = name.indexOf('####' )) >= 0 ) { value = name.substring(pos + 4, name.length); name = name.substring(0,pos); } if ( value != null && (pos = value.indexOf('####' )) >= 0 ) { limit = value.substring(pos + 4, value.length); value = value.substring(0,pos); } if ( limit != null ) { pos = limit.indexOf('%' ); if ( pos != 0 ) minval = Number(limit.substring(0, pos )); if ( pos >= 0 ) maxval = Number(limit.substring(pos + 1, limit.length)); } } else { if ( this.rowsection == this.head ) ityp = 'plain'; else ityp = this.input[colnum]; if ( typeof ityp != "string" ) ityp = "plain"; name = this.inputname + rownum + "_" + colnum; value = str; if ( value != null && (pos = value.indexOf('::::' )) >= 0 ) { secval = value.substring(pos + 4, value.length); value = value.substring(0,pos); } } if ( ityp != null ) { switch(ityp) { case "": case "plain": retval = this.win.document.createElement('span') retval.textContent = str; retval.wrapper = retval; if ( this.rowsection == this.body && typeof this.weblet != 'undefined' && this.weblet != null ) { if ( typeof this.weblet.inputlist_data[this.weblet.rids[colnum]] != 'undefined' ) { this.weblet.inputlist_data[name] = this.weblet.inputlist_data[this.weblet.rids[colnum]]; this.weblet.create_inputlist_output(retval, name, this.weblet.inputlist_data[name]["values"], 'table'); } } break; case "button": e = this.win.document.createElement("input"); e.datafield = e; e.valuefield = e; e.type = "button"; if ( value != null ) e.value = value; if ( name != null ) e.id = e.name = name; if ( this.navigator != "MSIE" ) e.appendChild(this.win.document.createTextNode(value)); e.win = this.win; e.vtype = "button"; retval = e; if ( this.inLength != 0 ) { e.weblet = this.weblet; e.onclick = function() { try { this.weblet[this.weblet.rids[colnum]].call(this.weblet); } catch(e) { this.weblet.exception("MneTable::ButonPress", e) } }; } break; case "rdbool": case "bool": case "checkbox": e = this.win.document.createElement("input"); e.type = 'checkbox'; e.vtype = 'bool'; e.defaultChecked = e.checked = ( value != null && value != "" && value != "0" && String(value).substr(0,1) != 'f' ); if ( ityp == 'rdbool' ) e.disabled = "disabled"; MneMisc.prototype.eleMkInputsSingle.call(this, e); if ( name != null ) e.wrapper.datafield.id = e.wrapper.datafield.name = name; e.wrapper.weblet = this.weblet; e.valuefield.value = ( e.defaultChecked ) ? "1" : "0"; e.secvalfield = this.win.document.createElement("input"); e.secvalfield.type = "hidden"; e.secvalfield.vtype = "bool"; e.secvalfield.checkbox = e.lastChild; e.secvalfield.value = secval; retval = e.wrapper; break; case "selection": var v; if ( name == null ) name = 'selection'; e = this.win.document.createElement("select"); MneMisc.prototype.eleMkSelectsSingle.call(this, e); e.wrapper.datafield = e; e.wrapper.valuefield = e; e.wrapper.weblet = this.weblet; e.id = e.name = name; e.vtype = "selection"; e.win = this.win; e.onchange = MneMisc.prototype.inOnmodify; e.onmodify = this.modify_function; e.table = this; if ( this.input.length == 0 ) { while ( value != "" ) { if ( ( pos = value.indexOf("#")) < 0 ) { v = value; value = ""; } else { v = value.substring(0, pos); value = value.substring(pos+1); } ee = this.win.document.createElement("option"); if ( ( pos = v.indexOf("%")) >= 0 ) { ee.value = v.substring(0,pos); v = v.substring(pos+1); ee.text = v; } else { ee.value = v; ee.text = v; } e.appendChild(ee); } } else { e.oldvalue = value; if ( typeof this.weblet.inputlist_data[this.weblet.rids[colnum]] != 'undefined' ) { this.weblet.inputlist_data[e.id] = this.weblet.inputlist_data[this.weblet.rids[colnum]]; ee = this.weblet.create_inputlist_select(e, e.id, this.weblet.inputlist_data[e.id]["values"], 'table', this.weblet.inputlist_data[e.id]["result"]); ee.datafield = e; e = ee; this.weblet.inputlist_data[this.weblet.rids[colnum]].result = e.values; } e.wrapper.datafield.value = value; } retval = e.wrapper; break; case "hidden": e = this.win.document.createElement("div"); e.appendChild(this.win.document.createTextNode(value)); ee = this.win.document.createElement("input"); ee.type = "hidden"; ee.wrapper = ee; ee.wrapper.weblet = this.weblet; if ( name != null ) ee.id = ee.name = name; e.datafield = ee; ee = e.appendChild(ee); ee.win = this.win; ee.vtype = "hidden"; if ( name != null ) ee.id = ee.name = name; if ( value != null ) ee.value = value; e.vtype = "hidden"; e.win = this.win; retval = e; break; case 'html': e = this.win.document.createElement("div"); e.className = 'shtml'; e.style.position = "relative"; e.weblet = this.weblet; e.vtype = "html"; e.datafield = this.win.document.createElement("input"); e.datafield.type = "hidden"; e.datafield.value = value; retval = e; if ( value != '' ) { this.weblet.eleMkClass(e, 'modifywait', true, 'modify'); e.innerHTML = '#mne_lang#warte auf Daten'; var ajax = new MneAjax(this.win); ajax.loadReadyObj = e; ajax.loadReady = function() { if ( this.req.readyState == 4 ) this.loadReadyObj.innerHTML = ajax.req.responseText; this.loadReadyObj.weblet.eleMkClass(this.loadReadyObj, 'modifyno', true, 'modify'); } ajax.load( "/xmltext/html.html", { xmltext : value, size : 504 }, true ); } e.onmouseover = function() { var diff = this.offsetHeight - this.scrollHeight; if ( diff > 0 ) return; this.style.maxHeight = this.scrollHeight + "px"; this.parentNode.style.height = this.scrollHeight + "px"; } e.onmouseout = function() { this.style.maxHeight = ''; this.parentNode.style.height = ''; } break; case 'ehtml': e = this.win.document.createElement("div"); e.weblet = this.weblet; e.className = 'ehtml'; e.style.position = "relative"; e.vtype = "html"; e.aname = "ehtml_" + rownum + "_" + colnum; e.rownum = rownum; e.colnum = colnum; e.table = this; e.datafield = this.win.document.createElement("input"); e.datafield.type = "hidden"; e.datafield.value = value; e.datafield.aname = "ehtml_" + rownum + "_" + colnum; e.innerHTML = "&nbsp;"; retval = e; e.onclick = function() { if ( typeof this.weblet != 'undefined' && this.weblet != null ) { if ( this.rownum != this.table.act_rownum ) { var ele = this; while(ele.tagName != "TD" && ele != null ) ele = ele.parentNode; if ( ele != null ) this.table.findCell(ele); } { var p = this.weblet.parent.popups['rte']; var w = this.weblet; var s = this; window.setTimeout(function() { s.popup = p p.show( p.weblet.initpar.popup_resize != false, p.weblet.initpar.popup_repos == true ); p.weblet.showValue(w, { datafield : s.datafield, htmlfield : s }); p.weblet.onbtnobj = w; w.obj.rte = p; },10) } } } e.onmouseover = function() { var diff = this.offsetHeight - this.scrollHeight; if ( diff > 0 ) return; this.style.maxHeight = this.scrollHeight + "px"; this.parentNode.style.height = this.scrollHeight + "px"; } e.onmouseout = function() { this.style.maxHeight = ''; this.parentNode.style.height = ''; } e.onbtnclick = function(id, button) { this.weblet.eleMkClass(this, 'modifyok', true, 'modify'); this.popup.onbtnobj = null; } if ( value != '' ) { this.weblet.eleMkClass(e, 'modifywait', true, 'modify'); e.innerHTML = '#mne_lang#warte auf Daten'; var ajax = new MneAjax(this.win); ajax.loadReadyObj = e; ajax.loadReady = function() { if ( this.req.readyState == 4 ) this.loadReadyObj.innerHTML = ajax.req.responseText; this.loadReadyObj.weblet.eleMkClass(this.loadReadyObj, 'modifyno', true, 'modify'); } ajax.load( "/xmltext/html.html", { xmltext : value, size : 504 }, true ); } break; case 'textarea': e = this.win.document.createElement("textarea"); e.datafield = e; e.valuefield = e; e.onkeyup = MneMisc.prototype.inOnmodify; e.onkeydown = function(evt) { if ( evt.shiftKey && evt.keyCode == 13 && this.className.indexOf("modifywrong") < 0 ) { if ( typeof this.onsave == 'function' ) { window.MneDocEvents.prototype.cancelEvent (win,e); if ( this.onsave() == false ) { MneMisc.prototype.eleMkClass(target, "modify", false, "modify"); } } } }; e.onsave = this.return_function; e.table = this; e.win = this.win; if ( name != null ) e.id = e.name = name; if ( value != null ) e.value = value; e.onmodify = this.modify_function; this.eleMkClass(e, this.tdclass[colnum], true); ( value.indexOf("\n") != -1 ) ? this.eleMkClass(e,"multicol", true) : this.eleMkClass(e,"multicol", false); e.rownum = rownum; e.colnum = colnum; e.onfocus = function() { if ( this.table.act_rownum != this.rownum ) { this.table.findCell(this.table.body.rows[this.rownum].cells[this.table.col2tab(this.colnum)], false); this.focus(); } }; if ( typeof this.weblet != 'undefined' && this.weblet != null ) { if ( typeof this.weblet.inputlist_data[this.weblet.rids[colnum]] != 'undefined' ) { this.weblet.inputlist_data[e.id] = this.weblet.inputlist_data[this.weblet.rids[colnum]]; ee = this.weblet.create_inputlist_select(e, e.id, this.weblet.inputlist_data[e.id]["values"], 'table'); ee.datafield = e; e = ee; } } retval = e; break; default: e = this.win.document.createElement("input"); MneMisc.prototype.eleMkInputsSingle.call(this, e); e.wrapper.datafield = e; e.wrapper.valuefield = e; if ( typeof this.weblet != 'undefined' && this.weblet != null ) { e.wrapper.weblet = this.weblet; e.weblet = this.weblet; e.mne_fieldnum = this.weblet.obj.fields.length; this.weblet.obj.fields[this.weblet.obj.fields.length] = e; } switch(ityp) { case "float": case "double": e.type = "text"; e.vtype = "float"; e.onkeyup = MneMisc.prototype.inOnfloat; if ( minval != null ) e.minValue = minval; if ( maxval != null ) e.maxValue = maxval; break; case "integer": e.type = "text"; e.vtype = "long"; e.onkeyup = MneMisc.prototype.inOninteger; if ( minval != null ) e.minValue = minval; if ( maxval != null ) e.maxValue = maxval; break; case "time": e.type = "text"; e.vtype = "time"; e.onkeyup = MneMisc.prototype.inOntime; break; case "clocktime": e.type = "text"; e.vtype = "time"; e.onkeyup = MneMisc.prototype.inOnclocktime; break; case "date": e.type = "text"; e.vtype = "date"; e.onkeyup = MneMisc.prototype.inOndate; break; default: { e.onkeyup = MneMisc.prototype.inOnmodify; if ( typeof this.weblet != 'undefined' && this.weblet != null && typeof this.weblet.regexps[colnum] != 'undefined' ) { this.weblet.create_checkpopup(e, this.weblet.regexps[colnum]); } e.type = "text"; e.vtype = ityp; } } e.table = this; e.inputtyp = ityp; e.onkeydown = MneMisc.prototype.inOnkeydown; e.win = this.win; if ( name != null ) e.id = e.name = name; if ( value != null ) this.showInput(e, value, ityp); e.onmodify = this.modify_function; e.onreturn = this.return_function; this.eleMkClass(e, this.tdclass[colnum], true); e.rownum = rownum; e.colnum = colnum; e.onfocus = function() { this.table.findCell(this.table.body.rows[this.rownum].cells[this.table.col2tab(this.colnum)], false); }; if ( typeof this.weblet != 'undefined' && this.weblet != null ) { if ( typeof this.weblet.inputlist_data[this.weblet.rids[colnum]] != 'undefined' ) { this.weblet.inputlist_data[e.id] = this.weblet.inputlist_data[this.weblet.rids[colnum]]; if ( e.tagName == "SELECT" ) { ee = this.weblet.create_inputlist_select(e, e.id, this.weblet.inputlist_data[e.id]["values"], 'table'); } else { ee = this.weblet.create_inputlist_input(e, e.id, this.weblet.inputlist_data[e.id]["values"]); } ee.datafield = e; e = ee; } } retval = e.wrapper; break; } } else { this.error("MneTable::mkContent - Format <" + value + ":" + errval + "> ist falsch"); return this.win.document.createTextNode("Format <" + value + ":" + errval + "> ist falsch"); } return retval; }; this.equal_table = function(section, arg ) { var s,secs; var max_anzahl; var i,j,n; max_anzahl = arg.length; s = null; secs = null; for ( s in this.sections ) { secs = this.sections[s]; if ( secs != null && secs.data.length > 0 ) if ( max_anzahl < secs.data[0].length ) max_anzahl = secs.data[0].length; } for ( s in this.sections ) { if ( secs != null && secs.data.length > 0 ) { for( i=0; i<secs.data.length; i++ ) { for ( n=secs.data[i].length; n < max_anzahl; n++ ) { if ( typeof this.invisible[n] == 'undefined' ) this.invisible[n] = false; secs.data[i][n] = ""; if ( this.invisible[n] != true ) { td = this.win.document.createElement("td"); td.className = this.classname + this.borderclass; if ( typeof this.tdclass[n] != 'undefined' ) this.eleMkClass(td, this.tdclass[n], true); td.table = this; td.section = section.sname; td.rownum = i; td.colnum = n; if ( this.ignoreEvent != true && this.classname != 'ignore' ) { td.onclick = function(e) { this.table.act_event = e; try { this.table.findCell(this); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.ondblclick = function(e) { this.table.act_event = e; try { this.table.findCell(this,true); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.onmouseover = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, true); }; td.onmouseout = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, false); }; } td.style.whiteSpace = "nowrap"; td.style.emptyCells = "show"; if ( typeof this.cellWidth[n] != 'undefined' ) tr.cells[n].style.width = this.cellWidth[n]; if ( typeof this.cellAlign[n] != 'undefined' ) tr.cells[n].style.textAlign = this.cellAlign[n]; td.appendChild(this.mkContent(secs.data[i][n],n,i)); td.appendChild(this.win.document.createTextNode(" ")); td.datafield = td.firstChild.datafield; td.secvalfield = td.firstChild.secvalfield; secs.rows[i].appendChild(td); } } } } } return max_anzahl; }; this.addRowSection = function(section, arg) { var tr; var td; var r,i; var max_anzahl = 0; this.rowsection = section; if ( section.rows.length >= this.max_rownum ) { r = section.data.length; this.mkNextbutton(); section.data[r] = new Array(); section.origdata[r] = new Array(); for ( i=0; i<arg.length; i++ ) { section.data[r][i] = new String(arg[i]); section.origdata[r][i] = arg[i]; } return r; } if ( this.fixcols == true ) max_anzahl = this.equal_table( section, arg ); while ( section.data.length <= section.rows.length ) { section.data[section.data.length] = new Array(); section.origdata[section.origdata.length] = new Array(); } r = section.rows.length; tr = this.win.document.createElement("tr"); tr.className = this.classname; section.appendChild(tr); for ( i=0; i<arg.length; i++ ) { if ( typeof this.invisible[i] == 'undefined' ) this.invisible[i] = false; section.data[r][i] = new String(arg[i]); section.origdata[r][i] = arg[i]; if ( this.invisible[i] != true ) { td = this.win.document.createElement("td"); td.className = this.classname + this.borderclass; if ( typeof this.tdclass[i] != 'undefined' ) this.eleMkClass(td, this.tdclass[i], true); td.table = this; td.section = section.sname; td.rownum = r; td.colnum = i; if ( this.ignoreEvent != true && this.classname != 'ignore' ) { td.onclick = function(e) { this.table.act_event = e; try { this.table.findCell(this); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.ondblclick = function(e) { this.table.act_event = e; try { this.table.findCell(this,true); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.onmouseover = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, true); }; td.onmouseout = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, false); }; } td.style.whiteSpace = "nowrap"; td.style.emptyCells = "show"; td.appendChild(this.mkContent(section.data[r][i].valueOf(),i,r)); td.datafield = td.firstChild.datafield; td.secvalfield = td.firstChild.secvalfield; tr.appendChild(td); if ( arg[i] == "") td.appendChild(this.win.document.createTextNode(" ")); if ( typeof this.cellWidth[i] != 'undefined' ) tr.cells[i].style.width = this.cellWidth[i]; if ( typeof this.cellAlign[i] != 'undefined' ) tr.cells[i].style.textAlign = this.cellAlign[i]; } else if ( this.rowsection == this.body ) { if ( this.input[i] == 'hidden' ) { section.data[r][i].datafield = this.doc.createElement("input"); section.data[r][i].datafield.value = arg[i]; } } } for ( ; i<max_anzahl; i++ ) { section.data[r][i] = new String(""); section.origdata[r][i] = ""; if ( this.invisible[i] != true ) { td = this.win.document.createElement("td"); td.className = this.classname + this.borderclass; if ( typeof this.tdclass[i] != 'undefined' ) this.eleMkClass(td, this.tdclass[i], true); td.table = this; td.section = section.sname; td.rownum = r; td.colnum = i; if ( this.ignoreEvent != true && this.classname != 'ignore' ) { td.onclick = function(e) { this.table.act_event = e; try { this.table.findCell(this); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.ondblclick = function(e) { this.table.act_event = e; try { this.table.findCell(this,true); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.onmouseover = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, true); }; td.onmouseout = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, false); }; } td.style.whiteSpace = "nowrap"; td.style.emptyCells = "show"; if ( typeof this.cellWidth[i] != 'undefined' ) tr.cells[i].style.width = this.cellWidth[i]; if ( typeof this.cellAlign[i] != 'undefined' ) tr.cells[i].style.textAlign = this.cellAlign[i]; td.appendChild(this.win.document.createTextNode("")); td.appendChild(this.win.document.createTextNode(" ")); tr.appendChild(td); } } return r; }; this.addRow = function() { var arg = this.addRow.arguments; return this.addRowSection(this.body, arg ); }; this.add = function() { var arg = this.add.arguments; return this.addRowSection(this.body, arg ); }; this.addHead = function() { var arg = this.addHead.arguments; if ( this.head == null ) { this.head = this.table.createTHead(); this.head.className = this.classname; this.head.sname = 'head'; this.head.data = new Array(); this.head.origdata = new Array(); this.sections["head"] = this.head; } return this.addRowSection(this.head, arg ); }; this.delRowSection = function(section, num) { var i,c,r; if ( num < 0 || num >= section.rows.length ) return; section.deleteRow(num); for ( i=num + 1; i<section.data.length; i++) { section.data[i - 1] = section.data[i]; section.origdata[i - 1] = section.origdata[i]; } delete section.data[i-1]; delete section.origdata[i-1]; section.data.length = section.data.length - 1; section.origdata.length = section.origdata.length - 1; for ( r=0; r<section.rows.length; r++ ) for ( c=0; c<section.rows[r].cells.length; c++ ) { section.rows[r].cells[c].rownum = r; section.rows[r].cells[c].cellnum = c; } }; this.delRow = function(num) { this.reset(); this.delRowSection(this.body, num); }; this.delHead = function(num) { if ( this.head != null ) this.delRowSection(this.head, num); }; this.clearHead = function() { if ( this.head == null ) return; if ( this.act_section == this.head) this.reset(); try { if ( this.head.parentNode != null ) this.table.removeChild(this.head); } catch(e) { this.exception("uuu",e); } this.sections["head"] = this.head = null; }; this.clearBody = function() { this.reset(); if ( this.next_button != null && this.next_button.parentNode != null ) { this.frame.removeChild(this.next_button); this.next_button = null; } if ( this.body.parentNode != null ) this.table.removeChild(this.body); this.body = this.win.document.createElement("tbody"); this.table.appendChild(this.body); this.body.className = this.classname; this.body.sname = 'body'; this.body.data = new Array(); this.body.origdata = new Array(); this.sections["body"] = this.body; this.max_rownum = 10000; this.max_rownum_step = 500; }; this.clear = function() { this.clearHead(); this.clearBody(); this.reset(); }; this.getHead = function( row, col ) { if ( this.head != null && row >= 0 && col >= 0 && row < this.head.data.length && col < this.head.data[0].length ) return this.head.data[row][col]; return null; }; this.getDatafield = function( row, col ) { if ( row >= 0 && col >= 0 && row < this.body.data.length && col < this.body.data[0].length ) { if ( this.invisible[col] != true ) { td = this.body.rows[row].cells[this.col2tab(col)]; return ( typeof td.datafield == 'object') ? td.datafield : null; } else { return ( typeof this.body.data[row][col].datafield == 'object' ) ? this.body.data[row][col].datafield : null; } } return null; } this.getData = function( row, col, orig ) { var retval = null; if ( row >= 0 && col >= 0 && row < this.body.data.length && col < this.body.data[0].length ) { if ( typeof orig != 'undefined' && orig == true ) retval = this.body.origdata[row][col]; else if ( this.invisible[col] != true ) { var td = this.body.rows[row].cells[this.col2tab(col)]; if ( typeof td.datafield == 'object') { if ( td.datafield.mne_timevalue ) retval = td.datafield.mne_timevalue; else retval = td.datafield.value; } else { retval = this.body.data[row][col].valueOf(); } } else { retval = this.body.data[row][col].valueOf(); } } return retval; }; this.setData = function( row, col, value, typ ) { var retval = null; if ( row >= 0 && col >= 0 && row < this.body.data.length && col < this.body.data[0].length ) { var str = this.txtFormat.call(this, value, typ); var d = this.body.data[row][col].datafield; this.body.data[row][col] = new String(str); this.body.origdata[row][col] = value; if ( typeof d == 'object' ) { d.value = str; this.body.data[row][col].datafield = d; } if ( this.invisible[col] != true ) { var td = this.body.rows[row].cells[this.col2tab(col)]; if ( typeof td.datafield == 'object' ) this.showInput(td.datafield, value, typ, true); else this.showOutput(td, value, typ ) retval = this.body.rows[row].cells[this.col2tab(col)]; } return retval; } throw "#mne_lang#Zeilennummer oder Spaltennummer sind ausserhalb des Bereichs" + "[" + row + "][" + col + "]"; }; this.getLength = function() { return this.body.data.length; }; this.getWidth = function() { if ( this.body.data.length >0 ) return this.body.data[0].length; return 0; }; this.up = function(p_pos1, p_pos2) { var r1,r2; var tmp; var pos1 = p_pos1; var pos2 = p_pos2; if ( typeof pos1 != 'number' ) pos1 = 1; else pos1++; if ( typeof pos2 != 'number' ) pos2 = this.body.rows.length - 1; if ( this.act_section != this.body || this.act_rownum < pos1 || this.act_rownum > pos2 ) { if ( this.act_rownum < 0 ) alert("#mne_lang#keine Zeile ausgewählt"); return; } r1 = this.body.rows[this.act_rownum]; r2 = this.body.rows[this.act_rownum - 1]; r1.parentNode.removeChild(r1); r2.parentNode.insertBefore(r1,r2); tmp = this.body.data[this.act_rownum]; this.body.data[this.act_rownum] = this.body.data[this.act_rownum - 1]; this.body.data[this.act_rownum - 1] = tmp; this.act_rownum--; }; this.down = function(p_pos1, p_pos2) { var r1,r2; var tmp; var pos1 = p_pos1; var pos2 = p_pos2; if ( typeof pos1 != 'number' ) pos1 = 0; if ( typeof pos2 != 'number' ) pos2 = this.body.rows.length - 2; else pos2 = pos2 - 1; if ( this.act_section != this.body || this.act_rownum < pos1 || this.act_rownum > pos2 ) { if ( this.act_rownum < 0 ) alert("#mne_lang#keine Zeile ausgewählt"); return; } r1 = this.body.rows[this.act_rownum]; r2 = this.body.rows[this.act_rownum + 1]; r2.parentNode.removeChild(r2); r1.parentNode.insertBefore(r2,r1); tmp = this.body.data[this.act_rownum]; this.body.data[this.act_rownum] = this.body.data[this.act_rownum + 1]; this.body.data[this.act_rownum + 1] = tmp; this.act_rownum++; }; this.getColnum = function(i) { if ( this.head != null && i >= 0 && this.head.rows.length > 0 && this.head.rows[0].cells.length > i ) return this.head.rows[0].cells[i].colnum; else if ( i >= 0 && this.body.rows.length > 0 && this.body.rows[0].cells.length > i ) return this.body.rows[0].cells[i].colnum; else return 0; }; this.unselect = function() { this.findCell(null); }; this.setInvisible = function( col ) { if ( col > this.invisible.length || this.invisible[col] == true ) { this.invisible[col] = true; return; } var s; var r; var tab_col = this.col2tab(col); this.invisible[col] = true; s = null; for ( s in this.sections ) { if ( typeof this.sections[s] != 'undefined' && this.sections[s] != null ) { for ( r = 0; r < this.sections[s].rows.length; r++ ) if ( this.sections[s].rows[r].cells.length > tab_col ) this.sections[s].rows[r].deleteCell(tab_col); } } }; this.setVisible = function ( col ) { if ( col > this.invisible.length || this.invisible[col] != true ) return; var s; var r; var tab_col = this.col2tab(col); s = null; for ( s in this.sections ) { if ( typeof this.sections[s] != 'undefined' && this.sections[s] != null ) { for ( r = 0; r < this.sections[s].rows.length; r++ ) { if ( this.sections[s].rows[r].cells.length >= tab_col ) { td = this.win.document.createElement("td"); if ( typeof this.sections[s].data[r][col] == 'undefined' ) this.sections[s].data[r][col] = ""; td.appendChild(this.mkContent(this.sections[s].data[r][col],col,r)); if ( this.sections[s].data[r][col] == "" ) td.appendChild(this.win.document.createTextNode(" ")); td.className = this.classname + this.borderclass; if ( typeof this.tdclass[col] != 'undefined' ) this.eleMkClass(td, this.tdclass[col], true); td.table = this; td.section = s; td.rownum = r; td.colnum = col; td.datafield = td.firstChild.datafield; td.secvalfield = td.firstChild.secvalfield; if ( this.ignoreEvent != true && this.classname != 'ignore' ) { td.onclick = function(e) { this.table.act_event = e; try { this.table.findCell(this); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.ondblclick = function(e) { this.table.act_event = e; try { this.table.findCell(this,true); } catch(ex) { this.table.act_event = null; throw ex}; this.table.act_event = null }; td.onmouseover = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, true); }; td.onmouseout = function(e) { this.table.eleMkClass(this, this.table.mouseoverclass, false); }; } td.style.whiteSpace = "nowrap"; td.style.emptyCells = "show"; if ( typeof this.cellWidth[col] != 'undefined' ) tr.cells[i].style.width = this.cellWidth[col]; if ( typeof this.cellAlign[col] != 'undefined' ) tr.cells[i].style.textAlign = this.cellAlign[col]; if ( this.sections[s].rows[r].cells.length == tab_col ) this.sections[s].rows[r].appendChild(td); else this.sections[s].rows[r].insertBefore(td, this.sections[s].rows[r].cells[tab_col]); } } } } this.invisible[col] = false; }; this.sort = function(col) { var i,n; var str; var length; var colnum; if ( this.body.data.length > 0 ) { length = this.body.data[0].length; colnum = this.body.rows[0].cells[col].colnum; } else if ( this.head != null && this.head.data.length > 0 ) { length = this.head.data[0].length; colnum = this.head.rows[0].cells[col].colnum; } else return; if ( col < 0 || col > length ) return; this.body.data.sort( function(x1, x2) { if ( x1[colnum] < x2[colnum] ) return -1; else if ( x1[colnum] == x2[colnum] ) return 0; else return 1; }); while ( this.body.hasChildNodes() > 0 ) this.body.removeChild(this.body.firstChild); for ( i=0; i<this.body.data.length && i < this.max_rownum; i++ ) { if ( this.body.data[i].length > 0 ) { str = "this.addRow('" + this.txtMascarade(this.body.data[i][0]) + "'"; for ( n=1; n < this.body.data[i].length; n++ ) str += ",'" + this.txtMascarade(this.body.data[i][n].valueOf()) + "'"; str += ");"; eval(str); } } this.reset(); if ( this.head != null && this.head.rows.length > 0 ) this.findCell(this.head.rows[0].cells[col], false, true); }; this.show_next = function() { var i,n; var str; if ( this.body.data.length < this.max_rownum ) return; i = this.max_rownum; this.max_rownum += this.max_rownum_step; for ( ; i<this.body.data.length && i < this.max_rownum; i++ ) { if ( this.body.data[i].length > 0 ) { str = "this.addRow('" + this.txtMascarade(this.body.data[i][0].valueOf()) + "'"; for ( n=1; n < this.body.data[i].length; n++ ) str += ",'" + this.txtMascarade(this.body.data[i][n].valueOf()) + "'"; str += ");"; eval(str); } } if ( typeof this.scroll_form != 'undefined' ) this.scroll_form.scrollTop = this.scroll_form.firstChild.clientHeight; }; }; MneAjaxTable.prototype = new MneMisc(window);
/** * @author v.lugovksy * created on 16.12.2015 */ (function () { 'use strict'; angular.module('ROA.theme.directives') .service('dashboardTodo', dashboardTodo); /** @ngInject */ function dashboardTodo() { } })();
define_browser_object_class( "page-title", "Get the title of the current page", function (I, prompt) { check_buffer(I.buffer, content_buffer); yield co_return(I.buffer.document.title); }); define_key(content_buffer_normal_keymap, "* p", "browser-object-page-title"); // So `* p c` will copy the title of the current buffer
import mongoose from 'mongoose'; function genToken() { return (new mongoose.Types.ObjectId).toHexString(); } const GENDERS = ['m', 'f', 'o']; const userSchema = new mongoose.Schema({ name: { type: String, trim: true }, token: { type: String, trim: true, unique: true, default: genToken }, age: { type: Number, min: 0, max: 200 }, gender: { type: String, enum: GENDERS } }); if (!userSchema.options.toJSON) { userSchema.options.toJSON = {}; } if (!userSchema.options.toObject) { userSchema.options.toObject = {}; } userSchema.options.toJSON.transform = userSchema.options.toObject.transform = (doc, ret) => { delete ret.token; delete ret.__v; }; userSchema.statics.findByToken = function (token, callback) { return this.findOne({ token }, (err, user) => { if (err) { return callback(err); } if (!user) { return callback(new Error('Unable to find user')); } return callback(false, user); }); }; const User = mongoose.model('User', userSchema); export default User;
import Big from 'big.js' import deckToText, { deckToPermutation, permutationToFactoradic, factoradicToNumber, toBase, baseToText } from '../src/decode' describe('decode', () => { test('works on a small deck and charset', () => { // these parameters work because 4! >= 2^4 const cardIndexes = { 'W': 0, 'X': 1, 'Y': 2, 'Z': 3 } const charset = [' ', 'X'] const message = deckToText(['W', 'X', 'Z', 'Y'], cardIndexes, charset, 4) expect(message).toBe(' X') }) }) describe('deckToPermutation', () => { test('works on a deck of three', () => { const deck = ['4S', '2S', '3S'] const order = { '2S': 0, '3S': 1, '4S': 2 } const permutation = deckToPermutation(deck, order) expect(permutation).toEqual([2, 0, 1]) }) }) describe('permutationToFactoradic', () => { test('works on a small permutation', () => { const permutation = [2, 0, 1] const factoradic = permutationToFactoradic(permutation) expect(factoradic).toEqual([2, 0, 0]) }) test('works on the wikipedia example', () => { const permutation = [1, 5, 0, 6, 3, 4, 2] const factoradic = permutationToFactoradic(permutation) expect(factoradic).toEqual([1, 4, 0, 3, 1, 1, 0]) }) }) describe('factoradicToNumber', () => { test('works on a small factoradic', () => { expect(factoradicToNumber([2, 0, 0]).eq(new Big(4))).toBe(true) }) test('works on the wikipedia example', () => { expect(factoradicToNumber([3, 4, 1, 0, 1, 0]).eq(new Big(463))).toBe(true) }) }) describe('toBase', () => { test('Works on small problems', () => { expect(toBase(new Big(8), 2)).toEqual([1, 0, 0, 0]) expect(toBase(new Big(0), 2)).toEqual([]) expect(toBase(new Big(15), 2)).toEqual([1, 1, 1, 1]) }) }) describe('baseToText', () => { test('Works on a small charset', () => { const charset = ['A', 'B', 'C', 'D', 'E'] expect(baseToText([1, 4, 4], charset)).toBe('BEE') }) })
import { MaterialCommunityIcons } from "@expo/vector-icons"; import React, { useState } from "react"; import { StyleSheet, TouchableOpacity, TextInput, View, Text, ToastAndroid, Image, Dimensions, ScrollView, } from "react-native"; import firebase from "firebase/app"; import { Formik } from "formik"; import * as Yup from "yup"; import * as ImagePicker from "expo-image-picker"; import { Colors } from "../config"; import ErrorMessage from "../components/Auth/ErrorMessage"; import { db } from "../config/firebase"; import { useAuthContext } from "../contexts/AuthProvider"; import PostsCustomHeader from "../components/PostsCustomHeader"; export default function AddPostScreen({ navigation }) { const { currentUser } = useAuthContext(); const [imageUrl, setImageUrl] = useState(""); let openImagePickerAsync = async () => { let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("Permission to access camera roll is required!"); return; } let pickerResult = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, quality: 0.5, }); setImageUrl(pickerResult.uri); }; const validationSchema = Yup.object().shape({ caption: Yup.string() .max(300, "Characters cannot be more than 300") .trim() .label("Caption"), }); const handleSubmit = values => { db.collection("users") .doc(currentUser.uid) .collection("posts") .add({ caption: values.caption, imageUrl, user: { username: currentUser.displayName, imageUrl: "https://phantom-marca.unidadeditorial.es/cad57253bb118bb77a748d848778cc81/f/webp/assets/multimedia/imagenes/2021/10/12/16340512953884.jpg", }, createdAt: firebase.firestore.FieldValue.serverTimestamp(), likes: 0, comments: [], }) .then(() => ToastAndroid.show("Post added", ToastAndroid.SHORT)) .catch(err => { console.log(err.message); ToastAndroid.show("Post added", ToastAndroid.SHORT); }); navigation.goBack(); }; return ( <ScrollView> <View style={styles.container}> <PostsCustomHeader navigation={navigation} headerTitle="New Post" /> <Formik initialValues={{ caption: "" }} validationSchema={validationSchema} onSubmit={handleSubmit} > {({ handleSubmit, handleChange, errors, values }) => ( <> <View style={styles.inputsContainer}> <TouchableOpacity style={styles.imageUploadContainer} onPress={openImagePickerAsync} > {!imageUrl ? ( <MaterialCommunityIcons name="camera" color={Colors.darkGrey} size={100} /> ) : ( <Image source={{ uri: imageUrl }} style={{ width: "100%", height: "100%" }} /> )} </TouchableOpacity> <View style={styles.textInputContainer}> <TextInput multiline style={styles.textInput} placeholder="Write a caption..." placeholderTextColor={Colors.grey} value={values.caption} onChangeText={handleChange("caption")} /> {errors.caption && <ErrorMessage error={errors.caption} />} </View> </View> <TouchableOpacity style={styles.shareButtonContainer} onPress={handleSubmit} > <Text style={styles.shareText}>Share</Text> </TouchableOpacity> </> )} </Formik> </View> </ScrollView> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", paddingHorizontal: 20, }, inputsContainer: { paddingTop: 20, }, imageUploadContainer: { width: Dimensions.get("window").width - 20, height: Dimensions.get("window").width - 20, overflow: "hidden", borderRadius: 10, backgroundColor: Colors.lightgrey, justifyContent: "center", alignItems: "center", }, textInputContainer: { height: 40, borderColor: Colors.grey, borderRadius: 4, borderWidth: 1, marginTop: 20, justifyContent: "center", }, textInput: { height: "100%", fontSize: 16, color: Colors.light, paddingHorizontal: 10, }, shareButtonContainer: { marginTop: 10, alignSelf: "center", }, shareText: { color: Colors.light, fontSize: 18, fontWeight: "600", }, });
function BobbyG(){ console.log(Math.round(Math.random()*10)); } BobbyG();
const path = require('path'); function resolve(url) { return path.resolve(path.join(__dirname, url)); } module.exports = { mode: 'production', // production:发布模式 development:开发模式 entry: { index: resolve('../src/index.js'), datetime: resolve('../src/datetime.js'), image: resolve('../src/image.js'), tool: resolve('../src/tool.js'), util: resolve('../src/util.js'), validator: resolve('../src/validator.js'), route: resolve('../src/route.js'), }, output: { filename: '[name].js', path: path.resolve(path.join(__dirname, '../lib')), libraryTarget: 'this', // 打包为前后端通用模块 }, };
import React, { Component } from 'react' import {ThemeProvider as MuiThemeProvider} from "@material-ui/styles"; import {AppBar, TextField, Button, Dialog, Toolbar, IconButton, Typography} from "@material-ui/core"; import MenuIcon from "@material-ui/icons/Menu"; export class FormUserDetails extends Component { continue = e => { e.preventDefault() this.props.nextStep() } render() { const { values, handleChange } = this.props return ( <MuiThemeProvider> <> <Dialog open fullWidth maxWidth='sm' > <div> <AppBar position="static"> <Toolbar variant="dense"> <IconButton edge="start" color="inherit" aria-label="menu"> <MenuIcon /> </IconButton> <Typography variant="h6" color="inherit"> Enter User Details </Typography> </Toolbar> </AppBar> </div> <TextField placeholder="Enter Your First Name" label="First Name" onChange={handleChange('firstName')} defaultValue={values.firstName} margin="normal" fullWidth /> <br /> <TextField placeholder="Enter Your Last Name" label="Last Name" onChange={handleChange('lastName')} defaultValue={values.lastName} margin="normal" fullWidth /> <br /> <TextField placeholder="Enter Your Email" label="Email" onChange={handleChange('email')} defaultValue={values.email} margin="normal" fullWidth /> <br /> <Button color="primary" variant="contained" onClick={this.continue} > Continue </Button> </Dialog> </> </MuiThemeProvider> ) } } export default FormUserDetails
import axios from 'axios'; import { put, takeEvery } from 'redux-saga/effects'; function* deleteHolding(action) { console.log('in deleteHolding saga! action.payload is:', action.payload); try { const response = yield axios({ method: 'DELETE', url: '/api/crypto/holdings', data: action.payload }); yield put({ type: 'FETCH_USER_HOLDINGS'}); } catch (error) { console.log('Failure to DELETE line in delete.saga.js', error); } } function* deleteHoldingSaga() { yield takeEvery('DELETE_HOLDING', deleteHolding); //important } export default deleteHoldingSaga;
import {combineReducers} from 'redux' import User from './user/UsersReducers' import Chatrooms from './chatroom/ChatroomReducer' export default combineReducers({ User, Chatrooms })
var MainCtrl = function ($scope) { $scope.title = "Ma première page" $scope.name = ""; }; /* Le scope ($scope) est ce qui fait le lien entre le contrôleur et la vue. Techniquement c'est un objet javascript, et les propriétés qu'on lui ajoute (variables et fonctions) sont accessibles dans la vue, elle sont en quelque sorte publiques. Mais il est égalemen possible de créer des variables et des fonctions privées (non accessibles dans la vue). */
var mongoose = require('mongoose'), {nanoid} = require("nanoid"), Schema = mongoose.Schema; var BadgeSchema = new Schema({ _id: { type: String, default: nanoid }, title: String, image: String, overrides: [String], cardDisplay: { type: Boolean, default: false }, description: String, colors: String }); module.exports = mongoose.model("Badge", BadgeSchema);
export const LOAD_DEFAULT_DATA = 'LOAD_DEFAULT_DATA'; export const CHANGE_CORRECT = 'CHANGE_CORRECT'; export const PUT_DATA = 'PUT_DATA';
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsGraphicEq = { name: 'graphic_eq', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 18h2V6H7v12zm4 4h2V2h-2v20zm-8-8h2v-4H3v4zm12 4h2V6h-2v12zm4-8v4h2v-4h-2z"/></svg>` };
import request from '@/utils/request'; export async function getStepForm(params) { return request('/api/userStepForms/'+params.pid+'/'+params.student_id, { }); } export async function getUserStore(params) { return request('/api/stores/'+params.pid+'/'+params.student_id, { }); }
const chai = require('chai'); const chaiHttp = require('chai-http'); const server = require('../../server'); const Concert = require('../../models/concert.model'); const Seat = require('../../models/seat.model'); const Day = require('../../models/day.model'); const Workshop = require('../../models/workshop.model'); chai.use(chaiHttp); const expect = chai.expect; const request = chai.request; describe('GET /api/concerts', () => { before(async () => { const testDay = new Day({ number: 2 }); const savedDay = await testDay.save(); dayId = savedDay._id; const testSeat = new Seat({ day: dayId, seat: 3, client: "Amanda Doe", email: "amandadoe@example.com" }); await testSeat.save(); const testConOne = new Concert({ _id: '5d9f1159f81ce8d1ef2bee48', performer: 'TestPerformer', genre: 'TestGenre', price: 5, day: dayId, image: 'con.png' }); await testConOne.save(); const testConTwo = new Concert({ _id: '5d9f1159f81ce8d1ef2bee49', performer: 'TestPerformer2', genre: 'TestGenre', price: 5, day: dayId, image: 'con.png' }); await testConTwo.save(); const testWorkshop = new Workshop({ name: 'Test', concertId: '5d9f1159f81ce8d1ef2bee48'}); await testWorkshop.save(); const testWorkshop1 = new Workshop({ name: 'Test1', concertId: '5d9f1159f81ce8d1ef2bee49' }); await testWorkshop1.save(); }); after(async () => { await Concert.deleteMany(); await Seat.deleteMany(); await Day.deleteMany(); await Workshop.deleteMany(); }); it('/ should return all concerts', async () => { const res = await request(server).get('/api/concerts'); expect(res.status).to.be.equal(200); expect(res.body).to.be.an('array'); expect(res.body.length).to.be.equal(2); }); it('/:id should return one concert by :id ', async () => { const res = await request(server).get('/api/concerts/5d9f1159f81ce8d1ef2bee48'); expect(res.status).to.be.equal(200); expect(res.body).to.be.an('object'); expect(res.body.performer).to.be.equal('TestPerformer'); }); it('/ should return concerts with tickets property showing number of available tickets', async () => { const res = await request(server).get('/api/concerts'); expect(res.body).to.be.an('array'); for (concert of res.body) { expect(concert.tickets).to.be.a('number'); expect(concert.tickets).to.be.equal(49); } }); it('/ should return concerts with workshops property with array of workshops', async () => { const res = await request(server).get('/api/concerts'); expect(res.body).to.be.an('array'); for (concert of res.body) { expect(concert.workshops).to.be.an('array'); expect(concert.workshops.length).to.be.equal(1); } }); });
const Batch = require('../model/batch'); exports.addSem = async (req, res) => { try { const batchData = req.batch; let body; body = { currentActiveSem: req.body.name, sem: [req.body], }; if (batchData.sem.length) { body = { sem: batchData.sem, currentActiveSem: req.body.name }; body.sem[batchData.sem.length - 1].endingDate = Date(); body['sem'].push(req.body); } await Batch.updateOne({ _id: batchData._id }, body); return res.json({ msg: "sem added" }); } catch (error) { return res.status(500).json({ error: "Error Occured" }); } } exports.listbatch = async (req, res) => { try { const query = req.query; const batchData = await Batch.find(query).populate('program'); return res.json({ data: batchData }); } catch (error) { return res.status(500).json({ error: "Error occured" }); } } exports.batchByID = async (req, res, next, id) => { try { if (!id.match(/^[0-9a-fA-F]{24}$/)) { return res.status(406).json({ status: false, error: "This batch is not acceptable" }); } const batchData = await Batch.findOne({ _id: id }); if (!batchData) return res.status(403).json({ status: false, error: "Batch is not found" }); req.batch = batchData; next(); } catch (error) { return res.status(500).json({ error: "Error Occured" }); } }
let postal = require('postal/lib/postal.lodash'); class EventMgr { constructor() { this.channel = postal.channel('anonymous'); } on(eventName, callback) { this.channel.subscribe(eventName, callback); } once(eventName, callback) { let subscription = this.channel.subscribe(eventName, (...args) => { subscription.unsubscribe(); callback(...args); }); } fire(eventName, params) { this.channel.publish(eventName, params); } } module.exports = new EventMgr();
import React from 'react'; import propTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; import FormControl from '@material-ui/core/FormControl'; import InputLabel from '@material-ui/core/InputLabel'; import useStyles from './View.style'; export default function View({ isCurrent, setIsCurrent }) { const classes = useStyles(); const handleChange = () => { setIsCurrent(!isCurrent); }; return ( <FormControl variant="outlined"> <InputLabel className={classes.label}> <FormattedMessage id="view" /> </InputLabel> <Select className={classes.select} classes={{ root: classes.selectRoot }} variant="outlined" defaultValue="current" onChange={handleChange} label={<FormattedMessage id="view" />} > <MenuItem className={classes.item} value="current" > <FormattedMessage id="currentState" /> </MenuItem> <MenuItem className={classes.item} value="upcoming" > <FormattedMessage id="upcomingState" /> </MenuItem> </Select> </FormControl> ); } View.propTypes = { isCurrent: propTypes.bool.isRequired, setIsCurrent: propTypes.func.isRequired, };
import React from "react"; import ReactDOM from "react-dom"; import Page from "./Page"; const app = document.getElementById('app'); ReactDOM.render(<Page/>, app);
const express = require("express"); const bodyparser= require("body-parser"); const mongoose= require("mongoose") const shortid= require("shortid"); const app = express(); app.use(bodyparser.json()) mongoose.connect(connection string,{useNewUrlParser: true, useUnifiedTopology: true }) const schema= new mongoose.Schema({ _id:{type:String, default : shortid.generate} , image:String, title:String, description:String, availableSizes:[String], price:Number }); const Product= mongoose.model("products",schema); app.get("/api/products",async(req,res)=>{ const product= await Product.find() res.send(product) }); app.post("/api/products",async(req,res)=>{ const newProduct = new Product(req.body); const savedProduct= await newProduct.save() res.send(savedProduct); }); app.delete("/api/products/:id",async (req,res)=>{ const deletedProduct = await Product.findByIdAndDelete(req.params.id); res.send(deletedProduct); }); app.listen(8000);
import { ImmutableStore } from "reshow-flux"; const [store, realTimeDispatch] = ImmutableStore((state, action) => { switch (action.type) { case "realTime": return action.params || []; default: return []; } }); export default store; export { realTimeDispatch };
export const muiStyles = theme => ({ typographyTitle: { maxWidth: '100%', }, snackbarContent: { backgroundColor: theme.palette.primary.light, } })
import get from 'lodash/get' import { GET_PROFILE_GITHUB_DATA_START, GET_PROFILE_GITHUB_DATA_SUCCESS, GET_PROFILE_GITHUB_DATA_ERROR, GET_PROFILE_GITHUB_REPOS_START, GET_PROFILE_GITHUB_REPOS_SUCCESS, GET_PROFILE_GITHUB_REPOS_ERROR } from '../../consts/actionTypes' const initialState = {} export default function (state = initialState, action) { switch (action.type) { case GET_PROFILE_GITHUB_DATA_START: return { ...state, error: null, githubData: null } // break case GET_PROFILE_GITHUB_DATA_SUCCESS: return { ...state, githubData: get(action, "githubData.data") } // break case GET_PROFILE_GITHUB_DATA_ERROR: return { ...state, error: true } // break case GET_PROFILE_GITHUB_REPOS_START: return { ...state, error: null } // break case GET_PROFILE_GITHUB_REPOS_SUCCESS: return { ...state, userRepos: get(action, "userRepos.data", []) } // break case GET_PROFILE_GITHUB_REPOS_ERROR: return { ...state, error: true } // break default: return { ...state } } }
let isMobile = false; let tripType = 'one'; let srcAirport = 'San Jose, CA (SJC)'; let destAirport = 'San Francisco, CA (SFO)'; let numPassenger = 1; let date = {}; let curLoc = ''; let isStorage = storageAvailable('localStorage'); let isLoggedIn = false; let nextAct = null; let userName = null; let email = localStorage.getItem('email'); let selectedFlights = 0; let guest = false; if (isStorage) { let status = localStorage.getItem('user'); if (status) { isLoggedIn = true; userName = status; } else { isLoggedIn = false; } } $(document).ready(function () { $(window).resize(update_windowResized); update_windowResized(); let loca = window.location.pathname; loca = loca.replace(/\//g, ""); curLoc = loca; if (loca.length === 0) loca = "home"; if (loca === 'rapid' || loca === 'frequent') { loadContent('programs|' + loca); } else { loadContent(loca); } $(".active-underline").removeClass('active-underline'); let loc = window.location.pathname; loc = loc.replace(/\//g, ""); if (loc.length === 0) loc = "home"; $("[data-nav-item*=" + loc + "]").addClass('active-underline'); window.onscroll = function () { windowScrolled() }; let navBarDown = false; var navbar = document.getElementsByClassName("navbar")[0]; var sticky = navbar.offsetTop; function windowScrolled() { navBarVisibility(); } if (isMobile) { $('.ui.fluid.dropdown').dropdown(); $('.ui.single.dropdown').dropdown({ onChange: function (value) { update_dateSelectType(value) } }); $('.dropdown.dest-m').dropdown({ fullTextSearch: "fuzzy", ignoreCase: "true", apiSettings: { url: '/api/airports/{query}' }, minCharacters: 0, onChange: function (value, text, el) { // closeTop(); airportSelected(value, text, el, 'dest') } }); $('.dropdown-m.src-m').dropdown({ fullTextSearch: "fuzzy", ignoreCase: "true", apiSettings: { url: '/api/airports/{query}' }, minCharacters: 0, onChange: function (value, text, el) { // closeTop(); airportSelected(value, text, el, 'src') } }); } else { $('.labeled.button').on('click', function (e) { if (e.target.classList.contains('clickable')) { $("#" + $(e.target).data('btn-target')).toggleClass('visible'); $("#" + $(e.target).data('btn-target') + " > div.menu-container > div").dropdown("show"); $("#" + $(e.target).data('btn-target') + " > div.menu-container > div > input").focus(); } }); $('.labeled.button').on("focusout", function (event) { let targElem = "#" + $(event.target.parentElement).data('btn-target'); if ($(targElem).hasClass('visible')) { $(event.target.parentElement.parentElement).animate({ opacity: 0 }, 500, function () { $(targElem).removeClass('visible'); $(event.target.parentElement.parentElement).css('opacity', 1); }); } }); $('.dropdown.dir').dropdown({ onChange: function (value, text, el) { $("#dir-display").text(text); update_dateSelectType(value); } }); $('.dropdown.dest').dropdown({ fullTextSearch: "fuzzy", ignoreCase: "true", apiSettings: { url: '/api/airports/{query}' }, minCharacters: 0, onChange: function (value, text, el) { // closeTop(); airportSelected(value, text, el, 'dest') } }); $('.dropdown.src').dropdown({ fullTextSearch: "fuzzy", ignoreCase: "true", apiSettings: { url: '/api/airports/{query}' }, minCharacters: 0, onChange: function (value, text, el) { // closeTop(); airportSelected(value, text, el, 'src') } }); $("input[type='text']").on("focus", function () { $(this).select(); }); $('.date-container .form-control').on("focusout", function (event) { if (!this.value) { this.value = 'Departure Date' } }); } $('.dropdown.num').dropdown({ onChange: function (value, text, el) { numPassenger = +value; $('.dropdown.num .drop-num').text(text); } }); // close opened tabs one by one $(document).keyup(function (event) { if (event.which === 13) { event.preventDefault(); } if (event.originalEvent.key === 'Tab') { setTimeout(function () { closeTop() }, 500) } if (event.originalEvent.key === 'Escape') { closeTop(); } }); $(document).on("click", function (event) { // close other tabs if this isn't one if ($(event.target).closest("[data-importance]").length === 0) { closeTop(); } }); function closeTop() { let mostImportant = null; let val = 1000; $("[data-importance]").each(function (i) { if (i < val && this.classList.contains('visible')) { mostImportant = this; } }); if (mostImportant) { mostImportant.classList.remove("visible"); } } // Add slideDown animation to Bootstrap dropdown when expanding. $('body > header > nav').on('show.bs.dropdown', function () { $(this).find('.dropdown-menu').first().stop(true, true).slideDown(250); }); // Add slideUp animation to Bootstrap dropdown when collapsing. $('body > header > nav').on('hide.bs.dropdown', function () { $(this).find('.dropdown-menu').first().stop(true, true).slideUp(175); }); $(function () { $('[data-toggle="tooltip"]').tooltip(); $('[data-toggle="tooltip"]').on('shown.bs.tooltip', function () { $('.tooltip').addClass('animated slideInUp'); }) }); //when user clicks back $(window).on("popstate", function (evt) { $('html, body').animate({ scrollTop: 0 }, 800); $(".active-underline").removeClass('active-underline'); let loc = window.location.pathname; loc = loc.replace(/\//g, ""); if (loc.length === 0) loc = "home"; $("[data-nav-item*=" + loc + "]").addClass('active-underline'); loadContent(loc); }); //set up nav buttons $(".nav-button").on('click', function (event) { event.stopPropagation(); event.stopImmediatePropagation(); let targetLoc = $(this).data("nav-target"); navAction(targetLoc); }); update_dateSelectType(); function update_dateSelectType(val) { //enable date pickers if (val) { tripType = val; } if (isMobile) { if (tripType === 'one' || tripType === 'rapid') { $('.single-date.form-control.mobile-d').show().datepicker({ autoclose: true }); $('.range-date.input-group.mobile-d').hide(); } else { $('.range-date.input-group.mobile-d').show().datepicker({ autoclose: true }); $('.single-date.form-control.mobile-d').hide(); } } else { if (tripType === 'one' || tripType === 'rapid') { $('#direction-indicator').removeClass('back-forth').addClass('to-right'); } else { $('#direction-indicator').addClass('back-forth').removeClass('to-right'); } if (tripType === 'one' || tripType === 'rapid') { $('.single-date.form-control:not(mobile-d)').show().datepicker({ autoclose: true }); $('.range-date.input-group:not(mobile-d)').hide(); } else { $('.range-date.input-group:not(mobile-d)').show().datepicker({ autoclose: true, format: "mm/dd" }); $('.single-date.form-control:not(mobile-d)').hide(); } } } window.navAction = navAction; function navAction(targetLoc) { if (targetLoc === '/') { window.location = './'; } $(".dropdown-menu").removeClass('show'); if (isMobile) { $('.collapse').collapse("hide"); } $('.land').click(); let loc = window.location.pathname; loc = loc.replace(/\//g, ""); curLoc = loc; if (loc.length === 0) loc = "home"; let sDest; if (['frequent', 'rapid'].includes(targetLoc)) { sDest = targetLoc; targetLoc = 'programs'; } if (loc !== targetLoc) { window.history.pushState({urlPath: '/' + targetLoc}, capitalizeFirstLetter(targetLoc) + ' - SFGo', '/' + targetLoc); $(".active-underline").removeClass('active-underline'); loadContent(targetLoc + (['programs'].includes(targetLoc) ? '|' + sDest : '')); } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } $("[data-nav-item*=" + targetLoc + "]").addClass('active-underline'); $('html, body').animate({ scrollTop: 0 }, 800); } function loadContent(loc) { loadNewSplash(loc.split('|')[0]); if (loc.split('|')[1]) { window.PROGRAM_LOC = loc.split('|')[1]; } else { window.PROGRAM_LOC = null; } $(".page-content").load('./public/views/' + loc.split('|')[0] + '.html'); } function loadNewSplash(loc) { let src = '/img/'; let bigHeader = 'Book Your Next Flight'; if (loc === 'careers') { src += 'ground-crew-sm.jpg'; bigHeader = 'Work With Us'; } else if (loc === 'contact') { src += 'support-lady-sm.jpg'; bigHeader = 'Contact Us'; } else if (loc === 'programs') { src += 'programs' + (isMobile ? '-m' : '') + '.jpg'; bigHeader = 'Join Our Programs' } else if (loc === 'home') { src += 'plane-taking-off-' + (isMobile ? 'm-' : '') + 'xl.jpg'; bigHeader = 'Book Your Next Flight'; } else { src += 'airport-xl.jpg'; bigHeader = isMobile ? 'Check Out Our Schedules' : 'Get Our Schedules' } $('#welcome-message').fadeOut(500, function () { if (isMobile && loc === 'schedules') { $(this).css('width', '78vw'); } else if (isMobile) { $(this).css('width', '67.5vw'); } else { $(this).css('width', 'unset'); } $(this).text(bigHeader).fadeIn(250); }); $('#tag-line').fadeOut(500, function () { $(this).text('Travel Seamlessly').fadeIn(250); }); let fullSrc = 'https://pixboost.com/api/2/img/https://sfgo.today' + src + '/resize?size=' + (isMobile ? '576' : Math.ceil($(window).width() / 256) * 256) + '&auth=MTc5MzczMTIxMA__'; // LOAD BACKGROUND IMAGE $('<img/>').attr('src', fullSrc).on('load', function () { $(this).remove(); // $('.land-section').css('background-image', 'url(' + src + ')'); $('.land-section').css({ backgroundImage: 'url(' + fullSrc + ')' }); if (isMobile && loc === 'programs') { $('.land-section').css({ backgroundPositionX: '-74px' }); } else { $('.land-section').css({ backgroundPositionX: '' }); } //calculate landing-splash size let image = new Image(); image.src = fullSrc; let width = image.width, height = image.height; $('.land-section').css('height', isMobile ? 'calc(100vw * 4464 / 5370 - 1px)' : 'calc(100vw * ' + height + ' / ' + width + ' - 1px)'); if (isMobile) { $('.land-section').css('background-size', 'cover'); } $('.land-section').animate({opacity: 1}, 500); if ($("#book-flight-bar").scrollTop !== 20) { // not sure what does this tbh let destHeight = $(window).height() / 20 + 107; let barHeight = $(window).height() / 100 + 2; //slide in animation for booking bar $("#book-flight-bar").animate({top: barHeight, opacity: 1}, 1000); setTimeout(function () { $("#welcome-message").animate({top: (isMobile ? 15 : destHeight), opacity: 1}, 1000); }, 250); setTimeout(function () { let ratio = screen.width / screen.height; $("#tag-line").animate({top: destHeight + 80 + (isMobile ? 10 + 30 * (1 - ratio) : 0), opacity: 1}, 1000); }, 400); } }); } function airportSelected(value, text, el, loc) { let iata = value.substr(-4, 3); let location = value.substring(0, value.length - 5).trim(); $("#selectable-" + loc).text(iata); $("#desc-" + loc).text(location); if (loc === 'src') { srcAirport = value; } else { destAirport = value; } } function navBarVisibility() { if (window.pageYOffset >= sticky + 4 * $(window).height() / 5) { if (navBarDown) return; navBarDown = true; let navHeight = $(navbar).outerHeight(); $('#navbar-space-holder').css('min-height', navHeight).css('display', 'block'); navbar.classList.add("sticky"); // navbar.classList.remove("bg-transparent"); // navbar.classList.add("bg-dark"); setTimeout(function () { if (!navbar.classList.contains('slideDown')) { navbar.classList.add('slideDown'); } }, 10); } else { if (navBarDown && window.pageYOffset > sticky) { return; } $('#navbar-space-holder').css('min-height', 0).css('display', 'block'); navBarDown = false; navbar.classList.remove("sticky"); navbar.classList.remove("slide", "slideDown"); // navbar.classList.remove("bg-dark"); // navbar.classList.add("bg-transparent"); } } $('.return-to-top').click(function () { $("html, body").animate({scrollTop: 0}, 600); return false; }); $('body').on('hidden.bs.modal', function () { if ($('.modal.show').length > 0) { $('body').addClass('modal-open'); } }); function update_windowResized() { isMobile = $(window).width() < 576; if ($(window).width() < 576) { //mobile $('.return-to-top').css('margin-bottom', $('.book-flight-m').outerHeight() - 6); if (curLoc === 'schedules') { $('#welcome-message').text('Check Out Our Schedules'); $('#welcome-message').css('width', '78vw'); reanim_welcomeMsg(); } $('.logo-img').attr('width', "105"); } else { //tablet/desktop $('.return-to-top').css('margin-bottom', 0); if (curLoc === 'schedules') { $('#welcome-message').text('Get Our Schedules'); $('#welcome-message').css('width', 'unset'); reanim_welcomeMsg(); } if ($(window).width() < 1024) { $('.logo-img').attr('width', "70"); } else { $('.logo-img').attr('width', "140"); } } function reanim_welcomeMsg() { let destHeight = $(window).height() / 20 + 107; $("#welcome-message").stop(true); $("#tag-line").stop(true); $("#welcome-message").animate({top: (isMobile ? 15 : destHeight), opacity: 1}, 1000); let ratio = screen.width / screen.height; $("#tag-line").animate({top: destHeight + 80 + (isMobile ? 10 + 30 * (1 - ratio) : 0), opacity: 1}, 1000); } } $('#passwordInput, #passwordIn').on("keyup", function () { if ($(this).val()) { $(this).addClass('hasvalue') } else { $(this).removeClass('hasvalue') } }); let forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission let validation = Array.prototype.filter.call(forms, function (form) { form.addEventListener('submit', function (event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } else { event.preventDefault(); } form.classList.add('was-validated'); }, false); }); $('#loginModal').on('hidden.bs.modal', function () { if (!$('.reset-container').hasClass('is-hide')) { $('.modal-content .display-6').text("Register for SFGo"); $('.lead .btn-dark').text("Register Now"); $('.modal-footer .btn-primary').text("Log In"); $('#loginModalLabel').text("Log In Now"); $('.reset-container [required]').removeAttr('required'); $('.register-container [required]').removeAttr('required'); $('.login-container input').attr("required"); $('.register-container').css({ 'top': '250', 'opacity': '0', 'display': 'none' }); $('.login-container').css({'top': '0', 'opacity': '1', 'display': 'block'}); $('.reset-container').addClass('is-hide'); } nextAct = null; }); $('.register-container').addClass('is-hide'); $('.reset-container').addClass('is-hide'); update_userImg(); $('.signout-drop').on("click", function () { $('.signout-drop').animate({opacity: 0}, 500); setTimeout(function () { $('.signout-drop').removeClass('visible'); }, 500); isLoggedIn = false; userName = null; email = null; localStorage.clear(); update_userImg(); }); $('.book-trip-container button.btn-primary').on("click", function (evt) { let $chck = $('#checkOutBtn'); if (selectedFlights === 0) { $chck.prop("disabled", false); } selectedFlights++; $chck.text('Check Out (' + selectedFlights + ')'); if ($(this).hasClass('flight-booked')) return; $(this).css('width', $(this).outerWidth()); $(this).prop("disabled", true); $(this).addClass('flight-booked'); $(this).html('<span class="spinner-border spinner-border-sm"></span>'); setTimeout(function () { $(evt.target).html('<i class="fas fa-check">'); }, rndInt(500, 4500)); console.info($(this).data('book-id')); }); }); function bookFlight() { $('.navbar-collapse').collapse('hide'); nextAct = 'book'; if (!isLoggedIn && !guest) { signIn('book'); } else { nextStep(); } } function signIn(isBook) { $('.navbar-collapse').collapse('hide'); if (!isBook && nextAct === 'book') { nextAct = null; } if (!isLoggedIn) { $('#loginModal').modal('show'); if ($('#passwordInput').val()) { $('#passwordInput').addClass('hasvalue') } if ($('#passwordIn').val()) { $('#passwordIn').addClass('hasvalue') } } } function registerClick(isReset) { $('.navbar-collapse').collapse('hide'); if (isMobile) { if (isReset) { let isRegVis = $('.register-container').is(':visible'); let isLogVis = $('.login-container').is(':visible'); $('.modal-content .display-6').fadeOut(function () { $(this).text("Log in to SFGo").fadeIn(); }); $('.lead .btn-dark').fadeOut(function () { $(this).text("Log In Now").fadeIn(); }); $('#loginModalLabel').fadeOut(function () { $(this).text("Reset Password").fadeIn(); }); $('.modal-footer .btn-primary').fadeOut(function () { $(this).text("Reset").fadeIn(); }); $('.register-container [required]').removeAttr('required'); $('.login-container [required]').removeAttr('required'); $('.reset-container input').attr("required"); if (isLogVis) { $('.login-container').animate({ 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}).addClass('is-hide'); } if (isRegVis) { $('.register-container').animate({ 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}).addClass('is-hide'); } $('.reset-container').css({'top': 250, 'opacity': 0}); $('.reset-container').removeClass('is-hide'); setTimeout(function () { $('.reset-container').animate({'top': '0', 'opacity': '1', 'display': 'block'}, 1000); }, 250); } else if ($('.register-container').is(':visible') || $('.reset-container').is(':visible')) { let isRegVis = $('.register-container').is(':visible'); let isResVis = $('.reset-container').is(':visible'); $('.modal-content .display-6').fadeOut(function () { $(this).text("Register for SFGo").fadeIn(); }); $('.lead .btn-dark').fadeOut(function () { $(this).text("Register Now").fadeIn(); }); $('.modal-footer .btn-primary').fadeOut(function () { $(this).text("Log In").fadeIn(); }); $('#loginModalLabel').fadeOut(function () { $(this).text("Log In Now").fadeIn(); }); $('.reset-container [required]').removeAttr('required'); $('.register-container [required]').removeAttr('required'); $('.login-container input').attr("required"); if (isResVis) { $('.reset-container').animate({ 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}).addClass('is-hide'); } if (isRegVis) { $('.register-container').animate({ 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}).addClass('is-hide'); } $('.login-container').css({'top': 250, 'opacity': 0}); setTimeout(function () { $('.login-container').removeClass('is-hide'); $('.login-container').animate({'top': '0', 'opacity': '1', 'display': 'block'}, 1000); setTimeout(function () { $('.register-container').addClass('is-hide'); $('.reset-container').addClass('is-hide'); }, 1000); }, 250); } else { $('.modal-content .display-6').fadeOut(function () { $(this).text("Log in to SFGo").fadeIn(); }); $('.lead .btn-dark').fadeOut(function () { $(this).text("Log In Now").fadeIn(); }); $('.modal-footer .btn-primary').fadeOut(function () { $(this).text("Register").fadeIn(); }); $('#loginModalLabel').fadeOut(function () { $(this).text("Register Now").fadeIn(); }); $('.login-container [required]').removeAttr('required'); $('.register-container input').attr("required"); $('.login-container').animate({ 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}).addClass('is-hide'); $('.register-container').css({'top': 250, 'opacity': 0}); $('.register-container').removeClass('is-hide'); setTimeout(function () { $('.register-container').animate({'top': '0', 'opacity': '1', 'display': 'block'}, 1000); }, 250); } return; } if (isReset) { let isRegVis = $('.register-container').is(':visible'); let isLogVis = $('.login-container').is(':visible'); $('.modal-content .display-6').fadeOut(function () { $(this).text("Log in to SFGo").fadeIn(); }); $('.lead .btn-dark').fadeOut(function () { $(this).text("Log In Now").fadeIn(); }); $('#loginModalLabel').fadeOut(function () { $(this).text("Reset Password").fadeIn(); }); $('.modal-footer .btn-primary').fadeOut(function () { $(this).text("Reset").fadeIn(); }); $('.register-container [required]').removeAttr('required'); $('.login-container [required]').removeAttr('required'); $('.reset-container input').attr("required"); if (isLogVis) { $('.login-container').animate({'top': '-200', 'opacity': '0', 'display': 'none'}, 1000).css({'top': 250}); } if (isRegVis) { $('.register-container').animate({ 'top': '-200', 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}); } $('.reset-container').css({'top': 250, 'opacity': 0}); setTimeout(function () { $('.reset-container').removeClass('is-hide'); $('.reset-container').animate({'top': '0', 'opacity': '1', 'display': 'block'}, 1000); }, 250); } else if ($('.register-container').is(':visible') || $('.reset-container').is(':visible')) { let isRegVis = $('.register-container').is(':visible'); let isResVis = $('.reset-container').is(':visible'); $('.modal-content .display-6').fadeOut(function () { $(this).text("Register for SFGo").fadeIn(); }); $('.lead .btn-dark').fadeOut(function () { $(this).text("Register Now").fadeIn(); }); $('.modal-footer .btn-primary').fadeOut(function () { $(this).text("Log In").fadeIn(); }); $('#loginModalLabel').fadeOut(function () { $(this).text("Log In Now").fadeIn(); }); $('.reset-container [required]').removeAttr('required'); $('.register-container [required]').removeAttr('required'); $('.login-container input').attr("required"); if (isResVis) { $('.reset-container').animate({'top': '-200', 'opacity': '0', 'display': 'none'}, 1000).css({'top': 250}); } if (isRegVis) { $('.register-container').animate({ 'top': '-200', 'opacity': '0', 'display': 'none' }, 1000).css({'top': 250}); } $('.login-container').css({'top': 250, 'opacity': 0}); setTimeout(function () { $('.login-container').animate({'top': '0', 'opacity': '1', 'display': 'block'}, 1000); setTimeout(function () { $('.register-container').addClass('is-hide'); $('.reset-container').addClass('is-hide'); }, 1000); }, 250); } else { $('.modal-content .display-6').fadeOut(function () { $(this).text("Log in to SFGo").fadeIn(); }); $('.lead .btn-dark').fadeOut(function () { $(this).text("Log In Now").fadeIn(); }); $('.modal-footer .btn-primary').fadeOut(function () { $(this).text("Register").fadeIn(); }); $('#loginModalLabel').fadeOut(function () { $(this).text("Register Now").fadeIn(); }); $('.login-container [required]').removeAttr('required'); $('.register-container input').attr("required"); $('.login-container').animate({'top': '-200', 'opacity': '0', 'display': 'none'}, 1000).css({'top': 250}); $('.register-container').css({'top': 250, 'opacity': 0}); setTimeout(function () { $('.register-container').removeClass('is-hide'); $('.register-container').animate({'top': '0', 'opacity': '1', 'display': 'block'}, 1000); }, 250); } } function loginClick(e) { let form = document.getElementById('loginForm'); if (!form.checkValidity()) return; let register = ($('.register-container').is(':visible')); let isReset = $('.reset-container').is(':visible'); if (isReset) { setTimeout(function () { window.alert('Email sent. Check your email for more instructions!'); window.location = './'; }, rndInt(1000, 2000)); return; } let dataPrep = {}; if (register) { dataPrep.email = $('#emailIn').val(); dataPrep.password = $('#passwordIn').val(); dataPrep.name = $('#nameIn').val(); } else { dataPrep.email = $('#emailInput').val(); dataPrep.password = $('#passwordInput').val(); } $.ajax({ type: 'POST', url: '/api/' + (register ? 'register' : 'signin'), data: dataPrep, success: function (data) { userName = data.name; isLoggedIn = true; localStorage.setItem('user', userName); localStorage.setItem('email', dataPrep.email); guest = false; update_userImg(); nextStep(); }, error: function (data) { if (!register) { $('input').val('').removeClass('hasvalue'); } } }); } function nextStep(isGuest) { if (isGuest) { guest = true; } $('.modal').modal('hide'); if (nextAct) { $('#bookModal').modal('show'); const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec" ]; if (tripType === 'round') { let startDate = ($('.date-container .input-sm[name=start]').datepicker('getDate')); let endDate = ($('.date-container .input-sm[name=end]').datepicker('getDate')); $('.details').text('Showing flights departing on ' + startDate + ' and returning on ' + endDate + ' from ' + srcAirport + ' to ' + destAirport + '...'); } else if (tripType === 'one') { let date = ($('.date-container .single-date').datepicker('getDate')); let startObj = new Date(date); let startStr = days[startObj.getDay()] + " " + monthNames[startObj.getMonth()] + " " + (startObj.getDate()); $('.details').text('Showing flights departing on ' + startStr + ' from ' + srcAirport + ' to ' + destAirport + '...'); } else { let date = ($('.date-container .single-date').datepicker('getDate')); let startObj = new Date(date); let startStr = days[startObj.getDay()] + " " + monthNames[startObj.getMonth()] + " " + (startObj.getDate()); $('.details').text('Showing Rapid Connect® flights departing on ' + startStr + ' from ' + srcAirport + ' to ' + destAirport + '...'); } $('.src-dest').each(function (index, elem) { $(elem).text(srcAirport.substr(-4, 3) + '-' + destAirport.substr(-4, 3)) }); } } function update_userImg() { if (isLoggedIn) { $('#user-pfp').html(' <i class="fas fa-user" id="icon-user"></i>' + userName.split(' ')[0]); $('#user-pfp').attr('onclick', 'signOut()'); } else { $('#user-pfp').html(' <i class="fas fa-user" id="icon-user"></i>Sign In'); $('#user-pfp').attr('onclick', 'signIn()'); } } function signOut() { if ($('.signout-drop').css('display') === 'block') { $('.signout-drop').animate({opacity: 0}, 500); setTimeout(function () { $('.signout-drop').css('display', 'none'); }, 500); } else { $('.signout-drop').css('display', 'block').animate({opacity: 1}, 500); setTimeout(function () { $('.signout-drop').animate({opacity: 0}, 500); setTimeout(function () { $('.signout-drop').css('display', 'none'); }, 500); }, 5000); } } function done() { $('.modal').modal('hide'); } function checkOut() { let $chckBtn = $('#checkOutBtn'); $chckBtn.css('width', $chckBtn.outerWidth()); $chckBtn.html('<span class="spinner-border spinner-border-sm"></span>'); setTimeout(function () { $('#checkOutBtn').html('<i class="fas fa-check">'); $('#bookModal').modal('hide'); $('#checkoutModal').modal('show'); $('#checkOutBtn').html('Check Out'); setTimeout(function () { let $form = $('#200621569630148'); console.info($form.attr('height')); if ($form.css('height') === "0px") { $form.css('height', 'unset'); } }, 1500); }, rndInt(500, 2500)); } function storageAvailable(type) { let storage; try { storage = window[type]; let x = '__storage_test__'; storage.setItem(x, x); storage.removeItem(x); return true; } catch (e) { return e instanceof DOMException && ( e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && (storage && storage.length !== 0); } } function rndInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; }
$(document).ready(function () { var messageList = []; var isMobile = { Android: function () { return navigator.userAgent.match(/Android/i); }, BlackBerry: function () { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function () { return navigator.userAgent.match(/IEMobile/i); }, any: function () { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; window.addEventListener("load", function () { // Set a timeout... setTimeout(function () { // Hide the address bar! window.scrollTo(0, 1); }, 0); }); var celebrity; var creditCounter = 0; var originalTitle; var hints = []; var clickedInputs = []; var networkFailure = false; getCeleberity(); function getCeleberity() { var apiUrl = 'http://localhost:2826/api/values'; if (networkFailure === false) $.ajax({ url: apiUrl, dataType: 'jsonp', crossDomain: true, timeout: 5000, error: function(e) { networkFailure = true; $.getJSON("app/stores/SampleCelebrities.txt", function (data) { startGame(data); }); }, success: function(data) { var celebJson = JSON && JSON.parse(data) || $.parseJSON(data); startGame(celebJson); }, statusCode: { 404: function() { alert("page not found"); } } }); if(networkFailure === true) { $.getJSON("app/stores/SampleCelebrities.txt", function (data) { startGame(data); }); } } function startGame(celebJson) { celebrity = celebJson; if (creditCounter >= celebrity.Credits.length) creditCounter = 0; var credit = celebrity.Credits[creditCounter]; loadHints(credit); var titleArray = credit.fullname.split(""); creditCounter = creditCounter + 1; originalTitle = titleArray; clickedInputs = []; var imageUrl = credit.imageurl; var myElements = document.querySelectorAll("#grid"); myElements[0].style.backgroundImage = "url(" + imageUrl + ")"; $('#answer input').remove(); $('#answer br').remove(); $('#characters input').remove(); $('#characters br').remove(); for (var i = 0; i < titleArray.length; i++) { if (titleArray[i] != " ") { var inputString = ''; if (isAlphaNumeric(titleArray[i]) === false) { inputString = '<input type="text" maxlength="1" id="mt_' + i + '" style="background-color:#98ACC8; color:#fff;" value="' + titleArray[i] + '" disabled></input>'; } else { inputString = '<input type="text" maxlength="1" id="mt_' + i + '" disabled></input>'; } $('#answer').append(inputString); } else { if (isMobile.any()) { $('#answer').append('</br>'); } $('#answer').append('<input type="text" maxlength="1" id="mt_blank" style="background:#96d1cc;" disabled>' + titleArray[i] + '</input>'); } } var maxchars = 1; $(':input').keydown(function (e) { if ($(this).val().length >= 2) { $(this).val($(this).val().substr(0, maxchars)); } }); $(':input').keyup(function (e) { if ($(this).val().length >= 2) { $(this).val($(this).val().substr(0, maxchars)); } validateInput(this); checkLen(1, $(this).val()); }); titleArray = scramble(credit.fullname).split(""); for (i = 0; i < titleArray.length; i++) { if (titleArray[i] != " ") { var characterString = ''; if (isAlphaNumeric(titleArray[i]) === false) { characterString = '<input type="text" maxlength="1" id="mt_' + i + '" style="background-color:#98ACC8; color:#fff;" value="' + titleArray[i] + '"></input>'; } else { characterString = '<input type="text" maxlength="1" id="mt_' + i + '" value="' + titleArray[i] + '" disabled></input>'; } $('#characters').append(characterString); } else { if (isMobile.any()) { $('#characters').append('</br>'); } } $('#characters').click(function (e) { e = window.event || e; var targ = e.target || e.srcElement; var inputExist = false; for (var j = 0; j < clickedInputs.length; j++) { if (clickedInputs[j] === $(targ)[0].id) { inputExist = true; break; } } if (inputExist === false) { clickedInputs[clickedInputs.length] = $(targ)[0].id; $($(targ)[0]).css("background-color", '#98ACC8'); checkInputs($(targ)[0].value); } }); } startCounting(); resetSelections(); } function loadHints(credit) { hints = []; hints[0] = "This actor's zodiac sign is: " + credit.zodiacsign; hints[1] = "This actor's acted in a movie: " + credit.longtitle; hints[2] = "This actor's part name was: " + credit.partname; } function startCounting() { var now = new Date(); now.setSeconds(now.getSeconds() + 60); $('#timer').countdown({ until: now, format: 'S', compact: true, onExpiry: doneCounting, onTick: watchCountdown }); } function watchCountdown(periods) { var mins = '00'; var secs = '00'; if (periods[5].toString().length === 1) mins = 'TL: 0' + periods[5].toString(); else mins = 'TL: ' + periods[5].toString(); if (periods[6].toString().length === 1) secs = ':0' + periods[6].toString(); else secs = ':' + periods[6].toString(); $('#timer').text(mins + secs); if (periods[6] > 45) { $('#hints')[0].innerHTML = ''; } if (periods[6] <= 45 && periods[6] > 30) { $('#hints')[0].innerHTML = 'Hints: ' + hints[0]; } if (periods[6] <= 30 && periods[6] > 15) { $('#hints')[0].innerHTML = 'Hints: ' + hints[1]; } if (periods[6] <= 15 && periods[6] > 0) { $('#hints')[0].innerHTML = 'Hints: ' + hints[2]; } if (periods[6] <= 0) { displayAnswer(); showImage(); } } function doneCounting() { console.log("done counting"); $('#timer').countdown('destroy'); $('#timer')[0].innerHTML = 'TL: 00:00'; } function checkInputs(value) { var inputs = $('#answer input'); for (var i = 0; i < inputs.length; i++) { if (inputs[i].id != "mt_blank" && inputs[i].value === "") { inputs[i].value = value; validateInput(inputs[i]); break; } } } function validateInput(input) { var arrayId = input.id.replace('mt_', ''); var inputValue = input.value; var originalValue = originalTitle[arrayId]; if (inputValue.toString().toLowerCase() === originalValue.toString().toLowerCase()) { $(input).css("background-color", '#98ACC8'); $(input).css("color", '#fff'); } else { $(input).css("background-color", '#fff'); $(input).css("color", '#F00'); } checkAnswer(); } getMessages(); function getMessages() { $.getJSON("app/stores/messages.txt", function (data) { $.each(data.messages, function (key, val) { messageList.push(val); }); }); } function checkAnswer() { var inputs = $('#answer input'); var allInputsValid = true; for (var i = 0; i < inputs.length; i++) { if (inputs[i].id != "mt_blank") { var color = $(inputs[i]).css("background-color"); if (color != 'rgb(152, 172, 200)') { allInputsValid = false; break; } } } if (allInputsValid === true) { showCorrect(); } } function showCorrect() { //var rand = messageList[Math.floor(Math.random() * messageList.length)]; $('#correct').show(); $('#correct_label').show(); //$('#correct_label').html(rand.name); showImage(); doneCounting(); } function displayAnswer() { var inputs = $('#answer input'); var allInputsValid = true; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; if (input.id != "mt_blank") { $(input).css("background-color", '#98ACC8'); $(input).css("color", '#fff'); input.value = originalTitle[i]; } } doneCounting(); } function scramble(str) { var scrambled = '', randomNum; while (str.length > 1) { randomNum = Math.floor(Math.random() * str.length); scrambled += str.charAt(randomNum); if (randomNum == 0) { str = str.substr(randomNum + 1); } else if (randomNum == (str.length - 1)) { str = str.substring(0, str.length - 1); } else { str = str.substring(0, randomNum) + str.substring(randomNum + 1); } } scrambled += str; return scrambled; } function isAlphaNumeric(x) { var regex = /^[a-zA-Z0-9]+$/g; if (regex.test(x)) { return true; } else return false; } function resetSelections() { clickedInputs = []; var inputs = $('#answer input'); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; if (input.id != "mt_blank") { inputs[i].value = ""; $(input).css("background-color", '#fff'); } } var charInputs = $('#characters input'); for (var j = 0; j < charInputs.length; j++) { var charInput = charInputs[j]; if (charInputs.id != "mt_blank") { $(charInput).css("background-color", '#fff'); } } } $('.ui-btnsolid').click(function (){ setNeighborTiles(this); }); $('.ui-btntranspo').click(function () { setNeighborTiles(this); }); $('#nav_button').click(function () { setNeighborTiles("#cell1"); getCeleberity(); $('#grid').removeClass('clearimage').addClass('blurimage'); }); $('#resetBtn').click(function () { resetSelections(); }); $('#GiveUp').click(function () { displayAnswer(); showImage(); }); function setNeighborTiles(cell) { $('#cell1').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell2').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell3').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell4').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell5').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell6').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell7').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell8').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $('#cell9').removeClass('ui-btntranspo').addClass('ui-btnsolid'); $(cell).removeClass('ui-btnsolid').addClass('ui-btntranspo'); } function showImage() { $('#cell1').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell2').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell3').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell4').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell5').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell6').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell7').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell8').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#cell9').removeClass('ui-btnsolid').addClass('ui-btntranspo'); $('#grid').removeClass('blurimage').addClass('clearimage'); } });
import React from "react" import {useSelector, useDispatch} from "react-redux" import {Link} from "react-router-dom" import {removeSession} from "../../actions/sessionActions" const NoSessionLinks = (props) => { return (<React.Fragment> <Link className="nav-link" to="/login">Login</Link> <Link className="nav-link" to="/signup">Signup</Link> </React.Fragment>) } const SessionLinks = (props) => { const dispatch = useDispatch(); const logoutHandler = (e) => { e.preventDefault() dispatch(removeSession()) } return (<React.Fragment> <Link className="nav-link" to="/chat">Chat</Link> <Link className="nav-link" to="/settings">Settings</Link> <button onClick={logoutHandler} className="btn btn-danger">Logout</button> </React.Fragment>) } const Header = (props) => { const {sessionInfo, checked} = useSelector((state) => state.session) return (<div id="header"> <nav className="navbar navbar-expand navbar-light bg-light"> <div className="container"> <Link className="navbar-brand" to="/">MERN Messenger</Link> <div className="collapse navbar-collapse"> <div className="navbar-nav ms-auto"> {!checked?<div/>:(!!sessionInfo?<SessionLinks/>:<NoSessionLinks/>)} </div></div> </div> </nav> </div>) } export default Header;
let threeSum = function(nums) { let results = []; if (nums.length < 3) { return results; } // [-1, 0, 1, 2, -1, -4] // [-4, -1, -1, 0, 1, 2] nums = nums.sort((a, b) => a - b); console.log({ message: "arraySorted", nums: JSON.stringify(nums) }); for (let i = 0; i < nums.length - 2; i++) { console.log("\n===============\n"); console.log({ message: "for loop", i, "nums.length": nums.length, "nums.length - 2": nums.length - 2 }); console.log({ message: "return results?", i, "nums[i]": nums[i], "nums[i] > 0": nums[i] > 0 }); if (nums[i] > 0) { return results; } console.log({ message: "if check continue", i, "nums[i]": nums[i], "nums[i - 1]": nums[i - 1], "i > 0": i > 0, "nums[i] == nums[i - 1]": nums[i] == nums[i - 1], "if result": i > 0 && nums[i] == nums[i - 1] }); if (i > 0 && nums[i] == nums[i - 1]) { continue; } for (var j = i + 1, k = nums.length - 1; j < k; ) { console.log({ message: "inner for loop", i, j, k: nums.length - 1, "j < k": j < k, "nums[i] + nums[j] + nums[k]": nums[i] + nums[j] + nums[k] }); console.log({ "nums[i] + nums[j] + nums[k]": nums[i] + nums[j] + nums[k] }); if (nums[i] + nums[j] + nums[k] === 0) { results.push([nums[i], nums[j], nums[k]]); j++; k--; while (j < k && nums[j] == nums[j - 1]) { j++; } while (j < k && nums[k] == nums[k + 1]) { k--; } } else if (nums[i] + nums[j] + nums[k] > 0) { k--; } else { j++; } } } return results; }; let input = [-1, 0, 1, 2, -1, -4]; let result = threeSum(input); console.log(JSON.stringify(result));
const { Glyph } = require('./glyph'); function Tile(glyph) { this.glyph = glyph; } const nullTile = new Tile(new Glyph()); const floorTile = new Tile(new Glyph('.')); const wallTile = new Tile(new Glyph('#')); module.exports = { Tile, nullTile, floorTile, wallTile, };
/** * 화면 초기화 - 화면 로드시 자동 호출 됨 */ function _Initialize() { // 단위화면에서 사용될 일반 전역 변수 정의 // $NC.setGlobalVar({ }); // 상단그리드 초기화 grdMasterInitialize(); // 하단그리드 초기화 grdDetailInitialize(); $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CSUSERCENTER", P_QUERY_PARAMS: $NC.getParams({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_CENTER_CD: "%" }) }, { selector: "#cboQCenter_Cd", codeField: "CENTER_CD", nameField: "CENTER_NM", onComplete: function() { $NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD); } }); $NC.setEnable("#btnItemAllocate", false); $NC.setEnable("#btnAllocate", false); $("#btnQBu_Cd").click(showUserBuPopup); $("#btnItemAllocate").click(onBtnItemAllocateClick); $("#btnAllocate").click(onBtnAllocateClick); } /** * 화면 초기화 - 화면 로드시 자동 호출 됨 */ function _OnLoaded() { $NC.setInitSplitter("#divMasterView", "h", 500); } function _SetResizeOffset() { $NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight; } /** * Window Resize Event - Window Size 조정시 호출 됨 */ function _OnResize(parent) { var clientWidth = parent.width() - $NC.G_LAYOUT.border1; var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight; // Splitter 컨테이너 크기 조정 $NC.resizeContainer("#divMasterView", clientWidth, clientHeight); // Grid 사이즈 조정 $NC.resizeGrid("#grdMaster", clientWidth, $("#grdMaster").parent().height() - $NC.G_LAYOUT.header); // Grid 사이즈 조정 $NC.resizeGrid("#grdDetail", clientWidth, $("#grdDetail").parent().height() - $NC.G_LAYOUT.header); } /** * Grid에서 CheckBox Fomatter를 사용할 경우 CheckBox Click 이벤트 처리 * * @param e * * @param view * 대상 Object * @param args * grid, row, cell, val */ function _OnGridCheckBoxFormatterClick(e, view, args) { if (G_GRDMASTER.view.getEditorLock().isActive()) { G_GRDMASTER.view.getEditorLock().commitCurrentEdit(); } $NC.setGridSelectRow(G_GRDMASTER, args.row); var rowData = G_GRDMASTER.data.getItem(args.row); if (args.cell == G_GRDMASTER.view.getColumnIndex("CHECK_YN")) { rowData.CHECK_YN = args.val === "Y" ? "N" : "Y"; } if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDMASTER.data.updateItem(rowData.id, rowData); G_GRDMASTER.lastModified = true; } /** * Input, Select Change Event 처리 */ function _OnConditionChange(e, view, val) { var id = view.prop("id").substr(4).toUpperCase(); switch (id) { case "BU_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: val }; O_RESULT_DATA = $NP.getUserBuInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onUserBuPopup(O_RESULT_DATA[0]); } else { $NP.showUserBuPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onUserBuPopup, onUserBuPopup); } return; } // 화면클리어 onChangingCondition(); } function onChangingCondition() { // 초기화 $NC.clearGridData(G_GRDMASTER); $NC.clearGridData(G_GRDDETAIL); // 버튼 활성화 처리 $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "0"; $NC.G_VAR.buttons._cancel = "0"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); $NC.setEnable("#btnItemAllocate", false); $NC.setEnable("#btnAllocate", false); } /** * Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨 */ function _Inquiry() { // 조회조건 체크 var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd", true); // 조회시 전역 변수 값 초기화 $NC.setInitGridVar(G_GRDMASTER); // 파라메터 세팅 G_GRDMASTER.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD }); // 데이터 조회 $NC.serviceCall("/CM04050E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster); } /** * New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨 */ function _New() { } /** * Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨 */ function _Save() { if (G_GRDMASTER.lastRow == null || G_GRDMASTER.data.getLength() === 0) { alert("저장할 데이터가 없습니다."); return; } if (G_GRDMASTER.focused) { // 현재 수정모드면 if (G_GRDMASTER.view.getEditorLock().isActive()) { G_GRDMASTER.view.getEditorLock().commitCurrentEdit(); } } else if (G_GRDDETAIL.focused) { // 현재 수정모드면 if (G_GRDDETAIL.view.getEditorLock().isActive()) { G_GRDDETAIL.view.getEditorLock().commitCurrentEdit(); } } var saveMasterDS = [ ]; var saveDetailDS = [ ]; var rowCount; var row; var rowData; var saveData; rowCount = G_GRDMASTER.data.getLength(); for (row = 0; row < rowCount; row++) { rowData = G_GRDMASTER.data.getItem(row); if (rowData.CRUD !== "R") { saveData = { P_CENTER_CD: rowData.CENTER_CD, P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD, P_BASE_CENTER_CD: rowData.BASE_CENTER_CD, P_DCTC_DIV: rowData.DCTC_DIV, P_REQUEST_MNG_DIV: rowData.REQUEST_MNG_DIV, P_REQUEST_UNIT_DIV: rowData.REQUEST_UNIT_DIV, P_REQUEST_UNIT_QTY: rowData.REQUEST_UNIT_QTY, P_SF_QTY: rowData.SF_QTY, P_FILL_LIMIT_DAY: rowData.FILL_LIMIT_DAY, P_BASE_OP_DAY: rowData.BASE_OP_DAY, P_CRUD: rowData.CRUD }; saveMasterDS.push(saveData); } } rowCount = G_GRDDETAIL.data.getLength(); for (row = 0; row < rowCount; row++) { rowData = G_GRDDETAIL.data.getItem(row); if (rowData.CRUD !== "R") { saveData = { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD, P_DEAL_DIV: rowData.DEAL_DIV, P_OPEN_DATE: rowData.OPEN_DATE, P_CLOSE_DATE: rowData.CLOSE_DATE, P_CRUD: rowData.CRUD }; saveDetailDS.push(saveData); } } if (saveMasterDS.length > 0 || saveDetailDS.length > 0) { $NC.serviceCall("/CM04050E/save.do", { P_DS_MASTER: $NC.toJson(saveMasterDS), P_DS_DETAIL: $NC.toJson(saveDetailDS), P_USER_ID: $NC.G_USERINFO.USER_ID }, onSave, onSaveError); } } /** * Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨 */ function _Delete() { if (G_GRDMASTER.data.getLength() == 0) { alert("삭제할 데이터가 없습니다."); return; } var saveDS = [ ]; var d_DS = [ ]; var chkCnt = 0; var rowCount = G_GRDMASTER.data.getLength(); for (var row = 0; row < rowCount; row++) { var rowData = G_GRDMASTER.data.getItem(row); if (rowData.CHECK_YN == "Y") { chkCnt++; var saveData = { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: $NC.getValue("#edtQBu_Cd"), P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD, P_CRUD: "D" }; saveDS.push(saveData); } } if (chkCnt == 0) { alert("삭제할 데이터를 선택하십시오."); return; } var result = confirm("삭제 하시겠습니까?"); if (result) { $NC.serviceCall("/CM04050E/save.do", { P_DS_MASTER: $NC.toJson(saveDS), P_DS_DETAIL: $NC.toJson(d_DS), P_USER_ID: $NC.G_USERINFO.USER_ID }, onSave, onSaveError); } } /** * Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨 */ function _Cancel() { var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, { selectKey: "ITEM_CD", isCancel: true }); _Inquiry(); G_GRDMASTER.lastKeyVal = lastKeyVal; } /** * Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨 * * @param printIndex * 선택한 출력물 Index */ function _Print(printIndex, printName) { } function grdMasterOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "CHECK_YN", field: "CHECK_YN", minWidth: 30, maxWidth: 30, resizable: false, sortable: false, cssClass: "align-center", formatter: Slick.Formatters.CheckBox, editorOptions: { valueChecked: "Y", valueUnChecked: "N" } }, false); $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "상품코드", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "상품명", minWidth: 180 }); $NC.setGridColumn(columns, { id: "ITEM_SPEC", field: "ITEM_SPEC", name: "규격", minWidth: 90 }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "판매사명", minWidth: 100 }); $NC.setGridColumn(columns, { id: "QTY_IN_BOX", field: "QTY_IN_BOX", name: "입수", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "BASE_CENTER_CD_F", field: "BASE_CENTER_CD_F", name: "모물류센터", minWidth: 120, editor: Slick.Editors.ComboBox, editorOptions: $NC.getGridComboEditorOptions("/CM04050E/getDataSet.do", { P_QUERY_ID: "CM04050E.RS_SUB1", P_QUERY_PARAMS: "{}" }, { codeField: "BASE_CENTER_CD", dataCodeField: "BASE_CENTER_CD", dataFullNameField: "BASE_CENTER_CD_F" }) }); $NC.setGridColumn(columns, { id: "DCTC_DIV_F", field: "DCTC_DIV_F", name: "발주상품구분", minWidth: 150, editor: Slick.Editors.ComboBox, editorOptions: $NC.getGridComboEditorOptions("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "DCTC_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { codeField: "DCTC_DIV", dataCodeField: "CODE_CD", dataFullNameField: "CODE_CD_F", isKeyField: true }) }); $NC.setGridColumn(columns, { id: "REQUEST_MNG_DIV_F", field: "REQUEST_MNG_DIV_F", name: "발주관리구분", minWidth: 150, editor: Slick.Editors.ComboBox, editorOptions: $NC.getGridComboEditorOptions("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "REQUEST_MNG_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { codeField: "REQUEST_MNG_DIV", dataCodeField: "CODE_CD", dataFullNameField: "CODE_CD_F", isKeyField: true }) }); $NC.setGridColumn(columns, { id: "REQUEST_UNIT_DIV_F", field: "REQUEST_UNIT_DIV_F", name: "발주단위구분", minWidth: 150, editor: Slick.Editors.ComboBox, editorOptions: $NC.getGridComboEditorOptions("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "REQUEST_UNIT_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { codeField: "REQUEST_UNIT_DIV", dataCodeField: "CODE_CD", dataFullNameField: "CODE_CD_F" }) }); $NC.setGridColumn(columns, { id: "REQUEST_UNIT_QTY", field: "REQUEST_UNIT_QTY", name: "발주단위수량", minWidth: 90, cssClass: "align-right", editor: Slick.Editors.Number }); $NC.setGridColumn(columns, { id: "SF_QTY", field: "SF_QTY", name: "안전계수", minWidth: 90, cssClass: "align-right", editor: Slick.Editors.Number }); $NC.setGridColumn(columns, { id: "FILL_LIMIT_DAY", field: "FILL_LIMIT_DAY", name: "보충기한일수", minWidth: 90, cssClass: "align-right", editor: Slick.Editors.Number }); $NC.setGridColumn(columns, { id: "BASE_OP_DAY", field: "BASE_OP_DAY", name: "기준운영일수", minWidth: 90, cssClass: "align-right", editor: Slick.Editors.Number }); return $NC.setGridColumnDefaultFormatter(columns); } function grdMasterInitialize() { var options = { editable: true, autoEdit: true, frozenColumn: 2 }; // Grid Object, DataView 생성 및 초기화 $NC.setInitGridObject("#grdMaster", { columns: grdMasterOnGetColumns(), queryId: "CM04050E.RS_MASTER", sortCol: "ITEM_CD", gridOptions: options }); G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll); G_GRDMASTER.view.onCellChange.subscribe(grdMasterOnCellChange); G_GRDMASTER.view.onHeaderClick.subscribe(grdMasterOnHeaderClick); $NC.setGridColumnHeaderCheckBox(G_GRDMASTER, "CHECK_YN"); $("#grdMaster").find("div.grid-focus,div.grid-canvas").focus(function(e) { if (G_GRDMASTER.focused) { return; } G_GRDMASTER.focused = true; G_GRDDETAIL.focused = false; if (G_GRDDETAIL.view.getEditorLock().isActive()) { G_GRDDETAIL.view.getEditorLock().commitCurrentEdit(); } }); } function grdMasterOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDMASTER.lastRow != null) { if (row == G_GRDMASTER.lastRow) { e.stopImmediatePropagation(); return; } } var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd", true); // 상품마스터 변수 초기화 $NC.setInitGridVar(G_GRDDETAIL); onGetDetail({ data: null }); var rowData = G_GRDMASTER.data.getItem(row); G_GRDDETAIL.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_BRAND_CD: rowData.BRAND_CD, P_ITEM_CD: rowData.ITEM_CD }); // 데이터 조회 $NC.serviceCall("/CM04050E/getDataSet.do", $NC.getGridParams(G_GRDDETAIL), onGetDetail); // 상단 현재로우/총건수 업데이트 $NC.setGridDisplayRows("#grdMaster", row + 1); } function grdMasterOnCellChange(e, args) { var rowData = args.item; if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDMASTER.data.updateItem(rowData.id, rowData); // 마지막 선택 Row 수정 상태로 변경 G_GRDMASTER.lastRowModified = true; } /** * 상단 그리드의 전체체크 선택시 처리 * * @param e * @param args */ function grdMasterOnHeaderClick(e, args) { if (args.column.id == "CHECK_YN") { if ($(e.target).is(":checkbox")) { if (G_GRDMASTER.data.getLength() == 0) { e.preventDefault(); e.stopImmediatePropagation(); return; } if (G_GRDMASTER.view.getEditorLock().isActive() && !G_GRDMASTER.view.getEditorLock().commitCurrentEdit()) { e.preventDefault(); e.stopImmediatePropagation(); return; } var checkVal = $(e.target).is(":checked") ? "Y" : "N"; var rowCount = G_GRDMASTER.data.getLength(); var rowData; G_GRDMASTER.data.beginUpdate(); for (var row = 0; row < rowCount; row++) { rowData = G_GRDMASTER.data.getItem(row); if (rowData.CHECK_YN !== checkVal) { rowData.CHECK_YN = checkVal; if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDMASTER.data.updateItem(rowData.id, rowData); } } G_GRDMASTER.data.endUpdate(); e.stopPropagation(); e.stopImmediatePropagation(); } return; } } function grdDetailOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "BU_CD", field: "BU_CD", name: "사업부", minWidth: 90 }); $NC.setGridColumn(columns, { id: "BU_NM", field: "BU_NM", name: "사업부명", minWidth: 180 }); $NC.setGridColumn(columns, { id: "SAFETY_QTY", field: "SAFETY_QTY", name: "안전재고수량", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "LEADTIME_STOCK_QTY", field: "LEADTIME_STOCK_QTY", name: "리드타임대응재고수량", minWidth: 100, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "REASONABLE_QTY", field: "REASONABLE_QTY", name: "적정재고수량", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MAX_REQUEST_QTY", field: "MAX_REQUEST_QTY", name: "최대발주수량", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MIN_REQUEST_QTY", field: "MIN_REQUEST_QTY", name: "최소발주수량", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MON3_OUT_QTY", field: "MON3_OUT_QTY", name: "3개월출하수량", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MON3_OUT_DAY", field: "MON3_OUT_DAY", name: "3개월출하일수", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MONAVG_OUT_DAY", field: "MONAVG_OUT_DAY", name: "월평균출하일수", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "DAYAVG_OUT_QTY", field: "DAYAVG_OUT_QTY", name: "일평균출하수량", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "OUT_CYCLE_DAY", field: "OUT_CYCLE_DAY", name: "출하주기(일수)", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "STD_DEVIATION", field: "STD_DEVIATION", name: "표준편차", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "LEADTIME_DAY", field: "LEADTIME_DAY", name: "리드타임일수", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "DEAL_DIV_F", field: "DEAL_DIV_F", name: "거래구분", minWidth: 90, editor: Slick.Editors.ComboBox, editorOptions: $NC.getGridComboEditorOptions("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "DEAL_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { codeField: "DEAL_DIV", dataCodeField: "CODE_CD", dataFullNameField: "CODE_CD_F", isKeyField: true }) }); $NC.setGridColumn(columns, { id: "OPEN_DATE", field: "OPEN_DATE", name: "거래시작일자", minWidth: 90, editor: Slick.Editors.Date }); $NC.setGridColumn(columns, { id: "CLOSE_DATE", field: "CLOSE_DATE", name: "거래종료일자", minWidth: 90, editor: Slick.Editors.Date }); return $NC.setGridColumnDefaultFormatter(columns); } function grdDetailInitialize() { var options = { editable: true, autoEdit: true, frozenColumn: 2 }; // Grid Object, DataView 생성 및 초기화 $NC.setInitGridObject("#grdDetail", { columns: grdDetailOnGetColumns(), queryId: "CM04050E.RS_DETAIL", sortCol: "BU_CD", gridOptions: options }); G_GRDDETAIL.view.onSelectedRowsChanged.subscribe(grdDetailOnAfterScroll); G_GRDDETAIL.view.onCellChange.subscribe(grdDetailOnCellChange); $("#grdDetail").find("div.grid-focus,div.grid-canvas").focus(function(e) { if (G_GRDDETAIL.focused) { return; } G_GRDMASTER.focused = false; G_GRDDETAIL.focused = true; if (G_GRDMASTER.view.getEditorLock().isActive()) { G_GRDMASTER.view.getEditorLock().commitCurrentEdit(); } }); } function grdDetailOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDDETAIL.lastRow != null) { if (row == G_GRDDETAIL.lastRow) { e.stopImmediatePropagation(); return; } } // 상단 현재로우/총건수 업데이트 $NC.setGridDisplayRows("#grdDetail", row + 1); } function grdDetailOnCellChange(e, args) { var rowData = args.item; switch (G_GRDDETAIL.view.getColumnField(args.cell)) { case "OPEN_DATE": if (!$NC.isNull(rowData.OPEN_DATE)) { if (!$NC.isDate(rowData.OPEN_DATE)) { alert("거래일자를 정확히 입력하십시오."); rowData.OPEN_DATE = ""; G_GRDDETAIL.data.updateItem(rowData.id, rowData); $NC.setGridSelectRow(G_GRDDETAIL, { selectRow: args.row, activeCell: G_GRDDETAIL.view.getColumnIndex("OPEN_DATE"), editMode: true }); return false; } else { rowData.OPEN_DATE = $NC.getDate(rowData.OPEN_DATE); G_GRDDETAIL.data.updateItem(rowData.id, rowData); } } break; case "CLOSE_DATE": if (!$NC.isNull(rowData.CLOSE_DATE)) { if (!$NC.isDate(rowData.CLOSE_DATE)) { alert("종료일자를 정확히 입력하십시오."); rowData.CLOSE_DATE = ""; G_GRDDETAIL.data.updateItem(rowData.id, rowData); $NC.setGridSelectRow(G_GRDDETAIL, { selectRow: args.row, activeCell: G_GRDDETAIL.view.getColumnIndex("CLOSE_DATE"), editMode: true }); return false; } else { rowData.CLOSE_DATE = $NC.getDate(rowData.CLOSE_DATE); G_GRDDETAIL.data.updateItem(rowData.id, rowData); } } break; } if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDDETAIL.data.updateItem(rowData.id, rowData); // 마지막 선택 Row 수정 상태로 변경 G_GRDDETAIL.lastRowModified = true; } function onSave(ajaxData) { var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, { selectKey: "ITEM_CD" }); _Inquiry(); G_GRDMASTER.lastKeyVal = lastKeyVal; } function onSaveError(ajaxData) { $NC.onError(ajaxData); } function onBtnItemAllocateClick() { var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd"); var BU_NM = $NC.getValue("#edtQBu_Nm"); if ($NC.isNull(BU_NM)) { alert("사업부를 입력하십시오."); $NC.setFocus("#edtQBu_Cd"); return; } $NC.G_MAIN.showProgramSubPopup({ PROGRAM_ID: "CM04051P", PROGRAM_NM: "상품개별할당", url: "cm/CM04051P.html", width: 800, height: 500, userData: { P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD }, onOk: function() { _Inquiry(); } }); } function onBtnAllocateClick() { var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd", true); var result = confirm("전체할당 하시겠습니까?"); if (result) { $NC.serviceCall("/CM04050E/callCenterItemAllocate.do", { P_QUERY_PARAMS: $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_USER_ID: $NC.G_USERINFO.USER_ID }) }, onAllocate); } } function onAllocate(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { if (resultData.O_MSG !== "OK") { alert(resultData.O_MSG); return; } _Inquiry(); } } function onGetMaster(ajaxData) { $NC.setInitGridData(G_GRDMASTER, ajaxData); // 체크 컬럼 헤터 초기화 $NC.setGridColumnHeaderCheckBox(G_GRDMASTER, "CHECK_YN"); if (G_GRDMASTER.data.getLength() > 0) { if ($NC.isNull(G_GRDMASTER.lastKeyVal)) { $NC.setGridSelectRow(G_GRDMASTER, 0); } else { $NC.setGridSelectRow(G_GRDMASTER, { selectKey: "ITEM_CD", selectVal: G_GRDMASTER.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdMaster", 0, 0); // 디테일 초기화 $NC.setInitGridVar(G_GRDDETAIL); onGetDetail({ data: null }); } $NC.setEnable("#btnItemAllocate"); $NC.setEnable("#btnAllocate"); // 버튼 활성화 처리 $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "1"; $NC.G_VAR.buttons._cancel = "1"; $NC.G_VAR.buttons._delete = "1"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); } /** * 조회버튼 클릭후 상단 그리드에 데이터 표시처리 */ function onGetDetail(ajaxData) { $NC.setInitGridData(G_GRDDETAIL, ajaxData); if (G_GRDDETAIL.data.getLength() > 0) { $NC.setGridSelectRow(G_GRDDETAIL, 0); } else { $NC.setGridDisplayRows("#grdDetail", 0, 0); } } /** * 검색조건의 사업부 검색 팝업 클릭 */ function showUserBuPopup() { $NP.showUserBuPopup({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: "%" }, onUserBuPopup, function() { $NC.setFocus("#edtQBu_Cd", true); }); } /** * 사업부 검색 결과 * * @param seletedRowData */ function onUserBuPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBu_Cd", resultInfo.BU_CD); $NC.setValue("#edtQBu_Nm", resultInfo.BU_NM); } else { $NC.setValue("#edtQBu_Cd"); $NC.setValue("#edtQBu_Nm"); $NC.setFocus("#edtQBu_Cd", true); } onChangingCondition(); }
function Comp03() { return( <div> <h1> This is Comp03</h1> <p> компонент03 компонент03 компонент03 компонент03 компонент03</p> </div> ) } export default Comp03;
/** * User: Niu Niu * Date: 3/2/13 * All rights reserved by Africa Swing */ function ProgressBar(director) { CAAT.ActorContainer.call(this); this.director = director; this.setClip(true); this.lastBehavior = null; return this; } ProgressBar.prototype = new CAAT.ActorContainer(); ProgressBar.prototype.constructor = ProgressBar; ProgressBar.prototype.setImage = function( imageName, w,h ,outerImgName) { if (!outerImgName){ outerImgName= "progressBarBg"; } this.actor = Util.createImageActorInBound(this.director, imageName,0,0,0,0); this.bg = Util.createImageActorInBound(this.director, outerImgName, 0, 0,0,0); this.addChild(this.bg); this.setMySize(w,h); var actor = this.actor; actor .setScale(0,1) .setScaleAnchor(0,0); this.addChild(actor); return this; }; ProgressBar.prototype.setMySize = function(w,h) { if (!w) {return;} h = h || this.height; var shortenLen = w * 0.07; var shortenH= h * 0.26; this.actor.setBounds( shortenLen, shortenH/2, w- shortenLen*1.2,h-shortenH); this.bg.setBounds(0, 0 ,w,h); this.setSize(w, h); return this; }; ProgressBar.prototype.getLocFromPercent = function(percent) { return this.width * ( percent - 1); }; ProgressBar.prototype.setPercent = function(percent) { this.percent = percent; this.actor.setScale(percent,1).setScaleAnchor(0,0); }; ProgressBar.prototype.getPercent = function() { return this.percent || 0; }; ProgressBar.prototype.incPercent = function(deltaPercent) { var percentNew = this.percent + deltaPercent; if ( percentNew > 1) { percentNew = 1; } else if ( percentNew <0) { percentNew = 0; } this.setPercent(percentNew); return percentNew; }; ProgressBar.prototype.setPercentAnimation = function(scene, fromPoint, toPoint, levelUpFun) { var that = this; var currentBehavior = new CAAT.ScaleBehavior(). setValues(fromPoint, toPoint, 1, 1, 0, 0). addListener({ behaviorExpired: function(behavior, time, actor) { if (toPoint ==1 ) { that.setPercent(0); if (levelUpFun !== undefined) { levelUpFun(); } } if (behavior == that.lastBehavior) { that.lastBehavior = null; } } }) ; // if last behavior exist if (that.lastBehavior) { that.lastBehavior.addListener({ behaviorExpired: function(behavior, time, actor) { currentBehavior.setFrameTime(time, 1000); actor.addBehavior(currentBehavior); } }); } else { currentBehavior.setFrameTime(scene.time, 1000); this.actor.addBehavior(currentBehavior); } that.lastBehavior = currentBehavior; }; // image with progress on percent function ImageProgressCon(imageActor_) { CAAT.ActorContainer.call(this); var that = this; var progressCon_ = new CAAT.ActorContainer() .setSize(imageActor_.width, imageActor_.height) .setFillStyle("black") .setAlpha(0.6); // percent from 0 to 1 this.setProgress = function( percent) { if (percent < 0 || percent > 1) { console.error("Image progress con set progress not in range 0-1"); } progressCon_.setScaleAnchored(1, 1-percent, 0, 1); return this; }; function init() { that.addChild(imageActor_); that.addChild(progressCon_); progressCon_.enableEvents(false); // transfer image's location to this container. Set size. that.setBounds(imageActor_.x, imageActor_.y, imageActor_.width, imageActor_.height); imageActor_.setLocation(0,0); that.setProgress(0); } init(); return this; } ImageProgressCon.prototype = new CAAT.ActorContainer();
import {useParams} from 'react-router-dom'; export default function SharedQuote() { const {id} = useParams(); var f = id; var e = f.split('+').join(' ') return ( <div className="app"> <div className="card"> <black>A wise man once said ...</black> <h2 className="heading">"{e}"</h2> </div> </div> ) }
// @flow import React, {Component} from 'react'; import {connect} from 'react-redux'; import {Animated, Easing, StyleSheet, TouchableOpacity} from 'react-native'; import {View, Text} from './core'; import {DEFAULT_FONT_SIZE} from '../constants/text'; import type {SnackBar as SnackBarType} from '../data/snackBar/SnackBar-type'; import type {RootState, Dispatch} from '../types'; /* * Values are from https://material.io/guidelines/motion/duration-easing.html#duration-easing-dynamic-durations */ const easingValues = { entry: Easing.bezier(0.0, 0.0, 0.2, 1), exit: Easing.bezier(0.4, 0.0, 1, 1), }; const SNACKBAR_TIMEOUT = 2500; const DEFAULT_VIEW_HEIGHT = 9999; const SNACKBAR_PADDING = 10; type Props = { snackBar: SnackBarType, onCloseSnackBar: () => void, }; export class SnackBarComponent extends Component<Props, void> { props: Props; _animatedValue: Animated.Value; _closeSnackBar: any; // ?TimeoutID _viewHeight: number; constructor() { super(...arguments); this._viewHeight = DEFAULT_VIEW_HEIGHT; this._animatedValue = new Animated.Value(this._viewHeight); } componentWillReceiveProps(newProps: Props) { let oldProps = this.props; if (oldProps.snackBar !== newProps.snackBar) { if (newProps.snackBar.visible) { this._animate(this._viewHeight, SNACKBAR_PADDING); clearTimeout(this._closeSnackBar); this._closeSnackBar = setTimeout(() => { if (this.props.snackBar.visible) { this.props.onCloseSnackBar(); } }, SNACKBAR_TIMEOUT); } else { this._animate(SNACKBAR_PADDING, this._viewHeight); } } } componentWillUnmount() { clearTimeout(this._closeSnackBar); } render() { let {textMessage, actionButton} = this.props.snackBar; let actionButtonComponent; if (actionButton) { let {actionText, actionHandler} = actionButton; let actionHandlerOnPress = () => { actionHandler(); this.props.onCloseSnackBar(); }; actionButtonComponent = ( <View style={styles.actionButton}> <TouchableOpacity onPress={actionHandlerOnPress}> <Text style={styles.actionText}>{actionText}</Text> </TouchableOpacity> </View> ); } return ( <Animated.View onLayout={({ nativeEvent: { layout: {height}, }, }) => { this._viewHeight = height; }} style={[ styles.container, { transform: [{translateY: this._animatedValue}], }, ]} > <Text style={styles.textMessage}>{textMessage}</Text> {actionButtonComponent} </Animated.View> ); } _animate(fromValue: number, toValue: number) { this._animatedValue.setValue(fromValue); Animated.spring(this._animatedValue, { toValue, easing: fromValue === SNACKBAR_PADDING ? easingValues.exit : easingValues.entry, }).start(); } } const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', position: 'absolute', bottom: 0, left: 0, right: 0, paddingHorizontal: 24, paddingTop: 14, paddingBottom: 24, backgroundColor: '#484848', }, textMessage: { fontSize: DEFAULT_FONT_SIZE, flex: 1, color: '#FFFFFF', }, actionButton: { paddingLeft: 10, alignItems: 'center', justifyContent: 'center', }, actionText: { fontSize: DEFAULT_FONT_SIZE, fontWeight: '600', color: '#FF9800', }, }); function mapStateToProps(state: RootState) { return { snackBar: state.snackBar, }; } function mapDispatchToProps(dispatch: Dispatch) { return { onCloseSnackBar: () => { dispatch({ type: 'HIDE_SNACKBAR_REQUESTED', }); }, }; } export default connect( mapStateToProps, mapDispatchToProps, )(SnackBarComponent);
import { useEffect, useState, } from 'react'; import { faSearch } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import ReactPaginate from 'react-paginate'; import { NavLink } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import { getActors } from '../../features/acteurs/action'; import { sendActor } from '../../features/acteur/acteur'; import { getActor } from '../../features/acteurs/action'; import { getSubActors } from '../../features/acteurs/action'; const ActeursOperation = () => { const acteurs = useSelector(state => state.acteurs.acteurs); const dispatch = useDispatch(); console.log(acteurs) var Acteurs = acteurs.reduce((unique, o) => { if(!unique.some(obj => obj.id === o.id)) { unique.push(o); } return unique; },[]); console.log(Acteurs); /* Pager */ const [pageNumber, setPageNumber] = useState(0); const ordersPerPage = 7; const pagesVisited = pageNumber*ordersPerPage; const pageCount = Math.ceil(Acteurs.length/ordersPerPage); const changePage = ({selected}) => { setPageNumber(selected); }; const [searchTerm, setSearchTerm] = useState(''); const display = Acteurs.slice(pagesVisited, pagesVisited+ordersPerPage).filter(acteur => { if (searchTerm == "") { return acteur; } else if (acteur.attributes.title.toLowerCase().includes(searchTerm.toLowerCase())) { return acteur; } }).map((acteur, key) => { let Parent = ''; if(acteur.childs[0] !== undefined){ if( acteur.parent.attributes !== undefined ){ Parent = acteur.parent.attributes.title return ( <tr key={key} > <td> <img src="/images/orgu.ico.gif" class="pd-b-7"/>&nbsp;&nbsp; <NavLink onClick={() => { dispatch(getActor(acteur.id)) }} className="text-dark" to={'/acteur/'+acteur.id}>{acteur.attributes.title}</NavLink> </td> <td>{acteur.attributes.field_type_acteur}</td> <td> <img src="/images/orgu.ico.gif" class="pd-b-7"/>&nbsp;&nbsp; <NavLink onClick={() => { dispatch(getActor(acteur.parent.id)) }} className="text-dark" to={'/acteur/'+acteur.parent.id}>{Parent}</NavLink> </td> <td> <NavLink onClick={() => { dispatch(getSubActors(acteur.childs)) }} className="text-dark" to={'/acteurs-rattache/'+acteur.id}>Rattachement</NavLink> </td> </tr> );} return ( <tr key={key} > <td> <img src="/images/orgu.ico.gif" class="pd-b-7"/>&nbsp;&nbsp; <NavLink onClick={() => { dispatch(getActor(acteur.id)) }} className="text-dark" to={'/acteur/'+acteur.id}>{acteur.attributes.title}</NavLink> </td> <td>{acteur.attributes.field_type_acteur}</td> <td>Pas d'acteur parent</td> <td> <NavLink onClick={() => { dispatch(getSubActors(acteur.childs)) }} className="text-dark" to={'/acteurs-rattache/'+acteur.id}>Rattachement</NavLink> </td> </tr> ); } else { if( acteur.parent.attributes !== undefined ){ Parent = acteur.parent.attributes.title return ( <tr key={key} > <td> <img src="/images/orgu.ico.gif" class="pd-b-7"/>&nbsp;&nbsp; <NavLink onClick={() => { dispatch(getActor(acteur.id)) }} className="text-dark" to={'/acteur/'+acteur.id}>{acteur.attributes.title}</NavLink> </td> <td>{acteur.attributes.field_type_acteur}</td> <td> <img src="/images/orgu.ico.gif" class="pd-b-7"/>&nbsp;&nbsp; <NavLink onClick={() => { dispatch(getActor(acteur.parent.id)) }} className="text-dark" to={'/acteur/'+acteur.parent.id}>{Parent}</NavLink> </td> <td>Pas de sous acteurs</td> </tr> );} return ( <tr key={key} > <td> <img src="/images/orgu.ico.gif" class="pd-b-7"/>&nbsp;&nbsp; <NavLink onClick={() => { dispatch(getActor(acteur.id)) }} className="text-dark" to={'/acteur/'+acteur.id}>{acteur.attributes.title}</NavLink> </td> <td>{acteur.attributes.field_type_acteur}</td> <td>Pas d'acteur parent</td> <td>Pas de sous acteurs</td> </tr> ); } } ); return ( <div className="content-wrapper"> <div className="content"> <div className="az-content-body az-content-body-dashboard-six mg-b-40 pd-l-25 pd-t-10"> <div className="row wd-100p"> <div className="col-12"> <h5 >Acteurs internes</h5> </div> <div className="search-box"> <button className="btn-search"><FontAwesomeIcon icon={faSearch}></FontAwesomeIcon></button> <input type="text" className="input-search" placeholder="Rechercher..." onChange={event => {setSearchTerm(event.target.value);}}/> </div> <div className="table-wrapper"> <table id="ActeurInterneTableId" className="fl-table" > <thead> <tr> <th className="wd-15p">Acteur</th> <th className="wd-5p">Type</th> <th className="wd-15p">Rattachement</th> <th className="wd-20p">Acteurs rattachés </th> </tr> </thead> <tbody> {display} </tbody> <ReactPaginate previousLabel={'<'} nextLabel={'>'} pageCount={pageCount} onPageChange={changePage} containerClassName={"page"} previousClassName={"page__btn"} nextClassName={"page__btn"} disabledClassName={"page__numbers"} activeClassName={"page__numbers active"} /> </table> </div> <br/> <br/> <br/> </div> </div> </div> </div> ) } export default ActeursOperation;
// Use the mongoose module for handling MongoDB connection const mongoose = require('mongoose') // Define the shape of a collection and settings for every values of the user element const taskSchema = mongoose.Schema({ title: String, content: String }) // Compile and export a model from the schema for the 'tasks' collection module.exports = mongoose.model("Task", taskSchema, 'tasks')
'use strict' module.exports = function(options) { return function(hook) { if (hook.data.type === 'resetGameState') { return hook.app.service("games").get(hook.id) .then((game) => { const defaultBoard = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] hook.data = { board: defaultBoard, winner: false, } }) } else { hook.id } } }
/** * 账号管理/账号详情 */ import React, { Component, PureComponent } from "react"; import { StyleSheet, Dimensions, View, Text, Button, Image, ScrollView, TouchableOpacity, Switch, Modal } from "react-native"; import { connect } from "rn-dva"; import Header from "../../components/Header"; import CommonStyles from "../../common/Styles"; import ImageView from "../../components/ImageView"; import TextInputView from "../../components/TextInputView"; import * as nativeApi from "../../config/nativeApi"; import * as requestApi from "../../config/requestApi"; import Line from "../../components/Line"; import Content from "../../components/ContentItem"; import { NavigationPureComponent } from "../../common/NavigationComponent"; const refunds = [ { title: "消费前可退", key: "CONSUME_BEFORE" }, { title: "限定时间前随时可退", key: "RESERVATION_BEFORE_BYTIME" }, { title: "预定时间前随时退", key: "RESERVATION_BEFORE" } ]; const { width, height } = Dimensions.get("window"); class AccountDetailScreen extends NavigationPureComponent { static navigationOptions = { header: null }; constructor(props) { super(props); this.state = { types: [], id: props.navigation.getParam('id',''), // 员工id currentAccount: {}, // 员工详情信息 merchantType: '', // 账号归属 accountBtlongVisible: false, // 账号归属Modal accountBtlong: [], roleData: { shop: [], notShop: { other: [], service: [], merchant: [] } }, // 权限配置页面保存的权限 shopResources: [], notShopResources: [] }; } blurState = { accountBtlongVisible: false, // 账号归属Modal } screenDidFocus = (payload)=> { super.screenDidFocus(payload) this.initData() } componentDidMount() { Loading.show() } initData = () => { Promise.all([ this.getData(), this.shopResourcePage(), this.notShopResourcePage() ]).then(res => { console.log('initData',res) let { roleData } = this.state roleData.shop = res[1]; res[2].map((notShopResourceItem, index) => { notShopResourceItem.childrenResources.map(item => { item['isSelect'] = false }) notShopResourceItem['isShow'] = true roleData.notShop[notShopResourceItem.key] = [notShopResourceItem] }) roleData.shop.map((shopItem, index) => { if (index === 0) { shopItem['isShow'] = true }else { shopItem['isShow'] = false } console.log('shopItem',shopItem) shopItem.resource && shopItem.resource.map(resourceItem => { resourceItem.childrenResources.map(roleItem => { roleItem['isSelect'] = false }) }) }) res[0].permissions.map(item => { if (item.shopId) { roleData.shop.map(shopItem => { shopItem.resource && shopItem.resource.map(resourceItem => { resourceItem.childrenResources.map(roleItem => { if (shopItem.shopId === item.shopId && item.key === roleItem.key) { roleItem['isSelect'] = true } }) }) }) } else { for (let key in roleData.notShop) { roleData.notShop[key].map(notShopResource => { console.log('123',notShopResource) notShopResource.childrenResources && notShopResource.childrenResources.map(roleItem => { if (item.key===roleItem.key) { roleItem['isSelect'] = true } }) }) } } }) console.log('roleDataroleData',roleData) this.setState({ currentAccount: res[0], roleData, merchantType: res[0].merchantType }) }).catch(err => { console.log(err) Toast.show('网络错误') }) } // 非店铺资源列表 notShopResourcePage = () => { return new Promise((resolve,reject) => { requestApi.notShopResourcePage().then(res => { console.log('notShopResourcePage',res) resolve(res) }).catch(err => { reject(err) console.log(err) }) }) } // 店铺资源列表 shopResourcePage = () => { const { navigation, userInfo } = this.props let merchantId = userInfo.merchantId; return new Promise((resolve,reject) => { requestApi.shopResourcePage({ merchantId, }).then(res => { console.log('shopResourcePage',res) resolve(res) }).catch(err => { console.log(err) reject(err) }) }) } // 获取详情 getData = (isRefresh) => { if (!isRefresh) { Loading.show(); } return new Promise((resolve,reject) => { requestApi.employeeDetail({ employeeId: this.state.id }).then(res=> { console.log('detail',res) resolve(res) }).catch(err => { reject(err) console.log(err) }) }) } componentWillUnmount() { } changeState(key, value) { this.setState({ [key]: value }); } // 获取商户账号归属 merchantTypePage = () => { Loading.show() requestApi.merchantTypePage().then(res => { console.log('reerer',res) let temp = []; if (res) { res.map(item => { if (item.auditStatus === 'success') { temp.push(item) } }) } this.setState({ accountBtlong: temp, accountBtlongVisible: true, }) }).catch(er => { }) } // 获取商户账号类型 getAccountType = (employeeType) => { return (this.props.merchant.find(item=>item.merchantType==employeeType) || {name:'获取中...'}).name // switch (employeeType) { // case 'personal': return '个人' // case 'anchor': return '主播' // case 'company': return '公司(合伙人)' // case 'shops': return '商户' // case 'familyL1': return '普通家族(家族长)' // case 'familyL2': return '钻石家族(公会)' // default: return '获取中...' // } } // 更新权限回调 handleUpdateRole = (type,otherRoleType,data) => { console.log('wrewrwrw',type,otherRoleType,data) let _roleData = JSON.parse(JSON.stringify(this.state.roleData)) if (type === 'shopRole') { _roleData.shop = data } else { _roleData.notShop[otherRoleType] = data } this.setState({ roleData: _roleData }) Loading.show() const currentAccount = this.state.currentAccount; let params = { employeeId: currentAccount.id, userPermissions: this.getRoleDataList(_roleData), merchantType:this.state.merchantType, name: currentAccount.realName }; console.log('参数',params) this.handleUpdateRoleRequest(params) } // 修改权限请求 handleUpdateRoleRequest = (params={}) => { requestApi.employeeUpdate(params).then(data => { console.log('更新权限回调',data) Toast.show("修改成功"); this.getData(true) if (this.state.accountBtlongVisible) { this.setState({ accountBtlongVisible: false }) } }).catch(error => { Loading.hide(); }); } getRoleDataList = (roleData) => { console.log('更新权限回调',roleData) let userPermissions = [] roleData.shop.map(shopItem => { shopItem.resource && shopItem.resource.map((resourceItem) => { resourceItem.childrenResources.map(roleItem => { if (roleItem.isSelect) { userPermissions.push({ shopId: shopItem.shopId, type: resourceItem.key, serviceList: roleItem.serviceList, key: roleItem.key, name: roleItem.name, icon: roleItem.icon }) } }) }) }) for (let key in roleData.notShop) { roleData.notShop[key].map(resourceItem => { resourceItem.childrenResources.map(roleItem => { if (roleItem.isSelect) { userPermissions.push({ type: resourceItem.key, serviceList: roleItem.serviceList, key: roleItem.key, name: roleItem.name, icon: roleItem.icon }) } }) }) } return userPermissions console.log('sdfasfdsfa',userPermissions) } saveEditor = () => { const currentAccount = this.state.currentAccount; Loading.show(); const params = { employeeId: currentAccount.id, phone: currentAccount.phone, name: currentAccount.realName }; requestApi.employeeUpdate(params).then(data => { console.log('res',data) Loading.hide(); Toast.show("修改成功"); }).catch(error => { Loading.hide(); }); }; // 保存的店铺权限配置 getRoleData = (type,otherRoleType,data) => { console.log('getRole',data) let _roleData = JSON.parse(JSON.stringify(this.state.roleData)) if (type === 'shopRole') { _roleData.shop = data } else { _roleData.notShop[otherRoleType] = data } this.setState({ roleData: _roleData }) } render() { const { navigation} = this.props; const { currentAccount,merchantType,accountBtlongVisible,accountBtlong } = this.state; let limit = []; for (item of currentAccount.resource || []) { limit.push(item.shopName); } let items = [ // { title: '账号', value: 'fdfdf', type: '' ,key:'account'}, { title: "账号", value: currentAccount.nickName || '', type: "", key: "yaoqingma" }, { title: "安全码", value: currentAccount.inviteCode || '', type: "", key: "yaoqingma" }, { title: "手机号", value: currentAccount.phone || '', type: "horizontal", key: "phone", nextPageTitle: "修改手机号" }, { title: "名称", value: currentAccount.realName || '', type: "horizontal", key: "name", nextPageTitle: "修改名称" }, { title: "密码", value: "重置初始密码", type: "horizontal", key: "password", nextPageTitle: "重置初始密码" }, ]; return ( <View style={styles.container}> <Header title="账号详情" navigation={navigation} goBack={true} /> <ScrollView alwaysBounceVertical={false} style={{ flex: 1,paddingBottom: 100 }}> <View style={styles.content}> <Content> {items.map((item, index) => { return ( <View key={index} style={{ position: "relative" }} > <Line title={item.title} type={item.type} rightValueStyle={{ textAlign: "right", color:item.title=='安全码'?CommonStyles.globalHeaderColor: '#222' }} point={null} value={item.value} onPress={() => { if (item.type == "horizontal") { navigation.navigate("AccountUpdate",{ page: item, currentAccount: this.state.currentAccount, callback: () => {this.getData(false)} } ); } }} /> </View> ); })} </Content> </View> <View style={[styles.selectBelong]} > <TouchableOpacity onPress={() => { this.merchantTypePage() }} style={[CommonStyles.flex_between,{padding: 15}]}> <Text style={{fontSize: 14,color: '#222',textAlign: 'right'}}>账号归属</Text> <View style={[CommonStyles.flex_start]}> { merchantType === '' ? <Text style={{fontSize: 14,color: '#777'}}>请选择</Text> :<Text style={{fontSize: 14,color: '#222'}}>{this.getAccountType(merchantType)}</Text> } <Image source={require('../../images/index/expand.png')}/> </View> </TouchableOpacity> </View> <View style={styles.roleWrap}> { merchantType === 'shops' ? <TouchableOpacity onPress={() => { navigation.navigate("AccountRoleConfi", { type: 'shopRole', // 分店铺权限(shopRole)和其他权限(otherRole),店铺权限会根据店铺个数渲染,其他的只有一个 callback: this.getRoleData, roleData: JSON.parse(JSON.stringify(this.state.roleData)), // 传入选择了的权限,配置页面自动打钩 isUpdate: true, updateCallBack: this.handleUpdateRole }) }} style={[CommonStyles.flex_between,{padding:15,borderBottomColor: '#f1f1f1',borderBottomWidth: 1}]}> <Text style={{fontSize: 14,color: '#222'}}>店铺权限</Text> <View style={[CommonStyles.flex_start]}> {/* <Text style={{fontSize: 14,color: '#777'}}>dsf</Text> */} <Image source={require('../../images/index/expand.png')}/> </View> </TouchableOpacity> : null } <TouchableOpacity onPress={() => { navigation.navigate("AccountRoleConfi", { type: 'otherRole', // 分店铺权限(shopRole)和其他权限(otherRole),店铺权限会根据店铺个数渲染,其他的只有一个 otherRoleType: 'merchant', // 其他权限类型 roleData: JSON.parse(JSON.stringify(this.state.roleData)), // 传入选择了的权限,配置页面自动打钩 callback: this.getRoleData, isUpdate: true, updateCallBack: this.handleUpdateRole }) }} style={[CommonStyles.flex_between,{padding:15,borderBottomColor: '#f1f1f1',borderBottomWidth: 1}]}> <Text style={{fontSize: 14,color: '#222'}}>联盟商权限</Text> <View style={[CommonStyles.flex_start]}> {/* <Text style={{fontSize: 14,color: '#777'}}>dsf</Text> */} <Image source={require('../../images/index/expand.png')}/> </View> </TouchableOpacity> <TouchableOpacity onPress={() => { navigation.navigate("AccountRoleConfi", { type: 'otherRole', // 分店铺权限(shopRole)和其他权限(otherRole),店铺权限会根据店铺个数渲染,其他的只有一个 otherRoleType: 'service', // 其他权限类型 roleData: JSON.parse(JSON.stringify(this.state.roleData)), // 传入选择了的权限,配置页面自动打钩 isUpdate: true, updateCallBack: this.handleUpdateRole, callback: this.getRoleData }) }} style={[CommonStyles.flex_between,{padding:15,borderBottomColor: '#f1f1f1',borderBottomWidth: 1}]}> <Text style={{fontSize: 14,color: '#222'}}>客服权限</Text> <View style={[CommonStyles.flex_start]}> {/* <Text style={{fontSize: 14,color: '#777'}}>dsf</Text> */} <Image source={require('../../images/index/expand.png')}/> </View> </TouchableOpacity> {/* <TouchableOpacity onPress={() => { navigation.navigate("AccountRoleConfi", { type: 'otherRole', // 分店铺权限(shopRole)和其他权限(otherRole),店铺权限会根据店铺个数渲染,其他的只有一个 otherRoleType: 'other', // 其他权限类型 roleData: JSON.parse(JSON.stringify(this.state.roleData)), // 传入选择了的权限,配置页面自动打钩 isUpdate: true, updateCallBack: this.handleUpdateRole, callback: this.getRoleData }) }} style={[CommonStyles.flex_between,{padding:15,borderBottomColor: '#f1f1f1',borderBottomWidth: 1}]}> <Text style={{fontSize: 14,color: '#222'}}>其他权限</Text> <View style={[CommonStyles.flex_start]}> <Image source={require('../../images/index/expand.png')}/> </View> </TouchableOpacity> */} </View> </ScrollView> {/* 选择员工账号归属modal */} <Modal animationType="slide" transparent={true} visible={accountBtlongVisible} onRequestClose={() => {this.changeState('accountBtlongVisible',false)}} > <View style={styles.modal}> <View style={styles.modalContent}> { accountBtlong.length === 0 ? <TouchableOpacity style={[styles.modalItem, styles.flex_center, styles.borderBottom]} onPress={() => {this.changeState('accountBtlongVisible',false)}} > <Text style={styles.modalItemText}>暂无数据</Text> </TouchableOpacity> : accountBtlong.map((item, index) => { return ( <TouchableOpacity key={index} style={[styles.modalItem, styles.flex_center, styles.borderBottom]} onPress={() => { if ((item.merchantType || '') === this.state.merchantType) { this.setState({ accountBtlongVisible: false }) return } this.setState({ merchantType: item.merchantType, accountBtlongVisible: false, },() => { let params = { employeeId: currentAccount.id, userPermissions: [], merchantType:this.state.merchantType, name: currentAccount.realName }; this.handleUpdateRoleRequest(params) }) }} > <Text style={styles.modalItemText}>{this.getAccountType(item.merchantType)}</Text> </TouchableOpacity> ); }) } { } <TouchableOpacity activeOpacity={1} onPress={() => {this.changeState('accountBtlongVisible',false)}} style={[styles.modalItem, styles.flex_center,{paddingBottom:CommonStyles.headerPadding}]} > <View style={styles.block} /> <Text style={[styles.modalItemText]}>取消</Text> </TouchableOpacity> </View> </View> </Modal> </View> ); } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, backgroundColor: CommonStyles.globalBgColor }, content: { alignItems: "center", paddingBottom: 10 }, line: { paddingVertical: 14, paddingHorizontal: 10, borderColor: "#F1F1F1", borderBottomWidth: 1 }, code: { backgroundColor: "#fff", position: "absolute", right: 15, top: 14, height: 22, alignItems: "center", justifyContent: "center", borderWidth: 1, borderColor: "#4A90FA", borderRadius: 10 }, bomView: { marginBottom: 20 + CommonStyles.footerPadding }, modalOutView: { flex: 1, justifyContent: "center", alignItems: "center" }, modalInnerTopView: { flex: 1, width: width, backgroundColor: "rgba(0, 0, 0, .5)" }, modalInnerBottomView: { width: width, height: 300 + CommonStyles.footerPadding, backgroundColor: "#fff" }, userImgLists_item: { justifyContent: "center", alignItems: "center", width: width, height: 50 }, userImgLists_item1: { borderTopWidth: 1, borderTopColor: "#E5E5E5" }, userImgLists_item2: { borderTopWidth: 5, borderTopColor: "#E5E5E5" }, userImgLists_item_text: { fontSize: 16, color: "#000" }, modal: { // height: 342, flex: 1, backgroundColor: "rgba(10,10,10,.5)", position: "relative" }, modalContent: { position: "absolute", bottom: 0, left: 0, width, backgroundColor: "#fff" }, color_red: { color: "#EE6161" }, modalItemText: { fontSize: 17, color: "#222", textAlign: 'center' }, modalItem: { paddingVertical: 15, width, position: "relative" }, marginTop: { marginTop: 5 }, borderBottom: { borderBottomColor: "#f1f1f1", borderBottomWidth: 1 }, block: { width, height: 5, backgroundColor: "#F1F1F1", position: "absolute", top: 0, left: 0 }, flex_end: { flexDirection: "row", justifyContent: "flex-end", alignItems: "center" }, flex_start: { flexDirection: "row", justifyContent: "flex-start", alignItems: "center" }, selectBelong: { // margin: 10, marginTop: 0, marginLeft:10, ...CommonStyles.shadowStyle, backgroundColor: '#fff', borderRadius: 6, width: width - 20, overflow: 'hidden' }, roleWrap: { borderRadius: 6, backgroundColor: '#fff', margin: 10, }, }); export default connect( (state) => ({ userInfo:state.user.user || {}, merchant:state.user.merchant || [], }) )(AccountDetailScreen);
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; export const TextBuild = (props) => { const [checked, setChecked] = useState( props.checkedToPrint[props.printName] === true, ); const handleChange = (event) => { const value = event.target.checked; setChecked(value); props.addToPrint(props.printName, value); }; return ( <> <p> Banku bude zajímat nejvíce co a za kolik se bude stavět. </p> <p> <strong>Co:</strong> </p> <p> Máš domeček zatím pouze v plánu a chceš si zjistit, kolik ti banka na výstavbu půjčí. Tuto část můžeš přeskočit. <div className="link-in-text"> <p>Vrhni se rovnou dále:</p> <p> <Link to="/prijem">2. Příjem</Link> </p> </div> </p> <p>Naopak víš, co chceš postavit? </p> <p> Připrav si <strong>projektovou dokumentaci</strong>. Jsi v začátku a nemáš ji? Nevadí, připrav si{' '} <strong>obrázek v katalogu s cenou </strong> nebo jen rozpočet. Ten nemusí být finální, ale měl bys mít přestavu, kolik bude dům stát. </p> <p> <strong>Rozpočet – nejzásadnější dokument u výstavby</strong>. Banka ti poskytne většinou vzor k vyplnění, ale já doporučuji si nad to sednout, již před návštěvou banky a hrubě si vše sepsat. Nejlepší je odborně vypracovaný rozpočet už stavební firmou (ideálně na referenci, aby se pak nenavyšoval). </p> <p> <strong>Plánuješ stavět svépomocí?</strong> O to víc se nad rozpočtem zamysli. Často používaný postup, dojít do banky kolik mi půjčí a za to to muset postavit, není správný. Informaci o rozpočtu najdeš i v projektu. Většinou jde jen o souhrnnou informaci. Je lepší si nechat vypracovat rozpočet detailní. Věř mi, i když se budeš rozpočtu věnovat na maximum, tak se do něj většinou nevejdeš. Je důležité, aby to ale nebylo o moc. </p> <p> Chceš půjčit polovinu a bance nic není do toho za kolik to postavíš celkem? To není bohužel pravda. Banka bude chtít jistotu, že stavba bude dokončena. Bohužel se stává, že někdo má plán, jak postaví za levno a pak se dostane do situace, že na dostavbu peníze chybí. Když se jedná o finální práce, tak to zásadní problém být nemusí a časem se vše dodělá. Když ale dojdou peníze v půlce, tak to může být neřešitelný problém. Připrav si proto informaci, jak dofinancuješ celý rozpočet: </p> <ul> <li>Peníze na účtu</li> <li>Končící investice za nějaký čas</li> <li>Prodej současného bydlení atd.</li> </ul> <p> <strong>TIP:</strong> Výstavba je možná pouze na pozemku určeném ke stavění. Toto zjistíš v územním plánu nebo se zastav na obci/městě a oni ti dají potvrzení. </p> <p> <strong>TIP:</strong> Budeš stavět na pozemku, který je jiné osoby než stavba. Toto není standardní situace, banka ti sdělí přesné informace. Že je jasné, že nebudeš stavět na cizím? Sem spadají i varianty, kdy pozemek je pouze ve tvém vlastnictví a dům stavíš s druhem/družkou/manželem/manželkou. I tady majitelé nejsou stejní. Je možné pozemek přepsat na oba stavebníky nebo to musíte ošetřit smluvně, protože jinak katastrální úřad stavbu nezapíše. </p> <p> <strong>TIP:</strong> Informuj se v bance na to, jak bude uvolňovat peníze. Hypotéka je do procentní hodnoty toho, co dáváš bance do zástavy. Hotovost banka může uvolňovat na části, dle toho, jak se zvedá hodnota rozestavěné stavby. Banky mají čerpání řešeno různě, mohou v době výstavby umožnit zaslání větších částek. Stavba na vlastním pozemku nebude problém, např. 7o% hodnoty pozemku bude na část stavby stačit. Co když na tom pozemku máš hypotéku na jeho koupi. V tomto případě už uvolnění hotovosti je komplikovanější. Najdi vhodnou banku, která nabízí benefit a umožní na nějakou dobu 70% <em>"přestřelit"</em>. </p> <p> <strong>TIP:</strong> Důležitá je podmínka finálního uvolnění poslední hotovosti. Banka může vyžadovat doložení kolaudace, prože poslední peníze má určeny na dodělávky. Kolaudace se může protáhnout a hypotéka bude dlouho nevyplacená. Co to znamená? Úroky navíc. </p> <p> <strong>Tip:</strong> Rozložení čerpání znamená více úroku. Někomu to ale může vyhovovat, protože 1. velká splátka začne odcházet až následně. Za celou dobu nižší splátky se hotovost může vkládat do stavby. </p> <p> <strong>Tip:</strong> Většina bank nabízí možnost nějakou část hypotéky nevyčerpat. Pokud je dostatečná zástavní hodnota, tak doporučuji promyslet, jestli rezervu nenastavit a pak ji nedočerpat. Je ale pravdou, že náklady na stavbu se většinou navyšují a nedočerpání se moc často nepodaří. Je ale určitě levnější než hypotéku nedočerpat. </p> <p> Závěrem informativní shrnutí. Kdy u hypotéky odchází první splátka? Záleží na době než se uvolní celá hotovost. První splátka odejde většinou měsíc po uvolnění poslední <em>"koruny"</em> z hypotéky. </p> <div className="row-print"> <label className="checkbox"> Přidat do tisku: <input className="print" type="checkbox" checked={checked} onChange={handleChange} /> <span></span> </label> <Link to="/print">Prohlédnout tisk</Link> </div> <div className="buttons-row__buttons"> <Link to="/"> <button className="button--back ">Domů</button> </Link> <Link to="/prijem"> <button className="button--forward">Pokračovat</button> </Link> </div> </> ); };
const body=document.querySelector('section'); const div=document.createElement('div'); const el = document.createElement('div'); el.classList.add('visualizzaDOT'); div.classList.add('container'); body.appendChild(el); el.appendChild(div); document.querySelector('body').classList.add('no-scroll'); const dot1=document.createElement('div'); dot1.classList.add('dot'); dot1.setAttribute('id', 'dot1'); div.appendChild(dot1); const dot2=document.createElement('div'); dot2.classList.add('dot'); dot2.setAttribute('id', 'dot2'); div.appendChild(dot2); const dot3=document.createElement('div'); dot3.classList.add('dot'); dot3.setAttribute('id', 'dot3'); div.appendChild(dot3); setTimeout(removeLoad, 4000, el); function removeLoad(el){ el.remove(); document.querySelector('body').classList.remove('no-scroll'); } function caricaFotografi(event){ fetch('AboutUs/fotografi').then(onResponse).then(onJsonFotografi); } function onJsonFotografi(json){ console.log(json); const section=document.querySelector('section'); const item=section.querySelector('button'); item.remove(); const newSep=document.createElement('div'); newSep.classList.add('separatore'); section.appendChild(newSep); const newTit=document.createElement('h1'); newTit.textContent='Fotografi'; section.appendChild(newTit); const article = document.createElement('article'); section.appendChild(article); for(let fotografo of json.fotografi){ const newDiv = document.createElement('div'); newDiv.classList.add('fotografo'); article.appendChild(newDiv); newDiv.dataset.CF=fotografo.CF; newDiv.dataset.citta=fotografo.citta; newDiv.dataset.cognome=fotografo.cognome; newDiv.dataset.dataInizio=fotografo.data_inizio; newDiv.dataset.dataNascita=fotografo.data_nascita; newDiv.dataset.fb=fotografo.facebook; newDiv.dataset.ig=fotografo.instagram; newDiv.dataset.nome=fotografo.nome; newDiv.dataset.sp=fotografo.playlist; newDiv.dataset.img=fotografo.propic; fetch('AboutUs/playlist/'+fotografo.playlist).then(onResponse).then(onJsonCaricaFotografi); } } function onJsonCaricaFotografi(json){ const playlist=json; const fotografi=document.querySelectorAll('.fotografo'); for(let fotografo of fotografi){ if(fotografo.dataset.sp===playlist.id){ const newFoto = document.createElement('img'); newFoto.src=fotografo.dataset.img; newFoto.classList.add('foto'); fotografo.appendChild(newFoto); const newInfo1 = document.createElement('div'); newInfo1.classList.add('info1'); fotografo.appendChild(newInfo1); const newName = document.createElement('p'); newName.textContent=fotografo.dataset.nome+' '+fotografo.dataset.cognome; newName.classList.add('nome'); newInfo1.appendChild(newName); const newCitt = document.createElement('p'); newCitt.textContent=fotografo.dataset.citta+' '+fotografo.dataset.dataNascita; newCitt.classList.add('txt'); newInfo1.appendChild(newCitt); const newInizio = document.createElement('p'); newInizio.textContent='scatta con noi dal '+fotografo.dataset.dataInizio; newInizio.classList.add('txt'); newInfo1.appendChild(newInizio); const newInfoSpotify = document.createElement('div'); newInfoSpotify.classList.add('infoSpot'); fotografo.appendChild(newInfoSpotify); const newPlayName = document.createElement('p'); newPlayName.textContent="Quando scatta ascolta '"+playlist.name+"'"; newPlayName.classList.add('musica'); newInfoSpotify.appendChild(newPlayName); const newImg = document.createElement('img'); newImg.src=playlist.images[0].url; newImg.classList.add('image'); newInfoSpotify.appendChild(newImg); const newInfoLink = document.createElement('div'); newInfoLink.classList.add('infoLinks'); fotografo.appendChild(newInfoLink); const newUrl1 = document.createElement('a'); newUrl1.href=fotografo.dataset.fb; const butt1=document.createElement('img'); butt1.src='immagini/facebook.png'; butt1.classList.add('link1'); newUrl1.appendChild(butt1); newInfoLink.appendChild(newUrl1); const newUrl2 = document.createElement('a'); newUrl2.href=fotografo.dataset.ig; const butt2=document.createElement('img'); butt2.src='immagini/instagram.png'; butt2.classList.add('link2'); newUrl2.appendChild(butt2); newInfoLink.appendChild(newUrl2); const newUrl3 = document.createElement('a'); newUrl3.href=playlist.external_urls.spotify; const butt3=document.createElement('img'); butt3.src='immagini/spotify.png'; butt3.classList.add('link3'); newUrl3.appendChild(butt3); newInfoLink.appendChild(newUrl3); } } } function onResponse(response){ return response.json(); } const button = document.querySelector('button'); button.addEventListener('click', caricaFotografi);
/** * Created by Evgi on 10/24/2017. */ import React from 'react'; import Divider from 'material-ui/Divider'; import ButtonsFrame from './/ButtonsFrame' import StarsFrame from './/StarsFrame' import NumbersFrame from './/NumberFrame' import AnswerFrame from './/AnswerFrame' import RaisedButton from 'material-ui/RaisedButton'; import Autorenew from 'material-ui/svg-icons/action/autorenew' import '../styles/nineGameStyle.css' export default class Game extends React.Component{ constructor(props){ super(props); this.state = {selectedNumbers: [], numberOfStars: Math.floor((Math.random() * 9) + 1), correct: null, alradyUsedNumbers: [] } this.clickOnNumber = this.clickOnNumber.bind(this); this.clickOnEqual = this.clickOnEqual.bind(this); this.acceptAnswer = this.acceptAnswer.bind(this); this.refreshGame = this.refreshGame.bind(this); } clickOnNumber(clickedValue){ if(this.state.selectedNumbers.indexOf(clickedValue) < 0 ){ this.setState( {selectedNumbers: this.state.selectedNumbers.concat(clickedValue), correct: null} ) } } clickOnNumberInAnswerFrame(clickedValue) { var newSelected = this.state.selectedNumbers.filter(val => val != clickedValue); this.setState( {selectedNumbers: newSelected, correct: null} ); } clickOnEqual() { var sum = this.state.selectedNumbers.reduce(function (a, b) { return a + b;}, 0); var isCorrect = this.state.numberOfStars == sum; this.setState({correct: isCorrect}) } acceptAnswer() { var newUsed = this.state.alradyUsedNumbers.concat(this.state.selectedNumbers) this.setState({ selectedNumbers: [], alradyUsedNumbers: newUsed, correct: null, numberOfStars: Math.floor((Math.random() * 9) + 1) }) } refreshGame() { this.setState({ selectedNumbers: [], alradyUsedNumbers: [], correct: null, numberOfStars: Math.floor((Math.random() * 9) + 1) }) } render() { var selectedNumbers = this.state.selectedNumbers; return ( <div id="game"> <h2 className="game-title">Play nine</h2> <Divider/> <div className="refreshbutton-frame"> <RaisedButton onClick ={this.refreshGame} icon={<Autorenew/>}/> </div> <StarsFrame numberOfStars1 = {this.state.numberOfStars}/> <div className="gameheart"> <NumbersFrame property2={selectedNumbers} clickNumber = {this.clickOnNumber} alreadyUsed = {this.state.alradyUsedNumbers}/> <AnswerFrame property1={selectedNumbers} clickWrongAnswer = {this.clickOnNumberInAnswerFrame.bind(this)}/> </div> <ButtonsFrame property3 = {selectedNumbers} isCorrect = {this.state.correct} afterClick={this.clickOnEqual} acceptAnswerFunction = {this.acceptAnswer} refreshGame = {this.refreshGame}/> </div> ) } };
import { createSelector } from "reselect"; import { initialState } from "../reducers/cart"; const selectCart = state => state.cart || initialState; export const makeSelectCartData = () => createSelector(selectCart, substate => substate.items); export const makeSelectCartTotalAmount = () => createSelector(selectCart, substate => substate.totalAmount);
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mysql = require('mysql'); var con = mysql.createConnection({ host : 'localhost', user : 'node', password : 'node', database : 'node' }); //測試 // con.connect(function(err) { // if (err) { // console.error('error connecting: ' + err.stack); // return; // } // // console.log('connected as id ' + con.threadId); // }); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); app.use('/', express.static('public')); app.post('/addUser',function(req,res){ var post = {id: 1, name: '失蹤龍'}; var query = con.query('INSERT INTO posts SET ?', post, function (error, results, fields) { if (error) throw error; // Neat! }); res.send("新增成功 新增資料為"+post.name+" 大大"); console.log(query.sql); }); app.get('/getUser',function(req,res){ con.connect(function(err) { if (err) throw err; con.query("SELECT * FROM posts", function (err, result, fields) { if (err) throw err; res.send(result); console.log(result); }); }); }); app.post('/create',function(req,res){ console.log(req.body); res.send('Post OK'); }); app.listen(3000, function () { console.log('Listen Port 3000!'); });
var playerControllers = angular.module('playerControllers', []); playerControllers.controller('ListController', ['$scope', '$http', function($scope, $http){ $http.get('js/data.json').success(function(data){ $scope.players = data; }); }]); playerControllers.controller('DetailsController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){ $http.get('js/data.json').success(function(data){ $scope.players = data; $scope.whichPlayer = $routeParams.itemId; if ($routeParams.itemId > 0){ $scope.prevId = Number($routeParams.itemId) - 1; }else{ $scope.prevId = $scope.players.length - 1; } if ($routeParams.itemId < $scope.players.length - 1){ $scope.nextId = Number($routeParams.itemId) + 1; }else{ $scope.nextId = 0; } }); }]);
import React from 'react'; const Button = ({ styles, text, icon, }) => { return ( <button className={styles}> <i className={icon}></i> {text} </button> ); } export default Button;
'use strict'; class Node { constructor(value) { this.value = value; } } class Graph{ constructor(){ this._adjacencyList = new Map(); } addNode(node){ this._adjacencyList.set(node,[]); } addEdge(startNode,endNode,weight = 0){ if(!this._adjacencyList.has(startNode) || !this._adjacencyList.has(endNode)) throw new Error('__ERROR__ invalid nodes'); let adjacencies = this._adjacencyList.get(startNode); adjacencies.push({ node:endNode, weight, }); } getNeighbors(node){ if(!this._adjacencyList.has(node)) throw new Error('__ERROR__ invalid node'); return [...this._adjacencyList.get(node)]; } breadthSearch(node){ let breadth = []; let result = []; breadth.push(node); // console.log(breadth) while(breadth.length){ // console.log(result); let cur = breadth.pop(); console.log('current',cur); if(!cur.touched) {result.push(cur);} cur.touched = true; console.log('result',result) let neighbors = this.getNeighbors(cur); // console.log(result) if(neighbors.length){ for (let i = 0; i<neighbors.length; i++){ breadth.push(neighbors[i]); } }//end if } return result; } }; let graph = new Graph(); let a = new Node('A') let b = new Node('B') let c = new Node('C') let d = new Node('D') let e = new Node('E') let f = new Node('F') graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addNode(e); graph.addNode(f); graph.addEdge(a,b); graph.addEdge(a,c); graph.addEdge(b,c); graph.addEdge(b,e); graph.addEdge(c,f); // console.log(graph.getNeighbors(a)); console.log(graph.breadthSearch(e))
import { SHOW_H1_START, SHOW_H1_SUCCESS, SHOW_H1_ERROR } from "./h1ActionTypes"; import { asyncFetchH1 } from "../../api/fetchH1Api"; export const doShowH1Start = () => { return { type: SHOW_H1_START, payload: { isFetching: true, }, }; }; export const doShowH1Success = (title) => { return { type: SHOW_H1_SUCCESS, payload: { h1Title: title, }, }; }; export const doShowH1Error = (error) => { return { type: SHOW_H1_ERROR, payload: { error: error, }, }; }; export const doAsyncFetchH1 = (url) => async (dispatch) => { dispatch(doShowH1Start()); try { const title = await asyncFetchH1(url); dispatch(doShowH1Success(title)); } catch (error) { dispatch(doShowH1Error(error)); } };
import React, { useRef, useState } from 'react'; import { useOnClickOutside } from './hooks'; import { Burger, Menu } from './components/nav'; import styled from 'styled-components'; import selfie from './ricktoews.me.jpg'; import SVGFunnel from './funnel.svg'; import SVGFunnelFill from './funnel-fill.svg'; import { theme } from './theme'; const TopBand = styled.div` position: absolute; top: 0; width: 100%; height: 6px; background-color: #666; `; const SiteHeader = styled.header` position: fixed; z-index: 100; top: 0; left: 0; width: 100vw; height: 70px; background: white; `; const SiteHeaderBackground = styled.header` position: relative; top: 0; left: 0; width: 100vw; height: 50px; background: ${({ theme }) => theme.mastheadBg}; `; const SiteHeaderOverlay = styled.div` position: absolute; top: 0; left: 0; width: 100vw; display: flex; justify-content: space-between; align-items: center; height: 100%; color: ${({ theme }) => theme.mastheadColor}; font-size: 20px; `; const Funnel = styled.div` display: inline-block; `; const Filter = styled.div` position: relative; display: flex; justify-content: center; font-size: 10px; ul { padding: 0; } li { display: inline; list-style-type: none; margin: 0; padding: 10px; cursor: pointer; } li: hover { color: black; } `; const Selfie = styled.div` width: 46px; height: 46px; margin-right: 10px; img { width: 100%; border-radius: 50%; border: 1px solid white; } `; const CategoryFilter = props => { const exclude = ['home', 'perambulations', 'bookshelf', 'autodidact', 'quote', 'travel']; return ( <Filter> <ul> <li onClick={() => { props.setCategoryFilter('') } }>Clear</li> <li><Funnel><img src={SVGFunnel} /></Funnel></li> { Object.keys(theme.categories).filter(cat => exclude.indexOf(cat) === -1).map((category, key) => ( <li key={key} onClick={() => { props.setCategoryFilter(category) } }>{category}</li> ))} </ul> </Filter> ); } function Masthead(props) { const { title, setCategoryFilter, showFilter, children } = props; const [open, setOpen] = useState(false); const node = useRef(); useOnClickOutside(node, () => setOpen(false)); return ( <SiteHeader> {/* Colored background for site header. */} <SiteHeaderBackground> <TopBand /> {/* Site header content: Menu button, Title, Photo */} <SiteHeaderOverlay> <div ref={node}> <Burger open={open} setOpen={setOpen}/> <Menu open={open} setOpen={setOpen}/> </div> {children} <div className="title">{title}</div> <Selfie><img src={selfie} /></Selfie> </SiteHeaderOverlay> </SiteHeaderBackground> {/* Category filter for home page items */} { showFilter && <CategoryFilter setCategoryFilter={setCategoryFilter} /> } </SiteHeader> ); } export default Masthead;
export default class User { constructor(firstName, lastName, email, dob, imageURL, gender){ this.firstName = this.capitalize(firstName); this.fullName = `${this.capitalize(firstName)} ${this.capitalize(lastName)}`; this.email = email; this.hiddenEmail = this.getData(); this.dob = this.formatDate(dob); this.imageURL = imageURL; this.gender = gender; } getData () { const a = this.email.split('@'); return a[0].slice(0,3)+'...'+a[0].slice(a[0].length-3, a[0].length )+'@'+a[1]; } formatDate(inputDate) { const date = new Date(inputDate); return `${date.getDate()}.${date.getMonth()+1}.${date.getFullYear()}` } capitalize(str){ return `${str.split(' ').map(name => `${name[0].toUpperCase()}${name.substring(1)}`).join(' ')}` } }
import Vue from 'vue' import Router from 'vue-router' import api from '@/http/api' import store from '@/store' import all from './modules/all' // 一级页面、注册登录找回密码页面 import my from './modules/my' // 个人中心的子级页面 import sale from './modules/sale' // 特价车的子级页面 import insurance from './modules/insurance' // 保险的子级页面 import index from './modules/index' // 首页的子级页面 import information from './modules/information' // 资讯的子级页面 Vue.use(Router) let router = new Router({ // mode: 'history', // base: '/dist/', routes: [ ...all, ...my, ...sale, ...insurance, ...index, ...information ] }) router.beforeEach((to, from, next) => { if(localStorage.getuser && localStorage.isLogin){ api.login.getMemberInfo().then(res => { if(res.code == 200){ console.log('changeUserData') console.log(res) store.commit('changeUserData', res.data) api.user.findMemberCarInfoByMemberId().then(carres=>{ if(carres.code == 200){ console.log('changeUserCarInfo') store.commit('changeUserCarInfo', carres.data) localStorage.getuser = '' } }) }else{ console.log(res) localStorage.removeItem('isLogin') } }).catch(()=>{ localStorage.removeItem('isLogin') store.commit('changeUserData', {}) store.commit('changeUserCarInfo', []) }) } next() }) export default router
import request from '../plugins/axios' export function getCommentList (pageNum = 0, pageSize = 8) { return request({ url: '/comments', method: 'GET', params: { pageNum: pageNum, pageSize: pageSize } }) } export function getCommentByArticleId (articleId) { return request({ url: '/comments', method: 'GET', params: { articleId: articleId } }) } export function getCommentByUserId (userId, pageNum = 0, pageSize = 8) { return request({ url: '/comments', method: 'GET', params: { userId: userId, pageNum: pageNum, pageSize: pageSize } }) } export function getCommentTotal (userId) { return request({ url: '/comments/total', method: 'GET' }) } export function creatComment (comment) { return request({ url: '/comments', method: 'POST', data: comment }) } export function updateComment (comment) { return request({ url: '/comments', method: 'PATCH', data: comment }) } export function deleteComment (commentId) { return request({ url: '/comments', method: 'DELETE', params: { commentId: commentId } }) }
//Libs import React from 'react'; import { Router, useNavigate } from '@reach/router'; //Components import Toolbar from '../../components/Toolbar'; import StepsNavBar from '../../components/StepsNavBar'; //Pages import ConnectAccount from './ConnectAccount'; import GenerateKey from './GenerateKey'; import AddKey from './AddKey'; import CloneRepo from './CloneRepo'; const steps = ['Connect', 'Generate', 'Add', 'Clone']; export default function SSHSetup() { const [activeStepIndex, setActiveStepIndex] = React.useState(0); const navigate = useNavigate(); function goBackToHomeScreen() { navigate('/'); } function onNext(path) { switch (path) { case 'oauth/success': case 'oauth/connect': setActiveStepIndex(0); break; case 'oauth/generate': setActiveStepIndex(1); break; case 'oauth/add': setActiveStepIndex(2); break; case 'oauth/clone': setActiveStepIndex(3); break; default: break; } navigate(path); } return ( <div className="bg-gray-300 h-screen"> <Toolbar onBackPressed={goBackToHomeScreen} title="Setup SSH" /> <StepsNavBar steps={steps} activeIndex={activeStepIndex} /> <Router> <ConnectAccount path="/connect" onNext={onNext} /> <GenerateKey path="/generate" onNext={onNext} /> <AddKey path="/add" onNext={onNext} /> <CloneRepo path="/clone" /> </Router> </div> ); }
import { DisplayObjectContainer } from "./DisplayObjectContainer.js"; import { Vector2 } from "../geom/Vector2.js"; import { AABB2 } from "../geom/AABB2.js"; const CAMERA_TRACKING_SPEED = 0.1; export class Camera extends DisplayObjectContainer { constructor() { super(); this.id = "Camera"; this.realPosition = new Vector2(); this.viewportSize = new Vector2(); this.halfViewportSize = new Vector2(); this.shake = new Vector2(); this.viewPortAABB = new AABB2(); this.worldExtentsAABB = new AABB2(); } focus(x, y) { //Need to move the camera container the oposite way to the actual coords this.realPosition.x = x; this.realPosition.y = y; //Clamp position inside shrunk camera extents this.cameraExtentsAABB.fitPoint(this.realPosition); var positionx = -this.realPosition.x + this.halfViewportSize.x; var positiony = -this.realPosition.y + this.halfViewportSize.y; if (Math.abs(positionx - this.position.x) > 2) this.position.x = this.position.x + (positionx - this.position.x) * CAMERA_TRACKING_SPEED; if (Math.abs(positiony - this.position.y) > 2) this.position.y = this.position.y + (positiony - this.position.y) * CAMERA_TRACKING_SPEED; // position.y = positiony; this.position.plusEquals(this.shake); this.position.x = this.rf(this.position.x); this.position.y = this.rf(this.position.y); this.shake.setTo(0, 0); } resize(width, height) { this.viewportSize.x = width; this.viewportSize.y = height; this.halfViewportSize.x = width / 2; this.halfViewportSize.y = height / 2; this.viewPortAABB.l = this.viewPortAABB.t = 0; this.viewPortAABB.r = this.viewportSize.x; this.viewPortAABB.b = this.viewportSize.y; //Clone the world size, then shrink it around the center by viewport size this.cameraExtentsAABB = this.worldExtentsAABB.clone(); this.cameraExtentsAABB.expand2(width, height); } rf(v) { return v; return Math.floor(v); return Math.round(v); } }
import React from "react"; import { Menu } from "antd"; import MenuConfig from "./../../config/menuConfig"; import "./index.less"; import { NavLink } from "react-router-dom"; import { connect } from "react-redux"; import { switchMenu } from "../../redux/action/action"; const { SubMenu } = Menu; class NavLeft extends React.Component { constructor(props) { super(props); let selectedKeys = [window.location.hash.replace(/#|\?.*$/g, "")]; this.state = { selectedKeys, }; this.menuTreeNode = this.renderMenu(MenuConfig); } //菜单渲染 renderMenu = (data) => { return data.map((item) => { if (item.children) { return ( <SubMenu title={item.title} key={item.key}> {this.renderMenu(item.children)} </SubMenu> ); } // 菜单渲染的时候顺便判断一下初始的key处在哪个title下并初始化面包屑 if (item.key === this.state.selectedKeys[0]) { this.changeTitle(item.title); } return ( <Menu.Item title={item.title} key={item.key}> <NavLink to={item.key}>{item.title}</NavLink> </Menu.Item> ); }); }; handleClick = (e) => { this.changeTitle(e.item.props.title); this.setState({ selectedKeys: [e.key], }); }; changeTitle = (title) => { // 使用redux更改值 const { dispatch } = this.props; dispatch(switchMenu(title)); }; render() { return ( <div> <div className="logo"> <img src="/assets/logo-ant.svg" alt="" /> <h1>共享单车管理</h1> </div> <Menu theme="dark" selectedKeys={this.state.selectedKeys} onClick={this.handleClick} onSelect={this.handleSelect} > {this.menuTreeNode} </Menu> </div> ); } } export default connect()(NavLeft);
const _ = require('lodash'); function getModifiedDate(data) { let context = data.context ? data.context : null; let modDate; context = _.includes(context, 'amp') ? 'post' : context; if (data[context]) { modDate = data[context].updated_at || null; if (modDate) { return new Date(modDate).toISOString(); } } return null; } module.exports = getModifiedDate;
import Head from 'next/head' import imgfooter from '../assets/img/img-footer.png' import FolderBox from '../components/FolderBox' import Header from '../components/Header' import DownHeader from '../components/DownHeader' import { Container, FooterBox} from './../styles/Home'; import Social from '../components/Social' import Information from '../components/Information' import Products from '../components/Products' import Questions from '../components/Questions' import MobileMenu from '../components/MobileMenu' import { ServerStyleSheet } from "styled-components"; export default function Home() { return ( <Container> <Head> <title>YouVisa</title> <link rel="icon" href="/favicon.ico" /> {/* <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"></link> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> */} </Head> <Header/> <DownHeader /> <Social /> <Information /> <Products /> <Questions /> <MobileMenu /> <FolderBox /> </Container> ) }
const priceSpan = { 'price': ['0'] } export default priceSpan;
// Day 4:File Read Operation Excercise 1 const lineReader = require('line-reader'); lineReader.eachLine('C:/Users/anasagar/Documents/InternalTraining/RandomText.txt', function(err,data) { if (!err) { console.log(line); } else { console.log(err); } console.log('File read operation at the end'); });
const express = require('express'); const app = express(); const server = require('http').Server(app); const router = express.Router(); const fs = require('fs') //文件系统 // 图片上传 const multer = require('multer'); const upload = multer({ dest: 'min-imgs/' }); const port = '8666'; const ip = '127.0.0.1'; server.listen(port, ip, function(){ console.log("释放端口:"+ip+':'+port); }); //设置公共静态路由 app.use(express.static('./')); app.use(router); //-------------------------Entry-------------------------- router.get('/',(req,res)=>{ res.sendFile(__dirname+'/index.html') }); router.post('/uploadImg', upload.any(), (req,res) => { console.log('uploadImg') });