text
stringlengths
7
3.69M
/** * @file san-xui/x/forms/builtins/RadioSelect.js * @author liyuan */ import RadioSelect from '../../components/RadioSelect'; const tagName = 'ui-form-radioselect'; export default { type: 'radioselect', tagName, Component: RadioSelect, builder(item, prefix) { return ` <${tagName} s-if="!preview" datasource="{{${prefix}.datasource}}" value="{=formData.${item.name}=}" /> <span s-else>{{formData.${item.name}}}</span>`; } };
import { useState } from 'react'; import Router from 'next/router'; import { Mutation } from 'react-apollo'; import gql from 'graphql-tag'; import Form from './styles/Form'; import formatMoney from '../lib/formatMoney'; import Error from './ErrorMessage'; const CREATE_ITEM_MUTATION = gql` mutation CREATE_ITEM_MUTATION( $title: String! $description: String! $price: Int! $image: String $largeImage: String ) { createItem( title: $title description: $description price: $price image: $image largeImage: $largeImage ) { id } } `; const CreateItem = () => { const [title, setTitle] = useState(''); const [price, setPrice] = useState(0); const [description, setDescription] = useState(''); const [image, setImage] = useState(''); const [largeImage, setLargeImage] = useState(''); const onSubmitHandler = async (e, createItem) => { e.preventDefault(); const res = await createItem(); Router.push({ pathname: '/item', query: { id: res.data.createItem.id }, }); }; const uploadFile = async e => { const files = e.target.files; const data = new FormData(); data.append('file', files[0]); data.append('upload_preset', 'sickfits'); const res = await fetch( 'https://api.cloudinary.com/v1_1/abasthrcodes/image/upload', { method: 'POST', body: data } ); const file = await res.json(); setImage(file.secure_url); setLargeImage(file.eager[0].secure_url); }; const variables = { title, description, price, image, largeImage, }; return ( <Mutation mutation={CREATE_ITEM_MUTATION} variables={{ ...variables }}> {(createItem, { loading, error }) => ( <Form onSubmit={e => onSubmitHandler(e, createItem)}> <Error error={error} /> <fieldset disabled={loading} aria-busy={loading}> <label htmlFor='file'> Image <input type='file' name='file' id='file' placeholder='Upload an image' required onChange={uploadFile} /> </label> <label htmlFor='title'> Title <input type='text' name='text' id='text' placeholder='Title' required value={title} onChange={e => setTitle(e.target.value)} /> </label> <label htmlFor='price'> Price <input type='number' name='price' id='price' placeholder='Price' required value={price} onChange={e => setPrice(e.target.value && parseFloat(e.target.value)) } /> </label> <label htmlFor='description'> Description <textarea name='description' id='description' placeholder='Enter A Description' required value={description} onChange={e => setDescription(e.target.value)} /> </label> <button type='submit'>Submit</button> </fieldset> </Form> )} </Mutation> ); }; export default CreateItem; export { CREATE_ITEM_MUTATION };
var User = require('../user'); module.exports = function(req, res, next){ /*每个请求都以userId抽取数据库的user数据*/ // 提供给外部接口的 if (req.remoteUser) { res.locals.user = req.remoteUser; } // 当用户ID出现时,表明用户已经通过认证了,所以从Redis中取出用户数据是安全的。 // 借助session中间件, 读取缓存的通信记录, 获取userId var uid = req.session.uid; if (!uid) return next(); User.find({_id:uid}, function(err, data){ var user = data[0]; if (err) { console.log('用户验证信息报错', err); return next(err); }else{ console.log('本请求的用户信息', user); } req.user = res.locals.user = user; // callback后才交出中间件控制权 next(); }); };
const PREFIX = 'auth' // @todo standardize this export const AUTH_REQUEST = `${PREFIX}/AUTH_REQUEST` export const AUTH_USER = `${PREFIX}/AUTH_USER` export const AUTH_FAIL = `${PREFIX}/AUTH_FAIL` export const UNAUTH_USER = `${PREFIX}/UNAUTH_USER` export const GET_JWT_FAILURE = `${PREFIX}/GET_JWT_FAILURE` export const GET_JWT_REQUEST = `${PREFIX}/GET_JWT_REQUEST` export const GET_JWT_SUCCESS = `${PREFIX}/GET_JWT_SUCCESS` export const GET_JWT_WAITING = `${PREFIX}/GET_JWT_WAITING` export const SET_JWT = `${PREFIX}/SET_JWT` export const SESSION_CHECK_FAILURE = `${PREFIX}/SESSION_CHECK_FAILURE` export const SESSION_CHECK_REQUEST = `${PREFIX}/SESSION_CHECK_REQUEST` export const SESSION_CHECK_SUCCESS = `${PREFIX}/SESSION_CHECK_SUCCESS` export const SESSION_CHECK_WAITING = `${PREFIX}/SESSION_CHECK_WAITING`
const hours = document.getElementById("hour"); const minute = document.getElementById("minute"); const second = document.getElementById("second"); const progress = document.getElementById("progress"); function showCurrentTime() { let setDate = new Date(); let hr = setDate.getHours(); let min = setDate.getMinutes(); let sec = setDate.getSeconds(); hours.textContent = hr; minute.textContent = min; second.textContent = sec; progress.style.width = (sec / 60) * 100 + '%'; } setInterval(showCurrentTime, 1000);
function ProgressTrackingController (Datas, CurrentProject) { 'ngInject' let vm = this vm.currentProject = CurrentProject.getCurrentProject() vm.progressInfo = Datas.Progress._items ? Datas.Progress._items[0] : [] vm.launchInfo = Datas.LaunchCeremony.launch_ceremony vm.operationSurveyInfo = Datas.OperationSurvey.precheck } // for route resolve ProgressTrackingController.resolver = function ($q, FormData, CurrentProject) { 'ngInject' const currentProject = CurrentProject.getCurrentProject() return $q.all({ Progress: FormData.PROJECT_PROGRESS.get({project_status: currentProject.status, project_id: currentProject._id, page: 1, max_results: 1, sort: '[("_created",-1)]'}).$promise, LaunchCeremony: FormData.PROJECT_LAUNCH_CEREMONY.get({project_status: currentProject.status, project_id: currentProject._id}).$promise, OperationSurvey: FormData.PROJECT_PRE_CHECK.get({project_status: currentProject.status, project_id: currentProject._id}).$promise }) } export default ProgressTrackingController
import model from '../db/models'; const { Users, Articles, Notifications, Reporting } = model; /** * Admin class functionality */ class AdminManager { /** * * @param {Object} req * @param {Object} res * @returns {Object} returns all users */ static async getAll(req, res) { try { const usersCount = await Users.count(); const articleCount = await Articles.count(); const reportCount = await Reporting.count(); const notifyCount = await Notifications.count(); const allUsers = await Users.findAll(); if (allUsers) { return res.status(200).json({ users: allUsers, usersCount, articleCount, reportCount, notifyCount }); } return res.status(404).json({ message: 'Users was not found' }); } catch (error) { return res.status(500).json({ error }); } } /** * * @param {Object} req * @param {Object} res * @returns {Object} return user deleted */ static async delete(req, res) { const { id } = req.params; try { const deleteUser = await Users.destroy({ where: { id } }); if (deleteUser) { return res.status(200).json({ message: 'user deleted successfully' }); } return res.status(409).json({ error: 'The user was not deleted please, try again' }); } catch (error) { return res.status(500).json({ error }); } } } export default AdminManager;
const db = require('./db') db.sequelize.sync() .then( ()=>{ console.log("db sync ok") process.exit() }, (err)=>{ console.log('db sync error', err) process.exit() } )
import {gsap} from "gsap"; import { ScrollTrigger } from "gsap/ScrollTrigger"; gsap.registerPlugin(ScrollTrigger); const snacksTL = gsap.timeline(); snacksTL.from("#snacks",{duration:4, x:-500}); export function snacksAnimation(){ ScrollTrigger.create({ // markers: true, animation: snacksTL, // toggleActions: "play none none none", trigger: "#snacks", start:"top, 100%", end: "bottom 50%", scrub: 2 }); } const ImgTL = gsap.timeline(); // gsap.set("#intro",{transformOrigin: "center"}); ImgTL.from(".img",{duration:2, x:-80, alpha:0.1}); export function imgAnimation(){ ScrollTrigger.create({ // markers: true, animation: ImgTL, // toggleActions: "play none none none", trigger: ".img", start:"top, 100%", end: "bottom, 40%", scrub: 2 }); }
var mini_menu = document.getElementById("mini-menu"); var list = mini_menu.getElementsByTagName("li"); var clear = function() { for (let i=0; i < list.length; i++) { list[i].style.right = "-99px"; mini_menu.style.height = "0"; } }; var dispose = function() { for (let i=0; i < list.length; i++) { list[i].style.right = "0px"; mini_menu.style.height = "200px"; } }; mini_menu.addEventListener("mouseout", clear, false); mini_menu.addEventListener("mousemove", dispose, false); /*var mini_menu = document.getElementById('mini-menu'); var lis = mini_menu.getElementsByTagName("li"); mini_menu.addEventListener("mousemove", function() { for (var i = 0; i < lis.length; i++) { lis[i].style.right = "0"; mini_menu.style.height = "160px"; } }, false) mini_menu.addEventListener("mouseout", function() { for (var i = 0; i < lis.length; i++) { lis[i].style.right = "-99px"; //mini_menu.style.height = "0"; } }, false)*/
var producto_consumido_nuevo_counter = 0; //tiene que ser una variable global var maquina_utilizada_nueva_counter = 0; //tiene que ser una variable global var movilidad_utilizada_nueva_counter = 0; //tiene que ser una variable global var mano_obra_nuevo_counter = 0; //tiene que ser una variable global var tipo_trabajo_nuevo_counter = 0; //tiene que ser una variable global var extra_nuevo_counter = 0; //tiene que ser una variable global var promotor_nuevo_counter = 0; function borrar_elemento(nombreElemento, elementoId){ stringSelector = `[data-${nombreElemento}-id=\'${elementoId}\']` console.log(stringSelector) elemento = document.querySelector(stringSelector); elemento.parentNode.removeChild(elemento); } function to_camel(s){ return s.replace(/([-_][a-z])/ig, ($1) => { return $1.toUpperCase() .replace('-', '') .replace('_', ''); }); } function anadir_elemento(nombreElemento, counter, cantidad=null, responsable=null) { console.log('-----------------------------------') console.log(nombreElemento) console.log(counter) var nuevo_data = "nuevo-" + counter; elemento = document.createElement('DIV'); elemento.className = `orden-${nombreElemento}_item`; elemento.setAttribute(`data-${nombreElemento}-id` ,nuevo_data); // este es el nombre, tambien lo llevan todos, no es necesario verificar elementoInput = document.createElement('INPUT'); elementoInput.type = "text"; elementoInput.className = `buscar-${nombreElemento} input_field`; elementoInput.addEventListener('keyup',function(){elementSearch(nuevo_data,nombreElemento)}, false) elementoInput.addEventListener('focus',elementSearch, false) elementoInput.addEventListener('focusout',cancelSearch, false) // lo llevan todos, no es necesario verificar elementoInputId = document.createElement('INPUT'); elementoInputId.type = "text"; elementoInputId.className = `buscar-${nombreElemento}-id`; elementoInputId.name = `${nombreElemento}_item--nuevo-${counter}`; // tambien todos llevan borrar elementoBorrar = document.createElement('DIV') elementoBorrar.className = `${nombreElemento}_borrar borrar-elemento` // TODO: la funcion borrar elemento tambien tiene que ser usada por todos // elementoBorrar.setAttribute("onClick",`borrar_${nombreElemento}(\'`+nuevo_data+"\')") elementoBorrar.setAttribute("onClick",`borrar_elemento(\'${nombreElemento}\',\'${nuevo_data}\')`) elementoBorrarIcon = document.createElement('I') elementoBorrarIcon.className = "far fa-trash-alt" elementoBorrar.appendChild(elementoBorrarIcon) elementoBusqueda = document.createElement('UL') elementoBusqueda.className = `lista_busqueda_${nombreElemento}` elemento.appendChild(elementoInput) elemento.appendChild(elementoInputId) if (responsable){ // hacer un fetch para traer el responsable_id var elementoInputResponsable = document.createElement('INPUT') elementoInputResponsable.type = "text" elementoInputResponsable.className = `buscar-${nombreElemento}_responsable`; //elementoInputResponsable.name= `cantidad_${nombreElemento}--${nuevo_data}` elemento.appendChild(elementoInputResponsable) } if (cantidad){ var elementoInputCantidad = document.createElement('INPUT') elementoCantidadContainer = document.createElement('DIV') elementoCantidadContainer.className = "cantidad-uom" elementoInputCantidad.type = "text" // elementoInputCantidad.className = `${nombreElemento}_cantidad` elementoInputCantidad.className = 'input_field' elementoInputCantidad.name= `cantidad_${nombreElemento}--${nuevo_data}` elementoUom = document.createElement('DIV') elementoUom.className = `${nombreElemento}_uom` elementoUom.innerHTML = 'uom' elementoCantidadContainer.appendChild(elementoInputCantidad) elementoCantidadContainer.appendChild(elementoUom) elemento.appendChild(elementoCantidadContainer) } elemento.appendChild(elementoBorrar) elemento.appendChild(elementoBusqueda) lista_elementos = document.querySelector(`.orden-${nombreElemento}_lista_body`); lista_elementos.appendChild(elemento); add_counter(nombreElemento) } function get_uom(prdocut_id){ Url = `/buscaruom?id=${productid}` fetch(Url).then(data=>{return data.json()}) .then(res => { console.log('---------------') console.log(res['uom']) return res['uom'] }) } function add_counter(nombreElemento) { switch (nombreElemento) { case "tipo_trabajo": window.tipo_trabajo_nuevo_counter++ break; case "mano_obra_utilizada": window.mano_obra_nuevo_counter++ break; case "producto_consumido": window.producto_consumido_nuevo_counter++; break; case "maquina_utilizada": window.maquina_utilizada_nueva_counter++; break; case "movilidad_utilizada": window.movilidad_utilizada_nueva_counter++; break; case "extra": window.extra_nuevo_counter++; break; case "promotor": window.promotor_nuevo_counter++; break; default: console.log('Hit default'); } } function get_counter(nombreElemento){ console.log(nombreElemento) switch (nombreElemento) { case "tipo_trabajo": return window.tipo_trabajo_nuevo_counter break; case "mano_obra_utilizada": return window.mano_obra_nuevo_counter break; case "producto_consumido": return window.producto_consumido_nuevo_counter; break; case "maquina_utilizada": return window.maquina_utilizada_nueva_counter; break; case "movilidad_utilizada": return window.movilidad_utilizada_nueva_counter; break; case "extra": return window.extra_nuevo_counter; break; case "promotor": return window.promotor_nuevo_counter; break; default: console.log('Hit default'); } } function elementSearch(item_data, tipo){ // data-producto-id o data-maquina-id //console.log("[data-"+tipo+"-id=\'"+item_data+"\']") item = document.querySelector("[data-"+tipo+"-id=\'"+item_data+"\']") input_element = item.querySelector(`.buscar-${tipo}`) input_value = input_element.value //console.log(`item: ${item}`) //console.log(`input_element: ${input_element}`) //console.log(`input_value: ${input_value}`) // type si el input tiene data-tipo = 'maquina' o 'producto' y lo añado a la url como get // generar la clase del searchList dinamicamente si es maquina o producto (necesitaria un data en realidad) searchList = item.querySelector(`.lista_busqueda_${tipo}`) if (input_value.length >= 3){ Url = `/buscarelemento?input=${input_value}&amp;tipo=${tipo}` // console.log(input); // fetch de busqueda if (tipo=='producto_consumido') { uom = (elemento[2]) ? elemento[2] : '' } fetch(Url).then(data=>{return data.json()}) .then(res => { // limpiar la lista while (searchList.firstChild) { searchList.removeChild(searchList.firstChild); } console.log(res) let elementos = res['elementos'] if (elementos.length > 0){ if (!searchList.classList.contains('active')){ searchList.classList.add('active') } elementos.forEach(function(elemento){ listLi = document.createElement('LI') searchInfo = document.createElement('DIV') searchInfo.className = 'search-item-info' searchInfo.innerHTML = elemento[1] //es el nombre elemento_id = elemento[0] elemento_name = elemento[1] responsable = '' if (tipo=='maquina_utilizada' || tipo=='movilidad_utilizada') { responsable = (elemento[2]) ? elemento[2] : '' } uom = '' console.log(`responsable antes de bla bla ---------: ${responsable}`) if(tipo === 'rubro'){ item.querySelector(`.buscar-${tipo}-id`).value = ''; } searchInfo.setAttribute("onClick","seleccionar_elemento(\'"+elemento_id+"\',\'"+elemento_name+"\',\'"+item_data+"\',\'"+tipo+"\',\'"+responsable+"\',\'"+uom+"\')") listLi.appendChild(searchInfo) searchList.appendChild(listLi) }) } }) } else { cancelSearch(item_data, tipo) } } function seleccionar_elemento(id, name, item_data, tipo, responsable=false, uom=false){ console.log("--------funcion seleccionar_elemento--------") item = document.querySelector("[data-"+tipo+"-id=\'"+item_data+"\']") item.querySelector(`.buscar-${tipo}`).value = name; item.querySelector(`.buscar-${tipo}-id`).value = id; console.log(`responsable en seleccion: ${responsable}`) if (responsable) { console.log(`clase buscada: .buscar-${tipo}_responsable`) item.querySelector(`.buscar-${tipo}_responsable`).value = responsable; } if (tipo==='producto_consumido') { console.log('........es producto consumido, cambiar uom') item.querySelector(`.${tipo}_uom`).innerHTML = uom } cancelSearch(item_data,tipo) } function cancelSearch(item_data, tipo){ console.log('cancel search') item = document.querySelector("[data-"+tipo+"-id=\'"+item_data+"\']") setTimeout(function(){ searchList = item.querySelector(`.lista_busqueda_${tipo}`) // borrar items while (searchList.firstChild) { searchList.removeChild(searchList.firstChild); } // desactivar clase active if (searchList.classList.contains('active')){ searchList.classList.remove('active') } },100) } function cargarEventListeners(){ mano_obra_utilizadas = document.querySelectorAll('.orden-mano_obra_utilizada_item'); tipos_trabajo = document.querySelectorAll('.orden-tipo_trabajo_item'); productos = document.querySelectorAll('.orden-producto_consumido_item'); maquinas = document.querySelectorAll('.orden-maquina_utilizada_item'); movilidades = document.querySelectorAll('.orden-movilidad_utilizada_item'); extras = document.querySelectorAll('.orden-extra_item'); //mano_obra_utilizadas.forEach(function(mo){ // data = mo.dataset.mano_obra_utilizadaId // input = mo.querySelector('.buscar-mano_obra_utilizada') // input.addEventListener('keyup',function(){elementSearch(mo.dataset.mano_obra_utilizadaId,'mano_obra_utilizada')}, false) //}); //tipos_trabajo.forEach(function(tt){ // data = tt.dataset.tipo_trabajoId // input = tt.querySelector('.buscar-tipo_trabajo') // input.addEventListener('keyup',function(){elementSearch(tt.dataset.tipo_trabajoId,'tipo_trabajo')}, false) //}); productos.forEach(function(prod){ data = prod.dataset.producto_consumidoId //console.log(`prod: ${prod},data: ${data}`) input = prod.querySelector('.buscar-producto_consumido') input.addEventListener('keyup',function(){elementSearch(prod.dataset.producto_consumidoId,'producto_consumido')}, false) }); //maquinas.forEach(function(maq){ // data = maq.dataset.maquina_utilizadaId // input = maq.querySelector('.buscar-maquina_utilizada') // input.addEventListener('keyup',function(){elementSearch(maq.dataset.maquina_utilizadaId,'maquina_utilizada')}, false) //}); //movilidades.forEach(function(mov){ // data = mov.dataset.movilidad_utilizadaId // input = mov.querySelector('.buscar-movilidad_utilizada') // input.addEventListener('keyup',function(){elementSearch(mov.dataset.movilidad_utilizadaId,'movilidad_utilizada')}, false) //}); //extras.forEach(function(ext){ // data = ext.dataset.extraId // input = ext.querySelector('.buscar-extra') // input.addEventListener('keyup',function(){elementSearch(ext.dataset.extraId,'extra')}, false) //}); } function anadir_elemento_select(nombreElemento, counter, cantidad=null, responsable=null) { console.log('-----------------------------------') console.log(nombreElemento) console.log(counter) var nuevo_data = "nuevo-" + counter; elemento = document.createElement('DIV'); elemento.className = `orden-${nombreElemento}_item`; // elemento.dataset.tipoTrabajoId = nuevo_data; elemento.setAttribute(`data-${nombreElemento}-id` ,nuevo_data); // crear elemento select y primera opcion vacia elementoSelect = document.createElement('SELECT'); elementoSelect.name = `${nombreElemento}_item--nuevo-${counter}`; elementoSelect.className = 'input_field'; //elementoSelect.addEventListener('change',function(){onchange_select(event, nombreElemento, nuevo_data)}, false) optionVacia = document.createElement('OPTION') elementoSelect.appendChild(optionVacia) // fetch de la lista de opciones (llamo a element search?), // deberia pero hace otras cosas que no deberia y no quiero ponerme a separarla ahora input_value = ''; Url = `/buscarelemento?input=${input_value}&amp;tipo=${nombreElemento}` fetch(Url).then(data=>{return data.json()}) .then(res => { console.log(res) let elementos = res['elementos'] //selectList = document.querySelector("[name='promotor_item--1']") elementos.forEach(function(elemento){ console.log(elemento) optionElement = document.createElement('OPTION'); optionElement.value = elemento[0]; // el id del elemento optionElement.innerHTML = elemento[1]; // el nombre del elemento elementoSelect.appendChild(optionElement); }) }) elemento.appendChild(elementoSelect) if (responsable){ // añade el evento onchange y cambia el responsable elementoSelect.addEventListener('change',function(){onchange_select(event, nombreElemento, nuevo_data)}, false) // hacer un fetch para traer el responsable_id var elementoResponsable = document.createElement('DIV') elementoResponsable.className = `buscar-${nombreElemento}_responsable responsable`; elementoResponsable.innerHTML = 'responsable' // elemento.appendChild(elementoResponsable) } //cantidad if (cantidad){ var elementoInputCantidad = document.createElement('INPUT') elementoInputCantidad.type = "text" elementoInputCantidad.className = 'input_field'; elementoInputCantidad.name= `cantidad_${nombreElemento}--${nuevo_data}` elemento.appendChild(elementoInputCantidad) } // tambien todos llevan borrar elementoBorrar = document.createElement('DIV') elementoBorrar.className = `${nombreElemento}_borrar borrar-elemento` // TODO: la funcion borrar elemento tambien tiene que ser usada por todos // elementoBorrar.setAttribute("onClick",`borrar_${nombreElemento}(\'`+nuevo_data+"\')") elementoBorrar.setAttribute("onClick",`borrar_elemento('${nombreElemento}',\'${nuevo_data}\')`) elementoBorrarIcon = document.createElement('I') elementoBorrarIcon.className = "far fa-trash-alt" elementoBorrar.appendChild(elementoBorrarIcon) elemento.appendChild(elementoBorrar) lista_elementos = document.querySelector(`.orden-${nombreElemento}_lista_body`); lista_elementos.appendChild(elemento); if (responsable){ insertAfter(elementoResponsable, elemento) } add_counter(nombreElemento) } function onchange_select(event, nombreElemento, data_id){ console.log('onchange select') item = document.querySelector(`[data-${nombreElemento}-id = '${data_id}']`) console.log('item', item) id = event.target.value console.log('id', id) Url = `/buscarresponsable?id=${id}&amp;tipo=${nombreElemento}` fetch(Url).then(data=>{return data.json()}) .then(res => { responsable_field = item.querySelector(`.${nombreElemento}_responsable`) responsable_field.innerHTML = `Responsable: ${res['elementos'][0]}` }) } function insertAfter(newNode, referenceNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); }
const mongoose = require('mongoose'); const { ObjectId } = mongoose.Schema.Types; const offerSchema = new mongoose.Schema({ price: { type: Number, required: true }, shipingAddress:{ type:String, require:true }, userId: { type: ObjectId, ref: "User", require:true }, itemId: { type: ObjectId, ref: "Item", require:true }, }, { timestamps: { createdAt: 'created_at' } }); module.exports = mongoose.model('Offer', offerSchema);
import React, { Component } from "react" import Button from './Buttonst' import Box from '@material-ui/core/Box' import Paper from '@material-ui/core/Paper'; import Grid from '@material-ui/core/Grid'; import { withStyles } from '@material-ui/core/styles'; import colorchange from "./colorchange"; import Title from './Title'; const styles = theme => ({ paper: { padding: theme.spacing(2), color: theme.palette.text.primary, width: "100%" } }); const storeLocation = [ { id: 9, name: "창고" } ] class WarehouseChoice extends Component { state = { cc5: null }; changeColor = row => { this.setState(colorchange(this.state, row)) console.log(this.state) } render() { const { classes } = this.props; return ( <div> <Grid container="container" item="item" xs={12} spacing={0}> <Paper className={classes.paper}> <Title>Store</Title> <Grid item="item"> 위치 : { storeLocation.map((list => ( <Button id={list.id} name={list.name} afd={this.state.cc5} clickColor={this.changeColor} clickHandler={this.handleClick}></Button> ))) } </Grid> </Paper> </Grid> </div> ); } } export default withStyles(styles)(WarehouseChoice);
/* eslint-disable import/no-commonjs */ function generate(values, template) { const properties = Object.assign( {}, ...Object.keys(values).map((value) => { return template(value); }) ); return properties; } function generateCustomMedia(values, { namespace = '', hyphens = true } = {}) { const properties = generate(values, (value) => { const prefix = `${hyphens ? '--' : ''}${namespace}-breakpoint`; return { [`${prefix}-${value}-min`]: `(min-width: ${values[value]}px)`, [`${prefix}-above-${value}`]: `(min-width: ${values[value] + 1}px)`, [`${prefix}-${value}-max`]: `(max-width: ${values[value]}px)`, [`${prefix}-below-${value}-max`]: `(max-width: ${values[value] - 1}px)`, }; }); return properties; } function generateCustomProperties( values, { namespace = '', hyphens = true } = {} ) { const properties = generate(values, (value) => { return { [`${hyphens ? '--' : ''}${namespace}-${value}`]: values[value], }; }); return properties; } module.exports = { generateCustomMedia, generateCustomProperties, };
// public filter variables let output = "Final Output"; let tags = ["no", "happy", "angry", "pepe"]; var variations = 10; const maxLenght = 20; const minLenght = 3; function filterInput(input) { output = input; //return input; if (output.length < minLenght) { return "To short"; } if (output.includes("how" || "you")) { variations = 3; return "I don't know"; //example: Do you know how to do that? } var msg = input.replace("yes", tags[0]); // replace a specific word return msg; //return tags[getRandomInt(0, tags.length - 1)]; // pick a specific or random word from tags array }
// src/demo05.js // 类函数 - 装饰器 function log(target, name, descriptor) { console.log('log.target: ', target); console.log('log.name: ', name); console.log('log.descriptor: ', descriptor); } class App { @log onClientList() { console.log('App.onClientList'); } } const app = new App(); app.onClientList();
import html from '/js/html.js'; let template = function() { return html` <header> <h1>Demo Project</h1> </header> <main></main> `; }; export default class App { render() { let dom = template(); return dom; } }
"use strict"; const ClientCnpj = use("App/Models/CnpjClient"); const Yup = use("yup"); class CnpjClientController { async index() { const data = await ClientCnpj.all(); return data; } async store({ request, response, auth }) { const schema = Yup.object().shape({ cnpj: Yup.string().required(), email: Yup.string().required(), name: Yup.string().required(), }); if (!(await schema.isValid(request.body))) { return response .status(400) .json({ error: "Erro de validação nos dados inseridos" }); } const data = request.only(["cnpj", "email", "name"]); const userClient = ClientCnpj.create({ ...data, cnpj_client_id: auth.user.id, }); return userClient; } } module.exports = CnpjClientController;
// В конструкторе можно создавать новые тесты, для которых есть настройки // по умолчанию которые хранятся в переменной defaultSettings.Во время // создания теста, все или часть настроек можно переопределить, они хранятся // в переменной overrideSettings. // Для того чтобы получить финальные настройки теста, необходимо взять настройки // по умолчанию и поверх них применить переопределённые настройки.Дополни код так, // чтобы в переменной finalSettings получился объект финальных настроек теста. const defaultSettings = { theme: 'light', public: true, withPassword: false, minNumberOfQuestions: 10, timePerQuestion: 60, }; const overrideSettings = { public: false, withPassword: true, timePerQuestion: 30, }; // Пиши код ниже этой строки const finalSettings = {...defaultSettings,...overrideSettings};
import mongoose from "mongoose" const Schema = mongoose.Schema const ObjectId = Schema.Types.ObjectId let _schema = new Schema({ creator: {type: ObjectId, ref: 'User', required: true}, user: {type: ObjectId, ref: 'User', required: true}, board: { type: ObjectId, ref: 'Board', required: true } }, { timestamps: true }) export default mongoose.model('Collaborator', _schema)
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var User = require('../models/User.js'); var Schedule = require('../models/Schedule.js'); // var riders = [ // { // name: "Van", // max: 15, // lat: 44.96804683, // lng: -93.22277069, // taking: [] // }, // { // name: "Yosub", // max: 4, // lat: 44.97328414, // lng: -93.24716806, // taking: [] // } // ]; function calc(fixed, users, riders){ var total = users.length; var riderMax = 0; for (var r = 0;r<riders.length;r++){ riderMax=riderMax+riders[r].max; } //console.log(riderMax); if (riderMax<total){ return "Too many people but cannot fulfill task"; } else { //find the closest locations from users to fixed location for (var i = 0;i< users.length;i++){ var loc1 = users[i]; var init = true; var diff = { index: 0, diff: 0 } for (var u = 0;u<fixed.length;u++){ var loc2 = fixed[u]; if (init){ diff.index = u; diff.diff = getDistanceFromLatLon(loc1,loc2); init = false; } else { var check = getDistanceFromLatLon(loc1,loc2); if (diff.diff>check){ diff.index = u; diff.diff = check; init = false; } } } users[i].assigned_location = fixed[diff.index].name; fixed[diff.index].n.push(users[i]); } // for (var i = 0;i< riders.length;i++){ var rider = riders[i]; var init = true; var diff = [{ index: 0, diff: 0 }]; while (total>0 && rider.max>0){ if (total > rider.max){ //채울수잇으면 빨리채우기로 //높은순으로 간다 업앤다 maxIndex = findMax(fixed); var n; if (rider.max>fixed[maxIndex].n.length){ n = fixed[maxIndex].n.length; } else { n = rider.max; } while (n>0){ rider.taking.push(fixed[maxIndex].n[fixed[maxIndex].n.length-1]); fixed[maxIndex].n.pop(); rider.max--; n--; total--; } riders[i] = rider; } else { //채울수업으면 가까운데로 //sort by distance //find shortest loc from current var temp = {}; for (var k =0;k<fixed.length;k++){ if (fixed[k].n.lengh!=0){ rider.taking = rider.taking.concat(fixed[k].n); } } for (var k = 0;k<rider.taking.lengh;k++){ rider.taking[k]; } rider.max = rider.max - total; total = 0; } } } } return riders; } function findMax(arrObj){ var init = true; var maxIndex=0; for (var k = 0;k<arrObj.length;k++){ if (init){ max = k; init = false; } else { if (arrObj[maxIndex].n.length<arrObj[k].n.length){ maxIndex = k; } } } return maxIndex; } function getDistanceFromLatLon(loc1,loc2){ var R = 6371; // Radius of the earth in km var lat1 = loc1.lat; var lon1 = loc1.lng; var lat2 = loc2.lat; var lon2 = loc2.lng; var dLat = deg2rad(lat2-lat1); // deg2rad below var dLon = deg2rad(lon2-lon1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; // Distance in km return d; } function deg2rad(deg) { return deg * (Math.PI/180) } var users; router.post('/',function(req, res, next) { var k = req.body._id; var fixed = [ { name: "University Commons", address: "", lat: 44.96976229, lng: -93.22253466, n: [] }, { name: "Wahu", address: "", lat:44.97287808, lng:-93.22317839, n: [] }, { name: "Yudoff", address: "", lat:44.97237334024413, lng:-93.23601007461548, n: [] }, { name: "McDonald", address: "", lat:44.98011471, lng:-93.2345295, n: [] } ]; Schedule.find({_id:k},function(err,data){ if (err) return next(err); var item = data[0]; var users = data[0]["join"]; var val = calc(fixed,users,item["rider"]); console.log("user length: "+users.length); console.log("rider length: "+item["rider"].length); console.log(val); if (data.length>0){ var d = new Date(); Schedule.update({_id: k},{ride: JSON.stringify(val),complete:true,timeComplete:d},function(err,data){ if (err) return next(err); res.send("success"); }) } }) }); router.get('/grab',function(req,res,next){ k = req.query._id; //var k = JSON.parse(req.query.name); Schedule.find({_id:k},function(err,data){ if (err) return next(err); if (data.length>0){ console.log(data[0].ride); res.json(data[0].ride); } else { res.send('fail'); } }) }); module.exports = router;
import SelectData from './SelectData'; import { ROLES } from '../Roles'; export default class TreeData extends SelectData { constructor(displayObject, role, domIdPrefix) { super(displayObject, role, domIdPrefix); this._reactProps['aria-orientation'] = 'vertical'; } /** * @inheritdoc */ addChild(displayObject) { if ( !displayObject.accessible || displayObject.accessible.role !== ROLES.TREEITEM ) { throw new Error( `Children of ${this.role} must have a role of ${ROLES.TREEITEM}` ); } super.addChild(displayObject); } /** * @inheritdoc */ addChildAt(displayObject, index) { if ( !displayObject.accessible || displayObject.accessible.role !== ROLES.TREEITEM ) { throw new Error( `Children of ${this.role} must have a role of ${ROLES.TREEITEM}` ); } super.addChildAt(displayObject, index); } /** * @access public * @param {boolean} value - true if more than 1 element can be selected at a time, * false for only 1 at a time, undefined to unset this field */ set multiselectable(value) { this._reactProps['aria-multiselectable'] = value; } /** * @access public * @returns {boolean} true if more than 1 element can be selected at a time, * false for only 1 at a time, undefined if this field is unset */ get multiselectable() { return this._reactProps['aria-multiselectable']; } /** * Sets whether user input is required or not * @access public * @param {boolean} value - true if the element is required, false otherwise, * undefined to unset this field */ set required(value) { this._reactProps['aria-required'] = value; } /** * Retrieves whether user input is required or not * @access public * @returns {boolean} true if the element is required, false otherwise, * undefined if this field is unset */ get required() { return this._reactProps['aria-required']; } }
window.onload = function() { var btnSelect = document.getElementById("btn_select"); var curSelect = btnSelect.getElementsByTagName("span")[0]; var oSelect = btnSelect.getElementsByTagName("select")[0]; var aOption = btnSelect.getElementsByTagName("option"); oSelect.onchange = function() { var text = oSelect.options[oSelect.selectedIndex].text; curSelect.innerHTML = text; } }
import { UPDATE_EVENTS, GET_EVENTS_BY_ORG_PENDING, GET_EVENTS_BY_ORG_SUCCESS, GET_EVENTS_BY_ORG_FAILED, CREATE_EVENT_PENDING, CREATE_EVENT_SUCCESS, CREATE_EVENT_FAILED, } from '../actions/eventsByOrg' let eventsByOrgState = { isLoading: false, showError: true, all: [], selected: {}, created: {} // Click on one to update it? } export const eventsByOrg = (state = eventsByOrgState, { type, payload }) => { switch (type) { case UPDATE_EVENTS: return { ...state, all: [...state.all, payload] } case GET_EVENTS_BY_ORG_PENDING: return { ...state, isLoading: true, showError: false } case GET_EVENTS_BY_ORG_SUCCESS: return { ...state, all: payload, isLoading: false, showError: false } case GET_EVENTS_BY_ORG_FAILED: return { ...state, isLoading: false, showError: true } case CREATE_EVENT_PENDING: return { ...state, isLoading: true, showError: false } case CREATE_EVENT_SUCCESS: return { ...state, isLoading: false, created: payload, showError: false } case CREATE_EVENT_FAILED: return { ...state, isLoading: false, showError: true } default: return state } }
import React from 'react'; import { action } from 'mobx'; import { inject } from 'mobx-react'; import { Link } from 'react-router'; import { MenuItem } from 'material-ui'; @inject('ui') class BaseMenu extends React.Component { static propertyTypes = { module: React.PropTypes.any, }; constructor() { super(); this.handleRemove = this.handleRemove.bind(this); this.handleRemoveConfirmed = this.handleRemoveConfirmed.bind(this); } @action handleRemove() { const { ui, id, module: { metadata: { title } } } = this.props; ui.showConfirmationDialog('Confirm', `Do you want to remove ${title} #${id}`, this.handleRemoveConfirmed); } @action handleRemoveConfirmed(submit) { if (submit) { const { module: { name }, id, resource } = this.props; const store = this.props[name]; return store.remove(id, resource); } } render() { const { id, module: { metadata }, resource } = this.props; return (<div> <Link to={`/${resource || metadata.resource}/edit/${id}`}>{ ({ onClick }) => <MenuItem primaryText="Edit" onClick={onClick} /> }</Link> <MenuItem primaryText="Remove" onClick={this.handleRemove} /> </div>); } } export default BaseMenu;
import { setIn } from 'immutable' // when editing, set post field on path to given value export default (state, action) => setIn(state, ['newPost', action.payload.path], action.payload.value )
function seleccionImagen(){ /* capturar un evento de selcceion por el id del checkbox */ const img1= document.getElementById("1").checked; const img2= document.getElementById("2").checked; const img3= document.getElementById("3").checked; const img4= document.getElementById("4").checked; const img5= document.getElementById("5").checked; const img6= document.getElementById("6").checked; /* capturar un evento de seleccion por el name del checkbox */ const nombre1= document.getElementById("1")[0].checked; const nombre2= document.getElementById("2")[0].checked; const nombre3= document.getElementById("3")[0].checked; const nombre4= document.getElementById("4")[0].checked; const nombre5= document.getElementById("5")[0].checked; const nombre6= document.getElementById("6")[0].checked; let arrayImgSelected= new Array(); arrayImgSelected.push(img1,img2,img3,img4,img5,img6); console.log(arrayImgSelected); }
import React from "react"; import Dashboard from "./components/Dashboard"; import "./App.css"; import LoginForm from "./components/LoginForm"; import { AppBar, Toolbar, Typography } from "@material-ui/core"; // import NavBar from './components/NavBar' function App() { return ( <div className="App"> <AppBar position="sticky" className="App-bar"> <Toolbar> <Typography variant="h6">My Music App</Typography> </Toolbar> </AppBar> {/* <NavBar /> */} <header className="App-header"> <LoginForm Login={ `Login` }></LoginForm> <p> <a className="App-link" href="https://reactjs.org" target="blank" rel="noopener noreferrer" > {/* Login */} </a> {/* <button>Click me</button> */} {/* <button onClick={() => console.log("button clicked")} variant="Contained" color="primary" > {/* Click me twice! */} {/* </button> */} </p> </header> </div> ); } export default App;
'use strict'; import angular from 'angular'; import uirouter from 'angular-ui-router'; import jwtDecode from 'jwt-decode'; class Auth { constructor($http) { this.$http = $http; this.token = localStorage.getItem('jwt'); this.user = this.token && jwtDecode(this.token); } isAuth() { return !!this.token; } getUser() { return this.user; } login(username, password) { return this.$http.post('http://localhost:3001/sessions/create', JSON.stringify({username, password}) ).then((res) => { this.token = res.data.id_token; localStorage.setItem('jwt', this.token); }); } logout() { localStorage.removeItem('jwt'); this.token = null; this.user = null; } } Auth.$inject = ['$http']; class AuthInterceptor { request(config) { const token = localStorage.getItem('jwt'); if (token) { config.headers.Authorization = 'Bearer ' + token; } return config; } } config.$inject = ['$httpProvider']; function config($httpProvider) { $httpProvider.interceptors.push('authInterceptor'); } export default angular.module('services.auth', [uirouter]) .service('auth', Auth) .service('authInterceptor', AuthInterceptor) .config(config) .name;
var mongoose = require('mongoose'), Schema = mongoose.Schema, connection = mongoose.connection; var taskSchema = new Schema({ start: { type: Date }, finish: { type: Date }, hours: { type: Number }, person: { type: Schema.Types.ObjectId, ref: 'Person', required: true }, customer: { type: Schema.Types.ObjectId, ref: 'Customer', required: true } }, { timestamps: true }); var Task = mongoose.model('Task', taskSchema); module.exports = Task;
import styled from 'styled-components' export const Wrapper = styled.div` position: relative; ` export const Input = styled.input` background: #191a21; border: 1px solid #101010; color: #f8f8f2; padding: 10px; width: 100%; `
/** * temporary database, changes applied here are updated after refresh. * Take Note: avoid similar ids. */ //[category,id,description,title,price,image_path] var item_list = [ ["cactus", 1, "The ‘Zebra Plant’ is a hardy, stemless succulent with a variety of vivid green color and white horizontal stripes.<br>Origin: South Africa<br>Size: up to 6”<br>Temperature: Warm coastal climates. Avoid freezing temperatures.", "Attenuata", 30, "plant2.jpg"], ["cactus", 2, "Echeveria Agavoides is known for its fleshy green pointed leaves, which are edged with a deep red. <br>Origin: Native to Mexico <br> Size: Up to 12” <br> Temperature: This plant does best in warm dry climates.", "Agavoides", 40, "Agavoides.jpg"], ["cactus", 3, "Sempervivum Arachnoideum 'Cob Web' is well known for its spider web-like structure across the face of the rosette.<br>Origin: Alps, Apennines and Carpathians<br>Size: 1-3”<br>Temperature: This plant does best in dry climates. During cold winter months, bring your succulent indoors near a bright sunny window, and keep away from frost.", "Cob Web", 30, "Aloe.jpg"], ["plant", 4, "Coveted for it’s delicate blue color and commonly used as a ground cover for ornamental landscape use.<br>Origin: Asia<br>Size: 3-6”<br>Temperature: Warm dry climates. Avoid freezing temperatures.", "Blue Spruce", 40, "Aloe1.jpg"], ["plant", 40, "This succulent is a delicate variety that is a vibrant greenish yellow.<br>Origin: Unknown<br>Size: up to 6”<br>Temperature: Warm coastal climates. Avoid freezing temperatures.", "De Oro", 30, "Bear Paw1.jpg"], ["plant", 6, "This fleshy Haworthia has a green flower-like shape with light green striping on the leaves of the plant.<br>Origin: Native to South Africa<br>Size: Up to 4”<br>Temperature: This plant does best in warm temperatures", "Magnifica", 30, "Bear Paw1.jpg"], ["plant", 7, "Crassula Rupestris ‘Rosary Vine' is known for its tight upright vertical form and unique leaf shape.<br>Origin: South Africa<br>Size: up to 12” long<br>Temperature: This plant does best in warm temperatures.", "Rupestris", 30, "Blazing Glory 1.jpg"], ["plant", 8, "The ‘Sea Urchin’ is a succulent that is a light silver green with white edges along the leaves.<br>Origin: Eastern Asia <br>Size: up to 2 feet<br>Temperature: Warm coastal climates. Avoid freezing temperatures.", "Sea Urchin", 30, "Blazing Glory.jpg"], ["plant", 9, "The ‘Royal Ruby’ is a deep maroon mounding, frost hardy rosette.<br>Origin: Garden cultivar<br>Size: under 3”<br>Temperature: Cool climates. Avoid freezing temperatures.", "Semp Ruby", 30, "plant3.jpg"], ["plant", 10, "'String of Pearls' is prized among many succulent collectors and home.<br>Origin: Southwest Africa<br>Size: Up to 3 ft draping<br>Temperature: This plant does best in warm dry climates.", "Sea Urchin", 30, "plant4.jpg"], ["succulents", 11, "Echeveria Agavoides is known for its fleshy green pointed leaves, which are edged with a deep red.<br>Origin: Native to Mexico<br>Plant Type: Succulent<br>Size: Up to 12”<br>Temperature: This plant does best in warm dry climates.", "Sea Urchin", 30, "plant5.jpg"], ["succulents", 12, "Graptopetalum Amethystinum is also known as Wedding Almond, Jewel Leaf Plant, Lavender Pebbles, or Wine Coolers.<br>Scientific Name: Graptopetalum Amethystinum<br>Origin: Mexico<br>Plant Type: Succulent<br>Size: 2-4”<br>Temperature: This plant does best in warm climates, keep away from frost.", "Sea Urchin", 30, "plant12.jpg"], ["succulents", 13, "Aloe vera is a stemless or very short-stemmed succulent plant.<br>Origin: Africa<br>Plant Type: Cactus<br>Size: Growing to 60–100 cm (24–39 in) tall.<br>Temperature: Grows in a wide variety of warm weather climates and soils.", "Sea Urchin", 30, "plant2.jpg"], ["succulents", 14, "Cotyledon Tomentosa 'Bear Paw' is a fleshy paw shaped succulent plant. Bear Paw succulent has fuzzy green leaves, which add a beautiful contrast and unique texture to any garden use of the plant.<br>Origin: Africa<br>Plant Type: Succulent<br>Size: Up to 20”<br>Temperature: This plant does best in warm dry climates.", "Bear Paw", 30, "plant3.jpg"], ["succulents", 15, "Echeveria 'Blue Atoll' is known for its highly structured rosette form. This fast growing rosette shaped succulent has long pointed leaves with a deep greenish blue color when exposed to the proper amount of sunlight.<br>Origin: Native to Mexico and Central America<br>Plant Type: Succulent<br>Size: Up to 6”<br>Temperature: This plant does best in warm climates.", "Blue Atoll", 30, "plant4.jpg"], ["succulents", 16, "Coveted for it’s delicate blue color and commonly used as a ground cover for ornamental landscape use. This drought tolerant succulent blooms bright yellow flowers during early summer.<br>Origin: Asia<br>Plant Type: Succulent<br>Size: 3-6”<br>Temperature: Warm dry climates.", "Sea Urchin", 30, "plant2.jpg"], ["succulents", 17, "The succulent ‘Blue Tears’ is a gorgeous, mounding rosette succulent that is turquoise blue in color, and produces clusters of white star shaped flowers accented with tiny black dots.<br>Origin: Garden cultivar<br>Plant Type: Succulent<br>Size:under 6”<br>Temperature: Warm coastal climates.", "Blue Tears", 30, "plant5.jpg"], ["succulents", 18, "This succulent is a sprawling, clumping rosette that is a gorgeous frosted grey green. During the fall and winter, it blooms vivid red-orange disk like flowers.<br>Origin: Unknown<br>Plant Type: Succulent<br>Size: up to 12-18”<br>Temperature: Warm coastal climates.", "Blazing Glory", 30, "plant6.jpg"], ["succulents", 19, "Sedum Morganianum ‘Burrito Sedum’ is prized among many succulent collectors and home decorators alike for its beautiful delicate draping form.<br>Origin: Mexico & Hondurus<br>Plant Type: Succulent<br>Size: Up to 3 ft draping<br>Temperature: This plant does best in warm dry climates.", "Burrito", 30, "plant19.jpg"], ["succulents", 20, "The ‘Zebra Plant’ is a hardy, stemless succulent with a variety of vivid green color and white horizontal stripes.<br>Origin: South Africa<br>Plant Type: Succulent<br>Size: up to 6”<br>Temperature: Warm coastal climates.", "Sea Urchin", 30, "plant8.jpg"], ["succulents", 21, "This succulent has compact rosettes with an orangish pink shade. The colors of the leaves are copper-gold with streaks of yellow, pink, and green overtones.<br>Origin: Garden (nursery-produced cultivar)<br>Plant Type: Succulent<br>Size: 6 to 12”", "Sea Urchin", 30, "plant21.jpg"], ["succulents", 22, "Kalanchoe ‘Chocolate Soldier’ sometimes referred to as “Teddy Bear Cactus” is native to Madagascar and is known for its fuzzy brown, ear shaped leaves.<br>Origin: Native to Madagascar<br>Plant Type: Succulent<br>Size: Up to 24”<br>Temperature: This plant does not tolerate frost but can greatly withstand high levels of heat.", "Sea Urchin", 30, "plant9.jpg"], ["succulents", 23, "This succulent is famous for its frosty blue green leaves that is lightly tipped with shades of pink when exposed to bright light.<br>Origin: Mexico<br>Plant Type: Succulent<br>Size: 4 to 6”<br>Temperature: This plant does not tolerate frost but can greatly withstand high levels of heat.", "Sea Urchin", 30, "plant23.jpg"], ["succulents", 24, "cheveria Colorata is a highly prized cultivar well known for its compact rosette form.<br>Origin: Native to Mexico.<br>Plant Type: Succulent<br>Size: Up to 12”<br>Temperature: This plant does best in warmer temperatures.", "Sea Urchin", 30, "plant10.jpg"], ["succulents", 25, "This is an evergreen succulent that for<br>Temperature: This plant does best in warmer temperatures.<br>ms a large rosette. The leaves are olive green to lavender rose in shades and are slight pointed, rounded, and fleshy. The surface is adorned with pink edges.<br>Origin: Garden cultivar<br>Plant Type: Succulent<br>Size: 12”<br>Temperature: This plant greatly appreciates warm temperatures most of the", "Sea Urchin", 30, "plant11.jpg"], ["succulents", 26, "This succulent is a delicate variety that is a vibrant greenish yellow. During mid summer, it blooms beautiful bright yellow star shaped flowers.<br>Origin: Unknown<br>Plant Type: Succulent<br>Size: up to 6”<br>Temperature: Warm coastal climates.", "Sea Urchin", 27, "plant12.jpg"], ["succulents", 27, "Echeveria 'Domingo' hen and chicks, is a whitish grey rosette shaped succulent with broad fleshy leaves coated in a white powder.<br>Origin: Native to Mexico<br>Plant Type: Succulent<br>Size: Up to 12”<br>Temperature: This plant does best in warm climates.", "Sea Urchin", 28, "plant13.jpg"], ["succulents", 28, "This is a slow growing type of shrub that has reddish brown stems and green glossy obovate leaves that can grow up to 0.8 inch longs.<br>Origin: South Africa<br>Plant Type: Succulent<br>Size: 120”<br>Temperature: This can thrive under bright light in a warm and draft-free area.", "Sea Urchin", 30, "plant14.jpg"], ["succulents", 29, "Kalanchoe Thyrsiflora 'Flapjacks' is a fleshy succulent with round paddle shaped leaves, stacked like flapjacks, hence the name!<br>Origin: Native to South Africa<br>Plant Type: Succulent<br>Size: Up to 24”<br>Temperature: This plant does best in warm climates.", "Sea Urchin", 30, "plant15.jpg"], ["succulents", 30, "The Echeveria Green Goddess is an open rosette with gorgeous frosty blue foliage that has blush red tips in partial sun.<br>Origin: Garden cultivar<br>Plant Type: Succulent<br>Size: under 6”<br>Temperature: Warm, drought tolerant climates. Avoid freezing temperatures.", "Sea Urchin", 30, "plant16.jpg"], ["succulents", 31, "Sempervivum Arachnoideum 'Cob Web' is well known for its spider web-like structure across the face of the rosette. This Succulent is beautifully hardy with a delicate look in designs and arrangements.<br>Origin: Alps, Apennines and Carpathians<br>Plant Type: Succulent<br>Size: 1-3”<br>Temperature: This plant does best in dry climates.", "Sea Urchin", 30, "plant17.jpg"], ["succulents", 32, "Crassula Ovata 'Jade' is a classical succulent that works great both indoors and outdoors.<br>Origin: South Africa<br>Plant Type: Succulent<br>Size: Up to 3<br>Temperature: This plant does best in warm climates.", "Sea Urchin", 30, "plant19.jpg"], ["succulents", 33, "This is the most popular member of the genus Crassula, which contains around two hundred succulent species.<br>Origin: Europe and America<br>Plant Type: Succulent<br>Size: Up to 5 feet tall.<br>Temperature: plants grow slightly cooler temperatures at night and in the winter.", "Sea Urchin", 30, "plant20.jpg"], ["succulents", 34, "‘Jelly Bean Sedum,’ commonly referred to as ‘Pork and Beans,’ adds a beautiful texture and unique height to succulent gardens.<br>Scientific Name: Sedum Rubrotinctum<br>Origin: Native to Mexico<br>Plant Type: Succulent<br>Size: Up to 8” or 20 cm<br>Temperature: This plant does best in hot temperatures.", "Sea Urchin", 30, "plant21.jpg"], ]; /** * selected items are stored on your cart */ var cart_items = []; /** * the default template of each item, * unifies the design of items. * @param {*} id - used for identifying list_items * @param {*} description - viewed on hover * @param {*} title - name of item * @param {*} price - the price value of item * @param {*} image_path - image source in local storage */ function generateTemplateContents(id, description, title, price, image_path) { return "<li><div class='container h-100'><a href='' target='_blank'> <img src='extension/img/ALL/" + image_path + "'></a>" + "<div class='overlay'>" + "<div class='text'> " + description + "</div>" + " </div> <br>" + " <span class='text-primary pt-4'>" + title + " | " + price + "<br></span>" + " <button class='btn btn-primary add-item' item='" + id + "'>Add to cart <span class='badge badge-danger'></span></button>" + " <button class='btn btn-danger remove-item d-none' item='" + id + "'>Remove</button>" + "</div>" + " </li>" } /** * loads all items in item_list using generateTemplateContents() * @param {*} type */ function populateItems(type) { for (var i = 0; i < item_list.length; i++) { if (type != null) { if (type != item_list[i][0]) { continue; } } console.log(item_list[i]); $("#ulpics").append( generateTemplateContents( item_list[i][1], item_list[i][2], item_list[i][3], item_list[i][4], item_list[i][5] ) ); } } /** * filter items by title, similar to populateItems(). * @param {*} search */ function searchItem(search) { for (var i = 0; i < item_list.length; i++) { if (item_list[i][3].toLowerCase().indexOf(search.toLowerCase()) > -1) { $("#ulpics").append( generateTemplateContents( item_list[i][1], item_list[i][2], item_list[i][3], item_list[i][4], item_list[i][5] ) ); } console.log(item_list[i]); } } /** * @param {*} sParam - takes the value with the same name from the url. */ function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); } } return ""; }; /** * Similar to generateTemplateContents(), * a uniform template for listing the cart items. * @param {*} id - might be use soon, reserved paramter * @param {*} name - item title * @param {*} qty - item count * @param {*} total - total amount value */ function getItemListTemplate(id,name,qty,total){ return "<tr>"+ "<td>"+name+"</td>" + "<td>"+qty+"</td>" + "<td>"+total+"</td>"+ "</tr>"; } /** * Key listeners (such as buttons) are implemented here after successfully loading the document. * Determines which type of query is selected. */ $(document).ready(function () { var type = getUrlParameter("type"); var search = getUrlParameter("search"); console.log(search); var cart_form = $("#my-cart"); cart_form.validate(); if (type == "") { searchItem(search); } else { populateItems(type); } $(".btn-search").click(function () { var search = $("#input-search").val(); if(search == ""){ document.location.search = ""; }else { window.location.href = "?search=" + search ; } }); $(document).on("click",".add-item",function(){ var cart_items = getCartItems(); var id = $(this).attr("item"); var item_index = itemAlreadyExist(id) ; if(item_index > -1){ cart_items[item_index][1] += 1; $(this).find("span").text(cart_items[item_index][1]); }else { cart_items.push([id,1]); $(this).find("span").text(1); } $(".remove-item[item='"+id+"']").removeClass("d-none"); updateCartItems(cart_items); console.log(cart_items); }); $(document).on("click",".remove-item",function(){ var cart_items = getCartItems(); var id = $(this).attr("item"); var item_index = itemAlreadyExist(id) ; if(cart_items[item_index][1] > 0){ cart_items[item_index][1] -= 1; if(cart_items[item_index][1] == 0){ $(this).addClass("d-none"); } } var qty = cart_items[item_index][1]; $(".add-item[item='"+id+"']").find("span").text(qty == 0 ? "" : qty ); updateCartItems(cart_items); console.log(cart_items); }) $(".show-cart").click(function(){ $("#background").removeClass("d-none"); $("#my-cart").removeClass("d-none"); var items = getCartItems(); $(".item-list").html(""); var total_amount = getCartTotalAmount(); $(".total-amount").text(total_amount); for(var i =0;i < items.length; i++){ var item = getItemById(items[i][0]); if(items[i][1] == 0){ continue; } $(".item-list").append(getItemListTemplate(items[i][0],item[3],items[i][1],item[4] * items[i][1])); } window.scrollTo(0, 0); }); $(".order").click(function(){ if(getTotalItemCount() == 0){ alert("your cart is empty"); } else if(cart_form.valid()){ window.location.href = "thankyou.html"; } }); $(".close-cart").click(function(){ $("#background").addClass("d-none"); $("#my-cart").addClass("d-none"); }) $("#payment-type").change(function(){ if($(this).val() == "dc"){ $(".debit-form").removeClass("d-none"); } else { $(".debit-form").addClass("d-none"); } }); }); /** * Takes the total number of items in the cart */ function getTotalItemCount(){ var total_item_count = 0; for(var i =0; i < cart_items.length; i++){ total_item_count += cart_items[i][1]; } return total_item_count; } /** * takes all items from cart; */ function getCartItems(){ return cart_items; } /** * updates the value from the cart * @param {*} items - new set of items */ function updateCartItems(items){ cart_items = items; } /** * determines if id already exist in the cart. * @param {*} id - cart to be examined. * @returns the index of the of item in item_list, if null returns -1 */ function itemAlreadyExist(id){ var items = getCartItems(); for(var i = 0; i < items.length; i++){ if(id == items[i][0]){ return i; } } return -1; } /** * get the item from item_list by id. * @param {*} id */ function getItemById(id){ for(var i =0; i< item_list.length; i++){ if(id == item_list[i][1]){ return item_list[i]; } } return null; } /** * the total amount from cart items. */ function getCartTotalAmount(){ var total = 0; for(var i =0; i < cart_items.length; i++){ var item = getItemById(cart_items[i][0]); total += item[4] * cart_items[i][1]; } return total; }
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'next/link'; import * as S from './styled'; const ButtonPrimary = ({ as, href, children, handleButtonClick, ...restProps }) => { if (as === 'a') { return ( <Link href={href} passHref> <S.ButtonPrimary as={as} {...restProps}> {children} </S.ButtonPrimary> </Link> ); } return ( <S.ButtonPrimary onClick={handleButtonClick ? () => handleButtonClick() : null} {...restProps} > {children} </S.ButtonPrimary> ); }; export default ButtonPrimary; ButtonPrimary.propTypes = { as: PropTypes.oneOf(['button', 'a']), href: PropTypes.string, variation: PropTypes.oneOf(['primary', 'secondary']), }; ButtonPrimary.defaultProps = { as: 'a', };
import React, { Component } from "react"; // import Fab from "@material-ui/core/Fab"; import Button from "@material-ui/core/Button"; // import CustomFab from "./layout/CustomFab"; class CustomButton extends Component { render() { return ( <div className="fabButtonDiv"> {/* <Fab disabled={this.props.disabled} className="fabButton" color={this.props.color} variant={this.props.variant} size={this.props.size} aria-label="Add" type={this.props.type} value={this.props.value} > {this.props.title} </Fab> */} <Button style={{ backgroundColor: this.props.bgcolor }} color={this.props.color} disabled={this.props.disabled} className="fabButton" variant="contained" size={this.props.size} aria-label="Add" type={this.props.type} value={this.props.value} > {this.props.title} </Button> </div> ); } } export default CustomButton;
import FlowTagsFooter from './FlowTagsFooter.jsx'; export default FlowTagsFooter;
import React, { Component } from "react"; import "./TabContent.css"; class TabContent extends Component { render() { return ( <div className="tabContent"> <div className="text_wrap"> <div className="tab_title">{this.props.title}</div> <div className="tab_text">{this.props.text}</div> </div> <img className="tab_img" src={this.props.img} alt="tab" /> </div> ); } } export default TabContent;
const log = require('../helper/logHelper') const strHelper = require('../helper/strHelper') const dateHelper = require('../helper/dateHelper') const assert = require('assert') const moment = require('moment') const it_name = (v) => { return `${v[0]} == ${v[1]}` } const check_equal = (v, func) => { if (Array.isArray(v[1])) { assert.equal(func(v[0]).join(), v[1].join()) } else if (v[1] && typeof v[1].isoWeekday === 'function') { if (!func(v[0]).isSame(v[1])) { log.warn(`${func(v[0])} ${v[1]}, result: ${func(v[0]).isSame(v[1])}`) } assert.equal(true, func(v[0]).isSame(v[1])) } else { assert.equal(func(v[0]), v[1]) } } describe('without equal value', () => { const v = ['01(05). 05 . 23', '01. 05 . 23'] it(it_name(v), () => { check_equal(v, strHelper.ignoreEqualsValue) }) }) describe('without spaces', () => { const v = ['01(05). 05 . 23', '01(05).05.23'] it(it_name(v), () => { check_equal(v, strHelper.ignoreSpaces) }) }) describe('without multiple equals', () => { const v = ['01(05).05(10).24', '01.05.24'] it(it_name(v), () => { check_equal(v, strHelper.ignoreEqualsValue) }) }) describe('check getTwoStringByLastDelim', () => { const v = ['hello everybody. something', ['hello everybody', 'something']] it(it_name(v), () => { check_equal(v, strHelper.getTwoStringByLastDelim) }) }) describe('check undefined alterDate', () => { const v = [undefined, undefined] it(it_name(v), () => { check_equal(v, dateHelper.ignoreAlterDate) }) }) describe('check alterDate', () => { const v = ['01(05).05(10).24', moment.utc('01.05.1924', 'DD.MM.YYYY')] it(it_name(v), () => { check_equal(v, dateHelper.ignoreAlterDate) }) const v2 = ['01.05(02.12).24', moment.utc('01.05.1924', 'DD.MM.YYYY')] it(it_name(v2), () => { check_equal(v2, dateHelper.ignoreAlterDate) }) const v3 = ['01-05(02-12)-24', moment.utc('01.05.1924', 'DD.MM.YYYY')] it(it_name(v3), () => { check_equal(v3, dateHelper.ignoreAlterDate) }) const v4 = ['1924', moment.utc('01.01.1924', 'DD.MM.YYYY')] it(it_name(v4), () => { check_equal(v4, dateHelper.ignoreAlterDate) }) const v5 = ['1924', moment.utc('01.01.1954', 'DD.MM.YYYY')] it(`False equal dates ${it_name(v5)}`, () => { assert.equal(false, dateHelper.ignoreAlterDate(v5[0]).isSame(v5[1])) }) }) describe('test human date', () => { const v5 = ['авг 1924', moment.utc('01.08.1924', 'DD.MM.YYYY')] it(it_name(v5), () => { check_equal(v5, dateHelper.ignoreAlterDate) }) }) describe('test mocha test system', () => { it('test assert', () => { assert.equal(false, false) assert.equal(true, true) assert.equal(undefined, undefined) }) })
import styled from "styled-components"; export const Label = styled.label` color: #fff; font-size: 18px; `; export const Input = styled.input` border: 4px solid #fff; border-radius: 5px; padding: 10px 15px; background-color: transparent; color: #fff; font-size: 18px; `;
import React from "react"; import { View, StyleSheet, Dimensions, Image, Text, TouchableOpacity, ScrollView, ImageBackground } from "react-native"; import LinearGradient from "react-native-linear-gradient"; import ButtonIcon from "./ButtonIcon"; import ButtonRound from "./ButtonRound"; const CardWithName = ({ cardBg, cardName, heartIcon, onPress }) => { const { main, cardBgStyle, cardNameStyle, heartIconStyle, } = styles; return ( <View style={main}> <TouchableOpacity onPress={onPress} > <Image style = {heartIconStyle} resizeMode="contain" source={heartIcon} /> <ImageBackground imageStyle={{ resizeMode: "cover" }} style={cardBgStyle} source={cardBg} /> <Text numberOfLines={1} style={cardNameStyle}>{cardName}</Text> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ main: { marginTop: 0, backgroundColor: "#fff", shadowColor: "rgba(211, 211, 211, 0.5)", shadowOffset: { width: 3, height: 3 }, shadowRadius: 6, shadowOpacity: 1, borderRadius: 4, }, linearGradient: { position: "absolute", left: 0 }, cardBgStyle: { height: 119.1, position: "relative" }, cardNameStyle: { padding: 8, fontFamily:"OpenSans-Regular", fontSize: 16.4, fontWeight: "normal", fontStyle: "normal", lineHeight: 21.1, letterSpacing: 0, }, itemArea: { backgroundColor: "#fff", paddingHorizontal: 10, paddingVertical: 15, paddingBottom: 5, borderBottomWidth: 0.5, borderBottomColor: "#ebebeb", }, itemAreaInner: { marginBottom: 5, }, heartIconStyle: { width: 21, height: 21, position: "absolute", zIndex: 999, right: 8, top: 8, }, }); export default CardWithName;
// ********************************************* // * logger // ********************************************* var Looger = function(module){ this.options = module.options; }; Looger.prototype = { debug : console.log } module.exports = Looger;
import {SubmissionError} from 'redux-form'; import jwtDecode from 'jwt-decode'; import {API_BASE_URL} from '../config'; import {normalizeResponseErrors} from './utils'; import {saveAuthToken, clearAuthToken} from '../local-storage'; export const SET_AUTH_TOKEN = 'SET_AUTH_TOKEN'; export const setAuthToken = authToken => ({ type: SET_AUTH_TOKEN, authToken }) export const SET_CURRENT_USER = 'SET_CURRENT_USER'; export const setCurrentUser = currentUser => ({ type: SET_CURRENT_USER, currentUser }) export const SET_CURRENT_WATCHLIST = 'SET_CURRENT_WATCHLIST'; export const setCurrentWatchlist = currentWatchlist => ({ type: SET_CURRENT_WATCHLIST, currentWatchlist }) export const SIGN_OUT = 'SIGN_OUT'; export const signOut = () => ({ type: SIGN_OUT }) export const LOADING_TOGGLE = 'LOADING_TOGGLE'; export const loadingToggle = () => ({ type: LOADING_TOGGLE }) export const ADD_TO_WATCHLIST = 'ADD_TO_WATCHLIST'; export const addToWatchlist = (gameId) => ({ type: ADD_TO_WATCHLIST, gameId }) export const REMOVE_FROM_WATCHLIST = 'REMOVE_FROM_WATCHLIST'; export const removeFromWatchlist = (gameId) => ({ type: REMOVE_FROM_WATCHLIST, gameId }) // Stores the auth token in state and localStorage, and decodes and stores // the user data stored in the token export const storeAuthInfo = (authToken,dispatch) => { const decodedToken = jwtDecode(authToken); dispatch(setAuthToken(authToken)); dispatch(setCurrentUser(decodedToken.user)); saveAuthToken(authToken); return fetch(`${API_BASE_URL}/api/dashboard`, { method: 'GET', headers: { Authorization: `Bearer ${authToken}` } }) .then(res => normalizeResponseErrors(res)) .then(res => res.json()) .then(watchlist => dispatch(setCurrentWatchlist(watchlist))) } export const storeFromTokenLoad = (authToken) => dispatch => { storeAuthInfo(authToken, dispatch); } export const login = (username, password) => dispatch => { return fetch(`${API_BASE_URL}/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) .then(res => normalizeResponseErrors(res)) .then(res => res.json()) .then(({authToken}) => storeAuthInfo(authToken, dispatch)) .catch(err => { const {code} = err; if(code === 401) { return Promise.reject( new SubmissionError({ _error: 'Incorrect username or password' }) ); } }) }; export const sendUpdatedWatchlist = () => (dispatch, getState) => { const authToken = getState().auth.authToken; const updatedList = getState().auth.currentWatchlist.gameIds; return fetch(`${API_BASE_URL}/api/dashboard`, { method: 'PUT', headers: { Authorization: `Bearer ${authToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ 'gameIds': updatedList }) }) .then(res => normalizeResponseErrors(res)) .then(res => res.json()) .then(res => { dispatch(setCurrentWatchlist(res)) }) .catch(err => console.log(err)) } export const refreshAuthToken = () => (dispatch, getState) => { const authToken = getState().auth.authToken; return fetch(`${API_BASE_URL}/auth/refresh`, { method: 'POST', headers: { Authorization: `Bearer ${authToken}` } }) .then(res => normalizeResponseErrors(res)) .then(res => res.json()) .then(({authToken}) => storeAuthInfo(authToken, dispatch)) .catch(err => { const {code} = err; if(code === 401) { // We couldn't get a refresh token because our current credentials // are invalid or expired, so clear them and sign us out dispatch(setCurrentUser(null)); dispatch(setAuthToken(null)); clearAuthToken(authToken); } }) }
const Sequelize = require("sequelize"); module.exports = { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV1, primaryKey: true }, userName: { type: Sequelize.STRING }, firstName: { type: Sequelize.STRING }, lastName: { type: Sequelize.STRING } }
const BASE_URL = "https://dataservice.accuweather.com"; const API_KEY = "KGbpl82jSGcs6sfPI0OXuZF5sAaNhBYB"; const search = document.getElementById("search"); search.addEventListener("submit", getWeatherForecast); function getWeatherForecast(event) { event.preventDefault(); const city = document.getElementById("city").value.trim(); getLocationKey(city); } function getLocationKey(city) { fetch(`${BASE_URL}/locations/v1/cities/search?apikey=${API_KEY}&q=${city}`) .then((response) => response.json()) .then((data) => { const location = data[0]; getCurrentCondition(location); }) .catch((err) => console.log(err)); } function getCurrentCondition(location) { fetch(`${BASE_URL}/currentconditions/v1/${location.Key}?apikey=${API_KEY}`) .then((response) => response.json()) .then((data) => { const forecast = data[0]; updateUI(location, forecast); }) .catch((err) => console.log(err)); } function updateUI(location, forecast) { document.getElementById("name").innerText = location.LocalizedName; document.getElementById( "condition" ).innerHTML = `<i class="wi icon-accu${forecast.WeatherIcon}"></i> ${forecast.WeatherText}`; document.getElementById("temperature").innerHTML = `${forecast.Temperature.Imperial.Value} &#8457`; }
/** * Created by Administrator on 2017/1/1 0001. */ // 原始写法 function func01() { console.log('func01'); } function func02() { console.log('func02'); } function func03() { console.log('func03'); }
/* fixture.js - fixtures to bridge between JS events and actor events The MIT License (MIT) Copyright (c) 2016 Dale Schumacher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var fixture = module.exports; //fixture.log = console.log; fixture.log = function () {}; fixture.asyncRepeat = function asyncRepeat(n, action, callback) { callback = callback || function callback(error, result) { fixture.log('asyncRepeat callback:', error, result); }; try { var result = action(); fixture.log('asyncRepeat:', n, result); if (n > 1) { setImmediate(function () { fixture.asyncRepeat(n - 1, action, callback); }); } else { callback(false, result); } } catch(ex) { callback(ex); } }; fixture.testEventLoop = function testEventLoop(test, n, eventLoop, log) { log = log || fixture.log; fixture.asyncRepeat(n, function action() { return eventLoop({ fail: function (error) { console.log('FAIL!', error); } }); }, function callback(error, result) { log('asyncRepeat('+n+'):', error, result); test.ok(!error && result); test.done(); } ); };
export { SendFundsSearch } from './send-funds-search';
'use strict' const FirebaseAdmin = use('FirebaseAdmin') class UserController { async index ({ request }) { let pageToken = request.input('pageToken') let limit = parseInt(request.input('limit', 50)) return FirebaseAdmin.auth().listUsers(limit, pageToken).then(async (users) => { return users }) } async store ({ request }) { let data = request.only(['displayName', 'email', 'password', 'phoneNumber']) return FirebaseAdmin.auth().createUser(data) .then(async (user) => { return user }) .catch(async (reason) => { return reason }) } async show ({ params }) { let uid = params.id return FirebaseAdmin.auth().getUser(uid) .then(async (user) => { return user }) .catch(async (reason) => { return reason }) } async update ({ params, request }) { let data = request.only(['displayName', 'email', 'password', 'phoneNumber', 'disabled']) let uid = params.id return FirebaseAdmin.auth().updateUser(uid, data) .then(async (user) => { return user }) .catch(async (reason) => { return reason }) } async destroy ({ params }) { let uid = params.id return FirebaseAdmin.auth().deleteUser(uid) .then(async (user) => { return user }) .catch(async (reason) => { return reason }) } } module.exports = UserController
import { FETCH_MEMBER_LIST, FETCH_MEMBER_LIST_LOADING, FETCH_MEMBER_LIST_ERROR } from './memberList.actionType' import { database } from '../../firebase/firebase' import { searchUser } from '../userData/userData.actions' export const fetchMemberList = (lastNotified) => { return dispatch => { dispatch(fetchMemberListLoading()) database().ref(`/smarthome/users`).on('value', (snaphot) => { let val = snaphot.val() if(val) { val = Object.values(snaphot.val()).reverse() } else { val = [] } dispatch(fetchMemberListSuccess(val)) dispatch(searchUser(val)) }, (err) => { dispatch(fetchMemberListError()) }) } } export const fetchMemberListSuccess = (payload) => { return { type: FETCH_MEMBER_LIST, payload: payload } } const fetchMemberListLoading = () => { return { type: FETCH_MEMBER_LIST_LOADING, } } const fetchMemberListError = () => { return { type: FETCH_MEMBER_LIST_ERROR } }
/** * */ (function() { countSum(); getTotalCost(); })(); function setCookie(c_name, value, expiredays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays * 24 * 3600 * 1000); document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()); } function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1 c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) c_end = document.cookie.length return unescape(document.cookie.substring(c_start, c_end)); } } return ""; } function delCookie(name)// 删除cookie { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } function addCart(itemId, amount) { var temp = getCookie("item_" + itemId); var total = parseInt(temp == "" ? "0" : temp) + amount; setCookie("item_" + itemId, total, 1); countSum(); } function countSum() { var aCookie = document.cookie.split(";"); var re = /^item_*/; var sum = 0; for (var i = 0; i < aCookie.length; i++) { var aCrumb = aCookie[i].split("="); if (!re.test(aCrumb[0].toString().trim())) { continue; } sum += parseInt(aCrumb[1].toString().trim()); } $('#cart_sum').html(sum); } $(function() { var offset = $("#cart_sum").offset(); $(".addcar").click(function(event) { var addcar = $(this); var img = $('#itemImg').attr('src'); var flyer = $('<img class="u-flyer" src="' + img + '">'); // alert(offset); flyer.fly({ start : { left : event.pageX - 400, // 开始位置(必填)#fly元素会被设置成position: // fixed top : event.pageY - 300 // 开始位置(必填) }, end : { left : offset.left, // 结束位置(必填) top : offset.top, // 结束位置(必填) width : 0, // 结束时宽度 height : 0 // 结束时高度 }, onEnd : function() { // 结束回调 // $("#msg").show().animate({ // width : '250px' // }, 200).fadeOut(1000); // 提示信息 // addcar.css("cursor", "default").removeClass('orange') // .unbind('click'); // this.destory(); // 移除dom } }); }); }); function removeCart(item_id) { delCookie(item_id); window.location.reload(); } function getTotalCost() { var sum = new Number(); $('.item').each(function() { var price = $(this).find('.price').first().html(); var amount = $(this).find('.amount').first().val(); var subSum = (parseFloat(price) * parseFloat(amount)); $(this).find('.subSum').first().html(subSum.toFixed(2)); sum += subSum; }); $('#sum').html(sum.toFixed(2)); } function onAmountInput(event, item_id, max) { var amount = event.target.value; var amountReg = /^[1-9]\d*$/; if (!amount || parseInt(amount) == 0) { event.target.value = 1; } else if (amountReg.test(amount)) { amount = amount > max ? max : amount; event.target.value = amount; setCookie('item_' + item_id, amount, 1); getTotalCost(); } else { event.target.value = getCookie('item_' + item_id); } } function onAmountPropChanged(event, item_id, max) { if (event.propertyName.toLowerCase() == "value") { var amount = event.target.value; var amountReg = /^[1-9]\d*$/; if (!amount || parseInt(amount) == 0) { event.target.value = 1; setCookie('item_' + item_id, amount, 1); getTotalCost(); } else if (amountReg.test(amount)) { amount = amount > max ? max : amount; setCookie('item_' + item_id, amount, 1); getTotalCost(); } else { event.target.value = getCookie('item_' + item_id); } } }
//bamazonCustomer.js var mysql = require("mysql"); var inquirer = require("inquirer"); var columnify = require('columnify'); let db_success = false; let prodCount = 0; var connection = mysql.createConnection({ host: "localhost", // Your port; if not 3306 port: 3306, // Your username user: "root", // Your password password: "BootCamp18", database: "bamazon_db" }); function displayAll() { var query = "SELECT * FROM products"; connection.query(query, function (err, res) { if (err) throw err; prodCount = res.length; console.log("number of products= " + res.length); var columns = columnify(res, { config: { item_id: { headingTransform: function(heading) { heading = "ID\n=="; return heading; }, align: 'right' }, product_name: { headingTransform: function(heading){ heading = "Product Name\n============"; return heading; }, align: 'left' }, department_name: { headingTransform: function(heading){ heading = "Department Name\n==============="; return heading; } }, price: { headingTransform: function(heading){ heading = "Price\n====="; return heading; } }, stock_quanity: { headingTransform: function(heading){ heading = "Quantity\n========\n\n"; return heading; }, align: 'left' } } }) console.log(columns + "\n"); startHere(); }); } function startHere() { inquirer .prompt({ type: "list", name: "action", message: "What would you like to do?", choices: [ "Place Order", "Exit Program" ] }) .then(function (answer) { switch (answer.action) { case "Place Order": runOrder(); break; case "Exit Program": process.exit() ; break ; } }); } function runOrder() { let question = [{ type: 'input', name: 'order_p_id', message: " Enter Product ID ", validate: function validItemNumber(value){ var pass = value.match(/[0123456789]+/); if (pass && value <= prodCount){ return true; } return "Please enter a valid item number." } }, { type: 'input', name: 'order_quant', message: ' Enter number of units to order ', validate: function validOrderQuant(value){ var pass = value.match(/[0123456789]+/); if (pass){ return true; } return "Please enter a valid item number."; } }]; inquirer.prompt(question).then(answer => { runPlaceOrder(answer.order_p_id, parseInt(answer.order_quant)); }); } function runPlaceOrder(item, quantity){ var query = "SELECT products.item_id, products.stock_quanity, products.price FROM products WHERE products.item_id = ?"; connection.query(query, item, function (err, res) { if (err) throw err; console.log("") if (res[0].stock_quanity < quantity ) { console.log("Insufficient quantity to fill order!\n"); inquirer.prompt( { type: 'input', name: 'anyKey', message: ' Press any key to continue ' } ).then(answer => { displayAll(); }); } else { rpo_quantity = res[0].stock_quanity; rpo_price = res[0].price; rpo_quantity -= quantity; var query = connection.query( "UPDATE products SET ? WHERE ?", [ { stock_quanity: rpo_quantity }, { item_id: item } ], function (err, res) { if (err) throw err; if ( res.affectedRows > 0 ) { console.log("Your order has been placed; total cost is " + parseInt(quantity) * rpo_price); inquirer.prompt( { type: 'input', name: 'anyKey', message: ' Press any key to continue ' } ).then(answer => { displayAll(); }); } }); } }); } displayAll();
var ping = []; var download = []; var upload = []; for(var test of tests) { ping.push({ x: new Date(test.timestamp), y: test.ping }); download.push({ x: new Date(test.timestamp), y: test.download/1000000 }); upload.push({ x: new Date(test.timestamp), y: test.upload/1000000 }); } var pingChart = document.getElementById("ping").getContext('2d'); var downloadChart = document.getElementById("download").getContext('2d'); var uploadChart = document.getElementById("upload").getContext('2d'); new Chart(pingChart, { type: 'line', data: { datasets: [{ data: ping, backgroundColor: [ 'rgba(33, 150, 243, 0.2)' ], borderColor: [ 'rgba(33, 150, 243, 1)' ], borderWidth: 1 }] }, options: { fill: false, legend: { display: false }, responsive: true, scales: { xAxes: [{ type: "time", display: false, scaleLabel: { display: true, labelString: 'Date' }, ticks: { major: { fontStyle: "bold", fontColor: "#FF0000" } } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'milliseconds' }, ticks: { beginAtZero:true } }] } } }); new Chart(downloadChart, { type: 'line', data: { datasets: [{ data: download, backgroundColor: [ 'rgba(33, 150, 243, 0.2)' ], borderColor: [ 'rgba(33, 150, 243, 1)' ], borderWidth: 1 }] }, options: { fill: false, legend: { display: false }, responsive: true, scales: { xAxes: [{ type: "time", display: false, scaleLabel: { display: true, labelString: 'Date' }, ticks: { major: { fontStyle: "bold", fontColor: "#FF0000" } } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'milliseconds' }, ticks: { beginAtZero:true } }] } } }); new Chart(uploadChart, { type: 'line', data: { datasets: [{ data: upload, backgroundColor: [ 'rgba(33, 150, 243, 0.2)' ], borderColor: [ 'rgba(33, 150, 243, 1)' ], borderWidth: 1 }] }, options: { fill: false, legend: { display: false }, responsive: true, scales: { xAxes: [{ type: "time", display: false, scaleLabel: { display: true, labelString: 'Date' }, ticks: { major: { fontStyle: "bold", fontColor: "#FF0000" } } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'milliseconds' }, ticks: { beginAtZero:true } }] } } });
/*************************************************** * 时间: 16/5/8 22:15 * 作者: zhongxia * 依赖: Zepto.js Util.js * 说明: 点读考试 (答题组件) * 1. 左右滑动, swiper * 2. 分为单选,多选,对错题 * 3. 自动判断是否答对 * 4. 自动记录是否已经答题 * ***************************************************/ function ExamShowList(selector, config) { this.selector = selector; this.config = config; this.data = config.data; this.callback = config.callback; this.scale = config.scale || 1; this.scale = this.scale > 1.5 ? 1.5 : this.scale; this.swiper; this.click = this.IsPC() ? 'click' : 'tap'; this.CLASSENUM = { radio: { UNSELECTRIGHT: 'exam-list-radio-unselect-right', ERROR: 'exam-list-radio-error', RIGHT: 'exam-list-radio-right', }, bool: { UNSELECTRIGHT: 'exam-list-bool-unselect-right', ERROR: 'exam-list-bool-error', RIGHT: 'exam-list-bool-right', }, checkbox: { UNSELECTRIGHT: 'exam-list-checkbox-unselect-right', ERROR: 'exam-list-checkbox-error', RIGHT: 'exam-list-checkbox-right' } } this.render(); } /** * 渲染页面 */ ExamShowList.prototype.render = function () { var html = this.config.isVertical ? this.createContainer() : this.createHContainer(); $(this.selector).html(html); this.initVar(); this.bindEvent(); this.setScale(); this.hRender(); } /** * 创建页面容器 * @returns {string} */ ExamShowList.prototype.createContainer = function () { var data = this.data; this.currentIndex = this.currentIndex || 1; this.total = data.questions.length || 1; var html = ''; html += '<div class="exam-list-container">' html += ' <div class="exam-list-righttop exam-radio">' html += ' </div>' html += ' <div class="exam-list-top">' html += ' <div class="exam-list-questionsList"></div>' html += ' <div class="exam-list-sortid">' html += ' <div class="exam-list-sortid-spandiv"><span data-id="currentIndex">' + this.currentIndex + '</span> / <span data-id="total">' + this.total + '</span></div>' html += ' </div>' html += ' </div>' html += this.createQuestions(data.questions); html += ' <div class="exam-list-show-answer">' html += ' </div>' html += '</div>' html += ' <div class="exam-list-close"></div>' return html; } ExamShowList.prototype.createHContainer = function () { var data = this.data; this.currentIndex = this.currentIndex || 1; this.total = data.questions.length || 1; var html = ''; html += '<div class="exam-list-container" style="flex-direction: row;">' html += ' <div class="exam-list-left" style="flex: 66;">' html += ' <div class="exam-list-righttop exam-radio"></div>' html += ' <div class="exam-list-top">' html += ' <div class="exam-list-questionsList"></div>' html += ' <div class="exam-list-sortid">' html += ' <div class="exam-list-sortid-spandiv"><span data-id="currentIndex">' + this.currentIndex + '</span> / <span data-id="total">' + this.total + '</span></div>' html += ' </div>' html += ' </div>' html += ' <div class="exam-list-question-title"><p data-id="_hTitle" style="word-wrap: break-word;word-break: break-all;" class="exam-hTitle"></p></div>' html += ' <div class="exam-list-show-answer">' html += ' </div>' html += ' </div>' html += ' <div class="exam-list-right" style="flex: 84;">' html += this.createQuestions(data.questions); html += ' </div>' html += '</div>' html += ' <div class="exam-list-close"></div>' return html; } /** * 创建问题页 * @param questions * @returns {string} */ ExamShowList.prototype.createQuestions = function (questions) { var html = ''; html += '<div class="exam-list-main swiper-container">' html += ' <div class="exam-list-questions swiper-wrapper">' for (var i = 0; i < questions.length; i++) { var question = questions[i]; html += '<div class="exam-list-question swiper-slide">' html += ' <p class="exam-list-question-title" style="word-wrap: break-word;word-break: break-all;">' + question.text + '</p>' html += this.createAnswers(question.answers, question.type, i) html += '</div>' } html += ' </div>' html += '</div>' return html; } /** * 创建答案项 * @param answers * @param type * @param index * @returns {string} */ ExamShowList.prototype.createAnswers = function (answers, type, index) { var html = ''; html += '<ul class="exam-list-question-answer">' for (var i = 0; i < answers.length; i++) { var answer = answers[i]; if (answer.text.length > 0) { html += ' <li data-type="' + type + '" data-flag="' + answer.answer + '" data-id="' + (index + '_' + i) + '">' //li列表上,标注着该选项是否为答案 html += ' <div class="exam-list-' + type + '">' html += '<span class="exam-list-answer-item" style="word-wrap: break-word;word-break: break-all;">' + answer.text + '</span>'; html += ' </div>' html += ' </li>' } } html += '</ul>' return html; } /** * 初始化变量 */ ExamShowList.prototype.initVar = function () { this.$container = $(this.selector); this.$currentIndex = this.$container.find('span[data-id="currentIndex"]') this.$total = this.$container.find('span[data-id="total"]') this.$questions = this.$container.find('.exam-list-question') this.$answers = this.$container.find('.exam-list-question-answer>li') //所有答案选项 this.$showAnswer = this.$container.find('.exam-list-show-answer') //显示答案 this.$btnQuestionsList = this.$container.find('.exam-list-questionsList'); //题干 this.$questionType = this.$container.find('.exam-list-righttop'); //题型图片 this.$top = this.$container.find('.exam-list-top'); this.$questionTitle = this.$container.find('.exam-list-question-title') this.$answerContainer = this.$container.find('.exam-list-question-answer') this.$close = this.$container.find('.exam-list-close'); //横屏title this.$hTitle = this.$container.find('p[data-id="_hTitle"]') } /** * 事件绑定 */ ExamShowList.prototype.bindEvent = function () { var that = this; /** * 初始化 Swiper 组件 * @type {*|Swiper} */ that.swiper = new Swiper('.exam-list-main', { autoplayStopOnLast: true, slidesPerView: 1, onSlideChangeEnd: function (swiper) { that.currentIndex = swiper.activeIndex + 1; that.renderCurrentIndex(); //切换题目类型图标 that.$questionType.removeClass('exam-radio') .removeClass('exam-bool') .removeClass('exam-checkbox') .addClass('exam-' + that.data.questions[swiper.activeIndex].type); //横屏下,左侧显示 题目 if (!that.config.isVertical) { that.$hTitle.text(that.data.questions[swiper.activeIndex].text) } } }); that.bindEvent_answer(); /** * 显示所有答案, [注释掉的是显示当前题目的答案] */ that.$showAnswer.off().on(that.click, function () { //隐藏答案 if (that.$showAnswer.hasClass('exam-list-hide-answer')) { that.$showAnswer.removeClass('exam-list-hide-answer') for (var i = 0; i < that.data.questions.length; i++) { that.hideAnswer4Index(i); } that.bindEvent_answer(); //that.hideAnswer4Index(that.currentIndex - 1); } else { //显示答案 that.$showAnswer.addClass('exam-list-hide-answer'); that.$answers.off(); for (var i = 0; i < that.data.questions.length; i++) { that.showAnswer4Index(i); } //that.showAnswer4Index(that.currentIndex - 1); } }); /** * 点击题干 */ that.$btnQuestionsList.off().on(that.click, function () { that.callback && that.callback(that.data) }) that.$close.off().on(that.click, function (e) { var $ctar = $(e.currentTarget); $ctar.parent().parent().hide(); }) } /** * 绑定点击答案的事件 * 在查看答案的时候,清除了点击事件 */ ExamShowList.prototype.bindEvent_answer = function () { var that = this; /** * tap 答案选项, 由于滑动屏幕会触发,所以改成下面的方式 * 分为 PC 端 和 移动端的展示方式 */ if (that.IsPC()) { that.$answers.off().on(that.click, function (e) { that.renderAnswer(e); }) } else { that.Moblie_MoveOrTap(that.$answers, function (e) { that.renderAnswer(e); }) } } /** 根据问题的下标,显示该问题的答案 * @param questionIndex 问题的下标 (this.currentIndex -1) */ ExamShowList.prototype.showAnswer4Index = function (questinoIndex) { var question = this.data.questions[questinoIndex]; var $question = $(this.$questions[questinoIndex]); var _$answers = $question.find('.exam-list-question-answer>li>div') var className = 'exam-list-' + question.type + '-active'; var classENUM = this.CLASSENUM[question.type]; for (var i = 0; i < question['answers'].length; i++) { var answer = question['answers'][i]; if (answer.answer && $(_$answers[i]).hasClass(className)) { //设置显示答案的样式 $(_$answers[i]).addClass(classENUM.RIGHT) } else if (answer.answer) { $(_$answers[i]).addClass(classENUM.UNSELECTRIGHT) } else if ($(_$answers[i]).hasClass(className)) { $(_$answers[i]).addClass(classENUM.ERROR) } } } /** * 隐藏答案,隐藏某一题的答案 * @param questinoIndex */ ExamShowList.prototype.hideAnswer4Index = function (questinoIndex) { var question = this.data.questions[questinoIndex]; var $question = $(this.$questions[questinoIndex]); var _$answers = $question.find('.exam-list-question-answer>li>div') var classENUM = this.CLASSENUM[question.type]; _$answers.removeClass(classENUM.RIGHT).removeClass(classENUM.ERROR).removeClass(classENUM.UNSELECTRIGHT); } /** * 渲染 第几题, 根据 控件里面的 this.currentIndex */ ExamShowList.prototype.renderCurrentIndex = function () { this.$currentIndex.text(this.currentIndex); } /** * 渲染答案选项,选中或者未选中 * @param id */ ExamShowList.prototype.renderAnswer = function (e) { var $cTar = $(e.currentTarget); var $answers = $cTar.parent().find('li>div'); var $answer = $cTar.find('div'); var type = $cTar.attr('data-type'); var id = $cTar.attr('data-id'); var className = 'exam-list-' + type + '-active' //单选,对错题, 则 默认清除之前选中的状态 if (type !== 'checkbox') { $answers.removeClass(className); } //已选中在点击 则 变成 未选中 if ($answer.hasClass(className)) { $answer.removeClass(className) } else { $answer.addClass(className) } this.setValue2Data() } /** * 横屏下的一些处理操作 */ ExamShowList.prototype.hRender = function () { if (!this.config.isVertical) { this.$hTitle.text(this.data.questions[0].text) } } /** * 把 答题的 题目 记录到 data 里面,并判断是否做对 */ ExamShowList.prototype.setValue2Data = function () { var $questions = this.$questions; var questionsData = this.data.questions; for (var i = 0; i < $questions.length; i++) { var $question = $($questions[i]); var $answers = $question.find('ul>li>div'); var _selected = ''; //判断题目是否已经做了 var flag = true; //标记多选题是否全部选对 var className = 'exam-list-' + questionsData[i].type + '-active' for (var j = 0; j < $answers.length; j++) { var $answer = $($answers[j]); //选中,表示题目已经选择答案了 if ($answer.hasClass(className)) { questionsData[i]['answers'][j].selected = true; //记录选项 _selected += "1"; //题目已做 } else { questionsData[i]['answers'][j].selected = false; _selected += "0"; //题目未做 } } if (_selected.indexOf('1') !== -1) { questionsData[i].selected = true; } else { questionsData[i].selected = false; delete questionsData[i].isRight; //如果为做题目,则没有做对做错之说法 } //判断题目是否答对 if (questionsData[i].selected) { for (var k = 0; k < questionsData[i]['answers'].length; k++) { var _answer = questionsData[i]['answers'][k]; //fix:如果题目有四个选项答案,但是只输入了三个,会导致判断作对题目有问题。 因为 selected 默认为 undefined _answer.selected = _answer.selected || false; if (_answer.selected !== _answer.answer) { flag = false; } } questionsData[i].isRight = flag; } } } /** * 设置题目的缩放 */ ExamShowList.prototype.setScale = function () { this.$top.css('zoom', this.scale); this.$questionType.css('zoom', this.scale); this.$questionTitle.css('zoom', this.scale); this.$answerContainer.css('zoom', this.scale); this.$close.css('zoom', this.scale) if (!this.config.isVertical) { this.$showAnswer.css('zoom', this.scale) } } /*========================工具方法===========================*/ /** * 判断是否为PC端 * @returns {boolean} * @constructor */ ExamShowList.prototype.IsPC = function () { var userAgentInfo = navigator.userAgent; var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"); var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } /** * 鼠标是点击或者移动 [Util里面也有该方法] * @param selector * @param cb_tap * @param cb_move */ ExamShowList.prototype.Moblie_MoveOrTap = function ($selector, cb_tap, cb_move) { var flag = false; $selector.on('touchstart touchmove touchend', function (event) { switch (event.type) { case 'touchstart': flag = false; break; case 'touchmove': flag = true; break; case 'touchend': if (!flag) { cb_tap && cb_tap(event); } else { cb_move && cb_move(event); } break; } }) }
export function getIndexDateFields(sinceDate, dayOffset) { const sinceDt = sinceDate || new Date(); if (dayOffset) { sinceDt.setDate(sinceDt.getDate() + dayOffset); } const parsableIndexDateStr = [ sinceDt.getFullYear(), (`0${sinceDt.getMonth() + 1}`).slice(-2), (`0${sinceDt.getDate()}`).slice(-2), ].join('-'); const indexStartMs = Date.parse(parsableIndexDateStr); const indexDateStr = parsableIndexDateStr.replace(/-/g, ''); return [indexDateStr, indexStartMs, sinceDt, sinceDt.getTime()]; } export function getCommonPrefix(val1, val2) { const str1 = val1.toString(); const str2 = val2.toString(); if (str1 === str2) { return str1; } const chars1 = str1.split(''); const chars2 = str2.split(''); let prefix = ''; for (let i = 0; i < chars1.length; i += 1) { if (chars1[i] !== chars2[i]) { break; } prefix += chars1[i]; } return prefix; } export function getIndexDateStr(date) { const [indexDateStr] = getIndexDateFields(date); return indexDateStr; } export function getPartition(eventId, paritionCount) { // floats are safe up to 52 bits, 13 hex characters = 52 bits. // parse last 13 chars of the cloudwatch eventId guid as base16 // to deterministically generate a number from the GUID return parseInt(eventId.replace(/[^0-9a-fA-F]/g, '').substr(-13), 16) % paritionCount; } export function getPartitionKey(eventId, paritionCount) { const indexDateStr = getIndexDateStr(); const partition = getPartition(eventId, parseInt(paritionCount, 10)); return `${indexDateStr}.p${partition}`; } export function parsePartitionKey(partitionKey) { const [indexDateStr, partition] = partitionKey.split('.p'); return { indexDateStr, partition, }; } export function zipPartitionKeys(indexDateStr, exclusiveStartKeys) { return Object.entries(exclusiveStartKeys).reduce((acc, [partition, sortKey]) => { acc[`${indexDateStr}.p${partition}`] = sortKey; return acc; }, {}); } export function getAllPartitionKeys(indexDateStr, paritionCount) { return Array(parseInt(paritionCount, 10)).fill().map((_, partition) => `${indexDateStr}.p${partition}`); } export function getSortKeyPrefix(serviceName, jobName, eventTime, eventId) { let parts = [ serviceName, jobName, eventTime, eventId, ]; let sortKeyPrefix = ''; const firstEmptyIndex = parts.findIndex(a => a === undefined || a === null); if (firstEmptyIndex !== -1) { parts = parts.slice(0, firstEmptyIndex); if (parts.length > 0 && parts.length < 3) { sortKeyPrefix = ':'; } } parts.reverse().forEach((val, i) => { const isLast = i + 1 === parts.length; if (val && (isLast || parts[i + 1])) { sortKeyPrefix = `${isLast ? '' : ':'}${val}${sortKeyPrefix}`; } }); return sortKeyPrefix; } export function getSortKey(serviceName, jobName, eventTime, eventId) { if (!eventTime || !serviceName || !jobName || !eventId) { throw new Error('Missing required input fields for creating job execution sort key'); } const eventTimeMs = (new Date(eventTime)).getTime(); return getSortKeyPrefix(serviceName, jobName, eventTimeMs, eventId); } export function parseSortKey(sortKey) { const [ serviceName, jobName, eventTimeMs, eventId, ] = sortKey.split(':'); return { serviceName, jobName, eventTimeMs, eventId, }; } export function encodeCallbackToken({ jobExecutionKey, jobExecutionName, jobGuid, }) { const version = 1; const json = JSON.stringify([ version, jobExecutionKey, jobExecutionName, jobGuid, ]); return Buffer.from(json).toString('base64'); } export function decodeEncodedCallbackToken(encodedCallbackToken) { const decoded = Buffer.from(encodedCallbackToken, 'base64').toString('ascii'); const [ _version, jobExecutionKey, jobExecutionName, jobGuid, ] = JSON.parse(decoded); return { jobExecutionKey, jobExecutionName, jobGuid, }; } export function encodeJobExecutionKey({ partitionKey, sortKey }) { const version = 1; return Buffer.from([version, partitionKey, sortKey].join(';')).toString('base64'); } export function decodeEncodedJobExecutionKey(encodedJobExecutionKey) { const decoded = Buffer.from(encodedJobExecutionKey, 'base64').toString('ascii'); const parts = decoded.split(';'); const version = parts.shift(); let partitionKey; let sortKey; switch (version) { case 1: default: ([partitionKey, sortKey] = parts); } return { partitionKey, sortKey, }; } export const jobKeyPropNames = [ 'jobName', 'serviceName', ]; export const jobStaticExecutionRelevantPropNames = [ ...jobKeyPropNames, 'async', 'exclusive', 'invocationTarget', 'invocationType', 'payload', 'ruleSchedule', 'schedule', 'ttlSeconds', ]; export const jobStaticPropNames = [ ...jobKeyPropNames, ...jobStaticExecutionRelevantPropNames, 'deletedAt', 'enabled', 'guid', 'key', 'payload', 'ruleName', ]; export function splitJobStaticProps(jobProps) { const resp = { job: {}, jobStatic: { key: {}, }, }; return Object.entries(jobProps).reduce((acc, [k, v]) => { const dest = jobStaticPropNames.includes(k) ? 'jobStatic' : 'job'; if (jobKeyPropNames.includes(k)) { acc.jobStatic.key[k] = v; } acc[dest][k] = v; return acc; }, resp); } export const jobExecutionResultPropNames = [ 'correlationId', 'state', 'status', 'summary', 'error', ]; export function filterJobExecutionResult(jobExecutionResult) { return Object.entries(jobExecutionResult).reduce((acc, [k, v]) => { if (jobExecutionResultPropNames.includes(k)) { acc[k] = v; } return acc; }, {}); } export function filterJobStaticExecutionRelevantProps(jobStaticProps) { return Object.entries(jobStaticProps).reduce((acc, [k, v]) => { if (jobStaticExecutionRelevantPropNames.includes(k)) { acc[k] = v; } return acc; }, {}); } export function genericEncode(val) { const valJson = JSON.stringify(val); return Buffer.from(valJson).toString('base64'); } export function genericDecode(encodedVal) { const valJson = Buffer.from(encodedVal, 'base64').toString('ascii'); return JSON.parse(valJson); }
import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import styles from '../styles/globalStyle'; export default function(props) { return ( <View style={styles.postItContainer}> <Text style={styles.title}>{props.titulo}</Text> <Text style={styles.date}>{props.data}</Text> <Text style={styles.f18}>{props.texto}</Text> </View> ); }
const Promise = require('bluebird'); const models = require('../../models'); // const obtainInformation = require('./obtainInformation'); const Sequelize = require('sequelize'); var { sequelize } = models; const courseMethods = {}; const Op = Sequelize.Op; courseMethods.addCourse = (info) => { info.filled = 0; return new Promise((resolve, reject) => { models.Course.create(info) .then((result) => { resolve(result); }) .catch((err) => { console.log(err); reject(err); }); }); }; courseMethods.getAllCourses = function(){ return new Promise((resolve,reject)=>{ models.Course.findAll({ raw : true, attributes : ['id','capacity','filled'] }) .then(res => { var re = {} res.forEach(element => { var x = [] x.push(element.capacity) x.push(element.filled) re[element.id] = x }); resolve(re); }) .catch(err => { reject(err); }) }) } courseMethods.getAllCourseDetails = function(){ return new Promise((resolve,reject)=>{ models.Course.findAll({ raw : true, attributes : ['id','courseID','name'] }) .then(res => { var re = {} res.forEach(element => { var x = [] x.push(element.courseID) x.push(element.name) re[element.id] = x }); resolve(re); }) .catch(err => { reject(err); }) }) } courseMethods.getCourses = function(){ return new Promise((resolve,reject) => { models.Course.findAll({ raw : true }) .then(res => { resolve(res) }) .catch(err => { reject(err) }) }) } courseMethods.getCourse = function(id){ return new Promise((resolve,reject) => { models.Course.findOne({ raw : true, where : { id : id }, attributes : ['courseID','name'] }) .then(res => { resolve(res) }) .catch(err => { reject(err) }) }) } courseMethods.deleteCourse = function(id){ return new Promise((resolve,reject) => { models.Course.destroy({ raw : true, where : { courseID : id }}) .then(res => { resolve(res) }) .catch(err => { reject(err) }) }) } module.exports = courseMethods;
const SERVER = 'http://127.0.0.1:3000/'; export const ADMIN_LOGIN = SERVER + 'admin/login'; export const USER_LOGOUT = SERVER + 'user/logout'; export const ADMIN_COUNT = SERVER + 'admin/count';
'use strict'; /* Copyright 2017 - present Sean O'Shea Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ function matchAlphabet(pattern) { var s = {}; for (var i = 0, l = pattern.length; i < l; i += 1) { s[pattern.charAt(i)] = 0; } for (var _i = 0, _l = pattern.length; _i < _l; _i += 1) { s[pattern.charAt(_i)] |= 1 << pattern.length - _i - 1; } return s; } function matchBitapScore(e, x, loc, pattern, matchDistance) { var accuracy = e / pattern.length; var proximity = Math.abs(loc - x); if (!matchDistance) { return proximity ? 1.0 : accuracy; } return accuracy + proximity / matchDistance; } function matchBitapOfText(text, pattern) { var loc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var options = arguments.length > 3 ? arguments[3] : undefined; var s = matchAlphabet(pattern); var matchDistance = options && options.distance || 1000; var matchThreshold = options && options.threshold || 0.5; var scoreThreshold = matchThreshold; var bestLoc = text.indexOf(pattern, loc); if (bestLoc !== -1) { scoreThreshold = Math.min(matchBitapScore(0, bestLoc, loc, pattern, matchDistance), scoreThreshold); bestLoc = text.lastIndexOf(pattern, loc + pattern.length); if (bestLoc !== -1) { scoreThreshold = Math.min(matchBitapScore(0, bestLoc, loc, pattern, matchDistance), scoreThreshold); } } var matchmask = 1 << pattern.length - 1; bestLoc = -1; var binMin; var binMid; var binMax = pattern.length + text.length; var lastRd; for (var d = 0; d < pattern.length; d += 1) { binMin = 0; binMid = binMax; while (binMin < binMid) { if (matchBitapScore(d, loc + binMid, loc, pattern, matchDistance) <= scoreThreshold) { binMin = binMid; } else { binMax = binMid; } binMid = Math.floor((binMax - binMin) / 2 + binMin); } binMax = binMid; var start = Math.max(1, loc - binMid + 1); var finish = Math.min(loc + binMid, text.length) + pattern.length; if (!finish) { finish = 0; } var rd = Array(finish + 2); rd[finish + 1] = (1 << d) - 1; for (var j = finish; j >= start; j -= 1) { var charMatch = s[text.charAt(j - 1)]; if (d === 0) { rd[j] = (rd[j + 1] << 1 | 1) & charMatch; } else { rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((lastRd[j + 1] | lastRd[j]) << 1 | 1) | lastRd[j + 1]; } if (rd[j] & matchmask) { var score = matchBitapScore(d, j - 1, loc, pattern, matchDistance); if (score <= scoreThreshold) { scoreThreshold = score; bestLoc = j - 1; if (bestLoc > loc) { start = Math.max(1, 2 * loc - bestLoc); } else { break; } } } } if (matchBitapScore(d + 1, loc, loc, pattern, matchDistance) > scoreThreshold) { break; } lastRd = rd; } return bestLoc; } /** * Executes a fuzzy match on the `text` parameter using the `pattern` parameter. * @param {String} text - the text to search through for the pattern. * @param {String} pattern - the pattern within the text to search for. * @param {String} loc - defines the approximate position in the text where the pattern is expected to be found. * @param {Object} options * @param {String} [options.distance] - Defines where in the text to look for the pattern. * @param {String} [options.threshold] - Defines how strict you want to be when fuzzy matching. A value of 0.0 is equivalent to an exact match. A value of 1.0 indicates a very loose understanding of whether a match has been found. * @since 0.1.0 * @return An Int indicating where the fuzzy matched pattern can be found in the text. */ function fuzzyMatchPattern(text, pattern) { var loc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var options = arguments.length > 3 ? arguments[3] : undefined; if (text == null || pattern == null) { throw new Error('Null input. (fuzzyMatchPattern)'); } var location = Math.max(0, Math.min(loc, text.length)); if (text === pattern) { return 0; } if (!text.length) { return -1; } if (text.substring(loc, loc + pattern.length) === pattern) { return location; } return matchBitapOfText(text, pattern, location, options); } /** * Provides a confidence score relating to how likely the `pattern` parameter is to be found in the `text` parameter. * @param {String} text - the text to search through for the pattern. * @param {String} pattern - the pattern to search for. * @param {Int} loc - the index in the element from which to search. * @param {Int} distance - determines how close the match must be to the fuzzy location. See `loc` parameter. * @since 0.1.0 * @return A number which indicates how confident we are that the pattern can be found in the host string. A low value (0.001) indicates that the pattern is likely to be found. A high value (0.999) indicates that the pattern is not likely to be found. */ function confidenceScore(text, pattern) { var loc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var distance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1000; // start at a low threshold and work our way up for (var index = 1; index < 1000; index += 1) { var threshold = index / 1000; if (fuzzyMatchPattern(text, pattern, loc, { threshold: threshold, distance: distance }) !== -1) { return threshold; } } return -1; } /** * Iterates over all elements in the array and executes a fuzzy match using the `pattern` parameter. * @param {Array} array - the array of Strings to sort. * @param {String} pattern - the pattern to search for. * @param {Int} loc - the index in the element from which to search. * @param {Int} distance - determines how close the match must be to the fuzzy location. See `loc` parameter. * @since 0.2.0 * @return The `array` parameter sorted according to how close each element is fuzzy matched to the `pattern` parameter. */ function sortArrayByFuzzyMatchPattern(array, pattern) { var loc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var distance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1000; var indexesAdded = []; var sortedArray = []; for (var i = 1, l = 10; i <= l; i += 1) { if (sortedArray.length === array.length) { break; } var options = { threshold: i / 10, distance: distance }; for (var index = 0, length = array.length; index < length; index += 1) { if (!indexesAdded.includes(index)) { var value = array[index]; var result = fuzzyMatchPattern(value, pattern, loc, options); if (result !== -1) { sortedArray.push(value); indexesAdded.push(index); } } } } for (var _index = 0, _length = array.length; _index < _length; _index += 1) { if (!indexesAdded.includes(_index)) { sortedArray.push(array[_index]); } } return sortedArray; } var fuzzyMatching = { confidenceScore: confidenceScore, fuzzyMatchPattern: fuzzyMatchPattern, sortArrayByFuzzyMatchPattern: sortArrayByFuzzyMatchPattern }; /* Copyright 2017 - present Sean O'Shea Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ fuzzyMatching.version = '0.3.0'; module.exports = fuzzyMatching;
var searchData= [ ['pics_5fdir',['PICS_DIR',['../struct_c_o_n_f.html#abc4633bb8e9a6a14e116abd19f2f391c',1,'CONF']]] ];
/* Copyright (c) 2020 Red Hat, Inc. */ 'use strict' import React from 'react' import { withRouter } from 'react-router-dom' import PropTypes from 'prop-types' import resources from '../../lib/shared/resources' import { Spinner } from '@patternfly/react-core' import { connect } from 'react-redux' import { updateSecondaryHeader } from '../actions/common' import {getPollInterval} from '../components/common/RefreshTimeSelect' import { GRC_REFRESH_INTERVAL_COOKIE } from '../../lib/shared/constants' import { Query } from 'react-apollo' import { POLICY_STATUS } from '../../lib/client/queries' import { DangerNotification } from '../components/common/DangerNotification' import PolicyStatusView from '../components/modules/PolicyStatusView' import { setRefreshControl } from '../../lib/client/reactiveVars' import NoResource from '../components/common/NoResource' import { getTabs } from '../../lib/client/resource-helper' import { LocaleContext } from '../components/common/LocaleContext' import msgs from '../../nls/platform.properties' resources(() => { require('../../scss/policy-status-tab.scss') }) class PolicyStatusTab extends React.Component { static propTypes = { location: PropTypes.object, policyName: PropTypes.string, policyNamespace: PropTypes.string, tabs: PropTypes.array, updateSecondaryHeader: PropTypes.func, url: PropTypes.string, } constructor (props) { super(props) } static contextType = LocaleContext getBreadcrumb() { const breadcrumbItems = [] const { location } = this.props, { locale } = this.context, urlSegments = location.pathname.split('/') const hubNamespace = urlSegments.length > 4 ? urlSegments.slice(4, 5) : '' const policyName = urlSegments.length > 5 ? urlSegments.slice(5, 6) : '' breadcrumbItems.push({ label: msgs.get('tabs.hcmcompliance', locale), noLocale: true, url: `${urlSegments.slice(0, 3).join('/')}/all` }, { label: policyName, noLocale: true, url: `${urlSegments.slice(0, 3).join('/')}/all/${hubNamespace}/${policyName}` }, { label: msgs.get('table.header.status', locale), noLocale: true, url: `${urlSegments.slice(0, 3).join('/')}/all/${hubNamespace}/${policyName}/status` }) return breadcrumbItems } componentDidMount() { const { policyName } = this.props const { tabs, url, updateSecondaryHeader: localUpdateSecondaryHeader } = this.props localUpdateSecondaryHeader( policyName, getTabs(tabs, (tab, index) => index === 0 ? url : `${url}/${tab}`), this.getBreadcrumb() ) } render() { const { policyName, policyNamespace:hubNamespace, } = this.props const { locale } = this.context const pollInterval = getPollInterval(GRC_REFRESH_INTERVAL_COOKIE) return ( <Query query={POLICY_STATUS} variables={{policyName, hubNamespace}} pollInterval={pollInterval} notifyOnNetworkStatusChange > {(result) => { const {data={}, loading, startPolling, stopPolling, refetch} = result const { status } = data if (!loading) { this.timestamp = new Date().toString() } setRefreshControl(loading, this.timestamp, startPolling, stopPolling, refetch) const error = status ? null : result.error if (error) { return ( <DangerNotification error={error} /> ) } else if (loading && status === undefined) { return <Spinner className='patternfly-spinner' /> } else if (Array.isArray(status) && status.length === 0) { return <NoResource title={msgs.get('no-status.title', [msgs.get('routes.grc', locale)], locale)} svgName='EmptyPagePlanet-illus.png'> </NoResource> } else { return ( <PolicyStatusView status={status} /> ) } }} </Query> ) } } const mapDispatchToProps = (dispatch) => { return { updateSecondaryHeader: (title, tabs, breadcrumbItems, links) => dispatch(updateSecondaryHeader(title, tabs, breadcrumbItems, links)) } } export default withRouter(connect(null, mapDispatchToProps)(PolicyStatusTab))
var fs = require('fs'); var timeObj = readFile(); for (var site in timeObj) { var item = timeObj[site]; //convert to hours var hoursSpent = item.timeSpent / 60, roundedHours = Math.round(hoursSpent * 100) / 100; if (roundedHours !== 0 && roundedHours) { console.log('==========\n' + site + ': ' + roundedHours + ' hours\n==========\n\n'); } } function readFile() { try { var data = fs.readFileSync('/Users/nathanaelsmith/timekeepr/timesaver.json'); return JSON.parse(data); } catch (e) { console.log(e); process.exit(1); } }
#pragma strict public var columnNumber : int; public var rowNumber : int; private var blackPiece : GameObject; private var whitePiece : GameObject; public var hostCoordinate : GameObject; public var stateOfSpot : Occupation; function Awake () { blackPiece = this.gameObject.transform.Find("BlackPiece").gameObject; whitePiece = this.gameObject.transform.Find("WhitePiece").gameObject; } function removePiece (){ whitePiece.renderer.enabled = false; blackPiece.renderer.enabled = false; stateOfSpot = Occupation.none; } function placePiece (placeWhite : boolean) { // Debug.Log("got the message"); if (stateOfSpot == Occupation.none){ if (placeWhite){ whitePiece.renderer.enabled = true; stateOfSpot = Occupation.white; }else { blackPiece.renderer.enabled = true; stateOfSpot = Occupation.black; } var info : CoordinateDetectorInfo = new CoordinateDetectorInfo(columnNumber, rowNumber ,stateOfSpot); hostCoordinate.SendMessageUpwards("update_theBoard", info, SendMessageOptions.RequireReceiver); } }
console.log("#S prod1111"); $(function () { $('#datetimepicker5').datetimepicker({ defaultDate: "11/1/2013", disabledDates: [ moment("12/25/2013"), new Date(2013, 11 - 1, 21), "11/22/2013 00:53" ] }); }); $("#btnProduce").click(function(event) { console.log("#S clclcl: ", $("#factoriesDDL").val()); console.log("#S clothId: ", $("#clothesDDL").val()); var factoryId = $("#factoriesDDL").val(); var clothId = $("#clothesDDL").val(); var productAmount = $("#amount").val(); console.log("#S factoryId: ", factoryId); console.log("#S clothId: ", clothId); console.log("#S productAmount: ", productAmount); if(factoryId != "" && clothId != "" && productAmount > 0) { console.log("#S success!!!!"); var productForm = {}; productForm.factoryId = factoryId; productForm.clothId = clothId; productForm.productAmount = productAmount; $.ajax({ type: "POST", contentType: "application/json", url: "/api/addProducts", data: JSON.stringify(productForm), dataType: 'json', timeout: 100000, success: function(data) { console.log("#S sucess in selectClothMOdel: ", data); resetForm(); $('.alert.alert-success').show(); setTimeout(function() { $('.alert.alert-success').hide(); }, 3000); } }); } else { var errorMessage = ""; if(factoryId == "") { errorMessage = "Please select factory name."; } else if(clothId == "") { errorMessage = "Please select cloth model."; } else if(productAmount < 1) { errorMessage = "Amount to produce must greater than zero."; } showErrorMessage(errorMessage); } }); function resetForm() { console.log("#S resetForm()"); $('#factoriesDDL').selectpicker('val', ''); $('#clothesDDL').selectpicker('val', ''); $('#price').html(0); $('#totalPrice').html(0); $("#amount").val(0); } function showErrorMessage(message) { $("#errorMessage").html(message); $(".alert.alert-danger").show(); setTimeout(function() { $(".alert.alert-danger").hide(); }, 3000); } function selectClothModel() { console.log("#S selectClothModel"); var id = $("#clothesDDL").val(); console.log("#S id: ", id); if(id == "") { $("#price").text(0); } else { $.ajax({ type: "POST", contentType: "application/json", url: "/api/getClothPrice", // data: JSON.stringify({ id: id }), data: id, dataType: 'json', timeout: 100000, success: function(data) { console.log("#S sucess in selectClothMOdel: ", data); // $("#clothPrice").val(data); $("#price").text(data); var price = data; var amount = $("#amount").val(); var total = amount * price; $("#totalPrice").text(total); } }); } } function getTotalPrice() { console.log("#S getTotalPrice()"); var amount = $("#amount").val(); var price = $("#price").text(); var total = amount * price; console.log("#S total: ", total); $("#totalPrice").text(total); }
import React from "react" import Translate from "../../components/Translate/Index" import playlist from '../../store/actions/general'; import { connect } from "react-redux" class Chat extends React.Component{ constructor(props){ super(props) this.state = { custom_url:props.custom_url, channel:props.channel, streamId:props.streamId, comments:props.comments ? props.comments : [], comment:"", showTab:"chat", finish:props.finish, banusers:props.pageInfoData.video && props.pageInfoData.video.banusers ? props.pageInfoData.video.banusers : [], banEnable:props.pageInfoData.banEnable ? props.pageInfoData.banEnable : 0, tipsData:[], tipsTip:{} } this.submitComment = this.submitComment.bind(this) this.deleteMessage = this.deleteMessage.bind(this) this.banMessage = this.banMessage.bind(this) this.changeTab = this.changeTab.bind(this) this.changeBan = this.changeBan.bind(this) this.checkTipData = this.checkTipData.bind(this) this.messagesEnd = React.createRef(); } static getDerivedStateFromProps(nextProps, prevState) { if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){ return null; } if(prevState.localUpdate){ return {...prevState,localUpdate:false} }else if (nextProps.channel != prevState.channel || nextProps.custom_url != prevState.custom_url || nextProps.streamId != prevState.streamId ) { return { streamId: nextProps.streamId, custom_url: nextProps.custom_url, channel: nextProps.channel, comments: nextProps.comments, showTab:"chat", finish:nextProps.finish, tipsData:[], banusers:nextProps.pageInfoData.video && nextProps.pageInfoData.video.banusers ? nextProps.pageInfoData.video.banusers : [], banEnable:nextProps.pageInfoData.banEnable ? nextProps.pageInfoData.banEnable : 0, tipsTip:{} } } else{ return null } } componentDidUpdate(prevProps, prevState) { if(this.props.channel != prevProps.channel || this.props.custom_url != prevProps.custom_url || this.props.streamId != prevProps.streamId ){ this.props.socket.emit('leaveRoom', {room:prevProps.channel,custom_url:prevProps.custom_url,streamId:prevProps.streamId}) this.props.socket.emit('roomJoin', {room:this.props.channel,streamId:this.props.streamId,custom_url:prevProps.custom_url}) this.scrollToBottom() } } shouldComponentUpdate(nextProps,nextState){ if(nextState.tipsData.length != this.state.tipsData || nextState.comments != this.state.comments || this.state.comment != nextState.comment || nextState.showTab != this.state.showTab || nextState.channel != this.state.channel || nextState.streamId != this.state.streamId){ return true }else{ return false } } componentWillUnmount() { //this.props.socket.disconnect(); //window.removeEventListener("beforeunload", this.onUnloadComponent); } scrollToBottom = () => { var _ = this _.messagesEnd.scrollTop = _.messagesEnd.scrollHeight; } componentDidMount(){ this.scrollToBottom() //roomJoin this.props.socket.emit('roomJoin', {streamId:this.state.streamId,room:this.state.channel,custom_url:this.state.custom_url}) this.props.socket.on('userMessage', data => { console.log(data,'user message'); if(data.ban){ let owner_id = 0 if(this.props.pageInfoData.loggedInUserDetails){ owner_id = this.props.pageInfoData.loggedInUserDetails.user_id } if(data.user_id == owner_id) this.props.openToast(this.props.t("You are banned."), "error"); return } let comments = [...this.state.comments] comments.push(data) let params = data.params ? JSON.parse(data.params) : {} let tipsData = [...this.state.tipsData] let tips = this.state.tipsTip if(params.tip){ tipsData.push(data) tips[data.chat_id] = 0 } this.setState( { localUpdate:true, comments:comments, tipsData:tipsData, tipsTip:tips },() => { this.scrollToBottom(); if(this.props.getHeight){ this.props.getHeight() } }) }); this.props.socket.on('deleteMessage', data => { let chat_id = data.chat_id const itemIndex = this.getCommentIndex(chat_id) if(itemIndex > -1){ const comments = [...this.state.comments] comments.splice(itemIndex, 1); this.setState({localUpdate:true,comments:comments}) } }); this.props.socket.on('banUserMessage', data => { let owner_id = data.user_id let banusers = [...this.state.banusers] banusers.push(data) this.setState({localUpdate:true,banusers:banusers,comments:[...this.state.comments]}) }); this.props.socket.on('unbanUserMessage', data => { let owner_id = data.user_id const itemIndex = this.getUserIndex(owner_id) if(itemIndex > -1){ const banusers = [...this.state.banusers] banusers.splice(itemIndex, 1); this.setState({localUpdate:true,banusers:banusers,comments:[...this.state.comments]}) } }); setInterval( () => this.checkTipData(), 1000 ); } checkTipData(){ if(Object.keys(this.state.tipsData).length == 0){ return; } let tipsData = [...this.state.tipsData] let tipsTip = {...this.state.tipsTip} this.state.tipsData.forEach(item => { if(tipsTip[item.chat_id] && tipsTip[item.chat_id] == 10 ){ delete tipsTip[item.chat_id] const data = [...this.state.tipsData]; const itemIndex = data.findIndex(p => p["chat_id"] == item.chat_id); if(itemIndex > -1){ tipsData.splice(itemIndex,1) } }else{ tipsTip[item.chat_id] = tipsTip[item.chat_id] + 1 } }) this.setState({localUpdate:true,tipsTip:tipsTip,tipsData:tipsData},() => { if(this.props.getHeight){ this.props.getHeight() } }); } getUserIndex(item_id){ if(this.state.banusers){ const banusers = [...this.state.banusers]; const itemIndex = banusers.findIndex(p => p["user_id"] == item_id); return itemIndex; } return -1; } submitComment = () => { if(this.state.comment){ this.postComment(); } } enterHit = (e) => { if (event.keyCode === 13) { e.preventDefault() this.postComment() return false }else{ return true } } postComment = () => { if(this.state.comment && this.props.pageInfoData.loggedInUserDetails){ let bannedUser = this.getUserIndex(this.props.pageInfoData.loggedInUserDetails.user_id); if(bannedUser > -1){ this.props.openToast(this.props.t("You are banned."), "error"); return } let data = {} data.room = this.state.channel data.streamId = this.state.streamId data.message = this.state.comment data.id = this.state.custom_url data.custom_url = this.state.custom_url data.displayname = this.props.pageInfoData.loggedInUserDetails.displayname data.user_id = this.props.pageInfoData.loggedInUserDetails.user_id data.image = this.props.pageInfoData.loggedInUserDetails.avtar this.setState({localUpdate:true,comment:""}) this.props.socket.emit('userMessage', data) } } deleteMessage = (e,chat_id) => { e.preventDefault(); let data = {} data.room = this.state.channel data.streamId = this.state.streamId data.chat_id = chat_id data.custom_url = this.state.custom_url this.props.socket.emit('deleteMessage',data) } banMessage = (e,chat_id,user) => { e.preventDefault(); let data = {} data.room = this.state.channel data.streamId = this.state.streamId data.chat_id = chat_id if(user){ const itemIndex = this.getCommentUserIndex(chat_id) if(itemIndex > -1){ const comments = [...this.state.banusers] data.user_id = comments[itemIndex].user_id data.displayname = comments[itemIndex].displayname data.username = comments[itemIndex].username data.image = comments[itemIndex].image } }else{ const itemIndex = this.getCommentIndex(chat_id) if(itemIndex > -1){ const comments = [...this.state.comments] data.user_id = comments[itemIndex].user_id data.displayname = comments[itemIndex].displayname data.username = comments[itemIndex].username data.image = comments[itemIndex].image } } data.custom_url = this.state.custom_url this.props.socket.emit('banUserMessage',data) } getCommentUserIndex(item_id){ if(this.state.comments){ const comments = [...this.state.banusers]; const itemIndex = comments.findIndex(p => p["user_id"] == item_id); return itemIndex; } return -1; } getCommentIndex(item_id){ if(this.state.comments){ const comments = [...this.state.comments]; const itemIndex = comments.findIndex(p => p["chat_id"] == item_id); return itemIndex; } return -1; } changeTab = (e) => { e.preventDefault(); this.setState({showTab:"participants"}) } changeBan = (e) => { e.preventDefault(); this.setState({showTab:"banusers"}) } getParticipantData = (e) => { let participants = [] this.state.comments.forEach(comment => { if(!participants[comment.user_id]) participants[comment.user_id] = comment }); return participants; } render(){ let mainPhoto = this.props.pageInfoData.loggedInUserDetails ? this.props.pageInfoData.loggedInUserDetails.avtar : null if (mainPhoto) { const splitVal = mainPhoto.split('/') if (splitVal[0] == "http:" || splitVal[0] == "https:") { } else { mainPhoto = this.props.pageInfoData.imageSuffix + mainPhoto } } return( <React.Fragment> <div className="ls_sdTitle"> { this.state.showTab == "chat" ? <React.Fragment> <div className="title">{Translate(this.props,'Live Chat')}</div> <div className="dropdown TitleRightDropdown"> <a className="lsdot" href="#" data-bs-toggle="dropdown"><i className="fas fa-ellipsis-v"></i></a> <ul className="dropdown-menu dropdown-menu-right edit-options"> <li> <a href="#" onClick={this.changeTab}>{Translate(this.props,'Participants')}</a> </li> { this.props.deleteAll || this.state.banEnable == 1 ? <li> <a href="#" onClick={this.changeBan}>{Translate(this.props,'Ban Users')}</a> </li> : null } </ul> </div> </React.Fragment> : this.state.showTab == "banusers" ? <div className="chat_participants_cnt"> <a href="#" onClick={(e) => {e.preventDefault();this.setState({showTab:"chat"})}}><span className="material-icons" data-icon="arrow_back"></span></a> <span>{Translate(this.props,'Ban Users')}</span> </div> : <div className="chat_participants_cnt"> <a href="#" onClick={(e) => {e.preventDefault();this.setState({showTab:"chat"})}}><span className="material-icons" data-icon="arrow_back"></span></a> <span>{Translate(this.props,'Participants')}</span> </div> } </div> { this.state.tipsData.length > 0 ? <div className="ls_sdTitle"> <div className="tip_cnt"> { this.state.tipsData.map(comment => { let commentImage = comment.image if (comment.image) { const splitVal = commentImage.split('/') if (splitVal[0] == "http:" || splitVal[0] == "https:") { } else { commentImage = this.props.pageInfoData.imageSuffix + comment.image } } let params = comment.params ? JSON.parse(comment.params) : {} return ( <div className="tip" key={comment.chat_id}> <div className="content animation"> <img className="userImg" src={commentImage} /> <span>{params.amount}</span> </div> </div> ) }) } </div> </div> : null } <div className="chatList custScrollBar" ref={(ref) => this.messagesEnd = ref}> { this.state.showTab == "chat" ? <div> { this.state.comments.map(comment => { let commentImage = comment.image if (comment.image) { const splitVal = commentImage.split('/') if (splitVal[0] == "http:" || splitVal[0] == "https:") { } else { commentImage = this.props.pageInfoData.imageSuffix + comment.image } } let params = comment.params ? JSON.parse(comment.params) : {} return ( <div className={`chatListRow${params.tip ? " tip" :""}`} key={comment.chat_id}> <img className="userImg" src={commentImage} /> <div className="chatMessege"> <a href={this.props.pageInfoData.siteURL+"/"+comment.username} target="_blank" className="name">{comment.displayname}</a> <span>{comment.message}</span> </div> { this.props.deleteAll || this.state.banEnable == 1 ? this.getUserIndex(comment.user_id,this.state.banusers) < 0 ? <a className="banbtn" href="#" title={this.props.t("Ban User")} onClick={(e) => this.banMessage(e,comment.chat_id)}><i className="fas fa-ban"></i></a> : <a className="unbanbtn banbtn" href="#" title={this.props.t("Unban User")} onClick={(e) => this.banMessage(e,comment.chat_id)}><i className="fas fa-ban"></i></a> : null } { this.props.deleteAll || (this.props.pageInfoData.loggedInUserDetails && (this.props.pageInfoData.loggedInUserDetails.user_id == comment.user_id || this.props.pageInfoData.loggedInUserDetails.level_id == 1)) ? <a className="deletebtn" href="#" onClick={(e) => this.deleteMessage(e,comment.chat_id)}><i className="fas fa-times"></i></a> : null } </div> ) }) } </div> : this.state.showTab == "banusers" ? this.state.banusers.map(comment => { let commentImage = comment.image if (comment.image) { const splitVal = commentImage.split('/') if (splitVal[0] == "http:" || splitVal[0] == "https:") { } else { commentImage = this.props.pageInfoData.imageSuffix + comment.image } } return ( <div className="chatListRow" key={comment.user_id}> <img className="userImg" src={commentImage} /> <div className="chatMessege"> <a href="#" onClick={(e) => e.preventDefault()} className="name">{comment.displayname}</a> </div> <a className="unbanbtn banbtn" href="#" title={this.props.t("Unban User")} onClick={(e) => this.banMessage(e,comment.user_id,1)}><i className="fas fa-ban"></i></a> </div> ) }) : this.getParticipantData().map(comment => { let commentImage = comment.image if (comment.image) { const splitVal = commentImage.split('/') if (splitVal[0] == "http:" || splitVal[0] == "https:") { } else { commentImage = this.props.pageInfoData.imageSuffix + comment.image } } return ( <div className="chatListRow" key={comment.chat_id}> <img className="userImg" src={commentImage} /> <div className="chatMessege"> <a href="#" onClick={(e) => e.preventDefault()} className="name">{comment.displayname}</a> </div> </div> ) }) } </div> <div className="Chattexttyping"> { mainPhoto && this.state.showTab == "chat" && !this.state.finish ? <React.Fragment> <div className="userName"> <img className="userImg" src={mainPhoto} /> <span className="name">{this.props.pageInfoData.loggedInUserDetails.displayname}</span> </div> <div className="chatInput clearfix"> <input className="chatbox" type="text" onKeyDown={(e) => this.enterHit(e) } placeholder={this.props.t("Say Something...")} value={this.state.comment} onChange={(e) => this.setState({localUpdate:true,comment:e.target.value})} /> <button className="chatsend float-right" onClick={this.submitComment}><i className="fas fa-paper-plane"></i></button> </div> </React.Fragment> : null } </div> </React.Fragment> ) } } const mapDispatchToProps = dispatch => { return { openToast: (message, typeMessage) => dispatch(playlist.openToast(message, typeMessage)), }; }; const mapStateToProps = state => { return { pageInfoData: state.general.pageInfoData, }; }; export default connect(mapStateToProps, mapDispatchToProps)(Chat);
import sTheme from "../../src/styledTheme"; import { NextSeo } from "next-seo"; import { makeStyles } from "@material-ui/core/styles"; import sizes from "../../src/sizes"; import { faStarOfLife, faChevronCircleRight } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import CostCalculator from "../../components/CostCalculator"; import Button from "@material-ui/core/Button"; import clsx from "clsx"; import Form from "../../components/Form"; import DentalImplantsInIstanbul from "../../components/DentalImplantsInIstanbul"; import WhyChooseIsc from "../../components/WhyChooseIsc"; import Layout from "../../components/Layout"; import HowAreWeAffordable from "../../components/HowAreWeAffordable"; const useStyles = makeStyles((theme) => ({ fontAwesomeIcon: { fontSize: "3rem", marginRight: ".5rem", color: theme.palette.third.dark, [sizes.down("lg")]: { fontSize: "2.8rem" }, [sizes.down("md")]: { fontSize: "2.5rem" } }, fontAwesomeIconCheck: { fontSize: "2.5rem", position: "relative", top: "3px", marginRight: "1rem", color: theme.palette.third.dark, [sizes.down("lg")]: { fontSize: "2.3rem" }, [sizes.down("md")]: { fontSize: "2rem" } }, regularButton: { borderRadius: "20px", fontSize: "1.5rem", backgroundColor: theme.palette.third.dark, letterSpacing: "1px", padding: "10px 25px", position: "relative", zIndex: 100, fontWeight: "bold", "&::before": { borderRadius: "inherit", content: "close-quote", backgroundImage: "linear-gradient(to right, rgba(26,59,112,1) 0%, rgba(40,85,130,1) 52%, rgba(0,164,189,1) 100%)", position: "absolute", top: 0, left: 0, opacity: 0, width: "100%", height: "100%", zIndex: -100, transition: "opacity 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms", display: "block" }, "&:hover": { // backgroundColor: theme.palette.primary.main, // background: // "linear-gradient(to right, rgba(26,59,112,1) 0%, rgba(40,85,130,1) 52%, rgba(0,164,189,1) 100%)", "&::before": { opacity: 1 }, color: theme.palette.secondary.main } }, pricesButton: { marginRight: "auto", marginLeft: "50%", transform: "translateX(-50%)", padding: "1rem 6rem" } })); const treatmentTemplate = (props) => { const classes = useStyles(); const handleChat = () => { if (typeof Tawk_API !== "undefined") { Tawk_API.maximize(); } }; const { open, handleCallbackClose, handleCallbackOpen } = props; return ( <Layout openCallback={open} handleCallbackOpen={handleCallbackOpen} handleCallbackClose={handleCallbackClose}> <NextSeo title="Pediatric Dentistry in Istanbul, Turkey - General Anesthesia and Sedation in Children - Dental Cost Calculator | Istanbul Smile Center" description="Calculate general anesthesia and sedation treatment costs with our dental cost calculator. We provide high quality and affordable pediatric dentistry treatments. Learn more about fluoride treatment and fissure sealant." openGraph={{ url: "https://www.istanbulsmilecenter.co/pediatric-dentistry", title: "Pediatric Dentistry in Istanbul, Turkey - General Anesthesia and Sedation in Children - Dental Cost Calculator | Istanbul Smile Center", description: "Calculate general anesthesia and sedation treatment costs with our dental cost calculator. We provide high quality and affordable pediatric dentistry treatments. Learn more about fluoride treatment and fissure sealant." }} /> <section className="treatment-img-section"> <div className="treatment-img-div" /> </section> <section className="treatment-section"> <div className="treatment-header"> <h1 className="treatment-header-text">Pediatric Dentistry</h1> </div> <section className="treatment-paragraph-section"> <DentalImplantsInIstanbul treatmentName="Pediatric Dentistry" /> </section> <section className="treatment-paragraph-section"> <WhyChooseIsc treatmentName="" /> </section> <section className="our-prices-section cost-calculator-section"> <div className="our-prices-header"> <h2 className="our-prices-header-text">Dental Cost Calculator</h2> <p className="our-prices-header-paragraph-text"> We even provide you a cost calculator to calculate the dental cost by yourself for your convenience. If you got your teeth checked up by a doctor and know your exact treatment needs or you need an estimated cost, feel free to use our calculator. </p> </div> <div className="cost-calculator-wrapper"> <CostCalculator /> </div> <div className="dental-treatments-buttons-div"> <Button variant="contained" color="primary" className={clsx(classes.regularButton, classes.pricesButton)} onClick={handleChat} > Chat&nbsp;Now </Button> </div> </section> <section className="treatment-paragraph-section"> <div className="treatment-paragraph-img-div-div"> <div className="treatment-paragraph-img-div treatment-paragraph-img-2" /> </div> <div className="treatment-general-text-div treatment-general-text-div-double treatment-general-text-div-double-extra "> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> Pediatric Dentistry </h2> <p className="treatment-paragraph"> Pediatric dentistry is a science that examines and provides solutions to oral and dental health problems of children from birth to the end of adolescence. As the teeth of the children start to emerge, the dental system goes through different periods until the permanent teeth emerge. Pediatric dentistry includes different applications such as; </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} Following and preventing dental disorders </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} Treatment of decay in milk (baby teeth) and permanent teeth </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} Preservation of toothless areas that will occur as a result of early tooth extraction </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> General Anesthesia and Sedation in Children </h2> <p className="treatment-paragraph"> General anesthesia and sedation in children make the treatments easier, faster and practical. With the new anesthesia techniques we use, anesthesia is a very easy process in Istanbul Smile Center. Our clinic is considered one of the best places in Pediatric Dentistry. </p> <p className="treatment-paragraph"> Sedation is different from general anesthesia. In sedation applications, children can communicate with dentists during treatment as well as answer questions. No respiratory support is required in sedations. </p> </div> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> Why Is Anesthesia Applied In Children's Dental Problems? </h2> <p className="treatment-paragraph"> Dental caries are the most common problem in the oral health of children. Dental caries may occur in children who do not brush their teeth regularly. In addition, general anesthesia can be applied if there are suitable conditions for tooth fractures or bigger problems in children. </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} If local anesthesia or sedation is not sufficient for the treatment </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} To prevent intense fear and anxiety </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} Physical or mental disability </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} Communication is not possible with the patient </p> <p className="treatment-paragraph"> <FontAwesomeIcon className={classes.fontAwesomeIconCheck} icon={faChevronCircleRight} />{" "} If baby bottle caries are seen at an early age </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> After General Anesthesia </h2> <p className="treatment-paragraph"> After general anesthesia, the parents and the patient are hosted in our clinic for a period of one to two hours. The waiting time may vary depending on the condition of the patient. After a day's rest, patient can continue their daily life. </p> </div> <div className="dental-treatments-buttons-div"> <Button variant="contained" color="primary" className={clsx(classes.regularButton, classes.pricesButton)} onClick={handleChat} > Chat&nbsp;Now </Button> </div> </div> </section> <section className="treatment-paragraph-section"> <div className="treatment-paragraph-img-div-div"> <div className="treatment-paragraph-img-div treatment-paragraph-img-3" /> </div> <div className="treatment-general-text-div treatment-general-text-div-double treatment-general-text-div-double-extra "> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> What Is Fluoride Treatment? </h2> <p className="treatment-paragraph"> The World Health Organization report states that inadequate intake of fluoride adversely affects health and leads to tooth decay. The UK National Health Service's (NHS) study of children with and without drinking water fluoride reported that children who drink fluorinated water have less than 60 percent tooth decay. </p> <p className="treatment-paragraph"> Fluoride treatment in children is the safest and cost-effective preventive application that has been developed both to protect teeth and prevent the progression of caries. It reduces tooth decay by 30-40%. </p> </div> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> How Does Fluoride Treatment Protect Teeth? </h2> <p className="treatment-paragraph"> Milk teeth complete an important part of the development before birth. Jaws continue to develop slowly over the years. In a 7-8-year-old child, the development of permanent teeth is completed. </p> <p className="treatment-paragraph"> During the development of the teeth, the fluoride taken by the child using fluorinated water is dispersed throughout the body and some of them participate in the structure of the developing teeth. Fluoride strengthens the tooth structure and increases its resistance to caries. </p> </div> <div className="dental-treatments-buttons-div"> <Button variant="contained" color="primary" className={clsx(classes.regularButton, classes.pricesButton)} onClick={handleChat} > Chat&nbsp;Now </Button> </div> </div> </section> <section className="treatment-paragraph-section"> <div className="treatment-paragraph-img-div-div"> <div className="treatment-paragraph-img-div treatment-paragraph-img-4" /> </div> <div className="treatment-general-text-div treatment-general-text-div-double treatment-general-text-div-double-extra "> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> What Is Fissure Sealant? </h2> <p className="treatment-paragraph"> No matter how much we brush our teeth, in some cases, we may not be able to prevent caries. Because toothbrushes cannot be designed to reach every point of the tooth. Fissures formed on molar teeth located at the back of our mouth cause caries. However, with the application of fissure sealant, we can prevent the formation of caries by sealing these fissures. Fissure sealing process, especially applied to molars in children, is done to prevent the accumulation of nutrients in the recesses and grooves that may cause caries formation. </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> Is It An Easy Procedure? </h2> <p className="treatment-paragraph"> It is an easy and painless procedure. The treatment duration is 3-5 minutes depending on the adaptation of the child. </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> Is Fissure Sealing a Repeated Application Like Fluoride? </h2> <p className="treatment-paragraph"> Fissure sealing is not a repeated application like fluoride. It is done once per tooth. </p> </div> <div className="treatment-general-text-side-div"> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> When Should Fissure Sealant Be Applied? </h2> <p className="treatment-paragraph"> It is necessary to consult a pediatric dentist for a fissure sealing process at the time when the molars of the child and the permanent teeth start to come out. Because new teeth can decay much faster. Therefore, it is very important to start preventive applications in the early period. </p> <h2 className="treatment-paragraph-header"> <FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> What Happens If The Fissure Sealing Is Not Done? </h2> <p className="treatment-paragraph"> If the fissure sealing is not made on time, the teeth are at risk of caries. Over time, the teeth may begin to decay from the pitted surfaces prone to caries. Depending on the depth of caries, filling, root canal treatment or tooth extraction may be required. These treatments are both higher in cost and more tedious for children. </p> </div> <div className="dental-treatments-buttons-div"> <Button variant="contained" color="primary" className={clsx(classes.regularButton, classes.pricesButton)} onClick={handleChat} > Chat&nbsp;Now </Button> </div> </div> </section> <section className="treatment-paragraph-section"> <HowAreWeAffordable /> </section> <section className="our-prices-section form-section"> <div className="our-prices-header"> <h2 className="our-prices-header-text">Get A Free Quote</h2> <p className="our-prices-header-paragraph-text"> Contacting us through live chat or WhatsApp is always the fastest way, but you may prefer sending us a good old form. Tell us your dental needs, and don't forget to attach at least the pictures of your teeth to the form. If you have an X-Ray or CT Scan, it's even better and crucial for most patients; this will help our doctors to make the right dental plan for you. It will also help us in giving you a more accurate quote for your treatment. Go ahead and fill out the form! Let's make your smile perfect! </p> </div> <div className="form-wrapper"> <Form /> </div> </section> </section> <style jsx>{` .treatment-img-section { width: 100%; } :global(.webp) .treatment-img-div { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/pediatric-dentistry-intro-img.webp")}); } :global(.no-webp) .treatment-img-div { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/pediatric-dentistry-intro-img.jpg")}); } .treatment-img-div { width: 100%; height: 70vh; background-repeat: no-repeat; background-size: cover; background-position: left 50% bottom 50%; clip-path: ellipse(100% 100% at 50% 0%); } .treatment-section { display: flex; align-items: center; flex-direction: column; padding: 2rem 1rem; } .treatment-header { display: flex; justify-content: center; flex-direction: column; align-items: center; width: 100%; text-align: center; } .treatment-process-header { width: 100%; text-align: center; margin-bottom: 1rem; } .treatment-header-text { font-family: ${sTheme.typography.serif}; color: ${sTheme.palette.primary.main}; font-size: 4rem; } .treatment-paragraph-section { width: 100%; display: flex; flex-direction: column; align-items: center; margin-top: 2rem; } .treatment-paragraph-img-div-div { width: 65%; } .treatment-paragraph-img-div { height: 300px; border-top-left-radius: 20px; border-top-right-radius: 20px; background-repeat: no-repeat; background-size: cover; background-position: left 50% bottom 80%; background-color: ${sTheme.palette.secondary.main}; } :global(.webp) .treatment-paragraph-img-2 { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/pediatric-dentistry-img.webp")}); } :global(.no-webp) .treatment-paragraph-img-2 { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/pediatric-dentistry-img.jpg")}); } .treatment-paragraph-img-2 { max-height: 750px; height: 32vmax; background-position: left 50% bottom 65%; } :global(.webp) .treatment-paragraph-img-3 { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/fluoride-treatment-img.webp")}); } :global(.no-webp) .treatment-paragraph-img-3 { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/fluoride-treatment-img.jpg")}); } .treatment-paragraph-img-3 { max-height: 750px; height: 32vmax; background-position: left 60% bottom 55%; } :global(.webp) .treatment-paragraph-img-4 { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/fissure-sealing-img.webp")}); } :global(.no-webp) .treatment-paragraph-img-4 { background-image: url(${require("../../public/treatments/pediatric-dentistry-page/fissure-sealing-img.jpg")}); } .treatment-paragraph-img-4 { max-height: 750px; height: 30vmax; background-position: left 40% bottom 65%; } .treatment-general-text-div { width: 65%; border: 0px solid ${sTheme.palette.primary.main}; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; border-top: none; padding: 3rem; background-color: ${sTheme.palette.secondary.main}; margin-top: 0; } .treatment-general-text-div-single { border-radius: 20px; } .treatment-general-text-div-double { display: flex; justify-content: space-between; flex-wrap: wrap; } .treatment-general-text-div-double-extra { align-items: center; } .treatment-general-text-div-multiple { flex-wrap: wrap; border-radius: 20px; align-items: center; } .treatment-general-text-side-div { width: 48%; } .treatment-paragraph-header { font-size: 3rem; color: ${sTheme.palette.primary.main}; font-family: ${sTheme.typography.serif}; } .treatment-paragraph { font-size: 2rem; font-weight: normal; margin-bottom: 1rem; } .treatment-paragraph-small-header { color: ${sTheme.palette.primary.main}; font-family: ${sTheme.typography.serif}; font-weight: bold; } .our-prices-section { display: flex; justify-content: center; flex-wrap: wrap; margin-top: -5px; padding-bottom: 4rem; width: 100%; } .our-prices-header { display: flex; justify-content: center; flex-direction: column; align-items: center; width: 100%; text-align: center; } .our-prices-header-text { font-family: ${sTheme.typography.serif}; color: ${sTheme.palette.primary.main}; font-size: 4rem; } .our-prices-header-paragraph-text { color: ${sTheme.palette.secondary.dark}; font-size: 2rem; width: 50%; } .cost-calculator-section { margin-top: 2rem; } .cost-calculator-wrapper { width: 70%; } @media (max-width: ${sizes.sizes.xl}) { .cost-calculator-wrapper { width: 80%; } } @media (max-width: ${sizes.sizes.lg}) { .cost-calculator-wrapper { width: 90%; } } @media (max-width: ${sizes.sizes.md}) { .cost-calculator-wrapper { width: 95%; } } .dental-treatments-buttons-div { display: flex; justify-content: flex-start; width: 100%; align-items: baseline; margin: 0 auto; margin-top: 4rem; } .form-section { margin-top: 2rem; } .form-wrapper { width: 97%; } .guarantees-div { margin: 1rem 0 2rem 0; } .guarantees-div .treatment-paragraph { font-weight: bold; color: ${sTheme.palette.primary.main}; } @media (max-width: ${sizes.sizes.xl}) { .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 70%; } .our-prices-header-paragraph-text { width: 60%; } } @media (max-width: ${sizes.sizes.lg}) { .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 80%; } .our-prices-header-paragraph-text { width: 70%; font-size: 1.8rem; } .our-prices-header-text { font-size: 3.5rem; } .treatment-header-text { font-size: 3.5rem; } .treatment-paragraph-header { font-size: 2.5rem; } .treatment-paragraph { font-size: 1.8rem; } } @media (max-width: ${sizes.sizes.md}) { .treatment-img-div { height: 50vh; } .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 90%; } .our-prices-header-paragraph-text { width: 80%; font-size: 1.6rem; } .our-prices-header-text { font-size: 3rem; } .treatment-header-text { font-size: 3rem; } .treatment-paragraph-header { font-size: 2.2rem; } .treatment-paragraph { font-size: 1.6rem; } } @media (max-width: ${sizes.sizes.mdsm}) { .treatment-paragraph-img-div-div, .treatment-general-text-div { width: 100%; } .treatment-paragraph-img-1 { height: 250px; } } @media (max-width: ${sizes.sizes.sm}) { .treatment-general-text-div { padding: 2.5rem; } } @media (max-width: ${sizes.sizes.xs}) { .treatment-img-div { height: 40vh; } .treatment-paragraph-img-1 { height: 200px; } .treatment-general-text-side-div { width: 100%; } .treatment-general-text-div-double-extra { flex-wrap: wrap; } .treatment-general-text-div { text-align: center; } } @media (max-width: ${sizes.sizes.xxs}) { .treatment-general-text-div { padding: 2rem; } } `}</style> </Layout> ); }; export default treatmentTemplate;
/* ES6 offers three keywords for identifying or naming data: const let var These differ in scope, which determines which identifiers are accessible at different points in your program. As a general rule, try to declare your identifiers with const first. If you need to reassign: change the const to a let. If you need to access the identifier outside of a block: change the let to a var. */ // var //////////////////////////////////////////////////////////////////////////////// var message = "hello"; const showMessage = function () { console.log(message); // a var in a global scope is accessible within functions. } showMessage(); // var within a function //////////////////////////////////////////////////////////////////////////////// const showLocalMessage = function () { // local message variable var message = "good morning"; // this shadows the global message var console.log( message ); } showLocalMessage(); // a var inside a block //////////////////////////////////////////////////////////////////////////////// const answer = 42; if (answer === 42) { var favoriteFood = 'sashimi'; // favoriteFood will exist/be visible outside the block } console.log( favoriteFood ); // Expect to see sashimi // a let inside a block //////////////////////////////////////////////////////////////////////////////// const password = 'swordfish'; if (password === 'swordfish') { let quote = 'The human mind has chords'; console.log( quote ); } // console.log(quote); // quote is inaccessible here. // A const follows the same rules as a let: block scope // Except you cannot reassign to it. const daysPerWeek = 7; if (daysPerWeek === 7) { const inspirationalQuote = 'Something very inspirational'; console.log( inspirationalQuote ); } // console.log( inspirationalQuote ); // inaccessible here
module.exports = function(rootProcess, settings) { let Spawn = function(callback) { process.emit('process:spawn') process.argv.shift() let processName = process.argv.shift() let processParameters = process.argv let childProcess = $.lib.spawn( processName, processParameters, settings.options ) if($.lib.browserSync.has('boilerplate')) { $.lib.browserSync.get('boilerplate').reload(['*.js']) } callback() } return Spawn }
const express = require("express"); const cors = require("cors"); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); require("dotenv").config(); // create conection const uri = process.env.DB_PATH; // mongoDB connect mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); // checking connection mongoose.connection.on("connected", () => { console.log("connected"); }); // initializing express app const app = express(); // MiddleWares app.use(cors()); app.use(bodyParser.json()); // Routes const route = require("./routes/users"); app.use("/user", route); // Start the server const port = process.env.PORT || 3200; app.listen(port, () => { console.log(`Server listening on port ${port}`); });
/* * Auto Complete Script for Ultra Video Gallery 3 * By Pengcheng Rong (rongers@hotmail.com, service@bizmodules.net) * Copyright (c) 2009 Pengcheng Rong * All rights reserved, donot use this script library out of Ultra Video Gallery. */ function getItemTitleHtml(title) { if (title.indexOf("$")>0) { return "<table width=100% border=0 cellpadding=0 cellspacing=0><tr><td class='Normal'>" + title.replace("$", "</td><td align=right class=Script>") + "</td></tr></table>" } return title; } function getItemTitlePure(title) { if (title.indexOf("$")>0) { return title.split("$")[0] } return title; }
/* * UMG Slide Script for Ultra Media Gallery 6 * By Pengcheng Rong (rongers@hotmail.com, service@bizmodules.net) * Copyright (c) 2010 Pengcheng Rong * All rights reserved, donot use this script library out of Ultra Media Gallery. */ function umgSlide(source, dest) { if (source.substring(0,1)!="#") { source = "#" + source; } source += " "; this.source = source; this.dest = dest; var _this=this; var umg_interval; var umg_playing = false; var umg_isloading = false; this.umg_instancename = "slide"; this.umg_slideTimeout = 5; this.umg_slideTimePassed = 0; this.umg_index = -1; this.umg_naviInited = false; this.umg_xofysplitter = " / "; this.umg_mouseoverbehavior = ""; this.umg_loopplay = true; //Hide the source jQuery(source).css("display", "none"); //identify source controls this.umg_freetextslide = false; this.umg_images = jQuery(source + " .image"); this.umg_titles = jQuery(source + " .title"); this.umg_descriptions = jQuery(source + " .description"); this.umg_links = jQuery(source + " .link"); this.umg_tags = jQuery(source + " .tags"); this.umg_authors = jQuery(source + " .author"); this.umg_takendates = jQuery(source + " .takendate"); this.umg_umgids = jQuery(source + " .umgid"); //identify dest controls this.umg_container = jQuery("#umg_container" + dest); this.umg_largelist = jQuery("#umg_largelist" + dest); this.umg_large = jQuery("#umg_large" + dest); this.umg_caption = jQuery("#umg_caption" + dest); this.umg_captiontext = jQuery("#umg_captiontext" + dest); this.umg_more = jQuery("#umg_more" + dest); this.umg_buttons = jQuery("#umg_buttons" + dest); this.umg_prev = jQuery("#umg_prev" + dest); this.umg_next = jQuery("#umg_next" + dest); this.umg_play = jQuery("#umg_play" + dest); this.umg_navi = jQuery("#umg_navi" + dest); this.umg_countdown = jQuery("#umg_countdown" + dest); this.umg_loading = jQuery("#umg_loading" + dest); this.umg_thumbs = jQuery("#umg_thumbs" + dest); this.umg_thumbslist = jQuery("#umg_thumbslist" + dest); this.umg_xofy = jQuery("#umg_xofy" + dest); //Show the gallery this.umg_container.css("display", "block"); /*if (this.umg_images.length > 0) { this.umg_images.click(function() { var index = this.getNodeIndex(this) / 2; this.moveTo(index); return false; }); }*/ if (this.umg_prev.length > 0) { this.umg_prev.click(function() { _this.navigateTo(_this.umg_index - 1); }); } if (this.umg_next.length > 0) { this.umg_next.click(function() { _this.navigateTo(_this.umg_index + 1); }); } if (this.umg_play.length > 0) { this.umg_play.click(function() { _this.umg_slideTimePassed = _this.umg_slideTimeout; if (_this.umg_playing) { _this.stopAutoPlay(); } else { _this.autoPlay(); } }); } if (this.umg_countdown.length > 0) { this.umg_countdown.click(function() { _this.stopAutoPlay(); }); } //definitions of functions this.play = function(params) { var umg_autoPlay = true; if (params) { if (params.autoPlay) { umg_autoPlay = params.autoPlay.toLowerCase() == "true"; } if (params.slideTimeout) { this.umg_slideTimeout = params.slideTimeout; } if (params.mouseOver) { this.umg_mouseoverbehavior = params.mouseOver.toLowerCase(); } if (params.loopPlay) { this.umg_loopplay = params.loopPlay.toLowerCase() == "loop"; } if (params.keyboardControl != "DonotUse") { jQuery(document).keydown(function(event) { if(event.keyCode ==37) //left _this.navigateTo(_this.umg_index - 1); if(event.keyCode ==39) //left _this.navigateTo(_this.umg_index + 1); }); jQuery(this.umg_container).mousewheel(function(event, delta) { if (delta > 0) _this.navigateTo(_this.umg_index - 1); else if (delta < 0) _this.navigateTo(_this.umg_index + 1); return false; }); } if (params.disabledControls) { var controls = params.disabledControls.split(","); for (var i=0;i<controls.length ;i++ ) { var control = jQuery("#umg_" + controls[i].toLowerCase() + dest); if (control.length > 0) { control.css("display", "none"); control.css("visibility", "hidden"); //alert(controls[i] + " is hidden"); } } } if (params.easing != "" && params.easing != "swing") { jQuery.easing.def = params.easing; } if (params.mode == "Freetext") { //is free text slide this.umg_freetextslide = true; } } if (this.umg_thumbs.css("display")!="none" && this.buildThumbList) { //build thumb list this.buildThumbList(); } this.moveTo(0); if (umg_autoPlay > 0) { if (this.umg_countdown.css("display")!="none") { this.umg_countdown.attr("visiblebefore","true"); this.umg_countdown.hide(); } this.autoPlay(); } else { this.stopAutoPlay(); } } /*this.getImageProperty = function(index, name) { var value = jQuery(this.umg_images[index]).attr(name); if (!value) { value = ""; } return value; }*/ this.autoPlay = function() { var source; if (!this.umg_freetextslide) source = this.umg_images; else source = this.umg_titles; if (source.length <= 1) { return; } this.umg_playing = true; if (this.umg_index == source.length-1) { this.moveTo(0); this.umg_interval = window.setInterval(this.umg_instancename + dest + ".onInterval()", 1000); } else { this.umg_interval = window.setInterval(this.umg_instancename + dest + ".onInterval()", 1000); } if (this.umg_play) this.umg_play.addClass("active"); } this.stopAutoPlay = function() { this.umg_playing = false; window.clearInterval(this.umg_interval); if (this.umg_play) this.umg_play.removeClass("active"); if (this.umg_countdown.css("display")!="none") { this.umg_countdown.hide(); this.umg_countdown.attr("visiblebefore","true"); //Hide it, but add a remark that it was visible before } } this.onInterval = function() { if (this.umg_isloading) return; this.umg_slideTimePassed += 1; if (this.umg_slideTimePassed >= this.umg_slideTimeout) { this.umg_slideTimePassed = 0; var source; if (!this.umg_freetextslide) source = this.umg_images; else source = this.umg_titles; if (this.umg_index + 1 >= source.length && !this.umg_loopplay) { this.stopAutoPlay(); } else { this.moveTo(this.umg_index + 1); } } //update the count down information if it's visible, or was visible if (this.umg_countdown.css("display")!="none" || this.umg_countdown.attr("visiblebefore") == "true") { if (this.umg_slideTimePassed == 0) { this.umg_countdown.hide(); this.umg_countdown.attr("visiblebefore","true"); } else { this.umg_countdown.show(); this.umg_countdown.html(this.umg_slideTimeout-this.umg_slideTimePassed); } } } /*var getNodeIndex = function(node) { var elem = node; var k = 0; while(elem.previousSibling){ k++; elem = elem.previousSibling; } return k; }*/ this.getResizedResolution = function(obj) { var xRatio = obj.width / obj.maxWidth; var yRatio = obj.height / obj.maxHeight; var ratio = Math.max(xRatio, yRatio); var newWidth = Math.round(obj.width / ratio); var newHeight = Math.round(obj.height / ratio); obj.newWidth = newWidth; obj.newHeight = newHeight; return; } this.getPrioritySize = function(obj) { var size = new Object(); size.width = obj.width(); size.height = obj.height(); size.priorityhdir = obj.css("priority-hdir"); size.priorityvdir = obj.css("priority-vdir"); var prioritywidth = obj.css("priority-width"); var priorityheight = obj.css("priority-height"); if (prioritywidth) { if (prioritywidth.indexOf("px") > 0) { prioritywidth = prioritywidth.substring(0,prioritywidth.indexOf("px")); } size.prioritywidth = prioritywidth * 1; } else { size.prioritywidth = size.width; } if (priorityheight) { if (priorityheight.indexOf("px") > 0) { priorityheight = priorityheight.substring(0,priorityheight.indexOf("px")); } size.priorityheight = priorityheight * 1; } else { size.priorityheight = size.height; } return size; } this.getSuggestedPosition = function(objImgTag) { var position = new Object(); position.suggestedX = 0; position.suggestedY = 0; var prioritysize = this.getPrioritySize(this.umg_large); if (objImgTag.width() <= prioritysize.width) { if (prioritysize.priorityhdir == "right") { if (objImgTag.width() <= prioritysize.prioritywidth) { position.suggestedX = (prioritysize.prioritywidth-objImgTag.width()) / 2 + prioritysize.width - prioritysize.prioritywidth; } else { position.suggestedX = prioritysize.width - objImgTag.width(); } } else { if (objImgTag.width() <= prioritysize.prioritywidth) { position.suggestedX = (prioritysize.prioritywidth-objImgTag.width()) / 2; //alert("gallery width="+prioritysize.width+", image width=" + objImgTag.width() + ", prioritywidth=" + prioritysize.prioritywidth + ", suggestedX=" + position.suggestedX); } } } //else keep margin-left to zero; if (objImgTag.height() <= prioritysize.height) { if (prioritysize.priorityvdir == "bottom") { if (objImgTag.height() <= prioritysize.priorityheight) { position.suggestedY = (prioritysize.priorityheight-objImgTag.height()) / 2 + prioritysize.height - prioritysize.priorityheight; } else { position.suggestedY = prioritysize.height - objImgTag.height(); } } else { if (objImgTag.height() <= prioritysize.priorityheight) { position.suggestedY = (prioritysize.priorityheight-objImgTag.height()) / 2; } } } return position; } this.navigateTo = function(index) { if (this.umg_playing) this.stopAutoPlay(); if (index == this.umg_index) { return; } this.moveTo(index); } this.moveTo = function(index) { var source; if (!this.umg_freetextslide) source = this.umg_images; else source = this.umg_titles; if (index >= source.length) index = 0; else if (index < 0) index = source.length - 1; this.umg_slideTimePassed = 0; var item = jQuery(source[index]); if(item.length < 1) { alert("No slides in gallery " + this.dest); this.stopAutoPlay(); return; } var previousContainer = this.umg_large.find("#img"+this.umg_index); var container = this.umg_large.find("#img"+index); if (this.umg_freetextslide) { if (container.length == 0) { this.umg_large.append("<div class='freetext' id='img" + index + "' style='display:none' index='"+index+"' />"); container = this.umg_large.find("#img" + index); container.html(jQuery(this.umg_descriptions[index]).html()); //previousContainer.css("display","none"); //container.css("display","block"); _this.umg_transition_freetext_align(container); _this.umg_transition_freetext_activate(container, previousContainer); } else { _this.umg_transition_freetext_activate(container, previousContainer); } } else { var url = item.attr("largeurl"); if (!url) { url = item.attr("src"); } if (container.length == 0) { this.umg_large.append("<img class='image' id='img" + index + "' style='display:none' index='"+index+"' />"); container = this.umg_large.find("#img" + index); var img = new Image(); // call this function after it's loaded img.onload = function() { var maxWidth = _this.umg_large.width(); var maxHeight = _this.umg_large.height(); // make wrapper fully visible //umg_large.fadeTo("fast", 1); // change the image if (this.width > maxWidth || this.height > maxHeight ) { var size ={"width":this.width,"maxWidth":maxWidth,"height":this.height,"maxHeight":maxHeight}; _this.getResizedResolution(size); container.attr("width", size.newWidth); container.attr("height", size.newHeight); } else { container.attr("width", this.width); container.attr("height", this.height); } if (_this.umg_loading) { _this.umg_loading.removeClass("active"); } _this.umg_isloading = false; _this.umg_transition_image_align(this, container); _this.umg_transition_image_activate(container, previousContainer); }; if (this.umg_loading) { this.umg_loading.addClass("active"); } this.umg_isloading = true; img.src = url; } else { this.umg_transition_image_activate(container, previousContainer); } // begin loading the image from flickr if (this.umg_captiontext) { this.umg_transition_caption_do(index); } var link= jQuery(this.umg_links[index]).attr("href") if (this.umg_more && link) { this.umg_more.attr("href", link); this.umg_more.show(); } else { this.umg_more.hide(); } } if (typeof(UPG_onPhotoLoad) != "undefined") { var umgid = jQuery(this.umg_umgids[index]).html(); UPG_onPhotoLoad(umgid); } if (typeof(this.onMoveTo) != "undefined") { this.onMoveTo(index); } this.umg_index = index; if (this.umg_navi) { var navi = ""; for (var i=0;i<source.length;i++) { var itemHtml = ""; if (i==index) { itemHtml = "<a href='javascript:void(0);' class='active'></a>"; } else { itemHtml = "<a href='javascript:void(0);' onclick='slide" + dest + ".navigateTo("+i+")'></a>"; } navi += itemHtml; } this.umg_navi.html( navi); if (!this.umg_naviInited) { this.umg_naviInited = true; var lastA = this.umg_navi.find("a"); var lastAObj = jQuery(lastA[lastA.length-1]); var lastX = lastAObj.position().left + lastAObj.width(); this.umg_navi.css("width", lastX+6);//because navi.margin=6; } } if (this.umg_xofy.length > 0) { this.umg_xofy.html((index+1) + this.umg_xofysplitter + source.length); } /*if (umg_prev) index>0?umg_prev.css("visibility","visible"):umg_prev.css("visibility","hidden"); if (umg_next) index<umg_images.length-1?umg_next.css("visibility","visible"):umg_next.css("visibility","hidden");*/ }; this.updateCaption = function(index) { if (!this.umg_captiontext.originalWidth) { this.umg_captiontext.originalWidth = this.umg_captiontext.width(); var originalHeight = this.umg_captiontext.height(); if (originalHeight <= 0) { originalHeight = this.umg_caption.height(); } this.umg_captiontext.originalHeight = originalHeight; } else { this.umg_captiontext.css("width", this.umg_captiontext.originalWidth); this.umg_captiontext.css("height", this.umg_captiontext.originalHeight); } this.umg_captiontext.find("#umg_captiontitle" + this.dest).html(jQuery(this.umg_titles[index]).html()); this.umg_captiontext.find("#umg_captiondescription" + this.dest).html(jQuery(this.umg_descriptions[index]).html()); var umg_captionauthor = this.umg_captiontext.find("#umg_captionauthor" + this.dest); if (umg_captionauthor.length > 0) { umg_captionauthor.html(jQuery(this.umg_authors[index]).html()); } var umg_captiontakendate = this.umg_captiontext.find("#umg_captiontakendate" + this.dest); if (umg_captiontakendate.length > 0) { umg_captiontakendate.html(jQuery(this.umg_takendates[index]).html()); } var umg_captiontags = this.umg_captiontext.find("#umg_captiontags" + this.dest); if (umg_captiontags.length > 0) { umg_captiontags.html(jQuery(this.umg_tags[index]).html()); } } //end of function definitions if (typeof(this.umg_init) != "undefined") { this.umg_init(sender); } //return this; }
import React from 'react'; import {Link} from 'react-router'; import HomeStore from '../stores/HomeStore'; import HomeActions from '../actions/HomeActions'; import {first, without, findWhere} from 'underscore'; class Home extends React.Component { constructor(props) { super(props); this.state = HomeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HomeStore.listen(this.onChange); HomeActions.getTwoCharacters(); } componentWillUnmount() { HomeStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } handleClick(character) { var winner = character.characterId; var loser = first(without(this.state.characters, findWhere(this.state.characters, { characterId: winner })) ).characterId; HomeActions.vote(winner, loser); } render() { /* Notice we are not just binding this.handleClick to a click event, but instead we do {this.handleClick.bind(this, character). Simply passing an event object is not enough, it will not give us any useful information, unlike text field, checkbox or radio button group elements. From the MSDN Documentation: function.bind(thisArg[, arg1[, arg2[, ...]]]) thisArg (Required) - An object to which the this keyword can refer inside the new function. arg1, arg2, … (Optional) - A list of arguments to be passed to the new function. To put it simply, we need to pass this context because we are referencing this.state inside handleClick method, we are passing a custom object containing character information that was clicked instead of the default event object. Inside handleClick method, the character parameter is our winning character, because that’s the character that was clicked on. Since we only have two characters it is not that hard to figure out the losing character. We then pass both winner and loser Character IDs to the HomeActions.vote action. */ var characterNodes = this.state.characters.map((character, index) => { return ( <div key={character.characterId} className={index === 0 ? 'col-xs-6 col-sm-6 col-md-5 col-md-offset-1' : 'col-xs-6 col-sm-6 col-md-5'}> <div className='thumbnail fadeInUp animated'> <img onClick={this.handleClick.bind(this, character)} src={'http://image.eveonline.com/Character/' + character.characterId + '_512.jpg'} /> <div className='caption text-center'> <ul className='list-inline'> <li><strong>Race:</strong>{character.race}</li> <li><strong>Bloodline:</strong>{character.bloodline}</li> </ul> <h4> <Link to={'/characters/' + character.characterId}><strong>{character.name}</strong></Link> </h4> </div> </div> </div> ); }); return ( <div className='container'> <h3 className='text-center'>Click on the portrait. Select your favorite.</h3> <div classsName='row'> {characterNodes} </div> </div> ); } } export default Home;
const express = require('express'); const router = express.Router(); const User = require('../models/user'); const catchAsync = require('../utils/catchAsync'); const passport = require('passport'); router.get('/register' , (req, res) => { res.render('users/register'); }); router.post('/register', catchAsync(async(req, res , next) => { try{ const {email , username , password} = req.body; const user = new User({email, username}); const newUser = await User.register(user, password); req.login(newUser, err => { if(err){ return next(err); } else{ req.flash('success', `Welcome to FindYourProperty!! ${username}`); res.redirect('/properties'); } }); }catch(e){ req.flash('error', e.message); res.redirect('/register'); } //console.log(newUser); })); router.get('/login', (req ,res) => { res.render('users/login'); }); router.post('/login', passport.authenticate('local',{failureFlash:true , failureRedirect: '/login'}),(req ,res) => { req.flash('success',`Welcome back!! ${req.body.username}`); const redirectUrl = req.session.returnTo || '/properties'; delete req.session.returnTo; res.redirect(redirectUrl); }); router.get('/logout', (req ,res )=>{ // const username = req.body.username; //console.log(req.body) req.flash('success', `Goodbye!`) req.logout(); res.redirect('/properties') }) module.exports = router;
import "./invalid_graph_modal.html"; Template.invalid_graph_modal.events({ "click #continueEditingBtn": function () { $("#invalidGraphModal").modal("hide"); } });
SinglePayView = React.createClass({ mixins: [ReactMeteorData], getMeteorData: function() { return { thisPay: PayStubs.findOne({_id: this.props.thisID}), }; }, enterEditMode: function() { Meteor.call("setModeAndEditID", "reviewPay", this.props.thisID); }, render: function() { var pay = this.data.thisPay; return <li key={pay._id}>{pay.sent? "approved and sent":"awaiting approval"}, {pay.tutor.username}, {pay.cycle.name}, <button className="btn btn-default btn-raised" onClick={this.enterEditMode}>Preview</button> </li>; } });
module.exports = `//#version 300 es //https://www.desultoryquest.com/blog/drawing-anti-aliased-circular-points-using-opengl-slash-webgl/ //#extension GL_OES_standard_derivatives : enable // https://www.desultoryquest.com/blog/drawing-anti-aliased-circular-points-using-opengl-slash-webgl/ // https://www.desultoryquest.com/blog/downloads/code/points.js precision mediump float; uniform sampler2D iChannel0; varying vec4 vVertexGlowColor; void main(void) { float r = 0.0, delta = 0.0, alpha = 0.3; vec2 cxy = 2.0 * gl_PointCoord - 1.0; r = dot(cxy, cxy); if (r > 1.0) { discard; } // delta = fwidth(r); // alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r); // @todo: gaussian blur // vec3 iResolution = vec3(50, 50, 0); // vec2 resolution = iResolution.xy; // vec2 uv = vec2(gl_FragCoord.xy / iResolution.xy); // vec2 direction = vec2(0.0); // vec4 color = vec4(vVertexGlowColor); // vec2 off1 = vec2(1.3333333333333333) * direction; // color += texture2D(iChannel0, uv) * 0.29411764705882354; // color += texture2D(iChannel0, uv + (off1 / resolution)) * 0.35294117647058826; // color += texture2D(iChannel0, uv - (off1 / resolution)) * 0.35294117647058826; // gl_FragColor = color * alpha; gl_FragColor = vVertexGlowColor * alpha; }`
let description = document.querySelectorAll('.keys-main__description'); [].forEach.call(description, function(el) { el.querySelector('.keys-main__description-show').addEventListener('click',function () { closeTab(el) }) }); function closeTab(el) { if (el.classList.contains('close')){ el.classList.toggle('close'); let showCase = el.querySelectorAll('.keys-main__description-showCase'); [].forEach.call(showCase, function(elem) { elem.style.maxHeight = '0'; elem.style.paddingBottom = '0'; }); let closeElem = el.querySelectorAll('.keys-close-elem'); [].forEach.call(closeElem, function(elem) { elem.style.opacity = '0'; }); if (window.innerWidth > 1020){ for (let i = 1;i < el.querySelectorAll('.keys-main__description-product').length;i++){ el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-key p')[0].style.opacity = '0'; el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-data p')[0].style.opacity = '0'; el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-active p')[0].style.opacity = '0'; } let descriptionProduct = el.querySelectorAll('.keys-main__description-product'); [].forEach.call(descriptionProduct, function(elem) { elem.style.marginBottom = '0px'; }); } el.querySelector('.keys-main__description-show span').innerHTML = 'подробнее о заказе'; el.querySelector('.keys-main__description-show img').style.transform = 'rotate(180deg)'; } else { el.classList.toggle('close'); let closeElem = el.querySelectorAll('.keys-close-elem'); [].forEach.call(closeElem, function(elem) { elem.style.opacity = '1'; }); if (window.innerWidth > 1020){ let descriptionShowCase = el.querySelectorAll('.keys-main__description-showCase'); [].forEach.call(descriptionShowCase, function(elem) { elem.style.maxHeight = 162 + ((elem.querySelectorAll('.keys-main__description-showCase-row-wrapper').length - 1) * 80) + 'px'; }); for (let i = 1;i < el.querySelectorAll('.keys-main__description-product').length;i++){ el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-key p')[0].style.opacity = '1'; el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-data p')[0].style.opacity = '1'; el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-active p')[0].style.opacity = '1'; } } else { let descriptionShowCase = el.querySelectorAll('.keys-main__description-showCase'); [].forEach.call(descriptionShowCase, function(elem) { elem.style.maxHeight = 192 + ((elem.querySelectorAll('.keys-main__description-showCase-row-wrapper').length - 1) * 110) + 'px'; }); for (let i = 1;i < el.querySelectorAll('.keys-main__description-product').length;i++){ el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-key p')[0].style.opacity = '1'; el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-data p')[0].style.opacity = '1'; el.querySelectorAll('.keys-main__description-product')[i].querySelectorAll('.keys-main__description-product-active p')[0].style.opacity = '1'; } } el.querySelector('.keys-main__description-show span').innerHTML = 'свернуть заказ'; el.querySelector('.keys-main__description-show img').style.transform = 'rotate(0deg)'; } }
/* * 坦克属性类 */ function tank_property(par){ this.name = '';//名字 this.hp = 0;//生命值 this.atk = 0;//攻击力 this.def = 0;//防御力 this.sp = 0;//移动速度 this.sd = 0;//攻击距离 this.dv = 0;//视野距离 this.tag = 0;//炮台角度 this.x = 0;//x轴坐标 this.y = 0;//y轴坐标 this.z = 0;//z轴坐标 this.face = 0;//坦克朝向 this.type = 0;//坦克类型 this.model = 0;//坦克模型 for(var i in par){ this[i] = par[i]; } }
const db = require('../db'); const DaoManager = require('./dao-manager'); module.exports = { connect: () => { return new Promise(async (resolve, reject) => { try { const dbConnection = await db.getConnection(); resolve(new DaoManager(dbConnection)); } catch (err) { reject(err); } }); } };
import React, {Component} from 'react'; import { Platform, StyleSheet, Text, View, Modal, Alert, Dimensions, Image, ScrollView, TouchableWithoutFeedback } from 'react-native'; var {width,height} = Dimensions.get('window'); import Header from "../CommonModules/Header"; import px2dp from "../tools/px2dp"; import {feach_request, Toast} from "../tools/public"; import Loading from '../CommonModules/Loading'; import constant from '../tools/constant'; export default class MsgDetail extends Component{ static navigationOptions = { header: null }; constructor(props){ super(props); this.state = { detailData:{}, loading:true } } componentDidMount(){ const mId = this.props.navigation.state.params.mId; feach_request(`/message/detail?mId=${mId}`,'GET') .then((data)=>{ console.log('detail',data) if(data.code==0){ this.setState({ detailData:data.data, loading:false }) } }) .catch((err)=>{ console.log(err); Toast('网络错误~'); }) } hasRead(){ const mId = this.props.navigation.state.params.mId; feach_request(`/message/msgread?mId=${mId}`,'GET') .then((data)=>{ console.log('detail',data) if(data.code==0){ Toast('提交成功~'); } }) .catch((err)=>{ console.log(err); Toast('网络错误~'); }) } //处理事务 manageOa(){ feach_request(`/activity/get?act_id=${this.state.detailData.oaId}`,'GET') .then((data)=>{ if(data.code==0){ if(data.data.program=='EventProcess'){ this.props.navigation.navigate('EventProcess',{msg:data.data}) }else if(rowData.program=='EventProcessResult'){ this.props.navigation.navigate('EventProcessResult',{msg:rowData}) }{ alert('暂无对应模版') } } }) .catch((err)=>{ console.log(err); Toast('网络错误~'); }) } render(){ const { navigate } = this.props.navigation; return( <View style={{flex:1,backgroundColor: '#fcfcfc'}}> <Header title={'消息详情'} navigate={this.props.navigation}/> <Loading loading={this.state.loading}/> <ScrollView> { this.state.detailData.image?( <View style={{padding: px2dp(15)}}> <Image style={{width: 200,height:200}} source={{uri: `${constant.url}${this.state.detailData.image}`}} /> </View> ):(null) } <View> <View style={[styles.flex_row,styles.msg_wrap]}> <Text style={styles.msg_title}>消息主题:</Text> <Text style={styles.msg_info}>{this.state.detailData.subject}</Text> </View> <View style={[styles.flex_row,styles.msg_wrap]}> <Text style={styles.msg_title}>消息类型:</Text> <Text style={styles.msg_info}>{this.state.detailData.type}</Text> </View> <View style={[styles.msg_wrap]}> <Text style={styles.msg_title}>消息详情:</Text> {/*<Text style={styles.msg_info}>{this.state.detailData.detail}</Text>*/} <Text style={[styles.msg_info,styles.msg_detail]}>{this.state.detailData.detail}</Text> </View> <View style={[styles.flex_row,styles.msg_wrap]}> <Text style={styles.msg_title}>预警时间:</Text> <Text style={styles.msg_info}>{this.state.detailData.datetime}</Text> </View> </View> </ScrollView> { this.state.detailData.oaId?( <TouchableWithoutFeedback onPress={()=>{this.manageOa()}}> <View style={{alignItems: 'center',marginBottom:px2dp(30)}}> <View style={styles.affirm_btn}> <Text style={styles.affirm_btn_font}>处理事物</Text> </View> </View> </TouchableWithoutFeedback> ):( <TouchableWithoutFeedback onPress={()=>{this.hasRead()}}> <View style={{alignItems: 'center',marginBottom:px2dp(30)}}> <View style={styles.affirm_btn}> <Text style={styles.affirm_btn_font}>我知道了</Text> </View> </View> </TouchableWithoutFeedback> ) } </View> ) } } const styles = StyleSheet.create({ container:{ flex:1, backgroundColor: '#fcfcfc' }, flex:{ flex:1 }, flex_row:{ flexDirection:'row', alignItems: 'center' }, msg_wrap:{ padding:px2dp(15) }, msg_title:{ flex:1, fontSize:px2dp(17), color:'#333' }, msg_info:{ flex:3, fontSize: px2dp(15), color:'#666', lineHeight: px2dp(25) }, affirm_btn:{ width:px2dp(300), height:px2dp(45), backgroundColor: '#66b3ff', borderRadius:px2dp(10) }, affirm_btn_font:{ lineHeight:px2dp(45), textAlign: 'center', fontSize:px2dp(18), color: '#fff', letterSpacing: px2dp(2) }, msg_detail:{ marginTop:px2dp(5), letterSpacing: px2dp(1) } });
import { connect } from 'react-redux'; import { hashHistory } from 'react-router'; import { fetchBookmarks, fetchBookmarksSuccess, fetchBookmarksFailure } from '../actions/bookmarks'; import { deleteBookmark, deleteBookmarkSuccess, deleteBookmarkFailure } from '../actions/bookmarks'; import { updateBookmark, updateBookmarkSuccess, updateBookmarkFailure } from '../actions/bookmarks'; import { logoutUser } from '../actions/auth'; import { loadState } from '../helpers/localStorage'; import Home from '../components/Home'; const mapStateToProps = (state) => { return { bookmarkList: state.bookmarks.bookmarks } } const mapDispatchToProps = (dispatch, props) => { return { fetchBookmarks: () => { const token = loadState().session.token; if (!loadState()) return; dispatch(fetchBookmarks(token)).then((response) => { if (!response.error) { dispatch(fetchBookmarksSuccess(response.payload.data)) } else { dispatch(fetchBookmarksFailure(response.error)) if (response.payload.response.status === 401) { dispatch(logoutUser()) if (hashHistory.getCurrentLocation().pathname !== '/home') { hashHistory.push('/home') } } } }) }, deleteBookmark: (event, bookmarkId) => { event.preventDefault(); const token = loadState().session.token; if (!loadState()) return; dispatch(deleteBookmark(bookmarkId, token)).then((response) => { if (!response.error) { dispatch(deleteBookmarkSuccess(response.payload.data)) } else { dispatch(deleteBookmarkFailure(response.error)) if (response.payload.response && response.payload.response.status === 401) { dispatch(logoutUser()) if (hashHistory.getCurrentLocation().pathname !== '/home') { hashHistory.push('/home') } } } }) }, updateBookmark: (event, bookmarkId, type) => { event.preventDefault(); const token = loadState().session.token; if (!loadState()) return; dispatch(updateBookmark(bookmarkId, type, token)).then((response) => { if (!response.error) { dispatch(updateBookmarkSuccess(response.payload.data)) } else { dispatch(updateBookmarkFailure(response.error)) if (response.payload.response.status === 401) { dispatch(logoutUser()) if (hashHistory.getCurrentLocation().pathname !== '/home') { hashHistory.push('/home') } } } }) } } } export default connect(mapStateToProps, mapDispatchToProps)(Home);
/** * Created by smoseley on 12/14/2015. */ (function(){ angular .module('home',[]); })();
import * as React from 'react'; import { styled, alpha } from '@mui/material/styles'; import AppBar from '@mui/material/AppBar'; import Box from '@mui/material/Box'; import Toolbar from '@mui/material/Toolbar'; import Typography from '@mui/material/Typography'; import InputBase from '@mui/material/InputBase'; import SearchIcon from '@mui/icons-material/Search'; import IconButton from '@mui/material/IconButton'; import { AddBox } from '@mui/icons-material'; import { FormControl, InputLabel, Select, MenuItem, TextField } from '@mui/material'; const Search = styled('div')(({ theme }) => ({ position: 'relative', borderRadius: theme.shape.borderRadius, backgroundColor: alpha(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.25), }, marginLeft: 0, width: '100%', [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(1), width: 'auto', }, })); const SearchIconWrapper = styled('div')(({ theme }) => ({ padding: theme.spacing(0, 2), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', })); const StyledInputBase = styled(InputBase)(({ theme }) => ({ color: 'inherit', '& .MuiInputBase-input': { padding: theme.spacing(1, 1, 1, 0), // vertical padding + font size from searchIcon paddingLeft: `calc(1em + ${theme.spacing(4)})`, transition: theme.transitions.create('width'), [theme.breakpoints.up('sm')]: { width: '22ch', }, }, })); export default function SearchAppBar({search, setSearch, playerCount, setPlayerCount, minLevel, maxLevel, setMinLevel, setMaxLevel, playersLevel, setPlayersLevels, playerName, setPlayerName, setList, list}) { return ( <Box sx={{ flexGrow: 1 }}> <AppBar position="static" className="appbar"> <Toolbar> <Typography className="title" variant="h61" noWrap component="div" sx={{ flexGrow: 1, display: { sm: 'block' } }} > PF2e Beast </Typography> <TextField className="playerinput" value={playerName} onChange={(event) => {setPlayerName(event.target.value)}} style={{marginLeft:12, textAlign:'center'}} id="input-with-sx" label="Player name" variant="standard" /> <IconButton onClick={() => { if(playerName) { var push = true; list.forEach((item) => { if(item.id === "player-"+playerName) push = false; }) if(push) { setList([...list, {hp:0, initiative:0, ac:0, id:"player-"+playerName, name: playerName, level: 1, count:1, type:"player"}]) setPlayerName(""); setPlayerCount(playerCount +1) } } }} color="primary" component="label"> <AddBox /> </IconButton> <FormControl sx={{ m: 1, minWidth: 120 }}> <InputLabel id="demo-simple-select-autowidth-label">Players Lv.</InputLabel> <Select labelId="demo-simple-select-autowidth-label" id="demo-simple-select-autowidth" autoWidth label="Players Lv." value={playersLevel} onChange={(event) => {setPlayersLevels(event.target.value)}} > <MenuItem value={1}>1</MenuItem> <MenuItem value={2}>2</MenuItem> <MenuItem value={3}>3</MenuItem> <MenuItem value={4}>4</MenuItem> <MenuItem value={5}>5</MenuItem> <MenuItem value={6}>6</MenuItem> <MenuItem value={7}>7</MenuItem> <MenuItem value={8}>8</MenuItem> <MenuItem value={9}>9</MenuItem> <MenuItem value={10}>10</MenuItem> <MenuItem value={11}>11</MenuItem> <MenuItem value={12}>12</MenuItem> <MenuItem value={13}>13</MenuItem> <MenuItem value={14}>14</MenuItem> <MenuItem value={15}>15</MenuItem> <MenuItem value={16}>16</MenuItem> <MenuItem value={17}>17</MenuItem> <MenuItem value={18}>18</MenuItem> <MenuItem value={19}>19</MenuItem> <MenuItem value={20}>20</MenuItem> </Select> </FormControl> <FormControl sx={{ m: 1, minWidth: 100 }}> <InputLabel id="demo-simple-select-autowidth-label">Min Lv.</InputLabel> <Select labelId="demo-simple-select-autowidth-label" id="demo-simple-select-autowidth" autoWidth label="Min Lv." value={minLevel} onChange={(event) => {setMinLevel(event.target.value)}} > <MenuItem value=""> <em>None</em> </MenuItem> <MenuItem value={-1}>-1</MenuItem> <MenuItem value={0}>0</MenuItem> <MenuItem value={1}>1</MenuItem> <MenuItem value={2}>2</MenuItem> <MenuItem value={3}>3</MenuItem> <MenuItem value={4}>4</MenuItem> <MenuItem value={5}>5</MenuItem> <MenuItem value={6}>6</MenuItem> <MenuItem value={7}>7</MenuItem> <MenuItem value={8}>8</MenuItem> <MenuItem value={9}>9</MenuItem> <MenuItem value={10}>10</MenuItem> <MenuItem value={11}>11</MenuItem> <MenuItem value={12}>12</MenuItem> <MenuItem value={13}>13</MenuItem> <MenuItem value={14}>14</MenuItem> <MenuItem value={15}>15</MenuItem> <MenuItem value={16}>16</MenuItem> <MenuItem value={17}>17</MenuItem> <MenuItem value={18}>18</MenuItem> <MenuItem value={19}>19</MenuItem> <MenuItem value={20}>20</MenuItem> <MenuItem value={21}>21</MenuItem> <MenuItem value={22}>22</MenuItem> <MenuItem value={23}>23</MenuItem> <MenuItem value={24}>24</MenuItem> <MenuItem value={25}>25</MenuItem> </Select> </FormControl> <FormControl sx={{ m: 1, minWidth: 100 }}> <InputLabel id="demo-simple-select-autowidth-label">Max Lv.</InputLabel> <Select labelId="demo-simple-select-autowidth-label" id="demo-simple-select-autowidth" autoWidth label="Min Lv." value={maxLevel} onChange={(event) => {setMaxLevel(event.target.value)}} > <MenuItem value=""> <em>None</em> </MenuItem> <MenuItem value={-1}>-1</MenuItem> <MenuItem value={0}>0</MenuItem> <MenuItem value={1}>1</MenuItem> <MenuItem value={2}>2</MenuItem> <MenuItem value={3}>3</MenuItem> <MenuItem value={4}>4</MenuItem> <MenuItem value={5}>5</MenuItem> <MenuItem value={6}>6</MenuItem> <MenuItem value={7}>7</MenuItem> <MenuItem value={8}>8</MenuItem> <MenuItem value={9}>9</MenuItem> <MenuItem value={10}>10</MenuItem> <MenuItem value={11}>11</MenuItem> <MenuItem value={12}>12</MenuItem> <MenuItem value={13}>13</MenuItem> <MenuItem value={14}>14</MenuItem> <MenuItem value={15}>15</MenuItem> <MenuItem value={16}>16</MenuItem> <MenuItem value={17}>17</MenuItem> <MenuItem value={18}>18</MenuItem> <MenuItem value={19}>19</MenuItem> <MenuItem value={20}>20</MenuItem> <MenuItem value={21}>21</MenuItem> <MenuItem value={22}>22</MenuItem> <MenuItem value={23}>23</MenuItem> <MenuItem value={24}>24</MenuItem> <MenuItem value={25}>25</MenuItem> </Select> </FormControl> <Search> <SearchIconWrapper> <SearchIcon /> </SearchIconWrapper> <StyledInputBase className="searchbar" placeholder="Search by name, traits or family..." inputProps={{ 'aria-label': 'search' }} value={search} onChange={(event) => {setSearch(event.target.value)}} /> </Search> </Toolbar> </AppBar> </Box> ); }
import { all } from 'redux-saga/effects' import booksSagas from './books' import securitySagas from './security' import dashboardSagas from './dashboard' export default function* rootSaga () { yield all([ ...booksSagas, ...securitySagas, ...dashboardSagas ]) }
module.exports = function getShortMessages(messages) { var array = []; messages.forEach(function (object) { if (object.message.length < 50) { array.push(object.message); } }); return array; };
var ID = 0 document.getElementById('btn').addEventListener('click',function(){ htmlcode = '<h3 id="%id%">%name%</h3>' name = document.getElementById('name').value htmlcode = htmlcode.replace('%name%',name) ID = ID + 1 htmlcode = htmlcode.replace('%id%',ID) document.querySelector('.main').insertAdjacentHTML('beforeend',htmlcode) })
import {ButtonBase} from "@material-ui/core"; import styled from "styled-components"; const ParagraphPrimitive = function ({liveMode, renderDynamicText, dynamicText, staticText, bottomMargin, ...props}) { return <p {...props}>{props.children}</p>; }; const StyledParagraph = styled(ParagraphPrimitive)` margin-top: 0; line-height: 1.6em; letter-spacing: 0.25px; &:empty { display: none; } margin-bottom: ${(props) => props.children && props.children.props && props.children.props.bottomMargin == true ? "32px" : props.bottomMargin == true ? "32px" : "0px"}; > p { margin-bottom: ${(props) => props.children && props.children.props && props.children.props.bottomMargin == true ? "-12px" : props.bottomMargin == true ? "-12px" : "0px"}; } @media screen and (min-width: 1280px) { line-height: 1.85em; } `; export {StyledParagraph};
import React from "react"; import "./Sidebar.css"; import LineStyleIcon from "@material-ui/icons/LineStyle"; import TimelineIcon from "@material-ui/icons/Timeline"; import TrendingUpIcon from "@material-ui/icons/TrendingUp"; import PersonOutlineIcon from "@material-ui/icons/PersonOutline"; import MonetizationOnIcon from "@material-ui/icons/MonetizationOn"; import AssessmentIcon from "@material-ui/icons/Assessment"; import MailIcon from "@material-ui/icons/Mail"; import FeedbackIcon from "@material-ui/icons/Feedback"; import SmsIcon from "@material-ui/icons/Sms"; import SupervisorAccountIcon from "@material-ui/icons/SupervisorAccount"; import { Link } from "react-router-dom"; const Sidebar = () => { return ( <div className="sidebar"> <div className="sidebar-wrapper"> <div className="sidebar-menu"> <h3 className="sidebar-title">Dashboard</h3> <ul className="sidebar-list"> <li className="sidebar-list-item"> <Link to={"/home"} style={{ textDecoration: "none", display: "flex", alignItems: "center", }} > <LineStyleIcon className="sidebar-icon" /> Home </Link> </li> <li className="sidebar-list-item"> <TimelineIcon className="sidebar-icon" /> Analytics </li> <li className="sidebar-list-item"> <TrendingUpIcon className="sidebar-icon" /> Sales </li> </ul> </div> <div className="sidebar-menu"> <h3 className="sidebar-title">Quick Menu</h3> <ul className="sidebar-list"> <li className="sidebar-list-item"> <Link to={"/users"} style={{ textDecoration: "none", display: "flex", alignItems: "center", }} > <PersonOutlineIcon className="sidebar-icon" /> Users </Link> </li> <li className="sidebar-list-item"> <TimelineIcon className="sidebar-icon" /> Products </li> <li className="sidebar-list-item"> <MonetizationOnIcon className="sidebar-icon" /> Transaction </li> <li className="sidebar-list-item"> <AssessmentIcon className="sidebar-icon" /> Reports </li> </ul> </div> <div className="sidebar-menu"> <h3 className="sidebar-title">Notification</h3> <ul className="sidebar-list"> <li className="sidebar-list-item"> <MailIcon className="sidebar-icon" /> Mail </li> <li className="sidebar-list-item"> <FeedbackIcon className="sidebar-icon" /> Feedback </li> <li className="sidebar-list-item"> <SmsIcon className="sidebar-icon" /> Messages </li> </ul> </div> <div className="sidebar-menu"> <h3 className="sidebar-title">Staff</h3> <ul className="sidebar-list"> <li className="sidebar-list-item"> <SupervisorAccountIcon className="sidebar-icon" /> Manage </li> <li className="sidebar-list-item"> <TimelineIcon className="sidebar-icon" /> Analytics </li> <li className="sidebar-list-item"> <AssessmentIcon className="sidebar-icon" /> Reports </li> </ul> </div> </div> </div> ); }; export default Sidebar;
import React from 'react'; import ReactDOM from 'react-dom'; import App from '../App'; describe('Test suite',()=>{ it('App component is displaying Button', () => { const div = document.createElement('div'); var renderer = ReactDOM.render(<App />, div); let tree = {"x":"y"}; jest.mock('../components/common/user-signup', () =>{ 'This is usersignup comonent '; }); expect(tree).toMatchSnapshot(); ReactDOM.unmountComponentAtNode(div); }); }); ;
var CT = require('./modules/country-list'); var AM = require('./modules/account-manager'); var EM = require('./modules/email-dispatcher'); var IM = require('./modules/image-manager'); var BM = require('./modules/blog-manager'); var CL = require('./modules/category-list'); var RS = require('./modules/recommendation-manager'); var express = require('express'); module.exports = function (app) { var router = express.Router(); // main login page // app.get('/', function (req, res) { // check if the user's credentials are saved in a cookie // if (req.cookies.user == undefined || req.cookies.pass == undefined) { res.render('login', { title: 'Hello - Please Login To Your Account' }); } else { // attempt automatic login // AM.autoLogin(req.cookies.user, req.cookies.pass, function (o) { if (o != null) { req.session.user = o; res.redirect('/user'); } else { res.render('login', { title: 'Hello - Please Login To Your Account' }); } }); } }); app.post('/', function (req, res) { AM.manualLogin(req.body['user'], req.body['pass'], function (e, o) { if (!o) { res.status(400).send(e); } else { req.session.user = o; if (req.body['remember-me'] == 'true') { res.cookie('user', o.user, { maxAge: 900000 }); res.cookie('pass', o.pass, { maxAge: 900000 }); } res.status(200).send(o); } }); }); // logged-in user homepage // app.get('/home', function (req, res) { if (req.session.user == null) { // if user is not logged-in redirect back to login page // res.redirect('/'); } else { res.render('home', { title: 'Control Panel', countries: CT, udata: req.session.user }); } }); app.post('/home', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { AM.updateAccount(req, function (e, o) { if (e) { console.log(e.message); res.status(400).send('error-updating-account'); } else { req.session.user = o; // update the user's login cookies if they exists // if (req.cookies.user != undefined && req.cookies.pass != undefined) { res.cookie('user', o.user, { maxAge: 900000 }); res.cookie('pass', o.pass, { maxAge: 900000 }); } res.status(200).render('home', { title: 'Control Panel', countries: CT, udata: req.session.user }); } }); } }); app.get('/user', function (req, res) { if (req.session.user == null) { // if user is not logged-in redirect back to login page // res.redirect('/'); } else { res.render('user', { title: 'Control Panel', udata: req.session.user, imagePath: host + ':' + appPort + '/' + req.session.user.image }); } }); app.get('/blogPage', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { var { blogTitleReply, blogId } = BM.getBlog(); res.redirect('/mainPage'); } }); app.get('/mainPage', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { var { blogTitleReply, blogId } = BM.getBlog(); var { resultCategory, resultTitle } = RS.getRecommendation(); if(blogId.length === 0) { res.redirect('/mainPage'); } else { res.render('mainPage', { title: 'main', blogData: blogTitleReply, blogs: blogId, recommendCategory: resultCategory, recommendTitle: resultTitle, udata: req.session.user }); } } }); app.get('/blogPost', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { res.render('blogPost', { title: 'Blog Data', categories: CL, udata: req.session.user }); } }); app.post('/blogPost', function (req, res) { BM.addBlog(req); }); app.get('/mainPage/:blogId', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { var blogId = req.params.blogId; var { blogTextareaReply, blogCategory, blogTT} = BM.getBlogData(blogId); res.redirect(`/blogPost/${blogId}`); } }); app.get('/blogPost/:blogId', function (req, res) { if (req.session.user == null) { res.redirect('/'); } else { var blogId = req.params.blogId; var { blogTextareaReply, blogCategory, blogTT} = BM.getBlogData(blogId); res.render('blogPage', { title: 'main', blogTextArea: blogTextareaReply, blogsCategory: blogCategory, blogsTitle: blogTT, udata: req.session.user }); } }); app.get('/accountSettings', function (req, res) { if (req.session.user == null) { // if user is not logged-in redirect back to login page // res.redirect('/'); } else { res.render('accountSettings', { title: 'Account Settings', countries: CT, udata: req.session.user }); } }); app.post('/logout', function (req, res) { res.clearCookie('user'); res.clearCookie('pass'); req.session.destroy(function (e) { res.status(200).send('ok'); }); }) // creating new accounts // app.get('/signup', function (req, res) { res.render('signup', { title: 'Signup', countries: CT }); }); app.post('/signup', function (req, res) { AM.addNewAccount(req, function (e) { if (e) { res.status(400).send(e); } else { res.status(200).send('ok'); } }); }); // password reset // app.post('/lost-password', function (req, res) { // look up the user's account via their email // AM.getAccountByEmail(req.body['email'], function (o) { if (o) { EM.dispatchResetPasswordLink(o, function (e, m) { // this callback takes a moment to return // // TODO add an ajax loader to give user feedback // if (!e) { res.status(200).send('ok'); } else { for (k in e) console.log('ERROR : ', k, e[k]); res.status(400).send('unable to dispatch password reset'); } }); } else { res.status(400).send('email-not-found'); } }); }); app.get('/reset-password', function (req, res) { var email = req.query["e"]; var passH = req.query["p"]; AM.validateResetLink(email, passH, function (e) { if (e != 'ok') { res.redirect('/'); } else { // save the user's email in a session instead of sending to the client // req.session.reset = { email: email, passHash: passH }; res.render('reset', { title: 'Reset Password' }); } }) }); app.post('/reset-password', function (req, res) { var nPass = req.body['pass']; // retrieve the user's email from the session to lookup their account and reset password // var email = req.session.reset.email; // destory the session immediately after retrieving the stored email // req.session.destroy(); AM.updatePassword(email, nPass, function (e, o) { if (o) { res.status(200).send('ok'); } else { res.status(400).send('unable to update password'); } }) }); // view & delete accounts // app.get('/print', function (req, res) { AM.getAllRecords(function (e, accounts) { res.render('print', { title: 'Account List', accts: accounts }); }) }); app.post('/delete', function (req, res) { AM.deleteAccount(req, function (e, obj) { if (!e) { res.clearCookie('user'); res.clearCookie('pass'); req.session.destroy(function (e) { res.status(200).send('ok'); }); } else { res.status(400).send('record not found'); } }); }); app.get('/reset', function (req, res) { AM.delAllRecords(function () { res.redirect('/print'); }); }); app.get('*', function (req, res) { res.render('404', { title: 'Page Not Found' }); }); return router; };
import React, { Component } from 'react' import PropTypes from 'prop-types' class DeleteItem extends Component { render() { return( <div> <button disabled={this.props.deleteDisabled} onClick={this.props.deleteLastItem}>Delete Last Item</button> </div> ) } } DeleteItem.propTypes = { deleteLastItem: PropTypes.func, deleteDisabled: PropTypes.bool } export default DeleteItem
//register_doit(); local_get(["sync", IP, Port]); variable_get(["channel_keys"], function(x) {register_doit(x)}); function register_doit(x) { if (typeof x == 'undefined'){ setTimeout(function() {variable_get(["channel_keys"], function(x) {register_doit(x)});}, 1000); } else if ( ( x.length == 1 ) && ( x.pop() == -6 ) ) { variable_get(["id"], new_channel); } else { console.log("did not work, x was"); console.log(x); } } function new_channel(id) { if (id == -1) {variable_get(["id"], new_channel);} else { variable_get(["balance"], function(x) {new_channel2(id,x);}) } } function new_channel2(id, bal) { C = Math.min(Math.floor(bal/2), 1000000); local_get(["new_channel", IP, Port, C, Math.floor(C/1.1), 50]); }
import { Flex } from "@chakra-ui/layout"; import React, { useState, useEffect } from "react"; import { Box, useBreakpointValue, Text, Stack, Spinner, Center, SlideFade, Alert, AlertIcon, AlertTitle, AlertDescription, SimpleGrid, } from "@chakra-ui/react"; import { FaCheckDouble, FaDollarSign, FaLayerGroup, FaUserAlt, } from "react-icons/fa"; import { FcCancel } from "react-icons/fc"; import { GrInProgress } from "react-icons/gr"; import TaskLinkBar from "../TasksFeed/TaskLinkBar"; import ErrorBanner from "../ErrorBanner"; import { useAuth } from "../../contexts/AuthProvider"; import ProfileCard from "./ProfileCard"; export default function DashoardHome({ setDash, setDashLoading, dashLoading, setDashErr, dashError, dash, fetchDash, }) { const [loading, setLoading] = useState(false); const [tasks, setTasks] = useState([]); const [users, setUsers] = useState([]); const [error, setErr] = useState(null); const { user } = useAuth(); const fetchAllTasks = async () => { if (user.role === "ADMIN") return fetchAllPending(); setLoading(true); setErr(null); try { const dt = await axios.get("/api/tasks/mytasks"); const { data } = dt.data; setTasks(data); console.log(data); setLoading(false); } catch (error) { setErr(error.message); setLoading(false); } }; const fetchAllPending = async () => { setLoading(true); setErr(null); try { const dt = await axios.get("/api/admin/pending"); const { data } = dt.data; setUsers(data.pending); setLoading(false); } catch (error) { setErr(error.message); setLoading(false); } }; useEffect(() => { fetchAllTasks(); fetchDash(); }, []); return ( <> <Box> <Text fontWeight="light" fontSize="23px" className="qfont"> {new Date().getHours() < 12 && "Good Morning " + user.firstname + "!"} {new Date().getHours() >= 12 && "Good Afternoon " + user.firstname + "!"} {new Date().getHours() >= 17 && "Good Evening " + user.firstname + "!"} </Text> <SimpleGrid columns={[1, 2, 2, 4]} pt={2} spacing="5" flexWrap="wrap"> <Center rounded="lg" p="4" flexDir="column" bg="white" shadow="md"> <Box as="span" bg="gray.200" fontSize="20px" p={4} rounded="md" color="green.500" m="auto" mb="2" > <FaCheckDouble /> </Box> <Text as="h4" textAlign="center" className="qfont"> {user.role == "CLIENT" ? "Tasks Completed" : user.role == "ADMIN" ? "Tasks Completed" : "Accepted Bids"} </Text> <Text fontWeight="bold" as="h1" className="qfont"> {dashLoading && ( <Box as="small" color="green.500"> loading... </Box> )} {!dashLoading && user.role == "CLIENT" && ( <>{dash && dash.accepted_tasks}</> )} {!dashLoading && user.role == "VENDOR" && ( <>{dash && dash.accepted_bids}</> )} {!dashLoading && user.role == "ADMIN" && ( <>{dash && dash.accepted_tasks}</> )} </Text> </Center> {/* end of first box */} <Center rounded="lg" p="4" flexDir="column" bg="white" shadow="md"> <Box as="span" bg="gray.200" fontSize="20px" p={4} color="green.500" mb="2" > <GrInProgress /> </Box> <Text as="h4" width="126px" textAlign="center" className="qfont"> {user.role == "CLIENT" ? "Tasks Pending" : user.role == "ADMIN" ? "Tasks Pending" : "Pending Bids"} </Text> <Text fontWeight="bold" as="h1" className="qfont"> {dashLoading && ( <Box as="small" color="green.500"> loading... </Box> )} {!dashLoading && user.role == "CLIENT" && ( <>{dash && dash.pending_tasks}</> )} {!dashLoading && user.role == "ADMIN" && ( <>{dash && dash.pending_tasks}</> )} {!dashLoading && user.role == "VENDOR" && ( <>{dash && dash.pending_bids}</> )} </Text> </Center> {/* end of second box */} <Center rounded="lg" p="4" flexDir="column" bg="white" shadow="md"> <Box as="span" bg="gray.200" fontSize="20px" p={4} rounded="md" color="green.500" mb="2" > {user.role !== "ADMIN" ? <FcCancel /> : <FaLayerGroup />} </Box> <Text as="h4" width="126px" textAlign="center" className="qfont"> {user.role == "CLIENT" ? "Tasks Cancelled" : user.role == "ADMIN" ? "All Tasks" : "Rejected Bids"} </Text> <Text fontWeight="bold" as="h1" className="qfont"> {dashLoading && ( <Box as="small" color="green.500"> loading... </Box> )} {!dashLoading && user.role == "CLIENT" && ( <>{dash && dash.cancelled_tasks}</> )} {/* cancelled is DONE for admin */} {!dashLoading && user.role == "ADMIN" && ( <>{dash && dash.cancelled_tasks}</> )} {!dashLoading && user.role == "VENDOR" && ( <>{dash && dash.cancelled_bids}</> )} </Text> </Center> <Center rounded="lg" p="4" flexDir="column" bg="white" shadow="md"> <Box as="span" bg="gray.200" fontSize="20px" p={4} rounded="md" color="green.500" mb="2" > {user.role !== "ADMIN" ? <FaDollarSign /> : <FaUserAlt />} </Box> <Text as="h4" textAlign="center" className="qfont"> {user.role === "ADMIN" ? "Users" : "Wallet Balance"} </Text> <Text fontWeight="bold" as="h1" className="qfont"> {user.role === "ADMIN" ? dash && dash.wallet : `$ ${dash && dash.wallet.amount}`} </Text> </Center> </SimpleGrid> </Box> {/* { _ __ _ { ___ _ _ __| | ___ / _| | |__ ___ __ __ ___ __ __ { / -_)| ' \ / _` | / _ \| _| | '_ \/ _ \\ \ // -_)\ \ / { \___||_||_|\__,_| \___/|_| |_.__/\___//_\_\\___|/_\_\ {*/} {user.role !== "ADMIN" && ( <Box> <Flex p={3} alignItems="center" justifyContent="space-between"> <Text id="top" color="#0ca25f" as="h1" fontSize="22px" fontWeight="bold" className="qfont" > {user && user.role === "CLIENT" ? "Recent Tasks" : "Accepted Bids"} </Text> </Flex> <Stack spacing={"4"}> {loading && !error && <Spinner size="lg" colorScheme="green.500" />} {!loading && !error && ( <> {tasks.map((s, i) => { return ( <SlideFade key={i} dir="left" in> <TaskLinkBar s={s} /> </SlideFade> ); })} </> )} {!loading && error && ( <> <ErrorBanner message={error.message} retry={fetchAllTasks} /> </> )} {tasks.length == 0 && ( <Alert status="info" variant="subtle" flexDirection="column" justifyContent="center" textAlign="center" minHeight="220px" > <AlertIcon size="40px" mr={0} /> <AlertTitle mt={4} mb={1} fontSize="lg" className="qfont"> Oops! Looks empty here! </AlertTitle> <AlertDescription maxWidth="sm" className="qfont"> You have no tasks at the moment </AlertDescription> </Alert> )} </Stack> </Box> )} {user.role === "ADMIN" && ( <Box> <Flex p={3} alignItems="center" justifyContent="space-between"> <Text id="top" color="#0ca25f" as="h1" fontSize="22px" fontWeight="bold" className="qfont" > Recent Vendor Signups </Text> </Flex> {loading && !error && <Spinner size="lg" colorScheme="green.500" />} <SimpleGrid columns={[1, 2]} spacing="3"> {!loading && !error && ( <> {users.map((s, i) => { return ( <SlideFade key={i} dir="left" in> <ProfileCard user={s} /> </SlideFade> ); })} </> )} </SimpleGrid> {!loading && error && ( <> <ErrorBanner message={error.message} retry={fetchAllPending} /> </> )} {users.length == 0 && ( <Alert status="info" variant="subtle" flexDirection="column" justifyContent="center" textAlign="center" minHeight="220px" > <AlertIcon size="40px" mr={0} /> <AlertTitle mt={4} mb={1} fontSize="lg" className="qfont"> Oops! Looks empty here! </AlertTitle> <AlertDescription maxWidth="sm" className="qfont"> You have no pending signups </AlertDescription> </Alert> )} </Box> )} </> ); }
/** Reducer which service some user experience */ const TOGGLE_GLOBAL_PRELOAD = 'TOGGLE_GLOBAL_PRELOAD' let initialState = { /** Show global preloader while fetching some data or passing connect generation*/ isGlobalPreloader:false } const preloadReducer = (state = initialState, action) => { switch (action.type) { /** Change document title */ case TOGGLE_GLOBAL_PRELOAD: { return { ...state, isGlobalPreloader:action.isGlobalPreloader } } default: return state } } export default preloadReducer export const ToggleGlobalPreloaderAC = isGlobalPreloader => { return { type:TOGGLE_GLOBAL_PRELOAD, isGlobalPreloader } }
import PropTypes from 'prop-types'; const { shape, arrayOf, number, string, func, bool } = PropTypes; // ========= functions ======= export const onSubmitType = func; export const addToCartStartType = func; export const onClickType = func; export const searchByTitleType = func; export const filterByPriceType = func; export const purchaseRequestType = func; export const logoutType = func; export const fetchOneBookType = func; export const fetchBooksType = func; export const loadMoreType = func; // ========= Books =========== export const idType = string; export const titleType = string; export const priceType = number; export const authorType = string; export const descriptionType = string; export const coverType = string; export const levelType = string; export const bookType = shape({ idType, titleType, authorType, levelType, descriptionType, coverType, tagsType: arrayOf(string), }); export const booksType = arrayOf(bookType); export const listingsType = arrayOf(booksType); // =========== cart =========== export const orderType = shape({ idType, titleType, priceType, }); export const cartType = arrayOf(orderType); // =========== else =========== export const usernameType = string; export const avatarType = string; export const loaderType = bool; export const tokenType = string; export const iconType = string; export const errorType = string; export const matchType = shape({ path: string, url: string, isExact: bool, });
export const NetworkType = { Webaverse: "webaverse", Mainnet: "mainnet" };
import React from 'react' import { StyleSheet } from 'quantum' import { ArrowIcon } from 'bypass/ui/icons' const styles = StyleSheet.create({ self: { border: '1px solid #e0e0e0', borderRadius: '50%', width: '27px', height: '27px', display: 'inline-block', boxSizing: 'border-box', '& svg': { fill: '#e0e0e0', left: '-2px', position: 'relative', }, }, hover: { borderColor: '#37474f', '& svg': { fill: '#37474f', }, }, }) const Collapse = ({ hover }) => ( <span className={styles({ hover })}> <ArrowIcon left /> </span> ) export default Collapse
import React from 'react'; import ReactDOM from 'react-dom'; import SzopinskiCalendar from './components/SzopinskiCalendar'; ReactDOM.render( <React.StrictMode> <SzopinskiCalendar /> </React.StrictMode>, document.getElementById('root') );
'use strict'; const {app, BrowserWindow, ipcMain} = require('electron'); let mainWindow = null; // keep reference to prevent GC. /** * Create Render window */ function createWindow() { const url = `file://${__dirname}/index.html`; mainWindow = new BrowserWindow({ show: true }); !process.env.production && mainWindow.webContents.openDevTools(); // only show development. mainWindow.loadURL(url); } app.on('ready', createWindow);
var gulp = require('gulp'); var sass = require('gulp-ruby-sass'); gulp.task('sass', function(){ return sass('src/sass/core.scss') .on('error', sass.logError) .pipe(gulp.dest('dest/styles')); }); gulp.task('default', ['sass']);
$(document).ready(function() { $('.do').hide() $('.linode').hide() $('.local').show() }); $('.provider_select').on('change', function() { var selection = this.value console.log("it changed") switch(selection) { case 'local': $('.do').hide() $('.linode').hide() $('.local').show() break; case 'do': $('.local').hide() $('.linode').hide() $('.do').show() break; case 'linode': $('.local').hide() $('.do').hide() $('.linode').show() } });
const navCenter = document.querySelector(".nav-center"); const toggle = document.querySelector(".close"); const signUp = document.querySelector(".signUp"); toggle.addEventListener("click", () => { navCenter.classList.toggle("active"); }); window.addEventListener("scroll", () => { if (window.scrollY > 200) { navCenter.classList.add("scroll"); signUp.style.margin = "0"; } else { signUp.style.margin = "2vw 3vw"; navCenter.classList.remove("scroll"); } navCenter.classList.remove("active"); });