text
stringlengths
7
3.69M
import React, { useState } from 'react'; import { Form, Col, Row, Button, Alert } from 'react-bootstrap'; import './contact.css'; import axios from 'axios'; import ContactSvg from '../../images/contact.svg'; import { Link } from 'react-router-dom'; const Contact = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); const [isSubmitted, setIsSubmitted] = useState(null); const handleSubmit = (e) => { e.preventDefault(); axios .post('http://localhost:8000/contact/backend/sendEmail', { name, email, message, }) .then((result) => { console.log(result.data); console.log('form submitted'); }); setName(''); setEmail(''); setMessage(''); setIsSubmitted(true); }; return isSubmitted ? ( <div className='mt-5 d-flex flex-column justify-content-between align-items-center'> <Alert variant='success'> 🎉 We received your message Thank you for your using <b> Shopistic </b> {' '} 🎉 </Alert> <Link className='btn btn-dark' to='/'> {' '} Go Back{' '} </Link> </div> ) : ( <div className='col-10 mx-auto mt-5'> <Row className='d-flex justify-content-between pt-5'> <Col lg={6} md={6} sm={12}> <h2 className='my-4'>Contact us</h2> <Form onSubmit={handleSubmit}> <Form.Row className='my-3'> <Form.Group as={Col} controlId='formGridName'> <Form.Control type='name' name='name' placeholder='Enter your name' required={true} value={name} onChange={(e) => setName(e.target.value)} /> </Form.Group> <Form.Group as={Col}> <Form.Control type='email' name='email' placeholder='Email' required={true} value={email} onChange={(e) => setEmail(e.target.value)} /> </Form.Group> </Form.Row> <Form.Group controlId='formBasicTextArea'> <Form.Control as='textarea' placeholder='Write your message' rows='5' name='message' value={message} onChange={(e) => setMessage(e.target.value)} /> </Form.Group> <Button type='submit' variant='info' className=' mt-3'> Send </Button> </Form> </Col> <Col lg={5} md={6} sm={12}> <img src={ContactSvg} alt='contactSvg' className='w-100 h-100' /> </Col> </Row> </div> ); }; export default Contact;
const rp = require('request-promise') const jirabot = require('./jirabot') require('dotenv').config() test('smoke test', () => { const options = { uri: `${process.env.BASE_URL}/issue/CHAT-1`, headers: { 'Authorization': `Basic ${process.env.BOT_API_TOKEN}` }, json: true } return rp(options).then(issue => { expect(issue.id).toBe('10000') }) }) test('test chat 2', () => { return jirabot.ticketDescription('chat 2').then(s => { expect(s).toBe("CHAT-2 is Build a Jira Chatbot") }) })
class Packet{ constructor(packetBody, frameLength = 0){ this.body = packetBody; this.frameLength = frameLength; } toRaw(){ if(!this.body || this.body.length <= 0) return null; const bufferHeader = new Buffer(Packet.frameHeaderLength+Packet.headerLength); const bufferBody = new Buffer(this.body, 'utf8'); const totalLength = bufferBody.length + Packet.frameHeaderLength + Packet.headerLength; bufferHeader.writeInt32LE(totalLength - Packet.frameHeaderLength, 0); bufferHeader.writeInt32LE(totalLength - Packet.frameHeaderLength, 4); bufferHeader.writeInt16LE(689, 8); bufferHeader.writeInt16LE(0, 10); return Buffer.concat([bufferHeader, bufferBody], totalLength); } getPacketFrameSize(){ return 2 * (this.frameLength + 4); } } Packet.frameHeaderLength = 4; Packet.headerLength = 8; Packet.sniff = function(bufferHex){ const bufferAvailable = bufferHex.length / 2; if(bufferAvailable <= Packet.frameHeaderLength + Packet.headerLength ){ return null; } const buffer = Buffer.from(bufferHex, 'hex'); const packetLength = buffer.readInt32LE(0); const packetLength1 = buffer.readInt32LE(Packet.frameHeaderLength); const packetType = buffer.readInt16LE(Packet.frameHeaderLength * 2); const enctype = buffer.readInt8(Packet.frameHeaderLength * 2 + 2); const reserve = buffer.readInt8(Packet.frameHeaderLength * 2 + 3); let body = buffer.toString('utf8', Packet.frameHeaderLength + Packet.headerLength); if(packetLength <= 0 || packetLength1 <= 0){ throw new Error('packet not vaild'); return null; } if(packetLength != packetLength1){ throw new Error('packet length not equal'); return null; } if(bufferAvailable >= packetLength + 4){ if(bufferAvailable > packetLength + 4){ body = buffer.toString('utf8', Packet.frameHeaderLength + Packet.headerLength, packetLength + 4); } return new Packet(body, packetLength); } return null; } Packet.fromMessage = function(message){ return new Packet(message.toString()); } module.exports = Packet;
module.exports.Hello = () => { console.log("Hello world!"); } module.exports.name = 'Ratul';
var contacts = new Array(); var lastEditIndex = 0; document.getElementById('update').style.display="none"; function val() { var result = ''; var formular = document.formular; if (formular.firstName.value == '') { formular.firstName.style.borderColor="#ff0000"; result += 'Geben Sie bitte ihren Vornamen ein\n'; }else{ formular.firstName.style.borderColor="#dcdcdc"; } if (formular.lastName.value == '') { formular.lastName.style.borderColor="#ff0000"; result += 'Geben Sie bitte ihren Nachnamen ein\n'; }else{ formular.lastName.style.borderColor="#dcdcdc"; } if (formular.address.value == '') { formular.address.style.borderColor="#ff0000"; result += 'Geben Sie bitte ihre Adresse ein\n'; }else{ formular.address.style.borderColor="#dcdcdc"; } if (formular.number.value == '') { formular.number.style.borderColor="#ff0000"; result += valNumber(formular.number.value); }else{ formular.number.style.borderColor="#dcdcdc"; } if (formular.mobile.value == '') { formular.mobile.style.borderColor="#ff0000"; result += valNumber(formular.mobile.value); }else{ formular.mobile.style.borderColor="#dcdcdc"; } if (formular.email.value != '') { formular.email.style.borderColor="#dcdcdc"; result += valEMail(formular.email.value); }else{ formular.email.style.borderColor="#ff0000"; result += 'Geben Sie bitte ihre Email-Adresse ein\n'; } if (result == '') { var contact = { firstName: formular.firstName.value, lastName: formular.lastName.value, address: formular.address.value, number: formular.number.value, mobile: formular.mobile.value, email: formular.email.value } writeToList(contact); } else { alert(result); } return false; } function writeToList(contact) { var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0]; var newRow = tableRef.insertRow(tableRef.rows.length); var getInsertedIndex = contacts.push(contact); newRow.id = 'row-'+getInsertedIndex; var newCell = newRow.insertCell(0); var newText = document.createTextNode(tableRef.rows.length) newCell.appendChild(newText); newCell = newRow.insertCell(1); newText = document.createTextNode(contact.firstName) newCell.appendChild(newText); newCell = newRow.insertCell(2); newText = document.createTextNode(contact.lastName) newCell.appendChild(newText); newCell = newRow.insertCell(3); newText = document.createTextNode(contact.address) newCell.appendChild(newText); newCell = newRow.insertCell(4); newText = document.createTextNode(contact.number) newCell.appendChild(newText); newCell = newRow.insertCell(5); newText = document.createTextNode(contact.mobile) newCell.appendChild(newText); newCell = newRow.insertCell(6); newText = document.createTextNode(contact.email) newCell.appendChild(newText); newCell = newRow.insertCell(7); var newButton = document.createElement("input"); newButton.type="button"; newButton.className = "btn btn-default"; newButton.value="löschen"; newButton.dataset.id = getInsertedIndex; newButton.onclick=function(){ alert("Möchten Sie diesen Kontakt wirklich löschen!"); var removeFromArray = this.dataset.id; document.getElementById('row-'+removeFromArray).remove(); contacts.splice(removeFromArray-1,1); updateIndex(); }; newCell.appendChild(newButton); newCell = newRow.insertCell(8); var editButton = document.createElement("input"); editButton.type="button"; editButton.className = "btn btn-default"; editButton.value="bearbeiten"; editButton.dataset.id = getInsertedIndex; editButton.onclick=function(){ var formular = document.formular; var editIndex = this.dataset.id - 1; formular.firstName.value = contacts[editIndex].firstName; formular.lastName.value = contacts[editIndex].lastName; formular.email.value = contacts[editIndex].email; formular.address.value = contacts[editIndex].address; formular.mobile.value = contacts[editIndex].mobile; formular.number.value = contacts[editIndex].number; lastEditIndex = editIndex+1; hideAddContact(); document.getElementById('update').style.display="block"; }; newCell.appendChild(editButton); } function valEMail(emailValue) { var email = emailValue; var at = email.indexOf("@"); var dot = email.lastIndexOf("."); if (at < 1 || dot < at + 2 || dot + 2 >= email.length) { return 'Geben Sie ihre Email Adresse bitte korrekt ein\n'; } else { return ''; } } function valNumber(numberValue) { if (!isNaN(numberValue)) { return 'Geben Sie ihre Telefonnummer bitte korrekt ein\n'; } else { return ''; } } function updateContact(){ var currentRow = document.getElementsByTagName('tr')[lastEditIndex].getElementsByTagName('td'); console.log(currentRow); //schreibt in die Tabelle currentRow[1].innerHTML = formular.firstName.value; currentRow[2].innerHTML = formular.lastName.value; currentRow[3].innerHTML = formular.address.value; currentRow[4].innerHTML = formular.number.value; currentRow[5].innerHTML = formular.mobile.value; currentRow[6].innerHTML = formular.email.value; //schreibt ins Array contacts[lastEditIndex-1].firstName = formular.firstName.value; contacts[lastEditIndex-1].lastName = formular.lastName.value; contacts[lastEditIndex-1].email = formular.email.value; contacts[lastEditIndex-1].address = formular.address.value; contacts[lastEditIndex-1].mobile = formular.mobile.value; contacts[lastEditIndex-1].number = formular.number.value; document.getElementById('addContact').style.display="block"; document.getElementById('update').style.display="none"; clearForm(); } function updateIndex() { var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0]; var rows = tableRef.rows.length; for(var i=1; i<= rows; i++){ var currentRow = document.getElementsByTagName('tr')[i]; currentRow.firstElementChild.innerHTML = i; currentRow.getElementsByClassName('btn')[0].dataset.id = i; currentRow.getElementsByClassName('btn')[1].dataset.id = i; } } function hideAddContact() { document.getElementById('addContact').style.display="none"; } function clearForm() { var obj = document.getElementsByName('formular')[0]; for(var i =0; i<obj.elements.length;i++){ if(obj.elements[i].type == 'text' || obj.elements[i] == 'button'){ obj.elements[i].value = ''; } } }
import { gulp as g } from './plugins' const out = 'assets' import gulp from 'gulp' export function size () { return gulp.src(`${out}/**`) .pipe(g.size()) }
const express = require("express"); const router = express.Router(); const AuthController = require("./../controllers/AuthController"); const PhoneController = require("./../controllers/PhoneController"); const AdminController = require("./../controllers/AdminController"); const LocationController = require("./../controllers/LocationController"); const UserController = require("./../controllers/UserController"); const ProductController = require("../controllers/ProductController"); const UploadController = require("./../controllers/UploadController.js"); const PostCategoryController = require("../controllers/PostCategoryController"); const PostController = require("../controllers/PostController"); const AppUserController = require("../controllers/AppUserController"); const ConversationController = require("../controllers/ConversationController"); const NotificationController = require("../controllers/NotificationController"); const LocationReviewController = require("../controllers/LocationReviewController"); const PetController = require("../controllers/PetController"); const ReportController = require("../controllers/ReportController"); const passport = require("passport"); require("./../middleware/passport")(passport); //#region Auth controller router.post("/auth/register", AuthController.register); router.post("/auth/login", AuthController.login); router.post("/auth/logout", AuthController.logout); //#endregion //#region User router.get("/users/forgotPassword/:phoneNumber", UserController.forgotPassword); router.get("/users/detail/:userId", UserController.getUserById); router.put( "/auth/changePassword", passport.authenticate("jwt", { session: false, }), AuthController.changePassword ); //#endregion //#region Location Category router.get( "/location/locationCategoriesByType/:type", LocationController.getLocationCategoriesByType ); router.get( "/location/locationCategories", LocationController.getLocationCategories ); router.get( "/location/locationCategoriesWithType", LocationController.getLocationCategoriesWithType ); router.post( "/admin/location/addLocationCategory", LocationController.addLocationCategory ); router.put( "/admin/location/updateLocationCategories", LocationController.updateLocationCategories ); //#endregion //#region Location admin router.get("/admin/getLocation", LocationController.getAllLocations); router.get("/admin/getLocationById/:locationId", LocationController.getLocationById); router.put("/admin/hideOrShowLocation", LocationController.hideShowLocation); router.post("/admin/addLocaionByAdmin", LocationController.addLocaionByAdmin); router.put("/admin/deleteAdminLocation", LocationController.deleteLocationByAdmin); //#endregion //#region Create Admin router.post("/admin/create", AuthController.createAdminUser); router.get( "/admin/wake-up", passport.authenticate("jwt", { session: false, }), (req, res) => res.send("👌") ); router.post( "/admin/addLocation", passport.authenticate("jwt", { session: false, }), AdminController.addLocation ); //#endregion //#region get product category router.get( "/product/productParentCategories/:ownerId", passport.authenticate("jwt", { session: false, }), ProductController.getProductParentCategories ); router.get( "/product/category/:ownerId", passport.authenticate("jwt", { session: false, }), ProductController.getProductParentCategoriesProduct ); router.post( "/product/addProductParentCategory", passport.authenticate("jwt", { session: false, }), ProductController.addProductParentCategory ); //#endregion //#region Location router.get( "/location/detail/:ownerId", LocationController.getLocationProfile ); router.put( "/location/update", passport.authenticate("jwt", { session: false, }), LocationController.updateLocation ); router.get( "/location/searchNear/:long/:lat/:radius", LocationController.searchNearByLatLong ); router.get( "/location/searchDist/:long/:lat/:radius", LocationController.searchDist ); router.get( "/location/searchAllLocations", LocationController.searchAllLocations ); router.get( "/location/locationProduct", LocationController.getLocationWithAllProduct ); router.get( "/location/locationByCategory", LocationController.searchLocationByCategory ); router.get( "/location/getAllActiveLocation", LocationController.getAllActiveLocation ); //#endregion //#region Product router.put( "/product/delete", passport.authenticate("jwt", { session: false, }), ProductController.deleteProduct ); router.put( "/product/update", passport.authenticate("jwt", { session: false, }), ProductController.updateProduct ); router.get( "/product/productDetailById/:id", ProductController.getProductDetailById ); router.put( "/product/updateProductCategory", passport.authenticate("jwt", { session: false, }), ProductController.updateProductParentCategory ); router.post( "/product/add", ProductController.addProduct ); router.get( "/product/productByUserIds/:ownerId", ProductController.getProductByIds ); router.get( "/product/productByIdForApp", ProductController.getProductDetailByIdForApp ); router.get( "/product/productInOneCategories", ProductController.getProductInOneCategories ); //#endregion //#region Phone router.post("/phone/sms", PhoneController.sendPhoneVerifyCode); router.post("/phone/verify", PhoneController.verifyPhoneVerifyCode); //#endregion //#region post category route router.get("/post/category/get", PostCategoryController.get); router.post("/post/category/add", PostCategoryController.add); router.delete("/post/category/deleteById", PostCategoryController.deleteById); router.get("/post/category/:typeId", PostCategoryController.getByID); router.put( "/post/category/updateNameById", PostCategoryController.updateNameById ); //#endregion //#region post route router.get("/post/getById/:postId", PostController.getPostById); router.get("/post/get", PostController.get); router.get("/post/search", PostController.postTextSearch); router.get("/post/:ownerId", PostController.getByOwnerId); router.get("/post/getById/:postId", PostController.getById); router.get("/post/get/:typeId", PostController.getPublicByTypeId); router.post("/post/add", PostController.add); router.put("/post/edit", PostController.editPost); router.delete("/post/deleteById", PostController.deleteById); router.get("/post/images/:postId", PostController.getImages); router.put("/post/images/add", PostController.addImages); router.delete("/post/images/removeImage", PostController.removeImage); router.get("/post/comment/:postId", PostController.getComments); router.post("/post/comment/add", PostController.addComment); router.put("/post/comment/edit", PostController.editComment); router.delete("/post/comment/delete", PostController.deleteComment); router.get("/post/vote/get", PostController.getVoteByType); router.post("/post/vote", PostController.vote); router.post("/post/report/add", PostController.addReport); router.get("/post/report/:postId", PostController.getReports); router.post("/post/testNotification", PostController.testNotification); //#endregion //#region app user service router.post("/app/user/add", AppUserController.createUser); router.post("/app/user/addExpoToken", AppUserController.addExpoToken); router.post("/app/user/removeExpoToken", AppUserController.removeExpoToken); router.post("/app/user/findByFbId", AppUserController.findUserByFbId); router.get("/app/user/:userId", AppUserController.findUser); router.post("/app/user/notification/add", AppUserController.addNotification); router.post("/app/user/editInfo", AppUserController.editAppInfo); router.get( "/app/user/notification/:userId", AppUserController.getNotifications ); //#endregion //#region conversation router.get( "/conversation/:userId", ConversationController.getConversationsByUser ); router.get( "/conversation/message/:conversationId", ConversationController.getMessagesInConversation ); router.post("/conversation/add", ConversationController.createConversation); router.post( "/conversation/match", ConversationController.findConversationByUsers ); router.post("/conversation/message/add", ConversationController.addMessage); //#endregion //#region pet route router.post("/pet/add", PetController.add); router.get("/pet/get/:userId", PetController.getByUser); router.get("/pet/getPet/:userId", PetController.getPet); router.get("/pet/getById/:petId", PetController.getById); router.delete("/pet/deletePet", PetController.deletePet); router.post("/pet/editPet", PetController.editPet); router.post("/pet/like", PetController.addUserLikePet); router.get("/pet/isLiked", PetController.isLiked); router.post("/pet/ignore", PetController.addUserIgnorePet); router.get("/pet/getLikeNumber/:petId", PetController.getLikeNumber); router.get("/pet/getNotIgnoredPet/:userId", PetController.getNotIgnoredPet); router.post("/pet/changeRequestStatus", PetController.changeRequestStatus); //#endregion //#region report route router.post("/report/addReport", ReportController.addReport); router.put("/report/updateReportStatus", ReportController.updateReportStatus); router.get("/report/getReportedPost", ReportController.adminGetAllReports); router.get("/report/:postId", ReportController.getReportByPostId); //#endregion //#region notification router.post("/app/notification/add", NotificationController.addNotification); router.post( "/app/notification/hide", NotificationController.hiddenNotification ); router.get( "/app/notification/:userId", NotificationController.getNotifications ); router.get( "/app/notification/getType/:userId/:type", NotificationController.getNotificationsByType ); //#endregion //#region location review router.post("/location/review/add", LocationReviewController.addRate); router.get("/location/review/:locationId", LocationReviewController.getRate); router.get( "/location/review/average/:locationId", LocationReviewController.getAvgRating ); //#endregion //#region Upload to Cloudinary router.get("/wake-up", (req, res) => res.send("👌")); router.post("/image-upload", UploadController.uploadImage); //#endregion //#region Get all user: ADMIN router.get("/admin/users", UserController.getAllUsers); router.put("/admin/users", UserController.banUserById); //#endregion // get router.get("/admin/users/status/:id", UserController.getStatusUserById); module.exports = router;
import { styled } from 'goober'; export const Text = styled('p')( ({ theme, size, faded, accent, ph, pl, pr, bold, color, mono, spaced, superSpaced }) => [ { margin: 0, fontWeight: bold ? 'bold' : 'normal', fontSize: theme.fontSizes[size] || theme.fontSizes[200], color: 'currentcolor', lineHeight: 1.6 }, ph && { padding: `0 ${theme.sizes[ph]}` }, pl && { paddingLeft: theme.sizes[pl] }, pr && { paddingRight: theme.sizes[pr] }, faded && { color: theme.colors['gray-300'] }, accent && { color: theme.colors['accent-200'] }, color && { color: theme.colors[color] }, mono && { fontFamily: 'monospace' }, mono && { fontFamily: 'monospace' }, spaced && { letterSpacing: '0.01em' }, superSpaced && { letterSpacing: '0.05em' } ] );
// En cada archivo dónde hagamos // la sintaxis especial de React (JSX) // debemos importar la librería import React from 'react' // Hacemos los componentes // también podríamos importarlos desde archivos externos // pero para efectos prácticos los crearé aquí mismo const Entry = () => { return( <div> <h1>Entry</h1> <div>Entrada de al aplicación</div> </div> ) } const Main = () => { return( <div> <h1>Main</h1> <div>Main de la aplicación</div> </div> ) } const Other = () => { return( <div> <h1>Otra ruta</h1> <div>Aquí no hay nada</div> </div> ) } // Exportamos un Array de items // que cada uno contendrá un path // es decir la dirección que le llegará en la petición // y el componente que renderizará en esa dirección // y una clave opcional que refiere si el componente // se renderizará sólo cuando la dirección sea totalmente exacta // además agregaremos una clave nosotros para hacer una pequeña // barra de navegación, y que nos diriga a cada ruta // en este ejemplo sólo usaremos tres rutas a los sumo export default [{ // Este equivaldría al punto de entrada de la aplicación // cómo si fuera nuestro index path: '/', exact: true, pathString: 'Inicio', component: Entry }, { // Main de la aplicación path: '/main', pathString: 'Main', component: Main }, { // Otra aplicación path: '/other', pathString: 'Otra Ruta', component: Other }]
import moment from 'moment'; import util from '../base/util.js'; import constant from '../base/constant.js'; import AbstractComponent from './abstract-component.js'; export default class EventEdit extends AbstractComponent { constructor(events) { super(); this._types = events.types; this._type = events.type; this._cities = events.cities; this._city = events.city ? events.city : null; this._options = events.type.options; this._timeStart = events.timeStart; this._timeEnd = events.timeEnd; this._price = events.price; this._description = events.city ? events.city.description : null; this._photos = events.city ? events.city.photos : null; this._isFavorite = events.isFavorite; this._eventElement = this.getElement(); this._subscribeOnEvents(); } getTemplate() { return `<li class="trip-events__item"> <form class="event event--edit" action="#" method="post"> <header class="event__header"> <div class="event__type-wrapper"> <label class="event__type event__type-btn" for="event-type-toggle-1"> <span class="visually-hidden">Choose event type</span> <img class="event__type-icon" width="17" height="17" src="img/icons/${this._type.name}.png" alt="Event type icon"> </label> <input class="event__type-toggle visually-hidden" id="event-type-toggle-1" type="checkbox"> <div class="event__type-list"> <fieldset class="event__type-group"> <legend class="visually-hidden">Transfer</legend> ${this._types.filter((it) => it.isMoving) .map(({name}) => `<div class="event__type-item"> <input id="event-type-${name}-1" class="event__type-input visually-hidden" type="radio" name="event-type" value="${name}" ${this._isTypeChecked(name, this._type.name)}> <label class="event__type-label event__type-label--${name}" for="event-type-${name}-1">${name}</label> </div>` .trim()) .join(``)} <fieldset class="event__type-group"> <legend class="visually-hidden">Activity</legend> ${this._types.filter((it) => !it.isMoving).map(({name}) => `<div class="event__type-item"> <input id="event-type-${name}-1" class="event__type-input visually-hidden" type="radio" name="event-type" value="${name}" ${this._isTypeChecked(name, this._type.name)}> <label class="event__type-label event__type-label--${name}" for="event-type-${name}-1">${name}</label> </div>` .trim()) .join(``)} </fieldset> </div> </div> <div class="event__field-group event__field-group--destination"> <label class="event__label event__type-output" for="event-destination-1"> ${util.getEventTitle(this._type.name)} </label> <input class="event__input event__input--destination" id="event-destination-1" type="text" name="event-destination" value="${this._city ? `${this._city.name}` : ``}" list="destination-list-1"> <datalist id="destination-list-1"> ${this._cities.map((it) => `<option value="${it.name}"></option>` .trim()) .join(``)}} </datalist> </div> <div class="event__field-group event__field-group--time"> <label class="visually-hidden" for="event-start-time-1"> From </label> <input class="event__input event__input--time" id="event-start-time-1" type="text" name="event-start-time" datetime="${moment(this._timeStart).format()}" value="${moment(this._timeStart).format(`DD/MM/YY HH:mm`)}"> &ndash; <label class="visually-hidden" for="event-end-time-1"> To </label> <input class="event__input event__input--time" id="event-end-time-1" type="text" name="event-end-time" datetime="${moment(this._timeEnd).format()}" value="${moment(this._timeEnd).format(`DD/MM/YY HH:mm`)}"> </div> <div class="event__field-group event__field-group--price"> <label class="event__label" for="event-price-1"> <span class="visually-hidden">Price</span> &euro; </label> <input class="event__input event__input--price" id="event-price-1" type="text" name="event-price" value="${this._price}"> </div> <button class="event__save-btn btn btn--blue" type="submit">Save</button> <button class="event__reset-btn" type="reset">Delete</button> <input id="event-favorite-1" class="event__favorite-checkbox visually-hidden" type="checkbox" name="event-favorite" ${this._isFavorite ? ` checked` : ``}> <label class="event__favorite-btn" for="event-favorite-1"> <span class="visually-hidden">Add to favorite</span> <svg class="event__favorite-icon" width="28" height="28" viewBox="0 0 28 28"> <path d="M14 21l-8.22899 4.3262 1.57159-9.1631L.685209 9.67376 9.8855 8.33688 14 0l4.1145 8.33688 9.2003 1.33688-6.6574 6.48934 1.5716 9.1631L14 21z"/> </svg> </label> <button class="event__rollup-btn" type="button"> <span class="visually-hidden">Close event</span> </button> </header> <section class="event__details ${this._city ? `` : ` visually-hidden`}"> <section class="event__section event__section--offers"> ${this._options ? `<h3 class="event__section-title event__section-title--offers">Offers</h3> <div class="event__available-offers"> ${this._options.map((option) => ` <div class="event__offer-selector"> <input class="event__offer-checkbox visually-hidden" id="event-offer-${option.name}-1" type="checkbox" name="event-offer" value="${option.name}" ${this._options.filter(({name}) => option.name === name).map(({isChecked}) => isChecked ? ` checked` : ``)}> <label class="event__offer-label event__offer-label--${option.name}" for="event-offer-${option.name}-1"> <span class="event__offer-title">${option.description}</span> &plus; &euro;&nbsp;<span class="event__offer-price">${option.cost}</span> </label> </div>` .trim()) .join(``)}` : ``} </div> </section> <section class="event__section event__section--destination ${this._city ? `` : ` visually-hidden`}"> <h3 class="event__section-title event__section-title--destination">Destination</h3> <p class="event__destination-description">${this._description ? `${this._description}` : ``}</p> <div class="event__photos-container"> <div class="event__photos-tape"> ${this._photos ? `${this._photos.map((photo) => `<img class="event__photo" src="${photo}" alt="Event photo">` .trim()) .join(``)}` : ``} </div> </div> </section> </section> </form> </li>`.trim(); } _getOffersTemplate(options) { return `<h3 class="event__section-title event__section-title--offers">Offers</h3> <div class="event__available-offers"> ${options.map((option) => ` <div class="event__offer-selector"> <input class="event__offer-checkbox visually-hidden" id="event-offer-${option.name}-1" type="checkbox" name="event-offer" value="${option.name}"> <label class="event__offer-label event__offer-label--${option.name}" for="event-offer-${option.name}-1"> <span class="event__offer-title">${option.description}</span> &plus; &euro;&nbsp;<span class="event__offer-price">${option.cost}</span> </label> </div>` .trim()) .join(``)}`; } _getDestinationTemplate(newCity) { return `<h3 class="event__section-title event__section-title--destination">Destination</h3> <p class="event__destination-description">${newCity.description}</p> <div class="event__photos-container"> <div class="event__photos-tape"> ${newCity.photos.map((photo) => `<img class="event__photo" src="${photo}" alt="Event photo">` .trim()) .join(``)} </div> </div>`; } _isTypeChecked(currentTypeName, checkedTypeName) { return currentTypeName === checkedTypeName ? ` checked` : ``; } _switchCheckingElement(element) { element.checked = !util.isElementChecked(element); } _subscribeOnEvents() { const offersElement = this._eventElement.querySelector(`.event__section--offers`); offersElement.addEventListener(`click`, (evt) => { evt.preventDefault(); if (util.isElementContainsClass(evt.target, `event__offer-label`)) { const inputElement = this._eventElement.querySelector(`#${evt.target.htmlFor}`); this._switchCheckingElement(inputElement); } if (util.isElementContainsClass(evt.target.parentNode, `event__offer-label`)) { const inputElement = this._eventElement.querySelector(`#${evt.target.parentNode.htmlFor}`); this._switchCheckingElement(inputElement); } }); const typeGroupElement = this._eventElement.querySelector(`.event__type-group`); typeGroupElement.addEventListener(`click`, (evt) => { if (util.isElementContainsClass(evt.target, `event__type-label`)) { const icon = this._eventElement.querySelector(`.event__type-icon`); icon.src = `img/icons/${evt.target.textContent}.png`; const eventPlaceholder = this._eventElement.querySelector(`.event__label`); eventPlaceholder.textContent = util.getEventTitle(evt.target.textContent); const eventDetailsElement = this._eventElement.querySelector(`.event__details`); const sectionDestinationElement = this._eventElement.querySelector(`.event__section--destination`); const options = this._types.find((type) => type.name === evt.target.textContent).options ? this._types.find((type) => type.name === evt.target.textContent).options : ``; if (util.isElementContainsClass(sectionDestinationElement, `visually-hidden`)) { if (options) { eventDetailsElement.classList.remove(`visually-hidden`); } else { eventDetailsElement.classList.add(`visually-hidden`); } } util.cleanElement(offersElement); offersElement.insertAdjacentHTML(constant.Position.BEFOREEND, `${options ? this._getOffersTemplate(options) : ``}`); } }); const inputDestinationElement = this._eventElement.querySelector(`.event__input--destination`); inputDestinationElement.addEventListener(`change`, (evt) => { const newCity = this._cities.find((city) => city.name === evt.target.value); const sectionDestinationElement = this._eventElement.querySelector(`.event__section--destination`); const eventDetailsElement = this._eventElement.querySelector(`.event__details`); eventDetailsElement.classList.remove(`visually-hidden`); sectionDestinationElement.classList.remove(`visually-hidden`); util.cleanElement(sectionDestinationElement); sectionDestinationElement.insertAdjacentHTML(constant.Position.BEFOREEND, this._getDestinationTemplate(newCity)); }); } }
var appInit = function(){ var initLocInput = document.getElementById('startLoc__Input'); var searchBox = new google.maps.places.SearchBox(initLocInput); searchBox.addListener('places_changed', function(){ var places = searchBox.getPlaces(); if (places.length == 0) return; var googleMap = new GoogleMap(); places.forEach(function(place) { googleMap.map.setCenter(place.geometry.location); }); googleMap.init(); $('.startLoc').css('display','none'); }); } appInit();
var classfsml_1_1Machine = [ [ "Machine", "classfsml_1_1Machine.html#a0666d3b6834e968bd0fe1461164de7ef", null ], [ "Machine", "classfsml_1_1Machine.html#a0c60fab103e0e65343c729ed3502ebac", null ], [ "~Machine", "classfsml_1_1Machine.html#a517f29b8c2e2b1815dd43c59a93a8390", null ], [ "addStep", "classfsml_1_1Machine.html#a863ac1a16a82e0fc0a8e85553061686f", null ], [ "getCurrentState", "classfsml_1_1Machine.html#a5bce113183b6d59b652b33f4369bb45c", null ], [ "operator FlatMachine", "classfsml_1_1Machine.html#a146384b88619887f03613f439781e9e0", null ], [ "operator<<", "classfsml_1_1Machine.html#a4c02303acf2c3bd89ffc6ceda604b02d", null ], [ "reachableFrom", "classfsml_1_1Machine.html#a7d184c839fe996141a692152b9b37e0a", null ], [ "registerAt", "classfsml_1_1Machine.html#a51b789ab95db22995529818bed9fef20", null ], [ "actionMap", "classfsml_1_1Machine.html#a02a00a80f4f77625cd1fbcb2314d3c21", null ], [ "current", "classfsml_1_1Machine.html#a8c4e7bc3c75c8b40a28d0b33a457be9d", null ], [ "stateMap", "classfsml_1_1Machine.html#a8d777492e8e8b0e79b041444f386c319", null ] ];
const { paginationResolvers } = require('@limit0/mongoose-graphql-pagination'); const moment = require('moment'); const Advertiser = require('../../models/advertiser'); const CreativeService = require('../../services/campaign-creatives'); const Campaign = require('../../models/campaign'); const Story = require('../../models/story'); const Contact = require('../../models/contact'); const Publisher = require('../../models/publisher'); const Image = require('../../models/image'); const Placement = require('../../models/placement'); const User = require('../../models/user'); const analytics = require('../../services/analytics'); const campaignDelivery = require('../../services/campaign-delivery'); const contactNotifier = require('../../services/contact-notifier'); const getNotifyDefaults = async (advertiserId, user) => { const advertiser = await Advertiser.strictFindById(advertiserId); const internal = await advertiser.get('notify.internal'); const external = await advertiser.get('notify.external'); const notify = { internal: internal.filter(c => !c.deleted), external: external.filter(c => !c.deleted), }; const contact = await Contact.getOrCreateFor(user); notify.internal.push(contact.id); return notify; }; module.exports = { /** * */ Campaign: { advertiser: campaign => Advertiser.findById(campaign.advertiserId), notify: async (campaign) => { const internal = await Contact.find({ _id: { $in: campaign.notify.internal }, deleted: false, }); const external = await Contact.find({ _id: { $in: campaign.notify.external }, deleted: false, }); return { internal, external }; }, hash: campaign => campaign.pushId, story: campaign => Story.findById(campaign.storyId), requires: campaign => campaign.getRequirements(), primaryImage: (campaign) => { const imageIds = campaign.creatives.filter(cre => cre.active).map(cre => cre.imageId); if (!imageIds[0]) return null; return Image.findById(imageIds[0]); }, publishers: async (campaign, { pagination, sort }) => { const placementIds = campaign.get('criteria.placementIds'); const publisherIds = await Placement.distinct('publisherId', { _id: { $in: placementIds }, deleted: false }); const criteria = { _id: { $in: publisherIds } }; return Publisher.paginate({ pagination, criteria, sort }); }, metrics: campaign => analytics.retrieveMetrics({ cid: campaign._id }), reports: campaign => campaign, creatives: campaign => campaign.creatives.filter(cre => !cre.deleted), createdBy: campaign => User.findById(campaign.createdById), updatedBy: campaign => User.findById(campaign.updatedById), }, /** * */ CampaignReportByDay: { day: ({ day }, { format }) => moment(day).format(format), }, /** * */ CampaignReports: { byDay: (campaign, { startDate, endDate }) => { const criteria = { cid: campaign._id }; return analytics.runCampaignByDayReport(criteria, { startDate, endDate }); }, }, CampaignCriteria: { placements: criteria => Placement.find({ _id: criteria.get('placementIds') }), }, CampaignCreative: { image: creative => Image.findById(creative.imageId), metrics: creative => analytics .retrieveMetrics({ cre: creative._id, cid: creative.campaignId }), reports: creative => creative, }, /** * */ CampaignCreativeReports: { byDay: (creative, { startDate, endDate }) => { const criteria = { cre: creative._id, cid: creative.campaignId }; return analytics.runCampaignByDayReport(criteria, { startDate, endDate }); }, }, /** * */ CampaignConnection: paginationResolvers.connection, /** * */ Query: { /** * */ campaign: (root, { input }, { auth }) => { auth.check(); const { id } = input; return Campaign.strictFindActiveById(id); }, /** * */ campaignCreative: (root, { input }, { auth }) => { const { campaignId, creativeId } = input; auth.checkCampaignAccess(campaignId); return CreativeService.findFor(campaignId, creativeId); }, /** * */ campaignHash: async (root, { input }, { auth }) => { const { advertiserId, hash } = input; const campaign = await Campaign.strictFindActiveOne({ advertiserId, pushId: hash }); auth.checkCampaignAccess(campaign.id); return campaign; }, /** * */ allCampaigns: (root, { pagination, sort }, { auth }) => { auth.check(); const criteria = { deleted: false }; return Campaign.paginate({ criteria, pagination, sort }); }, /** * */ searchCampaigns: (root, { pagination, phrase }, { auth }) => { auth.check(); const filter = { term: { deleted: false } }; return Campaign.search(phrase, { pagination, filter }); }, /** * */ runningCampaigns: (root, { pagination, sort }, { auth }) => { auth.check(); const criteria = campaignDelivery.getDefaultCampaignCriteria(); delete criteria.paused; return Campaign.paginate({ criteria, pagination, sort }); }, /** * */ campaignsStartingSoon: (root, { pagination, sort }, { auth }) => { auth.check(); const start = moment().add(14, 'days').toDate(); const criteria = { deleted: false, 'criteria.start': { $gte: new Date(), $lte: start }, }; return Campaign.paginate({ criteria, pagination, sort }); }, /** * */ campaignsEndingSoon: (root, { pagination, sort }, { auth }) => { auth.check(); const end = moment().add(14, 'days').toDate(); const criteria = { deleted: false, ready: true, 'criteria.end': { $gte: new Date(), $lte: end }, }; return Campaign.paginate({ criteria, pagination, sort }); }, /** * */ incompleteCampaigns: (root, { pagination, sort }, { auth }) => { auth.check(); const now = new Date(); const criteria = { deleted: false, ready: false, $and: [ { $or: [ { 'criteria.end': { $exists: false } }, { 'criteria.end': null }, { 'criteria.end': { $gt: now } }, ], }, ], }; return Campaign.paginate({ criteria, pagination, sort }); }, }, /** * */ Mutation: { /** * Clones a campaign */ cloneCampaign: async (root, { input }, { auth }) => { auth.check(); const { id } = input; const doc = await Campaign.strictFindActiveById(id); return doc.clone(auth.user); }, /** * */ deleteCampaign: async (root, { input }, { auth }) => { auth.check(); const { id } = input; const campaign = await Campaign.strictFindActiveById(id); campaign.setUserContext(auth.user); return campaign.softDelete(); }, pauseCampaign: async (root, { id, paused }, { auth }) => { auth.check(); const campaign = await Campaign.strictFindActiveById(id); campaign.setUserContext(auth.user); campaign.paused = paused; return campaign.save(); }, /** * */ createExternalUrlCampaign: async (root, { input }, { auth }) => { auth.check(); const { name, advertiserId } = input; const notify = await getNotifyDefaults(advertiserId, auth.user); const campaign = new Campaign({ name, advertiserId, criteria: {}, notify, }); campaign.setUserContext(auth.user); await campaign.save(); contactNotifier.sendInternalCampaignCreated({ campaign }); contactNotifier.sendExternalCampaignCreated({ campaign }); return campaign; }, /** * */ createExistingStoryCampaign: async (root, { input }, { auth }) => { auth.check(); const { name, storyId } = input; const story = await Story.strictFindActiveById(storyId); const { advertiserId } = story; const notify = await getNotifyDefaults(advertiserId, auth.user); const campaign = new Campaign({ name, advertiserId, storyId, criteria: {}, notify, }); campaign.setUserContext(auth.user); campaign.creatives.push({ title: story.title ? story.title.slice(0, 75) : undefined, teaser: story.teaser ? story.teaser.slice(0, 255) : undefined, imageId: story.primaryImageId, active: story.title && story.teaser && story.imageId, }); await campaign.save(); contactNotifier.sendInternalCampaignCreated({ campaign }); contactNotifier.sendExternalCampaignCreated({ campaign }); return campaign; }, /** * */ createNewStoryCampaign: async (root, { input }, { auth }) => { auth.check(); const { name, advertiserId, publisherId } = input; const notify = await getNotifyDefaults(advertiserId, auth.user); const story = new Story({ title: 'Placeholder Story', advertiserId, publisherId, placeholder: true, }); story.setUserContext(auth.user); await story.save(); const campaign = new Campaign({ name, storyId: story.id, advertiserId, criteria: {}, notify, }); campaign.setUserContext(auth.user); await campaign.save(); contactNotifier.sendInternalCampaignCreated({ campaign }); contactNotifier.sendExternalCampaignCreated({ campaign }); return campaign; }, /** * */ updateCampaign: async (root, { input }, { auth }) => { auth.check(); const { id, payload } = input; const campaign = await Campaign.strictFindActiveById(id); campaign.setUserContext(auth.user); campaign.set(payload); return campaign.save(); }, /** * */ assignCampaignValue: async (root, { input }, { auth }) => { const { id, field, value } = input; const campaign = await Campaign.strictFindActiveById(id); if (auth.user) { campaign.setUserContext(auth.user); } campaign.set(field, value); return campaign.save(); }, /** * */ campaignCriteria: async (root, { input }, { auth }) => { auth.check(); const { campaignId, payload } = input; const campaign = await Campaign.strictFindActiveById(campaignId); campaign.setUserContext(auth.user); campaign.criteria = payload; await campaign.save(); return campaign.criteria; }, campaignUrl: async (root, { input }, { auth }) => { const { campaignId, url } = input; auth.checkCampaignAccess(campaignId); const campaign = await Campaign.strictFindActiveById(campaignId); campaign.setUserContext(auth.user); campaign.url = url; return campaign.save(); }, /** * */ addCampaignCreative: (root, { input }, { auth }) => { const { campaignId, payload } = input; auth.checkCampaignAccess(campaignId); return CreativeService.createFor(campaignId, payload); }, /** * */ removeCampaignCreative: async (root, { input }, { auth }) => { const { campaignId, creativeId } = input; auth.checkCampaignAccess(campaignId); await CreativeService.removeFrom(campaignId, creativeId); return 'ok'; }, /** * */ campaignCreativeStatus: async (root, { input }, { auth }) => { const { campaignId, creativeId, active } = input; auth.checkCampaignAccess(campaignId); return CreativeService.setStatusFor(campaignId, creativeId, active); }, /** * */ campaignCreativeDetails: async (root, { input }, { auth }) => { const { campaignId, creativeId, payload } = input; auth.checkCampaignAccess(campaignId); const { title, teaser, active } = payload; return CreativeService.updateDetailsFor(campaignId, creativeId, { title, teaser, active }); }, /** * */ campaignCreativeImage: async (root, { input }, { auth }) => { const { campaignId, creativeId, imageId } = input; auth.checkCampaignAccess(campaignId); return CreativeService.updateImageFor(campaignId, creativeId, imageId); }, /** * */ campaignContacts: async (root, { input }, { auth }) => { auth.check(); const { id, type, contactIds } = input; const field = `notify.${type}`; const campaign = await Campaign.strictFindActiveById(id); campaign.set(field, contactIds); campaign.setUserContext(auth.user); return campaign.save(); }, campaignExternalContact: async (root, { input }, { auth }) => { const { campaignId, payload } = input; const { email, givenName, familyName } = payload; auth.checkCampaignAccess(campaignId); const campaign = await Campaign.strictFindActiveById(campaignId); const contact = await Contact.findOneAndUpdate({ email, deleted: false }, { $set: { familyName, givenName, name: `${givenName} ${familyName}`, }, $setOnInsert: { email, deleted: false }, }, { new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true, }); if (auth.user) { campaign.setUserContext(auth.user); } campaign.get('notify.external').push(contact.id); return campaign.save(); }, removeCampaignExternalContact: async (root, { input }, { auth }) => { const { campaignId, contactId } = input; auth.checkCampaignAccess(campaignId); const campaign = await Campaign.strictFindActiveById(campaignId); campaign.removeExternalContactId(contactId); if (auth.user) { campaign.setUserContext(auth.user); } return campaign.save(); }, }, };
import {combineReducers} from 'redux' import campusReducer from './campusReducer' import studentsReducer from './studentsReducer' export default combineReducers({ data: campusReducer, students: studentsReducer })
const BFX = require("bitfinex-api-node"); const symbols = require("./bfx-symbols"); const db = require("../util/database"); /** * Get OHLC from BFXws * * @param {String} slice Websocket must be split into 50 instruments at a time. Slice is the number of 50 multiples. i.e 1 = 0-49 * @public */ class Candles { constructor(slice) { const bfx = new BFX({ apiKey: "...", apiSecret: "...", ws: { autoReconnect: true, seqAudit: true, packetWDDelay: 10 * 1000 } }); this.ws = bfx.ws(2, { manageCandles: true, // Enable candle dataset persistence/management transform: true // Converts ws data arrays to Candle models (and others) }); this.slice = slice; this._getData(); } /** * Fetch candle data from BFXws * * @private */ _getData() { symbols.getSymbols(this.slice, instList => { console.log( `Slice[${this.slice}] fetching ${instList.length} instruments` ); if (instList.length > 0) { this.ws.on("error", err => console.log(err)); for (let i = 0; i < instList.length; i++) { this.ws.on("open", () => { this.ws.subscribeCandles(`trade:1D:${instList[i]}`); }); } instList.forEach(ticker => { this.ws.onCandle({ key: `trade:1D:${ticker}` }, candles => { try { // Get previous candle and save to database const c = candles[1]; const c_live = candles[0] this._updateLiveToDb(ticker, c) console.log(ticker, new Date(c_live.mts), c_live.close) this._updateLiveToDb(ticker, c_live) } catch (err) { console.log(err); } } ); }); this.ws.open(); } }); } /** * Save candle data to db * * @param {String} ticker Ticker string to be added to database * @param {object} candle Candle data from BFX, will contain dt, OHLC and volume in some weird order * @private */ _saveToDb(ticker, candle) { db.getDb() .collection("Price") .insertOne({ Date_Time: new Date(candle.mts), Ticker: ticker, Open: candle.open, High: candle.high, Low: candle.low, Close: candle.close, Volume: candle.volume, Exchange_ID: "BFX", TimeFrame: "D" }) .then() .catch(err => {}); }; /** * Update candle data to db * * @param {String} ticker Ticker string to be added to database * @param {object} candle Candle data from BFX, will contain dt, OHLC and volume in some weird order * @private */ _updateLiveToDb(ticker, candle) { db.getDb() .collection("Price") .updateOne({ Date_Time: new Date(candle.mts), Ticker: ticker, Exchange_ID: "BFX", TimeFrame: "D" }, { $set: { Date_Time: new Date(candle.mts), Ticker: ticker, Open: candle.open, High: candle.high, Low: candle.low, Close: candle.close, Volume: candle.volume, Exchange_ID: "BFX", TimeFrame: "D" } }, { upsert: true }) .then() .catch(err => {}); }; } exports.Candles = Candles;
export const getPosts = (state) => state.posts; export const getPost = (postSeq) => (state) => state.posts.find((v) => v.seq == postSeq);
import React, { Component } from "react"; import "../Style/me.css"; class Me extends Component { state = { logos: [ { name: "HTML", src: "logo_html.png" }, { name: "CSS", src: "logo_css.png" }, { name: "SCSS", src: "logo_scss.png" }, { name: "JavaScript", src: "logo_js.png" }, { name: "jQuery", src: "logo_jquery.png" }, { name: "React JS", src: "logo_react.png" }, { name: "PHP", src: "logo_php.png" }, { name: "MySQL/PDO", src: "logo_db.png" }, { name: "Wordpress", src: "logo_wp.png" } ] }; render() { return ( <React.Fragment> <div className="me-title-container"> <h1>Ricky Simadinata</h1> </div> <div className="me-content-container"> <div id="me-about" className="me-content-items"> <h2>Hello.</h2> <br /> <p>I am Ricky.</p> <p>Let me tell you about myself.</p> <br /> <p> I was born in Yogyakarta, Indonesia on 13 September 1999. I lived and was raised by my only beloved single parent mother for 15 years. In 2015 I moved to the Netherland. </p> <br /> <p> Moving to the Netherland open up a new chapter in my life that I have never expected before. I dreamt to become a journalist back in Indonesia, so at the time I moved I didn't know what the heck I am gonna do with in life. </p> <br /> <p> After 2 years of confusion, the door to development world was open for me. I am currently studying webdevelopment at Grafisch Lyceum Utrecht. </p> <br /> <p> Other things about myself is I like to game and to play basketball. </p> </div> <div className="me-skill me-content-items"> <h2>How am I doing so far?</h2> {this.state.logos.map(logo => ( <div className="me-skill-items"> <figure> <img src={require("../Images/" + logo.src)} alt={logo.name} /> </figure> <h4>{logo.name}</h4> </div> ))} </div> </div> </React.Fragment> ); } } export default Me;
var a = "relative_path in subdir";
'use strict' //Функция проверяет является числом или нет let isNumber = function(n) { return !isNaN(parseFloat(n)) & isFinite(n) } //Функция проверяет является буквой или нет let isStr = function(str) { let reg = /^[a-zA-Zа-яА-Я ,]+$/ return reg.test(str) } let buttonСalculate = document.querySelector('#start'), buttonPlus = document.getElementsByTagName('button'), buttonAddIncome = buttonPlus[0], buttonAddExpenses = buttonPlus[1], checkboxDeposit = document.querySelector('#deposit-check'), inputAdditionalIncome = document.querySelectorAll('.additional_income-item'), inputBudgetMonth = document.querySelector('.salary-amount'), inputIncomeTitle = document.querySelector('.income-title'), inputIncomeAmount = document.querySelector('.income-amount'), inputExpensesTitle = document.querySelector('.expenses-title'), expensesItems = document.querySelectorAll('.expenses-items'), inputAdditionalExpensesItem = document.querySelector('.additional_expenses-item'), inputTargetAmount = document.querySelector('.target-amount'), rangePeriodSelect = document.querySelector('.period-select'), resultBudgetMonth = document.querySelector('.budget_month-value'), resultBudgetDay = document.querySelector('.budget_day-value'), resultExpensesMonth = document.querySelector('.expenses_month-value'), resultAdditionalIncome = document.querySelector('.additional_income-value'), resultAdditionalExpenses = document.querySelector('.additional_expenses-value'), resultIncomePeriod = document.querySelector('.income_period-value'), resultTargetMonth = document.querySelector('.target_month-value') let appData = { budget: 0, budgetDay: 0, budgetMonth: 0, income: {}, addIncome: [], expenses: {}, expensesMonth: 0, addExpenses: [], deposit: false, percentDeposite: 0, moneyDeposite: 0, mission: 100000, period: 12, //Функция спрашивает пользователя его доход за месяц start: function() { if (inputBudgetMonth.value === '') { alert('Ошибка, поле "Месячный доход" должно быть заполнено!') return } appData.budget = inputBudgetMonth.value appData.getExpenses() // appData.asking() // appData.getExpensesMonth() // appData.getBudget() }, addExpensesBlock: function() { let expensesItems = document.querySelectorAll('.expenses-items'), cloneExpensesItem = expensesItems[0].cloneNode(true) expensesItems[0].parentNode.insertBefore(cloneExpensesItem, buttonAddExpenses) expensesItems = document.querySelectorAll('.expenses-items') if(expensesItems.length === 3) { buttonAddExpenses.style.display = 'none' } }, getExpenses: function() { expensesItems.forEach(function(item) { console.log(item) }) }, asking: function() { if (confirm('Есть ли у Вас дополнительный заработок?')) { let incomeName, incomeAmount do { incomeName = prompt('Какой у Вас дополнительный заработок?', 'Играю на пианино') } while (!isStr(incomeName)) do { incomeAmount = parseInt(prompt('Сколь Вы зарабатываете в месяц на ' + incomeName + '?',10000)) } while (!isNumber(incomeAmount)) appData.income[incomeAmount] = incomeName } let addExpenses do { addExpenses = prompt('Перечислите возможные расходы за рассчитываемый период через запятую', ['Интернет','Мобильная связь','Питание','Коммунальные платежи']) } while (!isStr(addExpenses)) appData.addExpenses = addExpenses.toLowerCase().split(',').map(i => i.trim()) appData.deposit = confirm('Есть ли у вас депозит в банке?') let expensesName, expensesAmount for(let i = 0; i < 2; i ++) { do { expensesName = prompt('Введите обязательную статью расходов?') } while (!isStr(expensesName)) do { expensesAmount = parseInt(prompt('Во сколько обойдется' + ' ' + expensesName + '?', 1000)) } while (!isNumber(expensesAmount)) appData.expenses[expensesName] = expensesAmount } }, //Возвращает сумму всех обязательных расходов за месяц getExpensesMonth: function() { let accum = 0 for (let key in appData.expenses) { accum += appData.expenses[key] } appData.expensesMonth = accum }, //Возвращает Накопления за месяц (Доходы минус расходы) getBudget: function() { appData.budgetMonth = appData.budget - appData.expensesMonth appData.budgetDay = Math.ceil(appData.budgetMonth / 30) }, //Подсчитывает за какой период будет достигнута цель, зная результат месячного накопления getTargetMonth: function() { return (Math.ceil(appData.mission / appData.budgetMonth)) }, getInfoDeposite: function() { if (appData.deposit) { do { appData.percentDeposite = parseInt(prompt('Какой у Вас годовой процент?', '10')) } while (!isNumber(appData.percentDeposite)) do { appData.moneyDeposite = parseInt(prompt('Какая сумма заложена?', 10000)) } while (!isNumber(appData.moneyDeposite)) } }, calcSavedMoney: function() { return (appData.budgetMonth * appData.period) } } buttonСalculate.addEventListener('click', appData.start) buttonAddExpenses.addEventListener('click', appData.addExpensesBlock) // appData.getInfoDeposite() // if (appData.getTargetMonth() > 0) { // alert('Цель будет достигнута за: ' + appData.getTargetMonth() + ' ' + 'месяцев') // } else { // alert('Цель не будет достигнута') // }
const rp = require('request-promise'); const cheerio = require('cheerio'); exports.run = (client,message,args) =>{ //total number of available memes = 2236 let rand = (Math.round(Math.random()*10000))%2236; if(rand==0){ message.channel.send("Unlucky day, Sorry!"); return; } let options = { uri : `https://xkcd.com/${rand}`, headers : { 'User-Agent' : 'Mozilla/5.0' } } rp(options).then(html => { const $ = cheerio.load(html); let link = $("#comic img").attr('src'); let title = $("#comic img").attr('title'); link = "https:"+link; message.channel.send(title,{ files : [link] }); }).catch(err => console.error); } exports.info = "Fetch a random image from internet, if you are unlucky then return a message";
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /*********************************************************************************************** * Portal Ajax Response Data Structure * {PortalResponse} * | * |--->{PortletResponse} * | * |--->{PortletResponse} * | |-->{portletId} * | | * | |-->{PortletResponseData} * | | * | |--->{BlockToUpdate} * | | |-->{BlockToUpdateId} * | | |-->{BlockToUpdateData} * | | * | |--->{BlockToUpdate} * | * |--->{PortalResponseData} * | | * | |--->{BlockToUpdate} * | | |-->{BlockToUpdateId} * | | |-->{BlockToUpdateData} * | | * | |--->{BlockToUpdate} * |--->{PortalResponseScript} * **************************************************************************************************/ /* * This object is wrapper on the value of each HTML block * returned by an eXo Portal AJAX call. * * This includes: * - the portle ID * - the portlet title * - the portlet mode * - the portlet state * - the portlet content * - the updated scripts to dynamically load in the browser * * Then each block to update within the portlet are place in a object * which is itself placed inside an array to provide an OO view of the * AJAX response */ function PortletResponse(responseDiv) { var DOMUtil = eXo.core.DOMUtil ; var div = eXo.core.DOMUtil.getChildrenByTagName(responseDiv, "div") ; this.portletId = div[0].innerHTML ; this.portletData = div[1].innerHTML ; this.blocksToUpdate = null ; var blocks = DOMUtil.findChildrenByClass(div[1], "div", "BlockToUpdate") ; if(blocks.length > 0 ) { this.blocksToUpdate = new Array() ; for(var i = 0 ; i < blocks.length; i++) { var obj = new Object() ; var div = eXo.core.DOMUtil.getChildrenByTagName(blocks[i], "div") ; obj.blockId = div[0].innerHTML ; obj.data = div[1] ; this.blocksToUpdate[i] = obj ; this.blocksToUpdate[i].scripts = eXo.core.DOMUtil.findDescendantsByTagName(div[1], "script") ; } } else { /* * If there is no block to update it means we are in a JSR 286 / 168 portlet * In that case we need to find all the script tags and dynamically execute them. * * Indeed, when being in an AJAX call that return some <script> tag, local functions are * lost when calling the eval() methods. When the code is written by eXo we use * global scoped funstions like "instance.myFunction = function(arguments)". * * But when the code is provided by a third party portlet, it is not possible to * force that good practise. Hence we have to dynamically reference the embedded * script in the head tag */ this.scripts = eXo.core.DOMUtil.findDescendantsByTagName(div[1], "script") ; } }; /*****************************************************************************************/ /* * This object is an OO wrapper on top of the returning HTML included in the PortalResponse * tag. * * It allows to split in two different arrays the portletResponse blocks and the one and the * PortalResponseData one * * It also extract from the HTML the javascripts script to then be dynamically evaluated */ function PortalResponse(responseDiv) { var DOMUtil = eXo.core.DOMUtil ; this.portletResponses = new Array() ; var div = DOMUtil.getChildrenByTagName(responseDiv, "div") ; for(var i = 0 ; i < div.length; i++) { if(div[i].className == "PortletResponse") { this.portletResponses[this.portletResponses.length] = new PortletResponse(div[i]) ; } else if(div[i].className == "PortalResponseData") { this.data = div[i] ; var blocks = DOMUtil.findChildrenByClass(div[i], "div", "BlockToUpdate") ; this.blocksToUpdate = new Array() ; for(var j = 0 ; j < blocks.length; j++) { var obj = new Object() ; var dataBlocks = DOMUtil.getChildrenByTagName(blocks[j], "div") ; obj.blockId = dataBlocks[0].innerHTML ; obj.data = dataBlocks[1] ; this.blocksToUpdate[j] = obj ; /* * handle embeded javascripts to dynamically add them to the page head * * This is needed when we refresh an entire portal page that contains some * standard JSR 168 / 286 portlets with embeded <script> tag */ this.blocksToUpdate[j].scripts = eXo.core.DOMUtil.findDescendantsByTagName(dataBlocks[1], "script") ; } } else if(div[i].className == "PortalResponseScript") { this.script = div[i].innerHTML ; div[i].style.display = "none" ; } } }; /* * This function is used to dynamically append a script to the head tag * of the page */ function appendScriptToHead(scriptId, scriptElement) { var head = document.getElementsByTagName("head")[0]; var descendant = eXo.core.DOMUtil.findDescendantById(head, scriptId); var script; if(descendant) { head.removeChild(descendant) ; } script = document.createElement('script'); script.id = scriptId; script.type = 'text/javascript'; //check if contains source attribute if(scriptElement.src) { script.src = scriptElement.src } else { script.text = scriptElement.innerHTML; } head.appendChild(script); }; /*****************************************************************************************/ /* * This is the main object that acts both as a field wrapper and a some status method wrapper * * It is also the object that has the reference to the XHR request thanks to a reference to * the eXo.core.Browser object */ function AjaxRequest(method, url, queryString) { var instance = new Object() ; instance.timeout = 80000 ; instance.aborted = false ; if(method != null) instance.method = method; else instance.method = "GET" ; if(url != null) instance.url = url; else instance.url = window.location.href ; if(queryString != null) instance.queryString = queryString; else instance.queryString = null ; instance.request = null ; instance.responseReceived = false ; instance.status = null ; instance.statusText = null ; instance.responseText = null ; instance.responseXML = null ; instance.onTimeout = null ; instance.onLoading = null ; instance.onLoaded = null ; instance.onInteractive = null ; instance.onComplete = null ; instance.onSuccess = null ; instance.callBack = null ; instance.onError = null; instance.isAsynchronize = function() { var isASync = false; var name = "ajax_async"; name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( instance.url ); if( results != null ) { isASync = (results[1] == "true") ? true : false; } return isASync; }; instance.onLoadingInternalHandled = false ; instance.onLoadedInternalHandled = false ; instance.onInteractiveInternalHandled = false ; instance.onCompleteInternalHandled = false ; instance.request = eXo.core.Browser.createHttpRequest() ; /* * This method is called several times during the AJAX request call, in * fact each time the request state changes. In each case the call is * delegated to one of the method of the AjaxRequest instance */ instance.request.onreadystatechange = function() { if (instance == null || instance.request == null) { return; } if (instance.request.readyState == 1) { instance.onLoadingInternal(instance) ; } if (instance.request.readyState == 2) { instance.onLoadedInternal(instance) ; } if (instance.request.readyState == 3) { instance.onInteractiveInternal(instance) ; } if (instance.request.readyState == 4) { instance.onCompleteInternal(instance) ; } } ; /* * This method is executed only if the boolean "onLoadingInternalHandled" is set to false * The method delegate the call to the ajaxLoading() method of the HttpResponseHandler */ instance.onLoadingInternal = function() { if (instance.onLoadingInternalHandled) return ; if (typeof(instance.onLoading) == "function") instance.onLoading(instance) ; instance.onLoadingInternalHandled = true ; } ; /* * This method is executed only if the boolean "onLoadedInternalHandled" is set to false * The method delegate the call to the instance.onLoaded() which is null for now */ instance.onLoadedInternal = function() { if (instance.onLoadedInternalHandled) return ; if (typeof(instance.onLoaded) == "function") instance.onLoaded(instance) ; instance.onLoadedInternalHandled = true ; } ; /* * This method is executed only if the boolean "onInteractiveInternalHandled" is set to false * The method delegate the call to the instance.onInteractive() which is null for now */ instance.onInteractiveInternal = function() { if (instance.onInteractiveInternalHandled) return ; if (typeof(instance.onInteractive) == "function") instance.onInteractive(instance) ; instance.onInteractiveInternalHandled = true ; } ; /** * evaluate the response and return an object */ instance.evalResponse = function() { try { return eval((instance.responseText || '')); } catch (e) { throw (new Error('Cannot eval the response')) ; } }; /* * This method is executed only if the boolean "onCompleteInternalHandled" is set to false * The method delegate the call to the ajaxResponse() method of the HttpResponseHandler after * calling the onSuccess() method of the current object * * During the processof this method, all the instance fields are filled with the content coming * back from the AJAX call. Once the ajaxResponse() is called then the callback object is called * if not null */ instance.onCompleteInternal = function() { if (instance.onCompleteInternalHandled || instance.aborted) return ; try{ instance.responseReceived = true ; instance.status = instance.request.status ; instance.statusText = instance.request.statusText ; instance.responseText = instance.request.responseText ; instance.responseXML = instance.request.responseXML ; }catch(err){ instance.status = 0; } if(typeof(instance.onComplete) == "function") instance.onComplete(instance) ; if (instance.status == 200 && typeof(instance.onSuccess) == "function") { instance.onSuccess(instance) ; instance.onCompleteInternalHandled = true ; if (typeof(instance.callBack) == "function") { instance.callBack(instance) ; } else if (instance.callBack) { // Modified by Uoc Nguyen: allow user use custom javascript code for callback try { eval(instance.callBack) ; } catch (e) { throw (new Error('Can not execute callback...')) ; } } } else if (typeof(instance.onError) == "function") { instance.onError(instance) ; instance.onCompleteInternalHandled = false ; } // Remove IE doesn't leak memory delete instance.request['onreadystatechange'] ; instance.request = null ; } ; /* * This method is executed only if the boolean "onLoadingInternalHandled" is set to false * The method delegate the call to the ajaxTimeout() method of the HttpResponseHandler */ instance.onTimeoutInternal = function() { if (instance == null || instance.request == null || instance.onCompleteInternalHandled) return ; instance.aborted = true ; instance.request.abort() ; if (typeof(instance.onTimeout) == "function") instance.onTimeout(instance) ; delete instance.request['onreadystatechange'] ; instance.request = null ; } ; /* * This method is directly called from the doRequest() method. It opens a connection to the server, * set up the handlers and sends the query to it. Status methods are then called on the request object * during the entire lifecycle of the call * * It also sets up the time out and its call back to the method of the current instance onTimeoutInternal() */ instance.process = function() { if (instance.request == null) return; instance.request.open(instance.method, instance.url, true); //instance.request.open(instance.method, instance.url, instance.isAsynchronize()); if (instance.method == "POST") { instance.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") ; } else { instance.request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8") ; } if (instance.timeout > 0) setTimeout(instance.onTimeoutInternal, instance.timeout) ; instance.request.send(instance.queryString); } ; return instance ; } ; /*****************************************************************************************/ /* * This object is also a wrapper object on top of several methods: * - executeScript * - updateBlocks * - ajaxTimeout * - ajaxResponse * - ajaxLoading * * Those methods are executed during the process of the AJAX call */ function HttpResponseHandler(){ var instance = new Object() ; /* * instance.to stores a timeout object used to postpone the display of the loading popup * the timeout is defined later in the instance.ajaxLoading function */ instance.to = null; /* * This internal method is used to dynamically load JS scripts in the * browser by using the eval() method; */ instance.executeScript = function(script) { if(script == null || script == "") return ; try { eval(script) ; return; } catch(err) { } var elements = script.split(';') ; if(elements != null && elements.length > 0) { for(var i = 0; i < elements.length; i++) { try { eval(elements[i]) ; } catch(err) { alert(err +" : "+elements[i] + " -- " + i) ; } } } } ; /* * This methods will replace some block content by new one. * This is the important concept in any AJAX call where JS is used to dynamically * refresh a part of the page. * * The first argument is an array of blocks to update while the second argument is * the id of the html component that is the parent of the block to update * * Each block in the array contains the exact id to update, hence a loop is executed * for each block and the HTML is then dynamically replaced by the new one */ instance.updateBlocks = function(blocksToUpdate, parentId) { if(blocksToUpdate == null) return ; var parentBlock = null ; if(parentId != null && parentId != "") parentBlock = document.getElementById(parentId) ; for(var i = 0; i < blocksToUpdate.length; i++) { var blockToUpdate = blocksToUpdate[i] ; // alert("block update" + blockToUpdate.blockId) ; var target = null ; if(parentBlock != null) { target = eXo.core.DOMUtil.findDescendantById(parentBlock, blockToUpdate.blockId) ; } else { target = document.getElementById(blockToUpdate.blockId) ; } if(target == null) alert(eXo.i18n.I18NMessage.getMessage("TargetBlockNotFound", new Array (blockToUpdate.blockId))) ; var newData = eXo.core.DOMUtil.findDescendantById(blockToUpdate.data, blockToUpdate.blockId) ; //var newData = blockToUpdate.data.getElementById(blockToUpdate.blockId) ; if(newData == null) alert(eXo.i18n.I18NMessage.getMessage("BlockUpdateNotFound", new Array (blockToUpdate.blockId))) ; // target.parentNode.replaceChild(newData, target); target.innerHTML = newData.innerHTML ; //update embedded scripts if(blockToUpdate.scripts) { if(blockToUpdate.scripts.length > 0) { for(var k = 0 ; k < blockToUpdate.scripts.length; k++) { var encodedName = 'script_' + k + '_' + blockToUpdate.blockId; appendScriptToHead(encodedName, blockToUpdate.scripts[k]); } } } } } ; /* * This method is called when the AJAX call was too long to be executed */ instance.ajaxTimeout = function(request){ // eXo.core.UIMaskLayer.removeMask(eXo.portal.AjaxRequest.maskLayer) ; eXo.core.UIMaskLayer.removeMasks(eXo.portal.AjaxRequest.maskLayer) ; eXo.portal.AjaxRequest.maskLayer = null ; eXo.portal.CurrentRequest = null ; window.location.reload() ; } /* * This method is called when the AJAX call is completed and that the request.responseText * has been filled with the returning HTML. Hence the goal of this method is to update the * diffent blocks dynamically. * * 1) Create a temporary div element and set the response HTML text to its innerHTML variable of the temp object * 2) Use the DOMUtil.findFirstDescendantByClass() method to get the div with the Id "PortalResponse" * out of the returned HTML * 3) Create the PortalResponse object by passing the previous DOM element as an argumen, it will * provide an OO view of the PortletResponse and other portal response blocks to update * 4) Each portlet response block is the updated using the naming convention "UIPortlet-" + portletId; * and then the script are loaded * 5) Then it is each portal block which is updated and the assocaited scripts are evaluated */ instance.ajaxResponse = function(request){ var temp = document.createElement("div") ; temp.innerHTML = this.request.responseText ; var responseDiv = eXo.core.DOMUtil.findFirstDescendantByClass(temp, "div", "PortalResponse") ; var response = new PortalResponse(responseDiv) ; //Handle the portlet responses var portletResponses = response.portletResponses ; if(portletResponses != null) { for(var i = 0; i < portletResponses.length; i++) { var portletResponse = portletResponses[i] ; if(portletResponse.blocksToUpdate == null) { /* * This means that the entire portlet fragment is included in the portletResponse.portletData * and that it does not contain any finer block to update. Hence replace the innerHTML inside the * id="PORTLET-FRAGMENT" block */ var parentBlock = document.getElementById(portletResponse.portletId) ; var target = eXo.core.DOMUtil.findFirstDescendantByClass(parentBlock, "div", "PORTLET-FRAGMENT") ; target.innerHTML = portletResponse.portletData; //update embedded scripts if(portletResponse.scripts) { if(portletResponse.scripts.length > 0) { for(var k = 0 ; k < portletResponse.scripts.length; k++) { var encodedName = 'script_' + k + '_' + portletResponse.portletId; appendScriptToHead(encodedName, portletResponse.scripts[k]); } } } } else { /* * Else updates each block with the portlet */ instance.updateBlocks(portletResponse.blocksToUpdate, portletResponse.portletId) ; } } } if(response.blocksToUpdate == undefined && temp.innerHTML !== "") { if(confirm(eXo.i18n.I18NMessage.getMessage("SessionTimeout"))) instance.ajaxTimeout(request) ; } //Handle the portal responses instance.updateBlocks(response.blocksToUpdate) ; instance.executeScript(response.script) ; /** * Clears the instance.to timeout if the request takes less time than expected to get response * Removes the transparent mask so the UI is available again, with cursor "auto" */ clearTimeout(instance.to); // eXo.core.UIMaskLayer.removeTransparentMask(); // eXo.core.UIMaskLayer.removeMask(eXo.portal.AjaxRequest.maskLayer) ; eXo.core.UIMaskLayer.removeMasks(eXo.portal.AjaxRequest.maskLayer) ; eXo.portal.AjaxRequest.maskLayer = null ; eXo.portal.CurrentRequest = null ; } ; /* * This method is called when doing an AJAX call, it will put the "Loading" image in the * middle of the page for the entire call of the request */ instance.ajaxLoading = function(request) { if (request.isAsynchronize()) return; /** * Waits 2 seconds (2000 ms) to display the loading popup * if the response comes before this timeout, the loading popup won't appear at all * Displays a transparent mask with the "wait" cursor to tell the user something is processing * * Modified by Truong LE to avoid double click problem */ Browser = eXo.core.Browser; if(eXo.portal.AjaxRequest.maskLayer == null ){ eXo.portal.AjaxRequest.maskLayer = eXo.core.UIMaskLayer.createTransparentMask(); } instance.to = setTimeout(function() { if(eXo.portal.AjaxRequest.maskLayer != null) { eXo.core.UIMaskLayer.showAjaxLoading(eXo.portal.AjaxRequest.maskLayer); } }, 2000); } return instance ; } ; /*****************************************************************************************/ /* * This is the main entry method for every Ajax calls to the eXo Portal * * It is simply a dispatcher method that fills some init fields before * calling the doRequest() method */ function ajaxGet(url, callback) { if (!callback) callback = null ; doRequest("Get", url, null, callback) ; } ; /* * This method is called when a HTTP POST should be done but in an AJAX * case some maniputalions are needed * Once the content of the form is placed into a string object, the call * is delegated to the doRequest() method */ function ajaxPost(formElement, callback) { if (!callback) callback = null ; var queryString = eXo.webui.UIForm.serializeForm(formElement) ; var url = formElement.action + "&ajaxRequest=true" ; doRequest("POST", url, queryString, callback) ; } ; /* * The doRequest() method takes incoming request from GET and POST calls * The second argument is the URL to target on the server * The third argument is the query string object which is created out of * a form element, this value is not null only when there is a POST request. * * 1) An AjaxRequest object is instanciated, it holds the reference to the * XHR method * 2) An HttpResponseHandler object is instantiated and its methods like * ajaxResponse, ajaxLoading, ajaxTimeout are associated with the one from * the AjaxRequest and will be called by the XHR during the process method */ function doRequest(method, url, queryString, callback) { request = new AjaxRequest(method, url, queryString) ; handler = new HttpResponseHandler() ; request.onSuccess = handler.ajaxResponse ; request.onLoading = handler.ajaxLoading ; request.onTimeout = handler.ajaxTimeout ; request.callBack = callback ; eXo.portal.CurrentRequest = request ; request.process() ; eXo.session.itvDestroy() ; if(eXo.session.canKeepState && eXo.session.isOpen && eXo.env.portal.accessMode == 'private') { eXo.session.itvInit() ; } } ; /** * Abort an ajax request * @return */ function ajaxAbort() { eXo.core.UIMaskLayer.removeMasks(eXo.portal.AjaxRequest.maskLayer) ; eXo.portal.AjaxRequest.maskLayer = null ; eXo.portal.CurrentRequest.request.abort() ; eXo.portal.CurrentRequest.aborted = true ; eXo.portal.CurrentRequest = null ; } ; /** * Create a ajax request * @param {String} url - Url * @param {boolean} async - asynchronous or none * @return {String} response text if request is not async */ function ajaxAsyncGetRequest(url, async) { if(async == undefined) async = true ; var request = eXo.core.Browser.createHttpRequest() ; request.open('GET', url, async) ; request.setRequestHeader("Cache-Control", "max-age=86400") ; request.send(null) ; eXo.session.itvDestroy() ; if(eXo.session.canKeepState && eXo.session.isOpen && eXo.env.portal.accessMode == 'private') { eXo.session.itvInit() ; } if(!async) return request.responseText ; } /** * Redirect browser to url * @param url * @return */ function ajaxRedirect(url) { url = url.replace(/&amp;/g, "&") ; window.location.href = url ; } eXo.portal.AjaxRequest = AjaxRequest.prototype.constructor ;
import React from 'react'; import { connect } from 'react-redux'; import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import { logout } from '../components/signinandup/_actions'; import { history } from '../configureStore.js'; const styles = theme => ({ container: { textAlign: 'right', }, button: { margin: theme.spacing.unit, }, }); class Footer extends React.Component { doLogout = () => { this.props.logout(); } doProfesores = () => { history.push('/main'); } render() { const { classes } = this.props; return (<div className={ classes.container }> {this.props.token ? <div> <Button variant="contained" className={classes.button} onClick={this.doProfesores} >Profesores</Button> <Button variant="contained" color="secondary" className={classes.button} onClick={this.doLogout} >Cerrar Sesi&oacute;n</Button> </div> : null} </div>); } } const mapStateToProps = ({ auth }) => ({ token: auth.token, }); export default connect(mapStateToProps, { logout, })(withStyles(styles)(Footer));
function foo(x=11, y=31){ return x+y } foo(1); function bar(val) { return y+val; } function foo2(x=y+3, z=bar(x)) { return [x, y] } var y = 5; foo2(); foo2(10); var y =6; foo2(undefined, 10);
var RecordModel = function() { var self = this; var data = null; var recordMap = {}; var waitingMap = {}; $.ajax({ type : 'GET', url : '/padmenu/rest/record/53c645aae4b0f128d3e9a274', contentType : 'application/json', success : function(result) { data = result; initItem(data); } }); function initItem(item) { if (item.child === null || item.child.length === 0) { recordMap[item.id] = item; if (item.id in waitingMap) { waitingMap[item.id].call(item, item); delete waitingMap[item.id]; } if ('root' in waitingMap) { waitingMap.root.call(item, item); delete waitingMap['root']; } } else { getChildRecords(item.id, function(records) { item.child = records; recordMap[item.id] = item; if (item.id in waitingMap) { waitingMap[item.id].call(item, item); delete waitingMap[item.id]; } if ('root' in waitingMap) { waitingMap.root.call(item, item); delete waitingMap['root']; } for (var i in records) { initItem(records[i]); } }); } } function getChildRecords(id, load) { $.ajax({ type : 'GET', url : '/padmenu/rest/record/children/' + id, contentType : 'application/json', success : function(result) { load.call(result, result); } }); } function isInited(id) { if (id in recordMap) { var record = recordMap[id]; if (record.child === null || record.child.length === 0) { return true; } if (typeof record.child[0] === 'string') { return false; } return true; } return false; } this.get = function() { if (arguments.length === 1 && typeof arguments[0] === 'function') { var callback = arguments[0]; if (data === null) { waitingMap['root'] = callback; return; } if (isInited(data.id)) { callback.call(data, data); return; } waitingMap[data.id] = callback; } if (arguments.length === 2 && typeof arguments[1] === 'function') { var id = arguments[0]; var callback = arguments[1]; if (isInited(id)) { callback.call(recordMap[id], recordMap[id]); return; } waitingMap[id] = callback; } }; this.update = function() { var update = arguments[0]; var callback = arguments[1]; if (update.id in recordMap) { $.ajax({ type : 'POST', url : '/padmenu/rest/record', contentType : 'application/json', data : JSON.stringify(update), success : function(result) { recordMap[result.id] = result; self.fire('change', result); if (callback) { callback.call(result, result); } } }); } }; this.fire = function() { // console.log('fire', arguments); }; }; var RecordManager = function($container, model) { function initItem($container, records) { $container.empty(); for (var i in records) { var record = records[i]; var $record = $('<div class="record"/>'); $record.data('record', record); if (record.type === 'category') { $record.addClass('category'); var $e = $('<input type="checkbox" class="e">'); $e.on('change', function() { var record = $(this).parent().data('record'); var $childs = $(this).siblings('.child'); if (this.checked) { $childs.append($loading.clone()); model.get(record.id, function() { initItem($childs, this.child); }); } else { $childs.empty(); } }); $record.append($e) } var $label = $('<label>' + record.attr.name + '</label>'); $label.on('click', function() { var $view = $(this).parents('.content'); $view.find('.select').removeClass('select'); $(this).addClass('select'); }); var $childs = $('<div class="child"/>'); $record .append($label) .append($childs); $container .append($record); } } var $toolbar = $('<div class="toolbar"/>'); var $view = $('<div class="content"/>'); var $loading = $('<div class="loading"/>'); $container.addClass('manager') .append($toolbar) .append($view); $view.append($loading); model.get(function() { $container.data('record', this); initItem($view, this.child); }); };
module.exports = { facebookAuth: { clientID: 'YOUR_ID', // your App ID clientSecret: 'YOUR_ID', // your App Secret callbackURL: 'YOUR_CB' }, intraAuth: { clientID: 'YOUR_ID', // your App ID clientSecret: 'YOUR_ID', // your App Secret callbackURL: 'YOUR_CB' }, googleAuth: { clientID: 'YOUR_ID', // your App ID clientSecret: 'YOUR_ID', // your App Secret callbackURL: 'YOUR_CB' }, githubAuth: { clientID: 'YOUR_ID', // your App ID clientSecret: 'YOUR_ID', // your App Secret callbackURL: 'YOUR_CB' } }
/*! * jQuery ClassyPaypal * www.class.pm * * Written by Marius Stanciu - Sergiu <marius@class.pm> * Licensed under the MIT license www.class.pm/LICENSE-MIT * Version 1.0.0 * */ (function($, c) { function _ClassyPaypal(e, d, f) { var g = 'cmd,notify_url,bn,amount,discount_amount,discount_amount2,discount_rate,discount_rate2,discount_num,item_name,item_number,quantity,shipping,shipping2,tax,tax_rate,undefined_quantity,weight,weight_unit,on*,os*,option_index,option_select*,option_amount*,business,currency_code,a*,p*,t*,src,srt,sra,no_note,custom,invoice,modify,usr_manage,page_style,image_url,cpp_cart_border_color,cpp_header_image,cpp_headerback_color,cpp_headerborder_color,cpp_logo_image,cpp_payflow_color,lc,cn,no_shipping,return,rm,cbt,cancel_return,address1,address2,city,country,email,first_name,last_name,charset,night_phone_a,night_phone_b,night_phone_c,state,zip'; this.button = $(e); this.options = d; this.fallback = f || {}; this.paypal = this.getPaypalVariables(g); this.checkout = null; this.init(); } _ClassyPaypal.prototype.init = function() { this.button.addClass('ClassyPaypal-type-' + this.options.type + ' ClassyPaypal-style-' + this.options.style); window.setTimeout($.proxy(function() { this.button.addClass('ClassyPaypal-transit'); }, this), 30); if (this.options.innerHTML) { this.button.html(this.options.innerHTML); } if (this.options.tooltip) { this.tooltip(); } this.button.on('click touchend', $.proxy(function(event) { event.preventDefault(); if (this.button.hasClass('ClassyPaypal-button-disabled')) { return; } this.checkout = this.getOptions(); if (typeof this.options.beforeSubmit === 'function') { var f = this.options.beforeSubmit.call(this.button.get(0), this.checkout); if (typeof f === 'object') { this.checkout = f; } else { return; } } this.submit(); }, this)); var self = this; this.api = { enable: function() { self.button.removeClass('ClassyPaypal-button-disabled'); return this; }, disable: function() { self.button.addClass('ClassyPaypal-button-disabled'); return this; }, setVariable: function(e, f) { if (e.indexOf('data-') !== 0) { e = 'data-' + e.toLowerCase(); } self.button.attr(e, f); return this; } }; this.button.data('ClassyPaypal-api', this.api); }; _ClassyPaypal.prototype.getPaypalVariables = function(value) { var g = value.split(','); for (var h = 0; h < g.length; h++) { var e = g[h]; if (e.charAt(e.length - 1) === '*') { e = e.slice(0, -1); for (var d = 0; d < 10; d++) { g.splice(h, (!d) & 1, e + d); } } } return g; }; _ClassyPaypal.prototype.getOptions = function() { var e = this.fallback; var g = this.button.data('json'); if (typeof g === 'object') { $.extend(e, g); } else { if (typeof g === 'string') { if (window.console) { console.log('Error: Invalid JSON string in "data-json" attribute'); } } } for (var h = 0; h < this.paypal.length; h++) { var d = this.paypal[h], f = this.button.attr('data-' + d); if (f !== c && f !== '') { e[d] = f; } } switch (this.options.type) { case 'buynow': e.cmd = '_xclick'; e.bn = 'PayNowPlugin_BuyNow_WPS_US'; break; case 'subscribe': e.cmd = '_xclick-subscriptions'; e.bn = 'PayNowPlugin_Subscribe_WPS_US'; break; case 'donate': e.cmd = '_donations'; e.bn = 'PayNowPlugin_Donate_WPS_US'; break; default: e.cmd = ""; } return e; }; _ClassyPaypal.prototype.submit = function() { if (!this.checkout.cmd || !this.checkout.business) { return; } this.form = $('<form/>'); this.form.attr({ action: 'https://www.paypal.com/cgi-bin/webscr', method: 'POST', target: this.options.checkoutTarget }).hide(); for (var e in this.checkout) { if (this.checkout.hasOwnProperty(e)) { var d = $('<input/>'); d.attr({ type: 'hidden', name: e, value: this.checkout[e] }); this.form.append(d); } } $(document.body).append(this.form); if (this.options.delaySubmit) { this.button.addClass('ClassyPaypal-submit'); window.setTimeout($.proxy(function() { this.form.submit().remove(); this.button.removeClass('ClassyPaypal-submit'); }, this), this.options.delaySubmit); } else { this.form.submit().remove(); } }; _ClassyPaypal.prototype.tooltip = function() { var e = this.options.tooltipTime; var d = $('body').children('.ClassyPaypal-tooltip'); if (d.length === 0) { d = $('<div class="ClassyPaypal-tooltip"></div>').appendTo('body'); } this.button.mouseenter($.proxy(function() { var g = this.button.outerWidth(), i = this.button.outerHeight(), h = this.button.offset().top - $(window).scrollTop(), f = this.button.offset().left - $(window).scrollLeft(); var j = (d.text(this.options.tooltip).outerWidth() - g) / 2; d.css({ top: h + i + parseFloat(this.options.tooltipOffset), left: f - j }).stop(true).delay(this.options.tooltipDelay).fadeIn(e); if (this.options.tooltipHide) { d.data('timer', window.setTimeout(function() { d.stop(true).fadeOut(e); }, this.options.tooltipHide)); } }, this)); this.button.mouseleave(function() { d.stop(true).fadeOut(e); window.clearTimeout(d.data('timer')); }); }; $.fn.ClassyPaypal = function(f, e) { var d = $.extend({ type: 'buynow', style: 'default', innerHTML: '', checkoutTarget: '_self', delaySubmit: 0, tooltip: '', tooltipHide: 3000, tooltipTime: 300, tooltipDelay: 400, tooltipOffset: 15, beforeSubmit: false }, f); return this.each(function() { new _ClassyPaypal(this, d, e); }); }; })(jQuery);
//$Id: ajax_quiz.js,v 1.1.2.6 2009/08/14 11:29:33 falcon Exp $ Drupal.AjaxLoadExample = Drupal.AjaxLoadExample || {}; /** * Ajax load example behavior. */ Drupal.behaviors.AjaxLoadExample = function (context) { // to proceed with the quiz $('.form-submit:not(.form-submit-clicked)', context) .each(function () { // The target should not be e.g. a node that will itself be // replaced, as this would mean no node is available for // ajax_load to attach behaviors to when all scripts are loaded. var target = this.parentNode; $(this) .addClass('form-submit-clicked') .click(function () { var tries = ''; $('[name^="tries"]:not(.form-submit-clicked)').each(function (i) { switch(this.type) { case 'radio': case 'checkbox': if (this.checked) { tries += '&' + this.name + '=' + this.value; } break; default: tries += '&' + this.name + '=' + this.value; break; } $(this).addClass('form-submit-clicked'); }); $(this).attr('disabled', true); $.ajax({ // Either GET or POST will work. type: 'POST', data: 'ajax_load_example=1&op=Next'+tries, // Need to specify JSON data. dataType: 'json', url: $(this).attr('href'), success: function(response) { $(this).prepend('answer saved'); // Call all callbacks. //alert('sucess'); if (response.__callbacks) { $.each(response.__callbacks, function(i, callback) { // The first argument is a target element, the second // the returned JSON data. //alert(response); eval(callback)(target, response); }); // If you don't want to return this module's own callback, // you could of course just call it directly here. // Drupal.AjaxLoadExample.formCallback(target, response); } }, error: function(xhr, opt, err) { alert(xhr.statusText); alert(opt); alert(err); }, }); return false; }); }); // to start the quiz $('a.ajax-load-example:not(.ajax-load-example-processed)', context) .each(function () { // The target should not be e.g. a node that will itself be // replaced, as this would mean no node is available for // ajax_load to attach behaviors to when all scripts are loaded. var target = this.parentNode; $(this) .addClass('ajax-load-example-processed') .click(function () { $.ajax({ // Either GET or POST will work. type: 'POST', data: 'ajax_load_example=1', // Need to specify JSON data. dataType: 'json', url: $(this).attr('href'), success: function(response){ // Call all callbacks. if (response.__callbacks) { $.each(response.__callbacks, function(i, callback) { // The first argument is a target element, the second // the returned JSON data. eval(callback)(target, response); }); // If you don't want to return this module's own callback, // you could of course just call it directly here. // Drupal.AjaxLoadExample.formCallback(target, response); } }, error: function(){ alert('An error has occurred. Please try again.'); }, }); return false; }); }); }; /** * Ajax load example callback. */ Drupal.AjaxLoadExample.formCallback = function (target, response) { target = $(target).append(response.content); Drupal.attachBehaviors(target); };
let UpdateCommunity = () => { return <div> <button>UpdateCommunity</button> </div> } export default UpdateCommunity
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var virtual_document_class_1 = require("./virtual-document-class"); exports.VirtualDocument = virtual_document_class_1.VirtualDocument; var virtual_document_demo_class_1 = require("./virtual-document-demo-class"); exports.VirtualDocumentDemo = virtual_document_demo_class_1.VirtualDocumentDemo; var virtual_document_enum_1 = require("./virtual-document-enum"); exports.ElementTag = virtual_document_enum_1.ElementTag;
var privated = {}, shared = {}; var Account = function () { self = this; self.__private = privated; } // private privated.wallet = {}; //shared.accountsList = new Array(); // Public methods Account.prototype.createAccount = function (num, cb) { // for (var i = 0; i < num; i++) { // account = web3.eth.accounts.create(web3.utils.randomHex(32)); // shared.accountsList.push(account); // } privated.wallet = web3.eth.accounts.wallet.create(num, web3.utils.randomHex(32)); //console.log(privated.wallet); cb(null, privated.wallet); //cb(null, shared.accountsList); } Account.prototype.getBalance = function (wallet, cb) { //console.log(wallet); for (i=0; i < wallet.length ; i++) { web3.eth.getBalance(wallet[i].address, function(err, res){ if(!err) console.log(res); }) } cb(null,null); } module.exports = Account;
import { Spinner } from 'react-bootstrap'; export default function SpinnerComponent() { return ( <div className="d-flex justify-content-center align-items-center" style={{height: "90vh"}}> <Spinner animation="border" role="status"> <span className="sr-only">Loading...</span> </Spinner> </div> ) }
import React from "react"; import "../../../node_modules/bootstrap/dist/css/bootstrap.min.css"; import "./ReviewItems.css"; const ReviewItems = (props) => { const { name, quantity, img, key, price } = props.product; const removeProduct = props.removeProduct; return ( <div className="my-2 mx-4 p-3 "> <div className="item-div"> <h6 className="text-info">{name}</h6> <img src={img} alt="" /> <p className="lead">Quantity: {quantity}</p> <p className="lead"> <p> <small>Price: {price}</small> </p> <button onClick={() => removeProduct(key)} className="btn btn-primary" > {" "} Remove </button> </p> </div> </div> ); }; export default ReviewItems;
var ships = new Backbone.Collection; ships.on("add", function(ship) { alert("Ahoy " + ship.get("name") + "!"); }); ships.add([ {name: "Flying Dutchman"}, {name: "Black Pearl"} ]); var myView = Backbone.View.extend({ initialize: function() { this.collection = new ProjectsCollection(); this.collection.bind("reset", _.bind(this.render, this)); this.collection.fetch({}); } });
import {Grid} from "@material-ui/core"; import {useEffect, useState} from "react"; import Select from "~/components/atoms/Select/Select"; import TextfieldTitle from "~/components/atoms/textfield/TextfieldTitle"; import TextfieldWithImageSelector from "~/components/atoms/textfield/TextfieldWithImageSelector"; import TextFieldWithTag from "~/components/atoms/textfield/TextFieldWithTag"; const GridConfigurator = function ({component, form, setForm, resetForm, updateForm, ...props}) { return ( <div> <Grid container> <Grid item xs={12}> <Select label="Grid container" onChange={setForm} value={form.isContainer} name="isContainer" items={[ {label: "Ja", value: true}, {label: "Nee", value: false}, ]} /> </Grid> <Grid item xs={12}> <Select label="Marge aan onderkant" onChange={setForm} value={form.bottomMargin} name="bottomMargin" items={[ {label: "Geen", value: 0}, {label: "Klein", value: 1}, {label: "Gemiddeld", value: 2}, {label: "Groot", value: 3}, {label: "Extra groot", value: 4}, ]} /> </Grid> <Grid item xs={12}> <Select label="Ruimte tussen grid cellen" onChange={setForm} value={form.spacing} name="spacing" items={[ {label: "Geen ruimte", value: 0}, {label: "Klein", value: 1}, {label: "Gemiddeld", value: 2}, {label: "Groot", value: 3}, {label: "Extra groot", value: 4}, ]} /> </Grid> </Grid> </div> ); }; export default GridConfigurator;
/* global describe, it, beforeEach */ /* eslint-disable global-require, strict */ const { expect } = require('chai'); const uuid = require('uuid'); const validate = require('../../index'); const clone = require('../../lib/utils/clone'); const { RESOURCE_TYPES } = validate; const sampleWithId = require('../fixtures/conditions/01_with_id.json'); const sampleWithoutId = require('../fixtures/conditions/02_without_id.json'); describe('validate/GenericeResource', () => { describe('valid resources', () => { it('changes nothing', () => validate(sampleWithId) .then((out) => { expect(out).to.deep.equal(sampleWithId); }) ); it('does not add id', () => validate(sampleWithoutId) .then((out) => { expect(sampleWithoutId.id).to.equal(undefined); expect(out.id).to.equal(undefined); }) ); }); describe('valid resources with required resourceType', () => { let sample; beforeEach(() => { sample = clone(sampleWithId); }); it('with Condition resourceType', () => validate(sample, { resourceType: RESOURCE_TYPES.CONDITION }) .then((out) => { expect(out).to.deep.equal(sample); }) ); it('with other resourceType', () => validate(sample, { resourceType: RESOURCE_TYPES.ENCOUNTER }) .then(() => { throw new Error('should have thrown'); }) .catch((err) => { expect(err.isBoom).to.equal(true); expect(err.output.statusCode).to.equal(422); }) ); }); describe('invalid resources', () => { let sample; beforeEach(() => { sample = clone(sampleWithId); }); it('has non-string id', () => { sample.id = {}; return validate(sample) .then(() => { throw new Error('should have thrown'); }) .catch((err) => { expect(err.isBoom).to.equal(true); expect(err.output.statusCode).to.equal(422); }); }); it('has no resourceType', () => { delete sample.resourceType; return validate(sample) .then(() => { throw new Error('should have thrown'); }) .catch((err) => { expect(err.isBoom).to.equal(true); expect(err.output.statusCode).to.equal(422); }); }); it('has invalid resourceType', () => { sample.resourceType = uuid.v4(); return validate(sample) .then(() => { throw new Error('should have thrown'); }) .catch((err) => { expect(err.isBoom).to.equal(true); expect(err.output.statusCode).to.equal(422); }); }); }); });
import {apiServices} from 'services' import { deleteService } from '../../../services/api_services.js' import ModalActionNumber from '../../../components/modal-action-number/modal-action-number.jsx' import {Loader} from 'components' import SingleClient from './single-client/single-client.jsx' import { SkeletonClientItem } from '../../../components/skeleton-client-item/skeleton-client.jsx' import './clients-list.less' const config = window.config let pressing class ClientsList extends React.Component { constructor (props) { super(props) this.state = { showComponent: false, isLoad: false, selectedUser: {}, selectedClientDelete: false, selectedClientAdd: false, isOffModal: false, pressingID: '', clientsLists: [], isAllClientsLoad: false, customersTotalCount: '' } this.onNumberClick = this.onNumberClick.bind(this) } onNumberClick (c) { this.setState({ showComponent: true, isOffModal: false, selectedUser: c }) } offActionsModal = () => { this.setState({ isOffModal: true }, () => { setTimeout(() => { this.setState({ showComponent: false, isOffModal: false }) }, 300) }) } componentDidMount () { this.setState({isLoad: true, skeleton: true}) apiServices.get(config.urls.api_get_clients, { timestamp: Date.now(), 'limit': (config.listLimit * config.startOffset), 'offset': this.state.clientsLists.length }).then(data => { this.setState({isLoad: false, skeleton: false }) if (data && data.length) { this.setState({clientsLists: data}) } }) setTimeout(() => { apiServices.head(config.urls.api_get_total_clients_count).then(response => { if (response.headers.get('x-total-count') !== null) { console.log(response.headers.get('x-total-count')) this.setState({customersTotalCount: response.headers.get('x-total-count')}) } }) }, 1000) } componentWillReceiveProps (props) { window.onscroll = () => { var handleClientAmount = () => { let allClientsEl = document.querySelectorAll('.item') let checkAmountClient = () => { let el = allClientsEl.length - ((config.startOffset - 1) * config.listLimit) if (el <= 0) { return 0 } else { return el - 1 } } if (allClientsEl.length) { let itemForLoad = checkAmountClient() return allClientsEl[itemForLoad].getBoundingClientRect().bottom } } // if scoll bottom if ((window.innerHeight + window.scrollY + 1) >= (document.body.offsetHeight - document.documentElement.clientHeight + handleClientAmount())) { if (!this.state.isAllClientsLoad && !this.state.isLoad) { this.setState({isLoad: true}) apiServices.get(config.urls.api_get_clients, { timestamp: Date.now(), 'limit': (config.listLimit * config.startOffset), 'offset': this.state.clientsLists.length, 'q': this.props.searchValue }).then(data => { if (data && data.length) { this.setState({clientsLists: this.state.clientsLists.concat(data)}) this.setState({isLoad: false}) this.setState({isAllClientsLoad: false}) } else if (!data.length) { this.setState({isAllClientsLoad: true}) this.setState({isLoad: false}) } }) } } } if (props.selectedClients.length !== this.props.selectedClients.length && !props.searchValue && !this.props.searchValue) { const arrayIds = props.selectedClients.map(({id}) => id) this.setState(prevState => ({ hideClient: true, clientsLists: [...props.selectedClients, ...prevState.clientsLists.filter(item => !arrayIds.includes(item.id))] })) } if (props.selectedClients.length !== this.props.selectedClients.length) { if (props.selectedClients.length > this.props.selectedClients.length) { this.setState({selectedClientDelete: false, selectedClientAdd: true}) } if (props.selectedClients.length < this.props.selectedClients.length) { this.setState({selectedClientDelete: true, selectedClientAdd: false}) } } if (props.searchValue !== this.props.searchValue) { this.setState({isAllClientsLoad: false, isLoad: true}) apiServices.get(config.urls.api_get_clients, { timestamp: Date.now(), 'limit': (config.listLimit * config.startOffset), 'offset': 0, 'q': props.searchValue }).then(data => { if (props.multiSelectionMode) { const arrayIds = props.selectedClients.map(({id}) => id) if ((!props.searchValue && !this.props.searchValue) && data && data.length) { this.setState(prevState => ({ isLoad: false, clientsLists: [...props.selectedClients, ...data.filter(item => !arrayIds.includes(item.id))] })) } if ((props.searchValue || this.props.searchValue) && data && data.length) { this.setState({clientsLists: data, isLoad: false}) } else if (!data.length) { this.setState({clientsLists: [], isLoad: false}) } } else { if (data && data.length) { this.setState({clientsLists: data, isLoad: false}) } else if (!data.length) { this.setState({clientsLists: [], isLoad: false}) } } }) } if (props.getClient) { this.setState({isLoad: true, skeleton: true}) apiServices.get(config.urls.api_get_clients, { timestamp: Date.now(), 'limit': (config.listLimit * config.startOffset), 'offset': 0 }).then(data => { this.setState(prevState => ({clientsLists: data, isLoad: false, skeleton: false})) this.props.onGetClient() }) setTimeout(() => { apiServices.head(config.urls.api_get_total_clients_count).then(response => { if (response.headers.get('x-total-count') !== null) { this.setState({customersTotalCount: response.headers.get('x-total-count')}) } }) }, 1000) } if (props.refreshClientList) { this.setState(prevState => ({ clientsLists: prevState.clientsLists.filter(item => !props.refreshClientArray.includes(item.id)), customersTotalCount: prevState.customersTotalCount - props.refreshClientArray.length }), () => { props.onRefreshClientList() }) } } handleDeleteCustomer = id => { const body = `clients=${id}` deleteService(config.urls.api_get_clients, body).then(r => { if (r.status === 204) { this.setState(prevState => ({ clientsLists: prevState.clientsLists.filter(i => i.id !== id), customersTotalCount: +prevState.customersTotalCount - 1 })) this.offActionsModal() this.props.rerenderActiveGroup() } }).catch(e => console.error(e)) } showPhone (permissionLevel, el) { if (permissionLevel === 'admin' || permissionLevel === 'senior' || permissionLevel === 'junior' || permissionLevel === 'readonly') { return (el && el.phone) } } handleClientsAmount = () => { if (this.state.customersTotalCount) { return <span className='app-clients-list__header-title count'>{`(${this.state.customersTotalCount})`}</span> } } pressingIndicator = pressingID => { clearTimeout(pressing) pressing = setTimeout(() => { this.setState({pressingID}) }, 200) } offPressingIndicator = () => { clearTimeout(pressing) this.props.clearTapTimeout() this.setState({pressingID: ''}) } render () { const skeletonClientItem = [1, 2, 3] const { pressingID, clientsLists } = this.state const { multiSelectionMode, onClientSelecting, selectedClients, onClickMultiSelectionMode } = this.props const arrayIds = selectedClients.map(({id}) => id) const lastOfSelected = arrayIds[arrayIds.length - 1] const skeletonHighlight = this.props.highlightClient ? ' highlight_client' : '' return (this.state.skeleton ? <div className='app-clients-list'> <div className='app-clients-list__header'> <span className='app-clients-list__header-title'>{config.translations.app_header_main_title}</span> </div> <div className='app-clients-list__content-wrap'> <div className='app-clients-list__content'> {skeletonClientItem.map(i => <SkeletonClientItem key={i} highlightClient={this.props.highlightClient} />)} </div> </div> </div> : <div className='app-clients-list'> <div className='app-clients-list__header'> <div className='text_wrap'> <p> <span className='app-clients-list__header-title'>{config.translations.app_header_main_title}</span> {this.handleClientsAmount()} </p> </div> {!multiSelectionMode && <button onClick={onClickMultiSelectionMode} className='multi_delete_btn' type='button'> <span className='delete_img_wrap'> <img src={config.urls.base_clients_list_data + 'ic_action_delete.svg'} alt='' /> </span> </button>} </div> {this.state.showComponent && <ModalActionNumber onDeleteCustomer={this.handleDeleteCustomer} offActionsModal={this.offActionsModal} isOffModal={this.state.isOffModal} onShowComponent={this.onNumberClick} showComponent onHandleCustomer={this.state.selectedUser} />} <div className='app-clients-list__content-wrap'> <div className='app-clients-list__content'> { clientsLists.map(el => ( <SingleClient key={el.id + el.name + el.profile_image} selectedClientDelete={this.state.selectedClientDelete} selectedClientAdd={this.state.selectedClientAdd} offPressingIndicator={this.offPressingIndicator} handleOnMultiSelectionMode={this.props.handleOnMultiSelectionMode} clearTapTimeout={this.props.clearTapTimeout} pressingIndicator={this.pressingIndicator} multiSelectionMode={multiSelectionMode} skeletonHighlight={skeletonHighlight} onClientSelecting={onClientSelecting} onNumberClick={this.onNumberClick} lastOfSelected={lastOfSelected} pressingID={pressingID} arrayIds={arrayIds} el={el} /> ) ) } {this.state.isLoad && <Loader />} </div> </div> </div>) } } export default ClientsList
function idealItems(itemweights, itemvals, maxWeight) { let lookup = new Array(itemweights.length); for (let i = 0; i < itemweights.length; i++) { lookup[i] = new Array(maxWeight+1) if (i === 0) lookup[i].fill(0); } // console.log(lookup) for (let i = 0; i < itemweights.length; i++) { let weight = itemweights[i]; for (let j = 0; j < maxWeight+1; j++) { if (i !== 0) { lookup[i][j] = lookup[i-1][j] if (j >= weight) lookup[i][j] = Math.max(itemvals[i]+ lookup[i-1][j-weight],lookup[i][j]) } else { if (j >= weight) lookup[i][j] = itemvals[i] } } } console.log(lookup) return lookup[lookup.length-1][lookup[0].length-1] } // console.log(idealItems([1,3,4,5],[1,4,5,7],7)) console.log(idealItems([5,4,3,1],[7,5,4,1],7))
const fs = require(`fs`); const path = require(`path`); const executor = require(`./executor`); const browsertimeResultFile = require(`./configuration`).browsertimeResultFile; const resultDirectory = require(`./configuration`).resultDirectory; module.exports = function browsertime(url, options) { const browsertimePath = path.resolve( __dirname, `../node_modules/browsertime/bin/browsertime.js` ); const browsertimeCommand = [ browsertimePath, `-b ${options.browser}`, `-c ${options.connectivity}`, `-n ${options.iterations}`, `-o ${path.parse(browsertimeResultFile).name}`, `--skipHar`, `--resultDir ${resultDirectory}`, url, ].join(` `); const resolver = () => { const benchmarkFilePath = path.resolve( resultDirectory, browsertimeResultFile ); const benchmarkFileContents = fs.readFileSync(benchmarkFilePath); return JSON.parse(benchmarkFileContents).statistics.timings; }; return executor(browsertimeCommand, resolver); };
import React, {useState, useEffect} from 'react' import utils from '../utils' const Color = ({rgb, alpha, type, weight, index}) => { const [ copySuccess, setCopySuccess ] = useState(false); const csv = rgb.join(","); const alertCopySuccess = (e) => { setCopySuccess(true); navigator.clipboard.writeText(csv) }//para mostrar las letras mas claras a partir de determinado index, necesito pasarlo por parametro //esto es para que la letra negra no se ccamufle con los colores oscuros useEffect(() => { const timeout = setTimeout(() => {setCopySuccess(false)},3000)//cada vez que aparezca el clipboard, quiero que desaparezca a los 3 segundos return () => { clearTimeout(timeout) } }, [copySuccess]) return ( <div className="color" style={{background:`rgb(${csv})`}} onClick={alertCopySuccess}> <p className="percent-value">{weight}</p> {copySuccess && <p className="alert">Copied to clipboard!</p>} </div> ) } export default Color
import React, { useEffect } from "react"; import { useDispatch } from "react-redux"; import { Table } from "reactstrap"; import { formatDDMMYYYY } from "../../../../utils/timeFunction"; import RutGonText from "../../../RutGonText"; import { popupModalToggle } from "../../../../actions/popupModal"; import { changeFormData } from "../../../../actions/formData"; //tooltip import ReactTooltip from "react-tooltip"; //material import DeleteIcon from "@material-ui/icons/Delete"; import EditIcon from "@material-ui/icons/Edit"; import AddIcon from "@material-ui/icons/Add"; export default function BangDanhSachPhim({ danhSachPhim, trangHienTai, soPhanTuTrenTrang, xoaPhim, themLichChieu, }) { const dispatch = useDispatch(); const handleEdit = (e, item) => { const values = { danhGia: item.danhGia, hinhAnh: item.hinhAnh, maNhom: item.maNhom, maPhim: item.maPhim, moTa: item.moTa, ngayKhoiChieu: formatDDMMYYYY(item.ngayKhoiChieu, "/"), tenPhim: item.tenPhim, trailer: item.trailer, }; dispatch( popupModalToggle({ title: "SỬA THÔNG TIN PHIM", }) ); dispatch( changeFormData({ button: "Sửa", type: "edit", values, }) ); }; const handleThemLichchieu = (maPhim) => { themLichChieu(maPhim); }; // useEffect(() => { // console.log(danhSachPhim); // }); return ( <Table hover> <thead> <tr> <th>#</th> <th>Mã Phim</th> <th>Tên Phim</th> {/* <th>Bí Danh</th> */} <th>Mô tả</th> <th>Hình Ảnh</th> <th>Trailer</th> <th>Ngày Khởi Chiếu</th> <th>Đánh giá</th> <th>{/* nút xóa + sửa */}</th> </tr> </thead> <tbody> {danhSachPhim?.map((item, index) => ( <tr key={index}> <th scope="row"> {index + 1 + (trangHienTai - 1) * soPhanTuTrenTrang} </th> <td>{item.maPhim}</td> <td>{item.tenPhim}</td> {/* <td>{item.biDanh}</td> */} <td> <RutGonText text={item.moTa} len={30} moreIcon="+" lessIcon="-" /> </td> <td> <img style={{ width: "40px" }} src={item.hinhAnh} alt={item.biDanh} /> </td> <td>{item.trailer.slice(29, 100)}</td> <td>{formatDDMMYYYY(item.ngayKhoiChieu)}</td> <td>{item.danhGia}</td> <td> <div className="actionCell"> <button data-tip="Xóa phim" className="btn delete" onClick={() => { xoaPhim(item); }} > <DeleteIcon /> </button> <button data-tip="Sửa thông tin phim" className="btn edit" onClick={(e) => { handleEdit(e, item); }} > <EditIcon /> </button> {/* Nut them lich chieu */} <button data-tip="Thêm lịch chiếu" className="btn add" onClick={(e) => { handleThemLichchieu(item.maPhim); }} > <AddIcon /> </button> <ReactTooltip /> </div> </td> </tr> ))} </tbody> </Table> ); }
var showval;//工作ID指定变量 $(function (){ //解析URL获取工作ID(showval) var thisURL = document.URL; var getval =thisURL.split('?')[1]; showval= getval.split("=")[1]; }); function modifyMsg(){ var com_name = $("#com_name").val(); var com_phone = $("#com_phone").val(); var address1 = $("#province option:selected").text(); var address2 = $("#city option:selected").text(); var address3 = $("#address3").val(); var address = address1+address2+address3; var job = $("#job").val(); var salary = $("#salary").val(); if(com_name==''){ layer.msg('公司名称不能为空',{icon:6,time:2000}); return; } if(com_phone==''){ layer.msg('公司电话不能为空',{icon:6,time:2000}); return; } if(address3==''){ layer.msg('详细地址不能为空',{icon:6,time:2000}); return; } if(job==''){ layer.msg('职位不能为空',{icon:6,time:2000}); return; } if(salary==''){ layer.msg('薪资不能为空',{icon:6,time:2000}); return; } $.ajax({ url:'../../classJobInfo/modifyMsg.do', data:'job_id='+showval+'&com_name='+com_name+'&com_phone='+com_phone+'&address='+address+'&job='+job+'&salary='+salary, type:'post', dataType:'json', success:function(data){ if(data.resultcode=="200"){//修改成功 alert("修改成功!"); history.back(); layer.msg(data.resultmsg,{icon:6,time:2000}); }else{//修改失败 alert("修改失败!"); history.back(); layer.msg(data.resultmsg,{icon:6,time:2000}); } } }); }
define( [ "ember", "utils/linkmatching" ], function( Ember, linkmatching ) { var hbs_string = "%@" + "{{#external-link" + " url='%@'" + " targetObject=targetObject}}" + "%@" + "{{/external-link}}", linkurl_re = linkmatching.linkurl_re, linkurl_fn = linkmatching.linkurl_fn( hbs_string ), twitter_re = linkmatching.twitter_re, twitter_fn = linkmatching.twitter_fn( hbs_string ); return Ember.Component.extend({ layout: function( context ) { return Ember.Handlebars.compile( Ember.get( context, "_text" ) ).apply( this, arguments ); }, _text: function() { return ( this.get( "text" ) || "" ) .replace( linkurl_re, linkurl_fn ) .replace( twitter_re, twitter_fn ); }.property( "text" ), textChangeObserver: function() { this.rerender(); }.observes( "text" ) }); });
import React from "react"; import BaseComponent from "core/BaseComponent/BaseComponent"; import { withStyles } from "@material-ui/core"; import Configs from "app.config"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faTimes } from "@fortawesome/free-solid-svg-icons"; class Image extends BaseComponent { constructor(props) { super(props); this.state = {}; } _onClickDeleteIcon = () => { const { imageId, onDelete } = this.props; typeof onDelete == "function" && onDelete(imageId); }; renderBody() { const { imageId, onDelete, classes, style, width, height, src, } = this.props; return ( <div className={classes.root}> <img className={classes.image} src={ src ? src : `${Configs.serviceHost}/api/file/GetFileDataById?fileId=${imageId}` } style={{ width: width ? width : "100px", height: height ? height : "100px", maxHeight: "90vw", maxWidth: "80vw", ...style, }} /> {onDelete ? ( <FontAwesomeIcon icon={faTimes} onClick={this._onClickDeleteIcon} className={classes.deleteIcon} style={{ width: "16px", height: "16px" }} /> ) : null} </div> ); } } export default withStyles({ root: { position: "relative", }, image: { margin: "16px", }, deleteIcon: { background: "#8a000070", position: "absolute", top: 18, right: 18, cursor: "pointer", color: "white", borderRadius: "8px", }, })(Image);
const express = require('express') const port = 4500; const app = express() const edwin = require('./router') app.use(express.json()) app.use('/api/v1/codelab', edwin) app.listen(port, ()=>{ console.log(`port ${port}`) })
/* * Generated by the Waxeye Parser Generator - version 0.8.0 * www.waxeye.org */ var waxeye = waxeye; if (typeof module !== 'undefined') { // require from module system waxeye = require('waxeye'); } var Parser = (function() { var parser = function() { return this; }; parser.prototype = new waxeye.WaxeyeParser(0, true, [new waxeye.FA("class", [new waxeye.State([new waxeye.Edge(6, 0, false), new waxeye.Edge("c", 1, false)], false), new waxeye.State([new waxeye.Edge("l", 2, false)], false), new waxeye.State([new waxeye.Edge("a", 3, false)], false), new waxeye.State([new waxeye.Edge("s", 4, false)], false), new waxeye.State([new waxeye.Edge("s", 5, false)], false), new waxeye.State([new waxeye.Edge(6, 6, false)], false), new waxeye.State([new waxeye.Edge(6, 6, false), new waxeye.Edge(5, 7, false)], false), new waxeye.State([new waxeye.Edge(6, 7, false), new waxeye.Edge("{", 8, false)], false), new waxeye.State([new waxeye.Edge(6, 9, false), new waxeye.Edge(1, 8, false), new waxeye.Edge(6, 10, false), new waxeye.Edge(2, 11, false), new waxeye.Edge(6, 12, false), new waxeye.Edge("}", 13, false)], false), new waxeye.State([new waxeye.Edge(6, 9, false), new waxeye.Edge(1, 8, false)], false), new waxeye.State([new waxeye.Edge(6, 10, false), new waxeye.Edge(2, 11, false)], false), new waxeye.State([new waxeye.Edge(6, 10, false), new waxeye.Edge(2, 11, false), new waxeye.Edge(6, 12, false), new waxeye.Edge("}", 13, false)], false), new waxeye.State([new waxeye.Edge(6, 12, false), new waxeye.Edge("}", 13, false)], false), new waxeye.State([], true)], waxeye.FA.LEFT), new waxeye.FA("classVarDec", [new waxeye.State([new waxeye.Edge("s", 1, false), new waxeye.Edge("f", 15, false)], false), new waxeye.State([new waxeye.Edge("t", 2, false)], false), new waxeye.State([new waxeye.Edge("a", 3, false)], false), new waxeye.State([new waxeye.Edge("t", 4, false)], false), new waxeye.State([new waxeye.Edge("i", 5, false)], false), new waxeye.State([new waxeye.Edge("c", 6, false)], false), new waxeye.State([new waxeye.Edge(6, 7, false)], false), new waxeye.State([new waxeye.Edge(6, 7, false), new waxeye.Edge(4, 8, false)], false), new waxeye.State([new waxeye.Edge(6, 9, false)], false), new waxeye.State([new waxeye.Edge(6, 9, false), new waxeye.Edge(5, 10, false)], false), new waxeye.State([new waxeye.Edge(6, 11, false), new waxeye.Edge(",", 12, false), new waxeye.Edge(6, 13, false), new waxeye.Edge(";", 14, false)], false), new waxeye.State([new waxeye.Edge(6, 11, false), new waxeye.Edge(",", 12, false)], false), new waxeye.State([new waxeye.Edge(6, 12, false), new waxeye.Edge(5, 10, false)], false), new waxeye.State([new waxeye.Edge(6, 13, false), new waxeye.Edge(";", 14, false)], false), new waxeye.State([], true), new waxeye.State([new waxeye.Edge("i", 16, false)], false), new waxeye.State([new waxeye.Edge("e", 17, false)], false), new waxeye.State([new waxeye.Edge("l", 18, false)], false), new waxeye.State([new waxeye.Edge("d", 6, false)], false)], waxeye.FA.LEFT), new waxeye.FA("subroutineDec", [new waxeye.State([new waxeye.Edge("c", 1, false), new waxeye.Edge("m", 23, false), new waxeye.Edge("f", 28, false)], false), new waxeye.State([new waxeye.Edge("o", 2, false)], false), new waxeye.State([new waxeye.Edge("n", 3, false)], false), new waxeye.State([new waxeye.Edge("s", 4, false)], false), new waxeye.State([new waxeye.Edge("t", 5, false)], false), new waxeye.State([new waxeye.Edge("r", 6, false)], false), new waxeye.State([new waxeye.Edge("u", 7, false)], false), new waxeye.State([new waxeye.Edge("c", 8, false)], false), new waxeye.State([new waxeye.Edge("t", 9, false)], false), new waxeye.State([new waxeye.Edge("o", 10, false)], false), new waxeye.State([new waxeye.Edge("r", 11, false)], false), new waxeye.State([new waxeye.Edge(6, 12, false)], false), new waxeye.State([new waxeye.Edge(6, 12, false), new waxeye.Edge(4, 13, false), new waxeye.Edge("v", 20, false)], false), new waxeye.State([new waxeye.Edge(6, 14, false)], false), new waxeye.State([new waxeye.Edge(6, 14, false), new waxeye.Edge(5, 15, false)], false), new waxeye.State([new waxeye.Edge(6, 15, false), new waxeye.Edge("(", 16, false)], false), new waxeye.State([new waxeye.Edge(6, 16, false), new waxeye.Edge(")", 17, false)], false), new waxeye.State([new waxeye.Edge(6, 17, false), new waxeye.Edge("{", 18, false)], false), new waxeye.State([new waxeye.Edge(6, 18, false), new waxeye.Edge("}", 19, false)], false), new waxeye.State([], true), new waxeye.State([new waxeye.Edge("o", 21, false)], false), new waxeye.State([new waxeye.Edge("i", 22, false)], false), new waxeye.State([new waxeye.Edge("d", 13, false)], false), new waxeye.State([new waxeye.Edge("e", 24, false)], false), new waxeye.State([new waxeye.Edge("t", 25, false)], false), new waxeye.State([new waxeye.Edge("h", 26, false)], false), new waxeye.State([new waxeye.Edge("o", 27, false)], false), new waxeye.State([new waxeye.Edge("d", 11, false)], false), new waxeye.State([new waxeye.Edge("u", 29, false)], false), new waxeye.State([new waxeye.Edge("n", 30, false)], false), new waxeye.State([new waxeye.Edge("c", 31, false)], false), new waxeye.State([new waxeye.Edge("t", 32, false)], false), new waxeye.State([new waxeye.Edge("i", 33, false)], false), new waxeye.State([new waxeye.Edge("o", 34, false)], false), new waxeye.State([new waxeye.Edge("n", 11, false)], false)], waxeye.FA.LEFT), new waxeye.FA("parameterList", [new waxeye.State([new waxeye.Edge(4, 1, false)], true), new waxeye.State([new waxeye.Edge(6, 2, false)], false), new waxeye.State([new waxeye.Edge(6, 2, false), new waxeye.Edge(5, 3, false)], false), new waxeye.State([new waxeye.Edge(6, 4, false), new waxeye.Edge(",", 5, false)], true), new waxeye.State([new waxeye.Edge(6, 4, false), new waxeye.Edge(",", 5, false)], false), new waxeye.State([new waxeye.Edge(6, 5, false), new waxeye.Edge(4, 6, false)], false), new waxeye.State([new waxeye.Edge(6, 7, false)], false), new waxeye.State([new waxeye.Edge(6, 7, false), new waxeye.Edge(5, 3, false)], false)], waxeye.FA.LEFT), new waxeye.FA("type", [new waxeye.State([new waxeye.Edge("i", 1, false), new waxeye.Edge("c", 4, false), new waxeye.Edge("b", 7, false), new waxeye.Edge(5, 3, false)], false), new waxeye.State([new waxeye.Edge("n", 2, false)], false), new waxeye.State([new waxeye.Edge("t", 3, false)], false), new waxeye.State([], true), new waxeye.State([new waxeye.Edge("h", 5, false)], false), new waxeye.State([new waxeye.Edge("a", 6, false)], false), new waxeye.State([new waxeye.Edge("r", 3, false)], false), new waxeye.State([new waxeye.Edge("o", 8, false)], false), new waxeye.State([new waxeye.Edge("o", 9, false)], false), new waxeye.State([new waxeye.Edge("l", 10, false)], false), new waxeye.State([new waxeye.Edge("e", 11, false)], false), new waxeye.State([new waxeye.Edge("a", 12, false)], false), new waxeye.State([new waxeye.Edge("n", 3, false)], false)], waxeye.FA.LEFT), new waxeye.FA("identifier", [new waxeye.State([new waxeye.Edge([[65, 90], "_", [97, 122]], 1, false)], false), new waxeye.State([new waxeye.Edge([[48, 57], [65, 90], "_", [97, 122]], 1, false)], true)], waxeye.FA.LEFT), new waxeye.FA("ws", [new waxeye.State([new waxeye.Edge([[9, 10], "\r", " "], 1, false)], false), new waxeye.State([], true)], waxeye.FA.VOID)]); return parser; })(); // Add to module system if (typeof module !== 'undefined') { module.exports.Parser = Parser; }
import React, { useState, useEffect } from "react"; import Loading from "../components/Loading"; import { useParams, Link } from "react-router-dom"; const url = "https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i="; const SingleCocktail = () => { const [loading, setLoading] = useState(false); const [info, setInfo] = useState({}); const { id } = useParams(); async function getCocktailById(id) { setLoading(true); const res = await fetch(url + id); const resJson = await res.json(); setInfo(resJson.drinks[0]); setLoading(false); } useEffect(() => { getCocktailById(id); }, [id]); const { // idDrink, strDrink, // strCategory, strDrinkThumb, strGlass, strInstructions, } = info; if (loading) { return <Loading />; } return ( <div className="container-fluid d-md-flex justify-content-center position-relative" id="cocktail-details" > <Link to="/"> <button className="position-absolute top-0 end-0 border-0 fs-3 iconBtn rounded me-2 px-2"> <i className="fas fa-arrow-left"></i> </button> </Link> <div className="img-container"> <img className="p-5 img-fluid" src={strDrinkThumb} alt={strDrink} /> </div> <div className="d-flex flex-column" id="cocktail-detail-text"> <h1>{strDrink}</h1> <h4>{strGlass}</h4> <p>{strInstructions}</p> </div> </div> ); }; export default SingleCocktail;
/** * @author v.lugovsky * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.fireControl') .controller('fireControlPageCtrl', fireControlPageCtrl); /** @ngInject */ function fireControlPageCtrl($scope, $filter, editableOptions, editableThemes,$location) { // $scope.smartTablePageSize = 20; // $scope.editableTableData = $scope.smartTableData.slice(0, 36); $scope.nationLaws = [ { "id": 1, "file_number":"主席令第30号", "name": "中华人民共和国刑法修正案(九)", "organization":"全国人大", "date":"2018-11-01", "status": 4, "group": 3 }, { "id": 2, "file_number":"根据2011年12月13日第十一届全国人民代表大会常务委员会《关于修改》", "name": "中华人民共和国职业病防治法", "organization":"人大常委会", "date":"2011-12-31", "status": 3, "group": 1 }, { "id": 3, "file_number":"国家安全生产监督管理总局令2007年第11号", "name": "注册安全工程师管理规定", "organization":"国家安全生产监督管理总局", "date":"2016-07-20", "status": 3, "group": 2 }, { "id": 4, "file_number":"主席令第4号 ", "name": "中华人民共和国循环经济促进法", "organization":"人大常委会", "date":"2009-01-01", "group": 4 }, { "id": 5, "file_number":"主席令第6号 ", "name": "中华人民共和国消防法(2008修订)", "organization":"人大常委会", "date":"2009-05-01", "status": 1, "group": 1 }, { "id": 6, "file_number":"主席令第30号", "name": "中华人民共和国刑法修正案(九)", "organization":"全国人大", "date":"2018-11-01", "status": 4, "group": 2 }, { "id": 7, "file_number":"主席令第30号", "name": "中华人民共和国刑法修正案(九)", "organization":"全国人大", "date":"2018-11-01", "status": 4, "group": 1 }, { "id": 8, "file_number":"主席令第30号", "name": "中华人民共和国刑法修正案(九)", "organization":"全国人大", "date":"2018-11-01", "status": 4, "group": 2 }, { "id": 9, "file_number":"主席令第30号", "name": "中华人民共和国刑法修正案(九)", "organization":"全国人大", "date":"2018-11-01", "status": 1, "group": 2 }, { "id": 10, "file_number":"主席令第30号", "name": "中华人民共和国刑法修正案(九)", "organization":"全国人大", "date":"2018-11-01", "status": 1, "group": 3 }, ]; // $scope.removeUser = function(index) { // $scope.users.splice(index, 1); // }; $scope.addLaw = function() { $scope.inserted = { id: $scope.nationLaws.length+1, file_number:"", name: "", organization:"", date:"", status: null, group: null }; $scope.nationLaws.push($scope.inserted); }; // 跳转编辑页面 $scope.editLaw = function(){ // $location.path(); console.log( $('#editContent') ); }; // 跳转删除页面 $scope.editLaw = function(){ // $location.path(); console.log( $('#editContent') ); }; editableOptions.theme = 'bs3'; editableThemes['bs3'].submitTpl = '<button type="submit" class="btn btn-primary btn-with-icon"><i class="ion-checkmark-round"></i></button>'; editableThemes['bs3'].cancelTpl = '<button type="button" ng-click="$form.$cancel()" class="btn btn-default btn-with-icon"><i class="ion-close-round"></i></button>'; } })();
'use strict' import path from 'path' import fs from 'fs' import test from 'ava' import m from '../../' const html = fs.readFileSync(path.join(__dirname, '../html/no-links.html'), 'utf8') test(t => { const out = m(html) t.true(Array.isArray(out)) t.true(out.length === 0) })
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import modalTypes from './modalTypes'; {/* import custom modal components*/} import PasswordResetModal from 'HomePage/ResetPassword'; import TermsOfServiceModal from 'HomePage/Statements/Terms'; import MissionStatementModal from 'HomePage/Statements/Mission'; import VisionStatementModal from 'HomePage/Statements/Vision'; import PassionStatementModal from 'HomePage/Statements/Passion'; import AboutUsModal from 'HomePage/Statements/About'; {/*import form modals*/} import EditBookModal from '../dashboard/modals/EditBookModal'; import EditAuthorModal from '../dashboard/modals/EditAuthorModal'; import ChangePasswordModal from '../dashboard/modals/ChangePasswordModal'; const MODAL_COMPONENTS = { RESET_PASSWORD_MODAL: PasswordResetModal, CHANGE_PASSWORD_MODAL: ChangePasswordModal, TERMS_OF_SERVICE_MODAL: TermsOfServiceModal, MISSION_STATEMENT_MODAL: MissionStatementModal, VISION_STATEMENT_MODAL: VisionStatementModal, PASSION_STATEMENT_MODAL: PassionStatementModal, ABOUT_US_MODAL: AboutUsModal, EDIT_BOOK_MODAL: EditBookModal, EDIT_AUTHOR_MODAL: EditAuthorModal } const contextTypes = { router: PropTypes.object.isRequired }; const propTypes = { modalType: PropTypes.string.isRequired } /** * @description - Custom modal component * @param {object} - props * @returns {JSX} - custom modal component to be rendered */ class ModalContainer extends Component { constructor(props){ super(props); this.state = { modalPayload: {} } } componentWillReceiveProps(nextProps){ if(this.state.modalPayload !== nextProps.payload){ this.setState({ modalPayload: Object.assign({}, this.state.modalPayload, nextProps.payload) }) } } render(){ if(!this.props.modalType){ return null } const SpecificModal = MODAL_COMPONENTS[this.props.modalType]; return( <div> <SpecificModal payload = {this.state.modalPayload}/> </div> ); } }; ModalContainer.contextTypes = contextTypes; ModalContainer.propTypes = propTypes; const mapStateToProps = state => ({ modalType: state.modal.modalType, payload: state.modal.payload }) export default connect(mapStateToProps)(ModalContainer);
angular.module('AdCshdwr').controller('NewCdrPymntItemController', function ($scope, $location, locationParser, CdrPymntItemResource ) { $scope.disabled = false; $scope.$location = $location; $scope.cdrPymntItem = $scope.cdrPymntItem || {}; $scope.pymntModeList = [ "CASH", "CHECK", "CREDIT_CARD", "VOUCHER" ]; $scope.save = function() { var successCallback = function(data,responseHeaders){ var id = locationParser(responseHeaders); $location.path('/CdrPymntItems/edit/' + id); $scope.displayError = false; }; var errorCallback = function() { $scope.displayError = true; }; CdrPymntItemResource.save($scope.cdrPymntItem, successCallback, errorCallback); }; $scope.cancel = function() { $location.path("/CdrPymntItems"); }; });
import React from 'react'; import Header from './Header'; import Form from './Form'; import Main from './Main'; class App extends React.Component { constructor() { super(); this.state = { name: "Next Transit of Venus", date: "10 Dec 2117", time: "23:58", timeLeftInSeconds: 0 } this.saveUserInput = this.saveUserInput.bind(this); this.formatTimeLeftDisplay = this.formatTimeLeftDisplay.bind(this); this.decrementTimeInSeconds = this.decrementTimeInSeconds.bind(this); } getEventTimeInSeconds(timeInput) { let timeInSeconds = 0; if (timeInput.length >= 4) { if (timeInput[1] === ':' || timeInput[2] === ':') { const hoursAndMinutes = timeInput.split(':'); const hours = parseInt(hoursAndMinutes[0]); const minutes = parseInt(hoursAndMinutes[1]); timeInSeconds = 3600*hours + 60*minutes; } } return timeInSeconds; } componentDidMount() { // Calculate seconds left to the default event (next transit of Venus). const timeLeftInSeconds = (Date.parse(this.state.date + ' ' + this.state.time) - Date.parse(new Date())) / 1000; this.setState({ timeLeftInSeconds: timeLeftInSeconds }); // Start decrementing seconds left to the event. setInterval(this.decrementTimeInSeconds, 1000); } decrementTimeInSeconds() { if (this.state.timeLeftInSeconds > 0) { this.setState(prevState => { return { timeLeftInSeconds: prevState.timeLeftInSeconds - 1 } }); } } formatTimeLeftDisplay() { let timeLeft = this.state.timeLeftInSeconds; if (timeLeft <= 0) { return 'It\'s happening! Or already happened.'; } let stringForDisplay = ''; const yearInSeconds = 31556926; const monthInSeconds = 2629744; const dayInSeconds = 86400; const hourInSeconds = 3600; const minuteInSeconds = 60; if (timeLeft >= yearInSeconds) { const yearCount = parseInt(timeLeft / yearInSeconds); stringForDisplay += yearCount; if (yearCount > 1) { stringForDisplay += ' years '; } else { stringForDisplay += ' year '; } timeLeft = timeLeft - yearCount * yearInSeconds; } if (timeLeft >= monthInSeconds) { const monthCount = parseInt(timeLeft / monthInSeconds); stringForDisplay += monthCount; if (monthCount > 1) { stringForDisplay += ' months '; } else { stringForDisplay += ' month '; } timeLeft = timeLeft - monthCount * monthInSeconds; } if (timeLeft >= dayInSeconds) { const dayCount = parseInt(timeLeft / dayInSeconds); stringForDisplay += dayCount; if (dayCount > 1) { stringForDisplay += ' days '; } else { stringForDisplay += ' day '; } timeLeft = timeLeft - dayCount * dayInSeconds; } const hourCount = parseInt(timeLeft / hourInSeconds); stringForDisplay += hourCount + ':'; timeLeft = timeLeft - hourCount * hourInSeconds; const minuteCount = parseInt(timeLeft / minuteInSeconds); if (minuteCount < 10) { stringForDisplay += '0'; } stringForDisplay += minuteCount + ':'; timeLeft = timeLeft - minuteCount * minuteInSeconds; if (timeLeft >= 10) { stringForDisplay += timeLeft; } else { stringForDisplay += '0' + timeLeft; } return stringForDisplay; } saveUserInput(e) { e.preventDefault(); const eventDateInMiliseconds = Date.parse(e.target.date.value); if (isNaN(eventDateInMiliseconds)) { console.warn('Please type in a valid date.'); alert('Hey, we can\'t start a countdown without properly formatted date!\n\n' + 'Please use one of the following formats:\n\n' + '2020-10-12\n12-10-2020\n12-10-20\n12 Oct 2020\n12 Oct 20'); } else if (e.target.name.value === '') { alert('What event do you want to start a countdown for? You didn\'t specify a name.'); } else { const eventTimeInSeconds = this.getEventTimeInSeconds(e.target.time.value); const eventDateTimeInSeconds = eventDateInMiliseconds / 1000 + eventTimeInSeconds; const currentDateTimeInSeconds = Date.parse(new Date()) / 1000; let timeLeftInSeconds = 0; if (eventDateTimeInSeconds - currentDateTimeInSeconds > 0) { timeLeftInSeconds = eventDateTimeInSeconds - currentDateTimeInSeconds; } let displayTime; if (eventTimeInSeconds > 0) { displayTime = e.target.time.value; } else { displayTime = '0:00'; } this.setState({ name: e.target.name.value, date: e.target.date.value, time: displayTime, timeLeftInSeconds: timeLeftInSeconds }); } } render() { return ( <div> <Header/> <Form eventData={this.state} saveUserInput={this.saveUserInput} /> <hr/> <Main eventData={this.state} formatTimeLeftDisplay={this.formatTimeLeftDisplay} /> </div> ); } } export default App;
// Calcola la somma e la media dei numeri compresi in un intervallo definito dall'utente // chiedo all'utente il numero minimo // e controllo che sia un numero valido // con ciclo do-while: var numero_minimo; do { numero_minimo = parseInt(prompt('inserisci limite minimo')); if(isNaN(numero_minimo)) { alert('input non corretto'); } } while (isNaN(numero_minimo)); // con ciclo while: // var numero_minimo = parseInt(prompt('inserisci limite minimo')); // while(isNaN(numero_minimo)) { // alert('input non corretto'); // numero_minimo = parseInt(prompt('inserisci limite minimo')); // } // chiedo all'utente il numero massimo // e controllo che sia un numero valido e che sia superiore al numero minimo var numero_massimo; do { numero_massimo = parseInt(prompt('inserisci limite massimo')); if(isNaN(numero_massimo) || numero_massimo <= numero_minimo) { alert('input non corretto'); } } while (isNaN(numero_massimo) || numero_massimo <= numero_minimo); // calcolo la somma dei numeri da numero_minimo a numero_massimo var somma = 0; // scorro tutti i numeri da numero_minimo a numero_massimo compreso for (var i = numero_minimo; i <= numero_massimo; i++) { // accumulo la somma dei numeri visti finora somma += i; // equivalente a: somma = somma + i; } // alla fine del ciclo ho la somma di tutti i numeri da numero_minimo a numero_massimo console.log('La somma dei numeri compresi tra ' + numero_minimo + ' e ' + numero_massimo + ' vale ' + somma); // // calcolo la media dei numeri da numero_minimo a numero_massimo var media = somma / (numero_massimo - numero_minimo + 1); console.log('La media dei numeri compresi tra ' + numero_minimo + ' e ' + numero_massimo + ' vale ' + media);
import React from 'react' import ClickOutside from 'react-click-outside' export default props => props.enabled ? ( <ClickOutside onClickOutside={ props.callback } > { props.children } </ClickOutside> ) : ( <> { props.children } </> )
const addButton = document.querySelector("#add-button"); const newTodo = document.querySelector("#new-to-do"); const taskList = document.querySelector("#task-list"); let temp = document.getElementsByTagName("template")[0]; let counter = 0; addButton.addEventListener("click", (event) => { event.preventDefault(); if(newTodo.value === "") { alert("You must add a task!"); } else { counter++; submitTask(); } }); function submitTask() { let docFrag = temp.content.cloneNode(true); //makes a clone of template let label = docFrag.querySelector("label") let inputTxt = docFrag.querySelector("input") label.textContent = newTodo.value; //add label inputTxt.id = "checkbox" + counter; //add unique id label.htmlFor = "checkbox" + counter; docFrag.querySelector(".deleteBtn").addEventListener("click", (event) => { event.target.parentElement.remove(); }) let checkbox = inputTxt; checkbox.addEventListener('change', () => { if (checkbox.checked){ label.style.textDecoration = "line-through" } else { label.style.textDecoration = "none" } }) taskList.appendChild(docFrag); document.querySelector("#new-to-do").value = ""; } //Image API window.addEventListener("load", () => { let randomNum = Math.floor(Math.random() * 10); fetch(`https://api.unsplash.com/photos/random?query=landscape&client_id=mtXzGZBpq9Gzv9wHdPMec37TIy6h6ZVclhfkxVRvygY&orientation=portrait`) .then((response) => { if (!response.ok) throw new Error(response.status); return response.json() }) .then((data) => { document.querySelector('.bg-image').src = data.urls.regular; }) .catch((error) => console.log(error)); });
var jq=$.noConflict();//避免和模板字面量发生冲突 var arrowUpFlg=1;//0表示下移,用在箭头动画上 var gNum=0;//用于存储作品的索引 jq(function(){ jq("#fullpageshow").fullpage({ sectionsColor : ["#8786c9", "#77b4c4", "#90ac78", "#70cfaf"], anchors: ["homepage", "educationpage","workspage", "contactpage"], menu: "#menu", loopBottom: true }); showImage(1);//显示默认作品图片 showPersonalInform(); jq(".icobox div").on("click",function(){ jq(".icobox div").attr("class","");//清除原class var imgIconNum=jq(this).data("imageiconnum"); jq(this).attr("class","active"); //console.log(imgIconNum); showImage(imgIconNum); }); setInterval(function(){//让箭头动起来 if(arrowUpFlg){ jq(".angledown").css({bottom:"0px"}); arrowUpFlg=0; }else{ jq(".angledown").css({bottom:"10px"}); arrowUpFlg=1; } jq(".angledown").fadeToggle(); },800); jq(".imagetitle").hover(function(){ jq(".imagebrief").css({"display":"block"}); jq(".imagebrief").empty(); var tempContent=`<div>${getImageBoxAndImageIntro[gNum-1].briefIntro}</div>`; jq(".imagebrief").append(tempContent); }); jq(".imagetitle").mouseout(function(){ jq(".imagebrief").empty(); jq(".imagebrief").css({"display":"none"}); }); }); function showPersonalInform(){ jq(".introlist").empty(); var arrLength=getPersonalInform.length-1;//最后一个是skillList //console.log(arrLength); for(var i=0;i<arrLength;i++){ var tempDiv=`<div class="${getPersonalInform[i].className}"> <i class="${getPersonalInform[i].iconAndText[0]}"></i> <p>${getPersonalInform[i].iconAndText[1]}</p> </div>`; jq(".introlist").append(tempDiv); } jq(".skill").empty(); var skArrLength=getPersonalInform[arrLength].skillList.length; for(var i=0;i<skArrLength;i++){ var tempSkillList=`<div> <i class="${getPersonalInform[arrLength].skillIcon}"></i> <span>${getPersonalInform[arrLength].skillList[i]}</span> </div>`; jq(".skill").append(tempSkillList); } } function showImage(num){//显示作品图片 gNum=num;//用于鼠标移动到title上显示内容; jq(".imagebox").empty();//清空以便显示 var tempImage=`<a href="${getImageBoxAndImageIntro[num-1].hrefValue}" target="_blank" title="点击体验"> <img src="${getImageBoxAndImageIntro[num-1].imageSrc}"></a>`; //console.log(getImageBoxAndImageIntro[num-1].imageSrc); jq(".imagebox").append(tempImage);//显示最新信息 /* --------- 以下显示作品标题-----------*/ jq(".imagetitle").empty();//清空以便显示 var tempP=jq("<p></p>"); tempP.text(getImageBoxAndImageIntro[num-1].title); jq(".imagetitle").append(tempP);//显示最新信息 } var getPersonalInform=[{ "className":"edubg", "iconAndText":["fa fa-mortar-board","学历/本科"], },{ "className":"age", "iconAndText":["fa fa-clock-o","出生/92年"], },{ "className":"location", "iconAndText":["fa fa-map-marker","目前/南京"], },{ "className":"state", "iconAndText":["fa fa-smile-o","状态/求职"], },{ "skillIcon":"fa fa-hand-o-right", "skillList":[ "熟悉javascript脚本、jquery框架和ajax、API技术等", "了解JS原型链、React、bootstrap等框架、用IIS搭过网站", "应用工具: Visual Studio Code、github桌面版、codeOpen、photoshop、npm等", "15年南通大学毕业,2年销售助理经验;17年10月自学前端开发", "计算机水平: 全国计算机二级、江苏省计算机二级(C++)、江苏省计算机三级(偏硬)证书", "外语水平: 六级" ] } ]; var getImageBoxAndImageIntro=[{ "hrefValue":"indexwiki.html", "imageSrc":"images/wiki.png", "title":"维基百科单词查询", "briefIntro":"该作品利用jQuery的Ajax等技术,通过维基百科API实现单词查询,点击可连接到维基百科了解详情" },{ "hrefValue":"indexweather.html", "imageSrc":"images/weather.png", "title":"天气查询", "briefIntro":"该作品利用jQuery的Ajax等技术,通过聚合数据的API实现天气查询,并显示当天及未来五天的天气情况.背景图片及天气图标随因早中晚的不同变化" },{ "hrefValue":"indexcard.html", "imageSrc":"images/game.png", "title":"纸牌游戏", "briefIntro":"该游戏由JS源码编写,未添加任何库。可实现游戏暂停、继续等操作" },{ "hrefValue":"indextwitch.html", "imageSrc":"images/twitch.png", "title":"Twitch最受欢迎游戏排行", "briefIntro":"该作品利用jQuery的Ajax技术,通过Twitch的API实现Twitch上最受欢迎游戏前三名排行,且前两名的最近一周最热主播排行,点击可观看" },{ "hrefValue":"indexmeme.html", "imageSrc":"images/meme.png", "title":"简易表情包制作", "briefIntro":"该作品利用JS源码及canvas,实现简易表情包制作,可实现保存、清除等(请用火狐浏览器体验)." },{ "hrefValue":"indexdanmu.html", "imageSrc":"images/danmu.png", "title":"弹幕", "briefIntro":"该弹幕利用jQuery和bootstrap完成,可实现颜色随机,出现几率随机" },{ "hrefValue":"indexquote.html", "imageSrc":"images/quote.png", "title":"随机引言", "briefIntro":"该作品利用jQuery、bootstrap及font-awesome完成,可实现颜色随机,出现几率随机" } ];
//Controller /* global angular, candy */ //コントローラーの作成 'use strict'; candy.controller('candyTopController', function($scope){ $scope.message = message; $scope.changeText = function(inputText){ $scope.message = inputText + '_output'; text.add(inputText); console.log(text.value); }; }); //必要な分コントローラーを作成する(ファイル分ける?) /* candy.controller('xxxController', function($scope){ $scope.varName = value; //ここにはあまり書かないで、サービスから持ってくるのがセオリー? }); */
import React from 'react'; import './../styles/article-template-styles/List.css'; const List = ({type, items}) => { let listContents = items.map((listItem) => { return(<li>listItem</li>) }) if (type === "unordered") { return ( <div> <ul> {listContents} </ul> </div> ) } else if (type === "ordered") { return ( <div> <ol> {listContents} </ol> </div> ) } } export default List;
import React, { Component } from 'react'; import { onClearAll, clearAll, connectLecturer, onQuestionReceived, onQuestionAnswered, joinRoom, Header, onRoomsRecieved, connectRoom, Footer } from './api'; let HtmlToReactParser = require('html-to-react').Parser; let htmlToReactParser = new HtmlToReactParser(); const HashMap = require('hashmap'); function makeRoom(room) { let html_component = '<div className="question">' + '<p>' + room.toString() + '</p>' + '<div className="button_info">' + '<a className="question_link" href="/lecturer/' + room.toString() + '">' + 'goto lecturer room' + '</a>' + '</div>' + '<div className="button_info">' + '<a className="question_link" href="/student/' + room.toString() + '">' + 'goto student room' + '</a>' + '</div>' + '</div>'; return html_component; } function Rooms(props) { let rooms = props.value; let i, res = "<br/>"; for (i = 0; i < rooms.length; i++) { res = res + makeRoom(rooms[i]); } let jsx_res = htmlToReactParser.parse(res); return ( jsx_res ); } class Room extends Component { constructor(props) { super(props); this.state = { rooms: [], roomName: "" } this.createRoom = this.createRoom.bind(this); this.updateRoomField = this.updateRoomField.bind(this); connectRoom(); onRoomsRecieved(rooms => { this.setState({rooms: rooms, roomName: this.state.roomName}); }); } createRoom() { joinRoom(this.state.roomName); } updateRoomField(e) { this.setState({roomName: e.target.value}); } render() { return ( <div> <Header value="Room"/> <div id="Question_box"> <h2>CREATE NEW ROOM</h2> <form id="Question_form"> <input type="text" value={this.state.roomName} onChange={this.updateRoomField}/> </form> <button onClick={this.createRoom}>Create Room</button> </div> <Rooms value={this.state.rooms}/> <Footer /> </div> ); } } export default Room;
$(()=>{ $.ajax({ url:"/", type:"POST", data:{ action: 'getRaisons' }, success:function(response){ var raisons = JSON.parse(response); for (var i = 0; i < raisons.length; i++){ var option = $('<option>').val(raisons[i]).text(raisons[i]); $('#raisons').append(option); } }, error: function(err){ } }); $('#tabAnnulationEtatDocuments').hide(); $('#select_raisons').hide(); $('#annulation_professeur').hide(); $("#choisirEtudiantAnnulation").on("click", function(){ let etudiant = $('#etudiantsAnnulation').val(); $.ajax({ url: '/', type: 'POST', data:{ action: 'etatDocuments', etudiant: etudiant }, success: function(response){ $('#tabAnnulationEtatDocuments').show(); $('#select_raisons').show(); $('#annulation_professeur').show(); const documents = JSON.parse(response); if(documents.contratBourse){ $('tabAnnulationEtatDocuments [name=contrat_de_bourse]').text('signé'); } else{ $('tabAnnulationEtatDocuments [name=contrat_de_bourse]').text('non-signé'); } if(documents.conventionEtude){ $('tabAnnulationEtatDocuments [name=convention_d_etude]').text('signé'); } else{ $('tabAnnulationEtatDocuments [name=convention_d_etude]').text('non-signé'); } if(documents.conventionStage){ $('tabAnnulationEtatDocuments [name=convention_stage]').text('signé'); } else{ $('tabAnnulationEtatDocuments [name=convention_stage]').text('non-signé'); } if(documents.charteEtudiant){ $('tabAnnulationEtatDocuments [name=charte_etudiant]').text('signé'); } else{ $('tabAnnulationEtatDocuments [name=charte_etudiant]').text('non-signé'); } if(documents.documentEngagement){ $('tabAnnulationEtatDocuments [name=document_engagement]').text('signé'); } else{ $('tabAnnulationEtatDocuments [name=document_engagement]').text('non-signé'); } if(documents.premierPaiement){ $('tabAnnulationEtatDocuments [name=paiement_bourse]').text('signé'); } else{ $('tabAnnulationEtatDocuments [name=paiement_bourse]').text('non-signé'); } }, error: function(e){ $('#tabAnnulationEtatDocuments').hide(); } }); }); }); $("#annulation_professeur").on("click", function(){ if($("#raison").val() === ""){ $("#alert").css("display", "block"); } let id_raison = $("#raisons option:selected").val(); let etudiant = $('#etudiantsAnnulation').val(); $.ajax({ url: '/', type: 'POST', data:{ action: 'annulationMobilite', etudiant: etudiant, id_raison: id_raison }, success: function(response){ if(response === "ok"){ $("#alert1").css("display", "none"); } }, error: function(e){ console.log("probleme logout"); } }) })
/** * 绘制彩色三角形 */ // 顶点着色器, 描述顶点特性 const VSHADER_SOURCE = ` // x' = x cos b - y cos b // y' = x sin b + y sin b // z' = z attribute vec4 a_Position; attribute vec4 a_Color; varying vec4 v_Color; void main() { gl_Position = a_Position; v_Color = a_Color; } `; // 片元着色器, 处理像素 const FSHADER_SOURCE = ` precision mediump float; varying vec4 v_Color; void main() { gl_FragColor = v_Color; } `; function main() { const canvas = document.querySelector("#canvas"); const gl = getWebGLContext(canvas); if (!gl) { console.error("无法取得WebGL渲染上下文!"); return; } const initShaderFlag = initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE); if (!initShaderFlag) { console.error("初始化着色器失败!"); return; } updateDraw(gl); } function initVertexBuffers(gl) { const vertexes = new Float32Array([ -0.5, -0.5, 1.0, 0, 0, 0.5, -0.5, 0, 1.0, 0, 0.0, 0.5, 0, 0, 1.0 ]); const FSIZE = vertexes.BYTES_PER_ELEMENT; const len = vertexes.length / 5; const vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertexes, gl.STATIC_DRAW); // 获取a_Position的存储位置 var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.error("无法找到attribute变量"); return -1; } gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 5, 0); // 建立缓冲区到attribute真正连接 gl.enableVertexAttribArray(a_Position); const a_Color = gl.getAttribLocation(gl.program, 'a_Color'); if (a_Color < 0) { console.error("无法找到a_Color变量"); return -1; } gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE* 5, FSIZE * 2); gl.enableVertexAttribArray(a_Color); return len; } let rotate = 0; function updateDraw(gl) { const len = initVertexBuffers(gl); gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, len); requestAnimationFrame(() => updateDraw(gl)); }
var searchData= [ ['fetch',['fetch',['../classca_1_1mcgill_1_1ecse211_1_1project_1_1_color_detection.html#aee26e087153652f917eeffaa401f2f66',1,'ca::mcgill::ecse211::project::ColorDetection']]], ['finalproject',['FinalProject',['../classca_1_1mcgill_1_1ecse211_1_1project_1_1_final_project.html',1,'ca::mcgill::ecse211::project']]], ['findmatch',['findMatch',['../classca_1_1mcgill_1_1ecse211_1_1project_1_1_color_detection.html#ae54bb939c7d1dec3027bf052d18865bf',1,'ca::mcgill::ecse211::project::ColorDetection']]] ];
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import AccountsUIWrapper from "./AccountsUIWrapper/AccountsUIWrapper"; import {Link} from "react-router-dom"; import {Button} from "@material-ui/core"; import Grid from "@material-ui/core/Grid"; import { green } from '@material-ui/core/colors'; const useStyles = makeStyles({ root: { flexGrow: 1, }, link: { color: 'gold' } }); export default () => { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position="static"> <Toolbar style={{backgroundColor: 'green'}}> <Grid justify="space-between" // Add it here :) container> <Grid item> <Link to={'/'} className={classes.link}> <Button color={'inherit'}> Home </Button> </Link> <Link to={'/games/new'} className={classes.link}> <Button color={'inherit'}> New Game </Button> </Link> <Link to={'/how-to-play'} className={classes.link}> <Button color={'inherit'}> How To Play </Button> </Link> </Grid> <Grid item> <AccountsUIWrapper/> </Grid> </Grid> </Toolbar> </AppBar> </div> ); }
const authorizedHandler = function () { load_uploader(); $('.drop').removeClass('blur'); $('.side:not(.section--problem-sidebar)').removeClass('blur'); $('.sidebar .menu__item:nth-child(1) a').attr("href","javascript:;") $('.sidebar .menu__item:nth-child(3) a').attr("href","/code_detail") $('.sidebar .menu__item:nth-child(4) a').attr("href","/user#analysis") } const unauthorizedHandler = function () { loginHandler(); $('#upload-login').removeClass('hide'); $('.sidebar .menu__item:nth-child(1) a').attr("href","javascript:unauthorizedHandler();") $('.sidebar .menu__item:nth-child(3) a').attr("href","javascript:unauthorizedHandler();") $('.sidebar .menu__item:nth-child(4) a').attr("href","javascript:unauthorizedHandler();") }
import React from 'react'; import { StyleSheet, View, TouchableHighlight } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import PropTypes from 'prop-types'; const FloatAction = ({ onPress, name }) => ( <View style={ styles.container }> <TouchableHighlight underlayColor="#2d919e" style={ styles.touchable } onPress={ onPress } > <View style={ styles.border }> <Icon name={ name } size={ 18 } color="#b6f6e4" /> </View> </TouchableHighlight> </View> ); FloatAction.propTypes = { onPress: PropTypes.func.isRequired, name: PropTypes.string, }; FloatAction.defaultProps = { name: 'close', }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', position: 'absolute', bottom: 25, width: '100%', }, touchable: { justifyContent: 'center', alignItems: 'center', backgroundColor: '#1b8796', width: 40, height: 40, borderRadius: 20, }, border: { borderColor: '#b6f6e4', borderWidth: 1, width: 32, height: 32, borderRadius: 16, justifyContent: 'center', alignItems: 'center', }, }); export default FloatAction;
const { Readable } = require('stream'); const path = require('path'); const fs = require('fs-extra'); const { SitemapStream, streamToPromise } = require('sitemap'); const dayjs = require('dayjs'); module.exports = async function (renderedPages) { // create sitemap const sitemapLinks = renderedPages .filter((p) => { return ( p.data.route.name === 'post-item' || p.data.route.name === 'index' || p.data.route.name === 'contatti' || (p.data.route.name === 'blog' && p.data.pagination.page === 1) || (p.data.route.name === 'blog-by-category' && p.data.pagination.page === 1) || (p.data.route.name === 'portfolio' && p.data.pagination.page === 1) ); }) .map((p) => { let priority; let format = 'YYYY-MM-DD'; let lastmod = dayjs().format(format); if (p.data.route.name === 'index') { priority = 1; } else if ( p.data.route.name === 'blog' || p.data.route.name === 'blog-by-category' || p.data.route.name === 'portfolio' ) { priority = 0.7; } else if (p.data.route.name === 'post-item') { priority = 0.3; lastmod = dayjs(p.data.pagination.items[0].updated).format( format, ); } return { url: p.data.route.href, lastmod, priority, }; }); const stream = new SitemapStream({ hostname: 'https://www.signalkuppe.com', }); const data = await streamToPromise( Readable.from(sitemapLinks).pipe(stream), ); await fs.writeFile( path.join(pequeno.config.outputDir, 'sitemap.xml'), data.toString(), 'utf8', ); };
(function(){ // rendering engine var Render = function(selector, data){ var tmpl = document.querySelector(selector).innerHTML.trim(); var matches = tmpl.match(/<(\w+)>(.*)<\/(\w+)>/); var newItem = document.createElement(matches[1]); newItem.innerHTML = matches[2].replace('{this}', data); return newItem; }; // Model class function Model(conf){ this.data = {}; this._listeners = {}; Object.assign(this, conf); } Model.prototype.trigger = function(events, data){ var events = events.split(/\W+/); var that = this; events.forEach(function(event){ if (that._listeners[event]){ that._listeners[event].forEach(function(listener){ listener(data); }); } }); }; Model.prototype.listen = function(events, listener){ var events = events.split(/\W+/); var that = this; events.forEach(function(event){ if (!that._listeners[event]){ that._listeners[event] = [listener]; } else { that._listeners[event].push(listener); } }); }; // View class function View(conf){ Object.assign(this, conf); this.init(); }; View.prototype.clear = function(){ this.$dom.parentNode.removeChild(this.$dom); }; View.prototype.listenTo = function(model, event, listener){ model.listen(event, listener); }; // app var appModel = new Model({ data: [], add: function(item){ this.data.push(item); this.trigger('add', item); }, remove: function(item){ var index = this.data.indexOf(item); this.data.splice(index, 1); this.trigger('delete', index); } }); var appView = new View({ $dom: document.querySelector('#view'), init: function(){ this.$count = this.$dom.querySelector('.jsCount'); this.$list = this.$dom.querySelector('.jsList'); this.$listEmpty = this.$dom.querySelector('.jsListEmpty'); this.$input = this.$dom.querySelector('.jsInput'); this.$add = this.$dom.querySelector('.jsAdd'); this.$add.addEventListener('click', this._onClickAdd.bind(this), false); this.listenTo(appModel, 'add', this.add.bind(this)); this.listenTo(appModel, 'delete', this.delete.bind(this)); this.listenTo(appModel, 'add delete', this.update.bind(this)); }, add: function(item){ var newItem = Render('#js-tmpl-item', item); newItem.querySelector('.jsDelete').addEventListener('click', function(){ appModel.remove(item); }, false); this.$list.appendChild(newItem); }, delete: function(index){ this.$list.removeChild(this.$list.querySelectorAll('li')[index + 1]); }, update: function(){ this.$count.innerHTML = appModel.data.length; if (appModel.data.length > 0){ this.$listEmpty.style.display = 'none'; } else { this.$listEmpty.style.display = 'block'; } }, _onClickAdd: function(){ var input = this.$input.value.trim(); if (input.length === 0){ return; } appModel.add(input); this.$input.value = ''; } }); })();
import Vue from 'vue' import Router from 'vue-router' // Containers const DefaultContainer = () => import ('@/containers/DefaultContainer') // Views const Dashboard = () => import ('@/views/Dashboard') const Login = () => import ('@/views/auth/Login') // User const Users = () => import ('@/views/user/Index') Vue.use(Router) export default new Router({ mode: 'hash', // https://router.vuejs.org/api/#mode linkActiveClass: 'open active', scrollBehavior: () => ({ y: 0 }), routes: [{ path: '/', name: 'Login', component: Login, }, // { // path: '/dashboard', // name: 'dashboard', // component: () => // import ( /* webpackChunkName: "Auth" */ "@/views/dashboard/Index"), // }, { path: '/home', redirect: '/dashboard', name: 'Home', component: DefaultContainer, children: [{ path: '/dashboard', name: 'Dashboard', component: Dashboard, }, { path: '/users', name: 'Users', component: Users }, ] }, ] })
import request from "request"; import fs from "fs"; import get from "lodash/get"; import axios, { post } from "axios"; var FormData = require("form-data"); import envVariables from "../EnvironmentVariables"; let egovFileHost = envVariables.EGOV_FILESTORE_SERVICE_HOST; /** * * @param {*} filename -name of localy stored temporary file * @param {*} tenantId - tenantID */ export const fileStoreAPICall = async function(filename, tenantId, fileData) { var url = `${egovFileHost}/filestore/v1/files?tenantId=${tenantId}&module=pdfgen&tag=00040-2017-QR`; var form = new FormData(); form.append("file", fileData, { filename: filename, contentType: "application/pdf" }); let response = await axios.post(url, form, { headers: { ...form.getHeaders() } }); return get(response.data, "files[0].fileStoreId"); };
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var tkn = ""; window.onload = function () { var btn = document.getElementById("btnBuscar"); btn.onclick = () => { let e = document.getElementById("cbxReporte"); let tipoReporte = e.value; console.log(tipoReporte); if (tipoReporte === "Materiales") { reportesMaterials(); } else if (tipoReporte === "Congestiones") { reportesCongestiones(); } }; var btnUser = document.getElementById("btnUser"); btnUser.onclick = () => { var user = document.getElementById("user"); var password = document.getElementById("password"); iniciarSesion(user.value, password.value); }; }; async function reportesMaterials() { if (tkn === "") { alert("Inicie sesión..."); } else if (tkn === "No se encontró el usuario") { alert("Inicie sesión..."); } else if (tkn !== "" && tkn !== "No se encontró el usuario") { try { let res = await fetch("http://localhost:8888/reportes/materiales", { method: 'POST', body: tkn, // data can be `string` or {object}! headers: { 'Content-Type': 'application/json; charset=UTF-8' } }) .then(res => res.json()) .then(reports => { console.log(reports) tablaMateriales(reports) }) } catch (error) { console.log(error); } } } ; async function reportesCongestiones() { if (tkn === "") { alert("Inicie sesión..."); } else if (tkn === "No se encontró el usuario") { alert("Inicie sesión..."); } else if (tkn !== "" && tkn !== "No se encontró el usuario") { try { let res = await fetch("http://localhost:8888/reportes/congestiones",{ method: 'POST', body: tkn, // data can be `string` or {object}! headers: { 'Content-Type': 'application/json; charset=UTF-8' } }) .then(res => res.json()) .then(reports => { console.log(reports) tablaCongestiones(reports) }) } catch (error) { console.log(error); } } } ; async function iniciarSesion(name, password) { try { let data = {name: name, password: password}; console.log(JSON.parse(JSON.stringify(data))) let res = await fetch("http://localhost:8888/usuario/validar", { method: 'POST', body: JSON.stringify(data), // data can be `string` or {object}! headers: { 'Content-Type': 'application/json; charset=UTF-8' } }) .then((res) => res.json()).then(json => { tkn = JSON.stringify(json); console.log(tkn) }); ; } catch (error) { console.log(error); } } ; async function tablaCongestiones(reports) { let tablaEncabezado = ` <table class="center"> <tr> <td>Id</td> <td>Eventualidad</td> <td>Ubicacion</td> <td>Causa</td> <td>Matricula</td> </tr> </table> `; borrar(); document.getElementById("materiales").innerHTML += tablaEncabezado; for (let i = 0; i < reports.length; i++) { let lista = ` <table class="center"> <tr> <td>${reports[i].id}</td> <td>${reports[i].eventualidad}</td> <td>${reports[i].ubicacion}</td> <td>${reports[i].causa}</td> <td>${reports[i].matricula}</td> </tr> </table> `; document.getElementById("materiales").innerHTML += lista; } } ; async function tablaMateriales(reports) { let tablaEncabezado = ` <table class="center"> <tr> <td>Id</td> <td>Tipo</td> <td>Cantidad</td> <td>Material</td> </tr> </table> `; borrar(); document.getElementById("materiales").innerHTML += tablaEncabezado; for (let i = 0; i < reports.length; i++) { let lista = ` <table class="center"> <tr> <td>${reports[i].id}</td> <td>${reports[i].tipo}</td> <td>${reports[i].cantidad}</td> <td>${reports[i].vehiculo}</td> </tr> </table> `; document.getElementById("materiales").innerHTML += lista; } } ; function borrar() { var dom = document.getElementById("materiales"); while (dom.hasChildNodes()) dom.removeChild(dom.firstChild); }
import React, { useState } from "react"; import { StyledInput } from "../../styles"; function EditableTd({ value, keyValue, editMode, onValueChange }) { const [loc, setLoc] = useState(value); function onChange({ target }) { setLoc(target.value); } function onBlur({ target }) { onValueChange(target); } return ( <td> {editMode && keyValue !== "id" ? ( <StyledInput value={loc} name={keyValue} type="text" onChange={onChange} onBlur={onBlur} /> ) : ( <span>{loc}</span> )} </td> ); } export default EditableTd;
// 初始變數 const list = document.querySelector("#my-todo"); const addBtn = document.querySelector("#add-btn"); const input = document.querySelector("#new-todo"); const container = document.querySelector(".container"); const doneList = document.querySelector('#done') const alert = document.querySelector('.text-alert') // 資料 let todos = [ '核心運動*3回合', '全聯採購防疫物資', '銀行辦事', '整理房間', '製作個人 side-project' ]; for (let todo of todos) { addItem(todo) } // 函式 function addItem(text) { let newItem = document.createElement("li") newItem.innerHTML = ` <label for="todo">${text}</label> <i class="delete fa fa-trash"></i> ` list.appendChild(newItem) } function addItemCheck(value) { if (value.trim() === '') { alert.hidden = false } else { alert.hidden = true addItem(value) } } // Create input.addEventListener("keypress", function (event) { const inputValue = input.value if (event.key === 'Enter') { addItemCheck(inputValue) input.value = '' } }) addBtn.addEventListener("click", function () { const inputValue = input.value addItemCheck(inputValue) input.value = '' }) // Delete, Checked, Sendback to myTodo container.addEventListener("click", function (event) { const target = event.target console.log(target) if (target.classList.contains("delete")) { let parentElement = target.parentElement parentElement.remove() } else if (target.tagName === "LABEL" && target.parentElement.parentElement.classList.contains('todo')) { target.classList.toggle('checked') const doneItem = document.createElement('li') doneItem.innerHTML = ` <label for="todo" class="checked">${target.innerText}</label> <i class="delete fa fa-trash"></i>` doneList.appendChild(doneItem) target.parentElement.remove() } else if (target.tagName === "LABEL" && target.parentElement.parentElement.classList.contains('done')) { target.classList.toggle('checked') const sendbackItem = target.parentElement sendbackItem.remove() list.appendChild(sendbackItem) } })
const jsonwebtoken = require('jsonwebtoken'); const User = require('../module/user/model'); module.exports = async (req, res, next) => { try { let authData = await jsonwebtoken.verify(req.headers['accesstoken'], 'secretkey'); req.user = await User.findOne({'username': authData.username}); next(); } catch (e) { res.json({ error: e.message }); } };
import babel from 'rollup-plugin-babel'; import cleanup from 'rollup-plugin-cleanup'; import camelCase from 'lodash/camelCase'; import commonjs from 'rollup-plugin-commonjs'; import path from 'path'; import resolve from 'rollup-plugin-node-resolve'; import sourceMaps from 'rollup-plugin-sourcemaps'; import typescript from 'rollup-plugin-typescript2'; import { terser } from 'rollup-plugin-terser'; import { DEFAULT_EXTENSIONS } from '@babel/core'; import pkg from './package.json'; const FORMATS = ['umd', 'cjs', 'esm']; const name = pkg.name; const libraryName = camelCase(name); const basePath = path.resolve(__dirname); const distPath = path.resolve(basePath, 'dist'); const inputPath = path.resolve(basePath, pkg.index); const bannerText = `/*! ${libraryName} v${pkg.version} | Copyright (c) 2016-2019 Jacob Müller */`; const banner = text => ({ name: 'banner', renderChunk: code => ({ code: `${text}\n${code}`, map: null }) }); const getFileName = (baseName, format, minify) => [baseName, format !== 'umd' ? format : null, minify ? 'min' : null, 'js'] .filter(Boolean) .join('.'); const createConfig = (format, minify = false) => ({ input: inputPath, output: { format, name: libraryName, file: path.resolve(distPath, getFileName(name, format, minify)), sourcemap: true }, plugins: [ resolve(), format === 'umd' ? commonjs() : null, typescript({ typescript: require('typescript'), cacheRoot: `.cache/typescript` }), babel({ exclude: 'node_modules/**', extensions: [...DEFAULT_EXTENSIONS, 'ts', 'tsx'] }), sourceMaps(), cleanup({ comments: 'none' }), minify ? terser({ sourcemap: true, compress: { passes: 10 }, ecma: 5, toplevel: format === 'cjs', warnings: true }) : null, banner(bannerText) ].filter(Boolean) }); export default [ ...FORMATS.map(format => createConfig(format)), ...FORMATS.map(format => createConfig(format, true)) ];
import React from 'react'; import { TOP_RATED_URL } from './../../constants'; import { MovieGrid } from './../../components/MovieGrid'; export const TopRated = () => { return ( <MovieGrid url={TOP_RATED_URL} title="Top Rated" /> ) }
import React from 'react'; import PropTypes from 'prop-types'; import { useMutation } from '@apollo/client'; import { FeatureGroup } from 'react-leaflet'; import { EditControl } from 'react-leaflet-draw'; import { CREATE_OBJECT, UPDATE_OBJECTS, REMOVE_OBJECTS } from './requests'; const EditableLayerService = ({ layer, options: { draw, edit }, children }) => { const [createObject] = useMutation(CREATE_OBJECT); const [updateObjects] = useMutation(UPDATE_OBJECTS); const [removeObjects] = useMutation(REMOVE_OBJECTS); function onCreateObject(created) { createObject({ variables: { id: layer, object: created.toGeoJSON() } }); } function onEditObjects(edited) { const objects = []; edited.eachLayer(object => { objects.push({ id: object.options.id, data: object.toGeoJSON() }); }); updateObjects({ variables: { id: layer, objects } }); } function onRemoveObjects(removed) { const objects = []; removed.eachLayer(object => { objects.push(object.options.id); }); removeObjects({ variables: { id: layer, objects } }); } function onLayerAdd({ layer: added, target: tables }) { if (added.options.id) { tables.eachLayer(table => { if (!table.options.id) { table.remove(); } }); } } return ( <FeatureGroup onLayeradd={onLayerAdd}> <EditControl position="topright" draw={{ ...draw }} edit={{ ...edit }} onCreated={({ layer: createdLayer }) => onCreateObject(createdLayer)} onEdited={({ layers: editedLayers }) => onEditObjects(editedLayers)} onDeleted={({ layers: removedLayers }) => onRemoveObjects(removedLayers)} /> {children} </FeatureGroup> ); }; const optionsType = { draw: PropTypes.object, edit: PropTypes.object }; EditableLayerService.propTypes = { layer: PropTypes.string.isRequired, options: PropTypes.shape(optionsType).isRequired, children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.element), PropTypes.element]) .isRequired }; export default EditableLayerService;
import React from "react"; import ReactDOM from "react-dom"; import Card from "../src/components/card"; import services from "../src/components/services" // inserting props from service file and later using map method to loop over it in renderDom function elements(items){ return( <Card key={items.cost} plan = {items.plan} cost={items.cost} duration={items.duration} service1={items.service1} service2={items.service2} service3={items.service3} service4={items.service4} service5={items.service5} service6={items.service6} service7={items.service7} service8={items.service8}/>) } ReactDOM.render( <div className="parentDiv"> {services.map(elements)} </div>, document.getElementById("root"));
/* global it, expect, describe */ import React from 'react' import Adapter from 'enzyme-adapter-react-16' import { shallow, configure } from 'enzyme' import renderer from 'react-test-renderer' import App from '../pages/index' configure({ adapter: new Adapter() }) const photos = new Array(15).fill(0).map((v, k) => k + 1) const url = { pathname: '/', query: {} } describe('With Enzyme', () => { it('App have 15 photos', () => { const app = shallow(<App photos={photos} url={url} />) expect(app.find('.photo').length).toBe(15) }) }) describe('With Snapshot Testing', () => { it('App have 15 photos', () => { const component = renderer.create(<App photos={photos} url={url} />) const tree = component.toJSON() expect(tree).toMatchSnapshot() }) })
import React, { useState } from 'react'; import '../design.css'; import {connect} from 'react-redux'; import myStore from '../store/store'; function Transaction(props){ const [transaction,setTransaction]=useState({}); return<div> <div class='lower'> <h4>Add New Transaction</h4> </div> <div> <h4>Text</h4> <input id='text' type='text' placeholder='Enter Text' class='width' onChange={(evt)=>{ setTransaction({ ...transaction, }) setTransaction({ ...transaction, text:evt.target.value }) }}/> <h4>Amount</h4> <h3>(-ve = expense , +ve = income)</h3> <input id='amount' type='number' placeholder='Enter Amount' class='width' onChange={(evt)=>{ const abc = parseFloat(evt.target.value, 10); setTransaction({ ...transaction, amount: abc }) }}/><br/><br/> <input class='btn' type='submit' value='Add Transaction' onClick={(evt)=>{ let id = props.balanceReducer.transaction.length; props.dispatch({ type: 'T', ID: id + 1, text: transaction.text, amount: transaction.amount }) }}/> </div> </div> } export default connect(function(myStore){ return myStore; })(Transaction);
import React from 'react'; import PropTypes from 'prop-types'; const SmallFeatureComponent = () => { return ( <div className="container"> <div className="row"> <div className="col-xl-4 col-md-4 col-sm-12"> <div className="about-smallservice"> <i class="fab fa-accessible-icon" aria-hidden="true"></i> <h5>Business with Thought Leadership</h5> </div> </div> <div className="col-xl-4 col-md-4 col-sm-12"> <div className="about-smallservice"> <i class="fab fa-accessible-icon" aria-hidden="true"></i> <h5>Business with Thought Leadership</h5> </div> </div> <div className="col-xl-4 col-md-4 col-sm-12"> <div className="about-smallservice"> <i class="fab fa-accessible-icon" aria-hidden="true"></i> <h5>Business with Thought Leadership</h5> </div> </div> </div> </div> ); }; SmallFeatureComponent.propTypes = {}; export default SmallFeatureComponent;
var GenerateBaseFilter = function(List, keyName, valueName, tipMsg){ // 纯函数 let _filter = function(list, keyName, keyValue, valueName, tipMsg){ let len = list.length; let tip = tipMsg?tipMsg:'(暂无信息)'; for (let i=0; i<len; i++) { if (list[i][keyName] == keyValue) { return list[i][valueName]; } } return tip; }; return function(key){ let arr = []; let resultArr = []; // if (typeof key === 'number') { // key = key+''; // } // if (typeof key === 'string') { // arr = key.split(','); // } else if (key instanceof Array) { // arr = key; // } if (key instanceof Array) { arr = key; } else { key = key+''; arr = key.split(','); } arr.map((item)=>{ resultArr.push(_filter(List, keyName, item, valueName)); }); return resultArr.join(','); }; }; export default GenerateBaseFilter;
// example theme file import theme from '@theme-ui/preset-dark'; export default { ...theme, sizes: { ...theme.sizes, container: 768, }, styles: { ...theme.styles }, fonts: { ...theme.fonts, body: 'Nunito Sans, sans-serif', }, links: { nav: { display: 'inline-block', px: 2, py: 2, mr: 1, color: 'rgba(255,255,255,.65)', textDecoration: 'none', fontSize: 2, fontWeight: 'bold', bg: 'transparent', transitionProperty: 'background-color', transitionTimingFunction: 'ease-out', transitionDuration: '.2s', borderRadius: 2, '&:hover': { bg: 'highlight', }, '&.active': { color: 'white', bg: 'highlight', }, }, }, text: { caps: { textTransform: 'uppercase', letterSpacing: '.2em', }, heading: { fontFamily: 'heading', fontWeight: 'heading', lineHeight: 'heading', }, display: { // extends the text.heading styles variant: 'text.heading', fontSize: [6, 7, 8], fontWeight: 'display', }, }, }
import Vue from 'vue' // import Vuex from 'vuex' import Router from 'vue-router' import login from '../components/login/login' import home from '../components/home/home' import search from '../components/home/search' import myAcount from '../components/home/myAcount' import parkingTicket from '../components/home/parkingTicket' import news from '../components/home/news' import appointment from '../components/acountComponents/appointment' import appoint from '../components/commonComponents/appoint' import payMent from '../components/commonComponents/payMent' import parkDetail from '../components/commonComponents/parkDetail' import counp from '../components/acountComponents/counp' import car from '../components/acountComponents/car' import addCar from '../components/acountComponents/addCar' import appointInfo from '../components/acountComponents/appointInfo' import orderInfo from '../components/acountComponents/orderInfo' import settingMore from '../components/acountComponents/more' import activities from '../components/acountComponents/activities' import suggestions from '../components/acountComponents/suggestions' import payFeedback from '../components/commonComponents/payFeedback' Vue.use(Router); export default new Router({ // mode: 'history', routes: [{ path: '/', redirect: '/home', }, { path: '/login', name: 'login', component: login }, { path: '/home', name: 'home', component: home }, { path: '/myAcount', name: 'myAcount', component: myAcount }, { path: '/settingMore', name: 'settingMore', component: settingMore }, { path: '/parkingTicket', name: 'parkingTicket', component: parkingTicket }, { path: '/appointment', name: 'appointment', component: appointment }, { path: '/counp', name: 'counp', component: counp }, { path: '/car', name: 'car', component: car }, { path: '/addCar', name: 'addCar', component: addCar }, { path: '/appoint', name: 'appoint', component: appoint }, { path: '/payMent', name: 'payMent', component: payMent }, { path: '/appointInfo', name: 'appointInfo', component: appointInfo }, { path: '/orderInfo', name: 'orderInfo', component: orderInfo }, { path: '/activities', name: 'activities', component: activities }, { path: '/suggestions', name: 'suggestions', component: suggestions }, { path: '/parkDetail', name: 'parkDetail', component: parkDetail }, { path: '/news', name: 'news', component: news }, { path: '/search', name: 'search', component: search }, { path: '/payfeedback', name: 'payfeedback', component: payFeedback } ] })
import styled from 'styled-components'; import '../../../global.css'; export const Container = styled.div` display: flex; flex-direction: column; width: 100%; height: 100vh; `; export const Content = styled.div` height: 90vh; display: flex; `; export const InternalContent = styled.div` display: flex; width: 80vw; height: 80vh; `; export const Card = styled.div` display: flex; flex-direction: column; border: 2px solid var(--color-red); margin: 1vh 2vw; position: relative; img { width: 15vw; opacity: 0.6; } span { position: absolute; width: 100%; margin-top: 0.5vh; text-align: center; font-family: "Londrina Solid", sans-serif; } p { position: absolute; bottom: 0; width: 100%; text-align: center; font-family: "Londrina Solid", sans-serif; } `;
import _ from 'lodash'; import AccessibilityModule from '@curriculumassociates/createjs-accessibility'; const PAD = 2; const MODES = { INSERT: 0, OVERWRITE: 1, }; export default class SingleLineTextInput extends createjs.Container { constructor(width, height, tabIndex, placeholderText = '') { super(); _.bindAll( this, 'onFocus', 'onBlur', '_onValueChanged', '_onSelectionChanged', '_onMouseDown', '_onMouseMove', '_onMouseUp' ); AccessibilityModule.register({ accessibleOptions: { tabIndex }, displayObject: this, role: AccessibilityModule.ROLES.SINGLELINETEXTBOX, events: [ { eventName: 'valueChanged', listener: this._onValueChanged, }, { eventName: 'selectionChanged', listener: this._onSelectionChanged, }, { eventName: 'focus', listener: this.onFocus, }, { eventName: 'blur', listener: this.onBlur, }, { eventName: 'mousedown', listener: this._onMouseDown, }, { eventName: 'pressmove', listener: this._onMouseMove, }, { eventName: 'pressup', listener: this._onMouseUp, }, ], }); this.setBounds(0, 0, width, height); const bg = new createjs.Shape(); bg.graphics .beginStroke('#000000') .setStrokeStyle(1) .beginFill('#ffffff') .drawRect(0, 0, width, height); this.addChild(bg); this._selectionDisplay = new createjs.Shape(); this._selectionDisplay.visible = false; this.addChild(this._selectionDisplay); const fontSize = height - PAD * 2; this._text = new createjs.Text('', `${fontSize}px Arial`); this._text.x = PAD; this._text.y = PAD; this.addChild(this._text); this._cursor = new createjs.Shape(); this._cursor.graphics .beginStroke('#000000') .setStrokeStyle(1) .moveTo(0, PAD) .lineTo(0, fontSize); this._cursor.x = PAD; this._cursor.visible = false; this.addChild(this._cursor); this._cursorIndex = 0; this._selection = { start: -1, end: -1 }; this._height = height; // Adding placeholder const placeholder = new createjs.Text(placeholderText, '20px Arial Bold'); placeholder.set({ x: 5, y: 5 }); placeholder.alpha = 0.5; this.addChild(placeholder); this.placeholder = placeholder; this.accessible.placeholder = placeholderText; this.addEventListener('click', this.onFocus); this.addEventListener('blur', this.onBlur); this._mode = MODES.INSERT; } get text() { return this._text.text; } set text(str) { this._text.text = str; this.accessible.value = str; } /** * Internal function for updating the string displayed in the text input * @access private * @param {String} str - string to display */ _updateDisplayString(str) { this._text.text = str; this.accessible.value = str; this.placeholder.visible = _.isEmpty(str); } /** * Event handler for when the text is changed in the DOM translation * @access private * @param {Event} evt - event */ _onValueChanged(evt) { this._text.text = evt.newValue; this.placeholder.visible = _.isEmpty(evt.newValue); } /** * Event handler for when the selection of text in the DOM translation is changed * @access private * @param {Event} evt - event */ _onSelectionChanged(evt) { this._selection.start = evt.selectionStart; this._selection.end = evt.selectionEnd; this._cursorIndex = evt.selectionDirection === 'backward' ? this._selection.start : this._selection.end; this._cursorToIndex(); this._updateSelection(); } onFocus(evt) { if (!this._cursorTimeline) { this._cursor.visible = true; this._cursorTimeline = new TimelineMax({ repeat: -1 }); this._cursorTimeline.call( () => { this._cursor.visible = false; }, null, null, '+=1' ); this._cursorTimeline.call( () => { this._cursor.visible = true; }, null, null, '+=1' ); } if (evt.type === 'click') { this.accessible.requestFocus(); // determine cursor x coordinate based on click position vs letters const tmp = this._mouseXToLetterIndexAndPos(evt.stageX); this._cursorIndex = tmp.index; this._cursor.x = tmp.x; } } onBlur() { this._cursor.visible = false; if (this._cursorTimeline) { this._cursorTimeline.kill(); this._cursorTimeline = undefined; } } _incrementCursorPos() { this._cursorIndex = Math.min(this._cursorIndex + 1, this._text.text.length); this._cursorToIndex(); } _decrementCursorPos() { this._cursorIndex = Math.max(this._cursorIndex - 1, 0); this._cursorToIndex(); } _cursorToIndex() { this._cursor.x = this._text._getMeasuredWidth( this._text.text.substring(0, this._cursorIndex) ) + this._text.x; } _isSelectionActive() { return this._selection.start !== this._selection.end; } _clearSelection() { this._selection.start = -1; this._selection.end = -1; this._updateSelection(); } _updateSelection() { if (this._isSelectionActive()) { const selectedStartText = this._text.text.substring( 0, this._selection.start ); const startMeasureWidth = this._text._getMeasuredWidth(selectedStartText); const startX = (this._selection.start <= 0 ? 0 : startMeasureWidth) + this._text.x; const selectedEndText = this._text.text.substring(0, this._selection.end); const width = this._text._getMeasuredWidth(selectedEndText) - startX + PAD; this._selectionDisplay.visible = true; this._selectionDisplay.graphics .clear() .beginFill('#31c7ec') .drawRect(startX, 1, width, this._height - 2); } else { this._selectionDisplay.visible = false; } } _mouseXToLetterIndexAndPos(x) { const back = { index: -1, x: PAD, }; const localPos = this.globalToLocal(x, 0); const textBounds = this._text.getBounds(); if (!textBounds) { back.x = PAD; back.index = 0; } else if (localPos.x >= textBounds.width) { back.x = textBounds.width + this._text.x; back.index = this._text.text.length; } else { back.x = textBounds.width + this._text.x; back.index = this._text.text.length; let prevWidth = PAD; for (let i = 1; i <= this._text.text.length; i++) { const substr = this._text.text.substring(0, i); const width = this._text._getMeasuredWidth(substr); if (width > localPos.x) { back.x = prevWidth + this._text.x; back.index = i - 1; break; } prevWidth = width; } } return back; } _onMouseDown(evt) { this._selection.start = this._mouseXToLetterIndexAndPos(evt.stageX).index; this._cursorIndex = this._selection.start; } _onMouseMove(evt) { const tmp = this._mouseXToLetterIndexAndPos(evt.stageX); this._selection.end = tmp.index; this._cursorIndex = this._selection.end; this._cursor.x = tmp.x; this._updateSelection(); } _onMouseUp(evt) { const tmp = this._mouseXToLetterIndexAndPos(evt.stageX); this._selection.end = tmp.index; this._cursorIndex = this._selection.end; this._cursor.x = tmp.x; this._updateSelection(); } }
/* * casePackInfoComponent.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * CasePack -> Case Pack Info page component. * * @author vn40486 * @since 2.3.0 */ (function () { angular.module('productMaintenanceUiApp').component('casePackInfo', { // isolated scope binding bindings: { itemMaster: '<', productMaster: '<', onCasePackChange: '&' }, // Inline template which is binded to message variable in the component controller templateUrl: 'src/productDetails/productCasePacks/casePackInfo.html', // The controller that handles our component logic controller: CasePackInfoController }); CasePackInfoController.$inject = ['ProductCasePackApi', 'UserApi', 'ProductDetailAuditModal', '$scope', '$rootScope', 'ProductSearchService', '$filter']; /** * Case Pack Info component's controller definition. * @constructor * @param productCasePackApi */ function CasePackInfoController(productCasePackApi, userApi, ProductDetailAuditModal, $scope, $rootScope, productSearchService, $filter) { /** All CRUD operation controls of Case pack Info page goes here */ var self = this; /** * String constants. */ self.SUCCESS = "success"; self.YES = "Yes"; self.NO = "No"; self.CASE_PACK_INFO_TITLE = "Case Pack Info"; self.CONFIRMATION_TITLE = "Confirmation"; self.DISCONTINUE_TITLE = "Discontinue"; self.REACTIVATE_ACTION = "RA"; self.DISCONTINUEDATE_ACTION = "DD"; self.REACTIVATE_MESSAGE = "Are you sure to re-activate this item ?"; self.DISCONTINUE_MESSAGE = "Do you really want to discontinue this item ?"; self.REACTIVATE_SUCCESS_MESSAGE = "Saved successfully. Use DSDS for authorizing stores to this item."; self.NO_CHANGE_UPDATE_MESSAGE = "There are no changes on this page to be saved. Please make any changes to update."; self.UNKNOWN_ERROR_MESSAGE = "An unknown error occurred."; self.ERROR_MESSAGE = "Error."; self.INCORRECT_MESSAGE = "Incorrect."; self.EDIT_ITEM_PRIMARY_UPC_TITLE = "Edit Item Primary UPC"; self.EDIT_ITEM_PRIMARY_UPC_MESSAGE = "Are you sure you want to set \"{0}\" UPC as Item Primary UPC?"; self.EDIT_ITEM_PRIMARY_UPC_ACTION = "ED_ITEM_PRIMARY_UPC"; self.EDIT_ITEM_PRIMARY_UPC_RESULTING_NEW_PROD_UPC_MESSAGE = "Changes to Item Primary UPC resulting in new product Primary UPC \"{0}\" "; self.EDIT_ITEM_PRIMARY_UPC_RESULTING_NEW_PROD_UPC_ACTION = "ED_ITEM_PRIMARY_UPC_RESULTING_NEW_PROD_UPC"; /**Returns discontinue action from ui. This flag will be define discontinue first action. * If an item is not discontinued, then user discontinue the item. this flag will turn true. * If an item is discontinued, then update date or reason discontinue. this flag will turn false. * */ self.isDiscontinueAction = false; /** * The check digit is correct on load because it comes back as a calculation when the page is loaded. * * @type {string} */ self.checkDigitMessage = 'Correct'; /** * The check digit is intially correct on load. This is used to determine whether the page can be saved or not. * * @type {boolean} */ self.correctCheckDigit = true; /** * Returns convertDate(date) function from higher scope. * @type {function} */ self.convertDate = $scope.$parent.$parent.$parent.$parent.convertDate; /** * If the discontinueDatePicker is opened. * @type {boolean} */ self.discontinueDatePickerOpened = false; /** * Current Discontinue Date. * @type {date} */ self.currentDiscontinueDate = null; /** * Boolean for whether or not dsd casepack is reactivate * @type {boolean} */ self.isReActivate = false; /** * The list of associate Upc basing on item id; * @type {Array} */ self.associateUpcs = []; /** * This is item primary upc number. * @type {string} */ self.itemPrimaryUPC; /** * Component ngOnInit lifecycle hook. This lifecycle is executed every time the component is initialized * (or re-initialized). */ this.$onInit = function () { self.disableReturnToList = productSearchService.getDisableReturnToList(); self.isLoading = true; } /** * Component ngOnInit lifecycle hook. This lifecycle is executed every time the component is initialized * (or re-initialized). */ this.$onChanges = function () { self.isDiscontinueAction = false; self.error = null; if(self.loadedItemMaster !=undefined && self.itemMaster.key.itemCode != self.loadedItemMaster.key.itemCode){ self.success = null; } var key = { itemCode: self.itemMaster.key.itemCode, itemType: self.itemMaster.key.itemType }; if(!self.loadedItemMaster || self.itemMaster.key.itemCode!=self.loadedItemMaster.key.itemCode){ productCasePackApi.getCasePackInformation(key, self.getData, self.fetchError); } }; /** * This will grab the latest ItemMaster. * @param results */ self.getData = function (results) { self.isLoading = false; self.itemMaster = results; self.setData(); self.setAssociateUpcs(); }; /** * Initialize component data. */ self.setData = function () { self.isDiscontinueAction = false; if(self.itemMaster.discontinueDate === "1600-01-01"){ self.itemMaster.discontinueDate = null; } self.loadedItemMaster = angular.copy(self.itemMaster); // Calculates the check digit according to the case upc. productCasePackApi.calculateCheckDigit({'upc': self.itemMaster.caseUpc}, self.getCheckDigit, self.fetchError); // If it is a warehouse, show warehouse table.. Else show the dsd table. self.isWarehouse = !!self.itemMaster.key.warehouse; self.setDataDiscontinueDate(); }; /** * Set list of Associate Upc basing on Item Id. */ self.setAssociateUpcs = function () { self.associateUpcs = []; if(self.isWarehouse){ self.associateUpcs = self.itemMaster.primaryUpc?self.itemMaster.primaryUpc.associateUpcs:[]; }else{ var associatedUpc = {}; associatedUpc["upc"] = self.itemMaster.key.itemCode; var sellingUnit = {}; sellingUnit["primaryUpc"] = true; sellingUnit["tagSize"] = self.itemMaster.itemSize; associatedUpc["sellingUnit"] = sellingUnit; self.associateUpcs.push(associatedUpc); } } /** * Returns a list of Item types. */ self.getAllItemTypes = function () { productCasePackApi.getAllItemTypes({}, self.loadItemTypes, self.fetchError); }; /** * Returns a list of one touch types. */ self.getAllOneTouchTypes = function () { productCasePackApi.getAllOneTouchTypes({}, self.loadOneTouchTypes, self.fetchError); }; /** * Component ngOnDestroy lifecycle hook. Called just before Angular destroys the directive/component. */ this.$onDestroy = function () { console.log('CasePackInfoComp - Destroyed'); /** Execute component destroy events if any. */ }; /** * Callback for a successful call to get item types. * * @param results The data returned by the back end(list of item Types). */ self.loadItemTypes = function (results) { self.itemTypeList = results; }; /** * Callback for a successful call to calculate the check digit. * * @param results The data returned by the back end(check digit). */ self.getCheckDigit = function (results) { self.checkDigit = results.data; self.loadedCheckDigit = self.checkDigit; self.confirmCheckDigit(); }; /** * Callback for when the backend returns an error. * * @param error The error from the back end. */ self.fetchError = function (error) { self.isLoading = false; self.error = self.getErrorMessage(error); }; /** * Returns error message. * * @param error * @returns {string} */ self.getErrorMessage = function (error) { if (error && error.data) { if (error.data.message) { return error.data.message; } else { return error.data.error; } } else { return self.UNKNOWN_ERROR_MESSAGE; } }; /** * This determines whether the yellow question mark has been clicked and the check digit information * modal box pops up. */ self.showCheckDigitInformation = function () { self.showingCheckDigitInformation = true; }; /** * The successful method when retrieving one touch type data. * * @param results the one touch type data. */ self.loadOneTouchTypes = function (results) { self.oneTouchTypeList = results; }; /** * Confirms whether or not the check digit is correct or not. Returns from the back end "Correct" if correct * or "Not Correct" if it is incorrect. */ self.confirmCheckDigit = function () { if (self.checkDigit !== null) { productCasePackApi.confirmCheckDigit({ checkDigit: self.checkDigit, upc: self.itemMaster.caseUpc }, //success function (results) { self.checkDigitMessage = results.message; self.correctCheckDigit = results.data; }, // error function () { self.correctCheckDigit = false; self.checkDigitMessage = self.ERROR_MESSAGE; }); } else { self.correctCheckDigit = false; self.checkDigitMessage = self.INCORRECT_MESSAGE; } }; /** * Saves any changes to the item from the case pack info changes. */ self.saveCasePackInfoChanges = function () { self.isLoading = true; self.error = null; self.success = null; if(self.isDifference()){ if(angular.toJson(self.loadedItemMaster.discontinueReason) === angular.toJson(self.itemMaster.discontinueReason)){ self.itemMaster.discontinueReason = null; } if(self.loadedItemMaster.discontinueDate === self.itemMaster.discontinueDate){ self.itemMaster.discontinueDate = null; } self.itemMaster.discontinueAction = self.isDiscontinueAction; productCasePackApi.saveCasePackInfoChanges(self.itemMaster, self.reloadSavedData, self.fetchError); } else { self.error = self.NO_CHANGE_UPDATE_MESSAGE; } }; /** * Returns true if there's been a change made. * @returns {boolean} */ self.isDifference = function(){ self.convertAllDates(); self.itemMaster.discontinueAction=null; self.loadedItemMaster.discontinueAction=null; return angular.toJson(self.loadedItemMaster) !== angular.toJson(self.itemMaster) || angular.toJson(self.loadedCheckDigit) !== angular.toJson(self.checkDigit); }; /** * After a save this reloads the succesful saved data. * @param results */ self.reloadSavedData = function (results) { self.isLoading = false; self.itemMaster = results.data; self.itemMaster.warehouseLocationItems = self.loadedItemMaster.warehouseLocationItems; var casePack = {casePack: results.data}; self.setData(); if (results.message !== null) { self.success = results.message; self.onCasePackChange(casePack); } else { results.message = null; } }; /** * Whether or not you can save the page. If you have made changes on the page and whether or not the check digit * is correct. * * @returns {boolean|*} */ self.canSave = function () { self.itemMaster.discontinueAction=null; if(self.loadedItemMaster != undefined){ self.loadedItemMaster.discontinueAction=null; } if(angular.toJson(self.loadedItemMaster) !== angular.toJson(self.itemMaster) && self.correctCheckDigit){ $rootScope.contentChangedFlag = true; return true; } else { $rootScope.contentChangedFlag = false; return false; } }; /** * When they have made some changes but they want to reset, on clicking the reset button this will reset them * back to the original values. */ self.reset = function () { self.error = null; self.success = null; self.itemMaster = angular.copy(self.loadedItemMaster); self.checkDigit = angular.copy(self.loadedCheckDigit); self.setDataDiscontinueDate(); self.confirmCheckDigit(); }; /** * The user can reset because they have made changes. * @returns {boolean} */ self.canReset = function () { self.convertAllDates(); return angular.toJson(self.loadedItemMaster) !== angular.toJson(self.itemMaster) || angular.toJson(self.loadedCheckDigit) !== angular.toJson(self.checkDigit); }; /** * Makes a call to the API to get the Audit information for the Case Pack info view */ self.showCasePackAuditInfo = function(){ self.casePackAuditInfo = productCasePackApi.getCasePackAudits; var title = self.CASE_PACK_INFO_TITLE; ProductDetailAuditModal.open(self.casePackAuditInfo, self.itemMaster.key, title); }; /** * Open the DiscontinueDate picker to select a new date. */ self.openDiscontinueDatePicker = function () { self.discontinueDatePickerOpened = true; self.options = { minDate: new Date() }; }; /** * Sets the current Discontinue Date. */ self.setDateForDiscontinueDatePicker = function () { self.discontinueDatePickerOpened = false; if (self.itemMaster.discontinueDate !== null) { self.currentDiscontinueDate = new Date(self.itemMaster.discontinueDate.replace(/-/g, '\/')); } else { self.currentDiscontinueDate = null; } }; /** * Sets the Discontinue Date data. */ self.setDataDiscontinueDate = function () { self.showReActivateCheckbox(); self.showDiscontinueReason(); self.setDateForDiscontinueDatePicker(); }; /** * Converts datepicker dates to local date format, and assigns to current Discontinue Date. */ self.convertAllDates = function(){ if(self.currentDiscontinueDate != null) { self.itemMaster.discontinueDate = self.convertDate(self.currentDiscontinueDate); } }; /** * Returns a list of Discontinue Reasons. */ self.getAllDiscontinueReasons = function () { productCasePackApi.getAllDiscontinueReasons({}, self.loadDiscontinueReasons, self.fetchError); }; /** * Callback for a successful call to get Discontinue Reasons. * * @param results The data returned by the back end(list of Discontinue Reasons). */ self.loadDiscontinueReasons = function (results) { self.discontinueReasonList = results; }; /** * Return if a passed in string is null or empty. * * @param string */ self.isEmptyString = function(string){ return (string == null || string.trim().length == 0); }; /** * This determines whether the ReActivate checkbox is visible. */ self.showReActivateCheckbox = function () { self.isReActivate = false; self.isReActivateShow = false; if(!(self.isEmptyString(self.itemMaster.discontinuedByUID) && self.isEmptyString(self.itemMaster.discontinueReason.id) && (self.itemMaster.discontinueDate === null))){ self.isReActivateShow = true; } }; /** * This determines whether the DiscontinueReason combobox is visible. */ self.showDiscontinueReason = function () { self.isDiscontinueReasonDisabled = true; if(!self.isEmptyString(self.itemMaster.discontinuedByUID)){ self.isDiscontinueReasonDisabled = false; } }; /** * ReActivate the DSD Discontinue data. */ self.reActivate = function () { if(self.isReActivate){ self.isLoading = true; var data = angular.copy(self.loadedItemMaster); data.discontinueDate = " "; data.discontinueReason = {}; data.discontinueReason["id"] = " "; data.reActive = true; productCasePackApi.saveCasePackInfoChanges(data, self.reloadSavedDataAfterReactivate, self.fetchError); } }; /** * After reactivate this reloads the successful saved data. * @param results */ self.reloadSavedDataAfterReactivate = function (results) { self.isLoading = false; self.itemMaster = results.data; self.setData(); if (results.message !== null) { if (results.message.indexOf(self.SUCCESS) != -1) { self.success = self.REACTIVATE_SUCCESS_MESSAGE; }else{ self.success = results.message; } } else { results.message = null; } }; /** * Show ReActivate popup. */ self.confirmReActivate = function () { if(self.isReActivate){ self.error = null; self.success = null; self.headerTitleConfirm = self.CONFIRMATION_TITLE; self.messageConfirm = self.REACTIVATE_MESSAGE; self.action = self.REACTIVATE_ACTION; self.yesBtnLabel = self.YES; self.closeBtnLabel = self.NO; self.yesBtnEnable = true; $('#confirmReActivateModal').modal({backdrop: 'static', keyboard: true}); } }; /** * User click yes on confirm message popup. */ self.yesConfirmAction = function () { $('#confirmReActivateModal').modal('hide'); if(self.action == self.REACTIVATE_ACTION){ self.reActivate(); } else if(self.action == self.DISCONTINUEDATE_ACTION){ self.isDiscontinueReasonDisabled = false; self.isDiscontinueAction = true; } else if(self.action == self.EDIT_ITEM_PRIMARY_UPC_ACTION){ self.allowChangeItemPrimaryUPC(); } else if(self.action == self.EDIT_ITEM_PRIMARY_UPC_RESULTING_NEW_PROD_UPC_ACTION){ self.doChangeItemPrimaryUPC(); } self.action = null; }; /** * User click no on confirm message popup. */ self.noConfirmAction = function () { if(self.action == self.REACTIVATE_ACTION){ self.isReActivate = false; } if(self.action == self.DISCONTINUEDATE_ACTION){ self.isDiscontinueAction=false; var tempDate = angular.copy(self.loadedItemMaster.discontinueDate); if (tempDate !== null) { self.currentDiscontinueDate = new Date(tempDate.replace(/-/g, '\/')); } else { self.currentDiscontinueDate = null; } self.itemMaster.discontinueDate = angular.copy(self.loadedItemMaster.discontinueDate) } self.action = null; }; /** * Show DiscontinueDate popup. */ self.confirmDiscontinueDate = function () { if(self.isDiscontinueReasonDisabled == true){ var tempDate = angular.copy(self.loadedItemMaster.discontinueDate); var orgDiscontinueDate = null; if (tempDate !== null) { orgDiscontinueDate = new Date(tempDate.replace(/-/g, '\/')); } if(angular.toJson(self.currentDiscontinueDate) !== angular.toJson(orgDiscontinueDate)){ self.error = null; self.success = null; self.headerTitleConfirm = self.DISCONTINUE_TITLE; self.messageConfirm = self.DISCONTINUE_MESSAGE; self.action = self.DISCONTINUEDATE_ACTION; self.yesBtnLabel = self.YES; self.closeBtnLabel = self.NO; self.yesBtnEnable = true; $('#confirmReActivateModal').modal({backdrop: 'static', keyboard: true}); } } }; /** * Show value for radio button Primary UPC Switch. * @param primaryUPCSw * @returns {*} */ self.valuePrimaryRadioButton = function (primaryUPCSw) { if(primaryUPCSw){ return primaryUPCSw; } return !primaryUPCSw; } /** * * @param primaryUPC */ self.itemPrimaryUPCChangedHandle = function (primaryUPC) { self.itemPrimaryUPC = primaryUPC; //Stop event change to show confirmation message. angular.forEach(self.associateUpcs, function(value) { if(value.upc == primaryUPC && value.sellingUnit){ value.sellingUnit.primaryUpc = false; } }); //Confirmation handle change Item Primary UPC before do it. self.error = null; self.success = null; self.headerTitleConfirm = self.EDIT_ITEM_PRIMARY_UPC_TITLE; self.messageConfirm = self.EDIT_ITEM_PRIMARY_UPC_MESSAGE.replace("{0}",primaryUPC); self.action = self.EDIT_ITEM_PRIMARY_UPC_ACTION; self.yesBtnLabel = self.YES; self.closeBtnLabel = self.NO; self.yesBtnEnable = true; $('#confirmReActivateModal').modal({backdrop: 'static', keyboard: true}); } /** * Do Allow Change Product Primary UPC. Will Call method update to back end. */ self.allowChangeItemPrimaryUPC = function () { //Find current selling primary UPC var sellingPrimaryUPC = ''; angular.forEach(self.productMaster.sellingUnits, function(value) { if(value.productPrimary){ sellingPrimaryUPC = value.upc; } }); //Check new item primary Upc is current selling primary upc during selling primary upc not be product // upc primary. if(self.itemPrimaryUPC == sellingPrimaryUPC && sellingPrimaryUPC != self.productMaster.productPrimaryScanCodeId){ //Confirmation handle change Item Primary UPC will Changes to Item Primary UPC resulting in new product // Primary UPC self.error = null; self.success = null; self.headerTitleConfirm = self.EDIT_ITEM_PRIMARY_UPC_TITLE; self.messageConfirm = self.EDIT_ITEM_PRIMARY_UPC_RESULTING_NEW_PROD_UPC_MESSAGE.replace("{0}",sellingPrimaryUPC); self.action = self.EDIT_ITEM_PRIMARY_UPC_RESULTING_NEW_PROD_UPC_ACTION; self.yesBtnLabel = self.YES; self.closeBtnLabel = self.NO; self.yesBtnEnable = true; $('#confirmReActivateModal').modal({backdrop: 'static', keyboard: true}); }else{ self.doChangeItemPrimaryUPC(); } } /** * Do Change Product Primary UPC. Call method update to back end. */ self.doChangeItemPrimaryUPC = function () { self.isLoading = true; //Set data for object UPC SWAP to sent back end. var upcSwap = {}; var source = {}; source["productId"] = self.productMaster.prodId; source["itemCode"] = self.itemMaster.key.itemCode; source["itemType"] = self.itemMaster.key.itemType; var destination = {}; destination["productId"] = self.productMaster.prodId; destination["itemCode"] = self.itemMaster.key.itemCode; destination["itemType"] = self.itemMaster.key.itemType; destination["primaryUpc"] = self.itemPrimaryUPC; //Set new primary switch angular.forEach(self.associateUpcs, function(value) { if(value.upc == self.itemPrimaryUPC){ value.sellingUnit.primaryUpc = true; }else if(value.sellingUnit.primaryUpc == true){ source["primaryUpc"] = value.upc; value.sellingUnit.primaryUpc = false; } }); //Set source, destination for upc swap upcSwap["source"] = source; upcSwap["destination"] = destination; //Call method update to back end. productCasePackApi.changeItemPrimaryUPC(upcSwap ,//successfully handle function (result) { self.isLoading = false; self.success = result.message; //refresh data if(result.data){ self.itemMaster.orderingUpc = angular.copy(result.data.orderingUpc); self.itemMaster.primaryUpc = angular.copy(result.data.primaryUpc); self.loadedItemMaster.orderingUpc = angular.copy(result.data.orderingUpc); self.loadedItemMaster.primaryUpc = angular.copy(result.data.primaryUpc); self.setAssociateUpcs(); } },//error handle self.fetchError); } /** * handle when click on return to list button */ self.returnToList = function(){ $rootScope.$broadcast('returnToListEvent'); }; /** * Returns the added date, or null value if date doesn't exist. */ self.getAddedDate = function() { if(self.itemMaster.createdDateTime === null || angular.isUndefined(self.itemMaster.createdDateTime)) { return '01/01/1901 00:00'; } else if (parseInt(self.itemMaster.createdDateTime.substring(0, 4)) < 1900) { return '01/01/0001 00:00'; } else { return $filter('date')(self.itemMaster.createdDateTime, 'MM/dd/yyyy HH:mm'); } }; /** * Returns createUser or '' if not present. */ self.getCreateUser = function() { if(self.itemMaster.displayCreatedName === null || self.itemMaster.displayCreatedName.trim().length == 0) { return ''; } return self.itemMaster.displayCreatedName; }; } })();
export default function searchModal() { return { isOpen: false, }; }
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import colorService from './colorService/index.js'; import ColorBox from './components/ColorBox.js'; import './index.css'; class ColorChanger extends Component { state = { color: "Red", hex: "#FF0000", fontColor:"white" } getRandomColor = () => { colorService().then( randomColor => { this.setState(prevState => { if(prevState.color !== randomColor.color){ var c = randomColor.hex.substring(1); // strip # var rgb = parseInt(c, 16); // convert rrggbb to decimal var r = (rgb >> 16) & 0xff; // extract red var g = (rgb >> 8) & 0xff; // extract green var b = (rgb >> 0) & 0xff; // extract blue var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709 var textColor = "white"; if (luma > 128) { // pick a different colour textColor = "black"; } console.log(textColor) return { color: randomColor.color , hex: randomColor.hex, fontColor: textColor} } else return {color: "Blue", hex: "#0000FF", fontColor:"white"} }) }) } componentDidMount() { this.getRandomColor(); } render() { return ( <div className="box"> <ColorBox inputColor= {this.state.color} fontColor={this.state.fontColor} getNewColor={() => this.getRandomColor()} /> <br/> Color displayed is {this.state.color} ({this.state.hex}). <br/> Get list of available colors <a href="https://www.w3schools.com/colors/colors_names.asp" target="_blank">here</a> </div> ); } } ReactDOM.render(<ColorChanger />, document.getElementById('root'));
import React, { Fragment, useEffect, useState } from "react"; import "../App.css"; import Avatar from "../components/avatarcomponent/Avatar"; import ProductScreen from "./ProductScreen"; import { Typography } from "@material-ui/core"; export default function HomeScreen() { const [items, setItems] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch("https://api-zoom.herokuapp.com/getProducts") .then(response => response.json()) .then(products => { setItems(products); setLoading(false) }); }, []); return ( <Fragment> <div className="main-image"> <img src={require("../images/zoom.jpg")} alt="mainImage" /> </div> <Avatar /> <br /> <Typography variant="h5"> Recently Published </Typography> <br /> <ProductScreen items={items} isLoading={loading} /> </Fragment> ); }
var express = require("express"); var router = express.Router(); // Import the model (burger.js) to use its database functions. var burger = require("../models/burger.js"); console.log("controller loaded"); // Create all our routes and set up logic within those routes where required. router.get("/", function(req, res) { burger.selectAll(function(data) { var hbsObject = { burger: data }; console.log(hbsObject); res.render("index", hbsObject); }); }); router.post("/api/add", function(req, res) { var burgerName = req.body.burgers_name; var devoured = req.body.devoured; burger.insertOne(burgerName, devoured, function() { res.redirect("/"); }); }); router.put("/api/update/:id", function(req, res) { var id = req.params.id; var devoured = req.body.devoured; console.log("ID " + id + " dev " + devoured); burger.updateOne(id, devoured, function(result) { console.log(result.changedRows); if (result.changedRows == 0) { // If no rows were changed, then the ID must not exist, so 404 return res.status(404).end(); } else { res.render("index"); // res.status(200); // res.send(); } }); }); // Export routes for server.js to use. module.exports = router;
init(); var canvas; var context; var CANVAS_WIDTH; var CANVAS_HEIGHT; var timerId; //set rightDown or leftDown if the right or left keys are down function onKeyDown(evt) { console.log("ON onKeyDown"); processKey(evt.keyCode); } //and unset them when the right or left key is released function onKeyUp(evt) { console.log("ON onKeyUp"); clear(); } $(document).keydown(onKeyDown); $(document).keyup(onKeyUp); function clear() { context.fillStyle = "#eee"; context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); var width = CANVAS_WIDTH / 3; var height = CANVAS_HEIGHT / 2; emptyRect(CANVAS_WIDTH / 3, 0, width, height); for (var x = 0; x <= CANVAS_WIDTH / 3; x++) { emptyRect(x * CANVAS_WIDTH / 3, CANVAS_HEIGHT / 2, width, height); } } function processKey(code) { clear(); var x, y; var notProcessed = false; if (code == 37) { // left x = 0; y = CANVAS_HEIGHT / 2; } else if (code == 38) { // up x = CANVAS_WIDTH / 3; y = 0; } else if (code == 39) { // right x = 2 * CANVAS_WIDTH / 3; y = CANVAS_HEIGHT / 2; } else if (code == 40) { // down x = CANVAS_WIDTH / 3; y = CANVAS_HEIGHT / 2; } else if (code == 18) { onStopMovement(); notProcessed = true; } else if (code == 17){ onForwardDirection(); notProcessed = true; } else { notProcessed = true; } if (!notProcessed) { var width = CANVAS_WIDTH / 3; var height = CANVAS_HEIGHT / 2; rect(x, y, width, height); sendKeyPressed(code); } } function rect(x, y, w, h) { context.beginPath(); context.lineWidth = "3"; context.strokeStyle = "red"; context.fillStyle = "#ccc"; context.rect(x, y, w, h); context.stroke(); context.closePath(); context.fill(); } function emptyRect(x, y, w, h) { context.fillStyle = "#eee"; context.beginPath(); context.lineWidth = "2"; context.strokeStyle = "black"; context.rect(x, y, w, h); context.stroke(); context.fill(); context.closePath(); } function inRectangle(x, y, rectX, rectY) { var width = CANVAS_WIDTH / 3; var height = CANVAS_HEIGHT / 2; return x >= rectX && x <= rectX + width && y >= rectY && y <= rectY + height } function defineRectangle(event) { var x = event.x; var y = event.y; x -= canvas.offsetLeft; y -= canvas.offsetTop; processClick(x, y); } function processClick(x, y) { var notProcessed = false; var code; if (inRectangle(x, y, 0, CANVAS_HEIGHT / 2)) { // left code = 37; } else if (inRectangle(x, y, CANVAS_WIDTH / 3, 0)) { // up code = 38; } else if (inRectangle(x, y, 2 * CANVAS_WIDTH / 3, CANVAS_HEIGHT / 2)) { // right code = 39; } else if (inRectangle(x, y, CANVAS_WIDTH / 3, CANVAS_HEIGHT / 2)) { // down code = 40; } else { notProcessed = true; } if (!notProcessed) { processKey(code); } } function handleTouchStart(event) { var x = event.targetTouches[0].pageX; var y = event.targetTouches[0].pageY; timerId = setTimeout(function () { event.stopPropagation(); event.preventDefault(); processClick(x, y) }, 30); } function handleTouchEnd(event) { clearTimeout(timerId); } function init() { canvas = $('#canvas')[0]; context = canvas.getContext("2d"); CANVAS_WIDTH = $("#canvas").width(); CANVAS_HEIGHT = $("#canvas").height(); canvas.addEventListener("mousedown", defineRectangle, false); canvas.addEventListener("touchstart", handleTouchStart, false); canvas.addEventListener("touchend", handleTouchEnd, false); clear(); }
/** * style */ import '../../styles/reset.sass' import '../../styles/global.sass' /** * js */ import '@babel/polyfill' import '../../js/matchesPolyfill' import '../../js/closestPolyfill' import '../../js/classListPolyfill' /** * components */ import '../../_includes/footer'
import firebase from "firebase"; var firebaseConfig = { apiKey: "AIzaSyA9tqoNu3DjJxR_Qi9lBgCSkzLwsjcidvs", authDomain: "marauders-map-9bc64.firebaseapp.com", projectId: "marauders-map-9bc64", storageBucket: "marauders-map-9bc64.appspot.com", messagingSenderId: "880016901620", appId: "1:880016901620:web:e14f28fcba5c041384e5a1" }; firebase.initializeApp(firebaseConfig) const auth = firebase.auth() const db = firebase.firestore() //eslint-disable-next-line // if(location.hostname === 'localhost'){ // auth.useEmulator('http://localhost:9099') // db.useEmulator('localhost', 8080) // } export default firebase export {db, auth}
// Some function used in this section will be used in other section. // This is one of the possible way to share them between sessions. let R4D = {}; { let n = 5; // the array with the progress bars & the PromiseGUI let pbs = []; let pguis = []; for(let i = 0; i < n; i++){ pbs[i] = new ProgressBar('ProgressBar' + i); pbs[i].resolvePercent = 35; pbs[i].errorPercent = 0; //pbs[i].isSynchronous = true; tools.append2Demo(pbs[i], 'tdR4DC2'); pguis[i] = new PromiseGUI(1); tools.prepend(pguis[i].$td, pbs[i].$tr); } // The 'Promise' that 'controls' all the other 'Promises' let pguiAny = new PromiseGUI(n); tools.prepend(pguiAny.$td, pbs[0].$tr); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // // The callbacks used by the 'Promise.any' R4D.resolve = function(pguiAny, folder, btn){ try{ folder.pgui.resolved(); folder.pgui.fulfilled(); pguiAny.resolved(); tools.highlight.resolved(btn); tools.stop(pbs); } catch(jse){ // this catch stops the chaining of the error to the function 'R4D-catch' window.console.promise.log.catch(jse); } } // The first progressBar that reject, stops the 'race' R4D.reject = function(pguiAny, error, btn){ try{ pguiAny.rejected(); pguiAny.fulfilled(); //window.console.promise.log.reject(folder.result.id); // As soon a 'ProgressBar' rejects, The 'PromiseAny' stops listening the other 'Promise' // That means, this stop is an option. It is up to developer write it, based on what he/she // needs to do. //tools.stop(pbs); tools.highlight.rejected(btn); } catch(jse){ window.console.promise.log.catch(jse); } } R4D.finally = function(pguiAny, btn){ window.console.promise.log.finally(); tools.enableBtns(btn); pguiAny.fulfilled(); } R4D.catch = function(error, pguiAny){ window.console.promise.log.catch(error); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // function btnR4DAny_onclick(btn){ if(!Promise.any){ alert("'Promise.any' not definet on this browser."); return false; } debugger; console.clear(); tools.disableBtns(btn); tools.highlight.clear(btn); tools.reset(pguis); pguiAny.reset(); let promises = []; for(let i = 0; i < pbs.length; i++){ // closure needs to be managed in that way, in a 'for loop' let pb = pbs[i]; let pgui = pguis[i]; // every promise is configurated to manage its own 'ProgressBar' promises[i] = new Promise(function(resolve, reject) { try{ let _resolve = function(result){ let folder = {result: result, pgui: pgui}; resolve(folder); } let _reject = function(result){ let folder = {result: result, pgui: pgui}; reject(folder); } pb.start(_resolve, _reject); } catch(jse){ window.console.promise.log.catch(jse); let rejectionResult = pb.getRejectionResult(jse); let folder = {result: rejectionResult, pgui: pgui}; // this ensures '_reject' will always receive the correct // type parameter, and Any the info it needs. reject(folder); } }) } // The new promise does not controls the 'ProgressBar', instead it controls an array // of 'promises' like an orchestra conductor. // Now we have 2 levels of 'Promise': it's a little bit more complex, but the concepts // are Any the same! let promiseAny = Promise.any(promises); // and now we can use the 'promise' in the way we learned promiseAny.then( folder => R4D.resolve(pguiAny, folder, btn), folder => R4D.reject (pguiAny, folder, btn) ) .finally(() => R4D.finally(pguiAny, btn)) .catch((error) => R4D.catch (error, pguiAny)); } }
import { FETCH_WORK_PLACE, FETCH_WORK_PLACE_LIST_BY_FLOOR, RESERVE_WORK_PLACE, SEARCH_WORK_PLACE_BY_PROPERTIES, SEARCH_WORK_PLACE_BY_USER_ID } from './types'; import {firebaseTools} from "../utils/firebase"; export const fetchWorkPlace = async (workPlaceId, dispatch) => { await firebaseTools.fetchWorkPlace(workPlaceId).then(workPlaceInfo => { return dispatch({ type: FETCH_WORK_PLACE, payload: workPlaceInfo.data() }) }) }; export const fetchWorkPlaceList = async (dispatch) => { await firebaseTools.fetchWorkPlaceList().then(workPlaceList => { return dispatch({ type: FETCH_WORK_PLACE_LIST_BY_FLOOR, payload: { workPlaceList: workPlaceList } }) }) }; export const reserveWorkPlace = async (workPlaceId, dispatch) => { await firebaseTools.reserveWorkPlace(workPlaceId); await dispatch({ type: RESERVE_WORK_PLACE }) }; export const searchWorkPlaceByUserId = async (userId, dispatch) => { await firebaseTools.searchWorkPlaceByUserId(userId).then(workPlaceInfo => { return dispatch({ type: SEARCH_WORK_PLACE_BY_USER_ID, payload: { userWorkPlace: workPlaceInfo[0]} }) }) }; export const searchWorkPlaceByProperties = async (properties, dispatch) => { await firebaseTools.searchWorkPlaceByProperties(properties).then(workPlaceList => { return dispatch({ type: SEARCH_WORK_PLACE_BY_PROPERTIES, payload: workPlaceList.data() }) }) };
Polymer( { iconChanged: function () { this.icon = 'editor:insert-photo'; }, labelChanged: function () { this.label = 'Image'; } } );
const Config = require("../config"); module.exports = { login: (email, password) => { return Config.db.execute(`SELECT * FROM user_dashboard.users WHERE email = ?`, [email]); }, register: (email, first_name, last_name, password, user_level) => { return Config.db.execute(`INSERT INTO user_dashboard.users (email, first_name, last_name, password, user_level, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())`, [email, first_name, last_name, password, user_level]); }, createProfile: () => { return Config.db.execute(`INSERT INTO user_dashboard.profiles (user_id, created_at, updated_at) VALUES (LAST_INSERT_ID(), NOW(), NOW())`); }, checkEmail: (email) => { return Config.db.execute(`SELECT id, email FROM user_dashboard.users WHERE email = ?`, [email]); }, checkIfFirstUser: () => { return Config.db.execute("SELECT * FROM user_dashboard.users"); }, getUser: (id) => { return Config.db.execute(`SELECT u.*, p.id AS 'profile_id', p.description FROM user_dashboard.users AS u INNER JOIN profiles AS p ON u.id = p.user_id WHERE u.id = ?`, [id]); }, getAllUsers: () => { return Config.db.execute(`SELECT u.*, p.id AS 'profile_id' FROM user_dashboard.users AS u INNER JOIN profiles AS p ON u.id = p.user_id ORDER BY u.user_level DESC`); }, updateUser: (id, email, first_name, last_name, user_level = null) => { if(user_level != null){ return Config.db.execute(`UPDATE user_dashboard.users SET email = ?, first_name = ?, last_name = ?, user_level = ?, updated_at = NOW() WHERE id = ?`, [email, first_name, last_name, user_level, id]); } else{ return Config.db.execute(`UPDATE user_dashboard.users SET email = ?, first_name = ?, last_name = ?, updated_at = NOW() WHERE id = ?`, [email, first_name, last_name, id]); } }, changePassword: (id, password) => { return Config.db.execute(`UPDATE user_dashboard.users SET password = ?, updated_at = NOW() WHERE id = ?`, [password, id]); }, updateDescripton: (id, description) => { return Config.db.execute(`UPDATE user_dashboard.profiles SET description = ?, updated_at = NOW() WHERE user_id = ?`, [description, id]); }, deleteUser: (id) => { return Config.db.execute("DELETE FROM user_dashboard.users WHERE id = ?", [id]); }, calculateTime: (time) => { if(time < 60) result = "A few seconds ago."; else if(time >= 60 && time < 120) result = "A minute ago."; else if(time >= 120 && time < 3600) result = `${Math.floor(time/60)} minutes ago`; else if(time >= 3600 && time < 86400 && Math.floor(time/(60*60)) == 1) result = "An hour ago."; else if(time >= 3600 && time < 86400 && Math.floor(time/(60*60)) > 1) result = time = `${Math.floor(time/(60*60))} hours ago`; else if(time >= 86400 && time < 604800 && Math.floor(time/(60*60*24)) == 1) result = "A day ago."; else if(time >= 86400 && time < 604800 && Math.floor(time/(60*60*24)) > 1) result = `${Math.floor(time/(60*60*24))} days ago`; else if(time >= 604800 && time < 691200) result = "A week ago"; else result = "None"; return result; }, getMessages: (id) => { return Config.db.execute(`SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) AS 'name', m.id AS 'message_id', m.user_id AS 'sender_id', CONCAT(u_2.first_name, ' ', u_2.last_name) AS 'sender', m.content, m.created_at, TIMESTAMPDIFF(SECOND, m.created_at, NOW()) AS 'sent' FROM users AS u INNER JOIN profiles AS p ON u.id = p.user_id INNER JOIN messages AS m ON p.id = m.profile_id INNER JOIN users AS u_2 ON m.user_id = u_2.id WHERE u.id = ? ORDER BY m.created_at DESC`, [id]); }, getComments: (id) => { return Config.db.execute(`SELECT c.message_id AS 'message_id', c.id AS 'comment_id', c.user_id AS 'sender_id', CONCAT(u_2.first_name, ' ', u_2.last_name) AS 'sender', c.content, TIMESTAMPDIFF(SECOND, c.created_at, NOW()) AS 'sent' FROM users AS u INNER JOIN profiles AS p ON u.id = p.user_id INNER JOIN messages AS m ON p.id = m.profile_id INNER JOIN comments AS c ON m.id = c.message_id INNER JOIN users AS u_2 ON c.user_id = u_2.id WHERE u.id = ?`, [id]); }, postMessage: (profile_id, sender_id, message) => { return Config.db.execute(`INSERT INTO user_dashboard.messages (profile_id, user_id, content, created_at, updated_at) VALUES(?, ?, ?, NOW(), NOW())`, [profile_id, sender_id, message]); }, postComment: (message_id, sender_id, message) => { return Config.db.execute(`INSERT INTO user_dashboard.comments (message_id, user_id, content, created_at, updated_at) VALUES(?, ?, ?, NOW(), NOW())`, [message_id, sender_id, message]); } }
import Vue from 'vue'; import axios from 'axios'; let instance = axios.create({ timeout: 3000 }) //请求拦截 instance.interceptors.request.use( config => { if (token) { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了 config.headers.Authorization = token; } return config; }, err => { return Promise.reject(err); } ) //响应拦截 instance.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // 这里写清除token的代码 router.replace({ path: 'login', query: { redirect: router.currentRoute.fullPath } //登录成功后跳入浏览的当前页面 }) } } return Promise.reject(error.response.data) } ) let httpPlugin = { install(Vue) { // 防止$http 在将来被覆盖 Object.defineProperty(Vue.prototype, '$http', { value: instance }) } } export default httpPlugin;
var Either = function(x) { this._value = x == null || x== undefined ? Lift.of(x) : Right.of(x) } Either.of = x => new Either(x) Either.prototype.map = function(f) { return this._value.map(f) } Either.prototype.join = function() { return this._value.join() } Either.prototype.ap = function(m) { return m.map(this._value.join()) } module.exports = Either
import React, { useState, useEffect, useContext } from 'react'; import axios from "axios"; import { useHistory } from "react-router-dom"; import { API_REGISTRATION } from "../../Adress"; import Slide from 'react-reveal/Slide'; import Content from '../Home/Content' import Flip from 'react-reveal/Flip'; const Login = () => { let history = useHistory(); let [users, setUsers] = useState([]); let [user, setUser] = useState({}); useEffect(() => { axios.get(API_REGISTRATION).then(res => { setUsers(res.data); }) }, []); function handleInps(e) { let obj = { ...user, [e.target.name]: e.target.value }; setUser(obj); } function login() { let check = false; let currentUser = {}; users.forEach((p) => { if (p.account === user.account && p.password === user.password) { check = true; currentUser.account = p.account; currentUser.password = p.password; localStorage.setItem('currentUser', JSON.stringify(currentUser)); } }); console.log(localStorage.getItem('currentUser')); check ? history.push('/') : alert('No such user'); localStorage.setItem('admin', JSON.parse(currentUser)); } return ( <> <Content /> <div> <Slide left> <div style={{ background: "url(https://checkyeti.imgix.net/images/optimized/freeriding-snowboard-private---all-levels-board-at-hero.jpg)", left: 0, top: 0, right: 0, bottom: 0, minHeight: "600px", height: "100%" }}> <Flip left> <input placeholder="Login" onChange={handleInps} type={'text'} name={'account'} style={{color: "black", margin: "5px",borderRadius: "10px", border: "outlined"}} /> <input placeholder="Password" onChange={handleInps} type={'text'} name={'password'} style={{color: "black", margin: "5px",borderRadius: "10px", border: "outlined"}} /> </Flip> <Flip right> <button onClick={login} >Login</button> </Flip> </div> </Slide> </div> </> ); }; export default Login
export default 'transaction-history';