text
stringlengths
7
3.69M
export default { label: '6 Letter Words', id: '6-letter-words', list: [ { id: 'reading', type: 'passage', label: 'Words List', data: { title: 'Words List', text: [ `Find below some basic six letter words. Get familiar with them.`, { type: 'sitewords', text: `active, afraid, amount, animal, answer, anyone, appear, attack, attend, author, battle, become, bottle, bottom, branch, bright, burden, camera, charge, circle, coffee, course, damage, danger, degree, demand, device, direct, driver, eleven, energy, enough, export, family, famous, female, follow, forget, future, health, lesson, listen, manner, market, matter, member, memory, middle, minute, mirror, mother, museum, myself, normal, number, office, online, option, output, please, prison, recent, remain, repair, report, result, reward, salary, school, screen, season, second, select, silver, simple, single, speech, street, strong, summer, system, talent, twenty, update, useful, volume, weight, window, winner, wonder`, width: 100 } ] } }, { id: 'jumble', type: 'sequence', label: 'Form Words', commonData: { title: 'Connect the blocks to form meaningful word.' }, data: [ 'active, forget, silver, degree, remain, bottle, minute, update, middle, twenty', 'afraid, future, single, device, repair, branch, mother, volume, recent, author', 'animal, health, speech, direct, report, bright, myself, window, select, damage', 'anyone, lesson, street, driver, result, burden, normal, member, talent, follow', 'appear, listen, system, eleven, reward, camera, number, course, prison, attack', 'attend, manner, useful, energy, salary, charge, office, summer, family, season', 'battle, memory, weight, enough, screen, coffee, option, online, answer, matter', 'become, mirror, winner, famous, second, danger, output, export, school, circle', 'bottom, museum, wonder, female, simple, demand, please, amount, market, strong' ] }, { id: 'reading-2', type: 'passage', label: 'Words List - 2', data: { title: 'Words List', text: [ `Find below more six letter words. Get familiar with them.`, { type: 'sitewords', text: `accept, action, advice, always, august, beauty, before, better, border, breath, bridge, button, cannot, center, change, choice, common, corner, create, decide, define, depend, design, detail, dinner, doctor, eighth, engine, escape, expand, expert, finger, finish, forest, friend, garden, global, ground, height, honest, income, inside, leader, length, letter, liquid, little, manage, margin, master, mobile, narrow, nation, nature, object, orange, parent, people, person, planet, plenty, police, profit, proper, public, reader, reason, record, remote, remove, repeat, replay, sample, search, secret, silent, sister, social, source, square, status, thirty, travel, trying, unique, wealth, winter, worker, writer, yellow`, width: 100 } ] } }, { id: 'jumble-2', type: 'sequence', label: 'Form Words - 2', commonData: { title: 'Connect the blocks to form meaningful word.' }, data: [ 'breath, narrow, writer, finger, sister, detail, police, replay, change, nation', 'choice, nature, accept, garden, social, doctor, profit, margin, square, expand', 'common, object, always, ground, source, eighth, public, center, mobile, advice', 'corner, orange, august, height, status, expert, reason, silent, escape, remove', 'create, parent, beauty, honest, thirty, finish, record, master, action, manage', 'decide, people, before, income, travel, forest, remote, engine, reader, cannot', 'define, person, better, inside, wealth, friend, repeat, yellow, liquid, secret', 'depend, planet, border, leader, winter, global, sample, proper, button, little', 'design, plenty, bridge, letter, worker, length, search, dinner, unique, trying' ] } ] };
var express = require('express'); var router = express.Router(); const jwt = require('jsonwebtoken'); /* GET users listing. */ router.get('/', function(req, res, next) { let token = jwt.sign({ user_id: 'user_id'}, 'secret_key'); console.log(`token : ${token}`); res.json({token}); }); module.exports = router;
/** * 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. */ /** * @author Nguyen Ba Uoc */ function RTEManager() { this.HTMLUtil = eXo.core.HTMLUtil ; this.coreEditor = eXo.core.CoreEditor ; } RTEManager.prototype.init = function() { this.preSplitNodes = [] ; if(window.getSelection) { // Netscape/Firefox/Opera var selObj = window.getSelection() ; var anchorTextNode = selObj.anchorNode ; var anchorOffset = selObj.anchorOffset ; var focusTextNode = selObj.focusNode ; var focusOffset = selObj.focusOffset ; if (focusTextNode === anchorTextNode && (this.coreEditor.isEditableNode(focusTextNode) || this.coreEditor.isEditableNode(focusTextNode.parentNode))) { var nodeValue = anchorTextNode.nodeValue ; nodeValue = this.HTMLUtil.entitiesDecode(nodeValue) ; this.preSplitNodes[0] = this.createEditableNode(nodeValue.substr(0, anchorOffset)) ; this.preSplitNodes[1] = this.createEditableNode(nodeValue.substr(anchorOffset, focusOffset)) ; this.preSplitNodes[2] = this.createEditableNode(nodeValue.substr(focusOffset, nodeValue.length - 1)) ; } else { if (this.coreEditor.isEditableNode(anchorTextNode) || this.coreEditor.isEditableNode(anchorTextNode.parentNode)) { var anchorNodeContent = this.HTMLUtil.entitiesDecode(anchorTextNode.nodeValue) ; this.preSplitNodes[0] = this.createEditableNode(anchorNodeContent.substr(0, anchorOffset)) ; this.preSplitNodes[1] = this.createEditableNode(anchorNodeContent.substr(anchorOffset, anchorNodeContent.length - 1)) ; } var iNode = anchorTextNode ; // TODO: Fix bug: can not nextSibling to get next selected node while (iNode && (iNode = iNode.nextSibling)) { if (iNode == focusTextNode || iNode == focusTextNode.parentNode) break ; if (this.coreEditor.isEditableNode(iNode)) { this.preSplitNodes[this.preSplitNodes.length] = iNode ; } } if (this.coreEditor.isEditableNode(focusTextNode) || this.coreEditor.isEditableNode(focusTextNode.parentNode)) { var focusNodeContent = this.HTMLUtil.entitiesDecode(focusTextNode.nodeValue) ; this.preSplitNodes[this.preSplitNodes.length] = this.createEditableNode(focusNodeContent.substr(0, focusOffset)) ; this.preSplitNodes[this.preSplitNodes.length] = this.createEditableNode(focusNodeContent.substr(focusOffset, focusNodeContent.length - 1)) ; } } } else if(document.selection) { return true ; } // Check data var strTmp = '' ; for (var i=0; i < this.preSplitNodes.length; i++) { strTmp += i + '.' + this.preSplitNodes[i].innerHTML + '\n' ; } window.alert(strTmp) ; } ; // Create editable node wrapper for text node. RTEManager.prototype.createEditableNode = function(nodeContent, tagName) { if (!tagName) tagName = 'SPAN' ; var editableNode = document.createElement(tagName) ; editableNode.setAttribute('editable', '1') ; editableNode.innerHTML = nodeContent ; return editableNode ; } ; eXo.core.text.RTEManager = new RTEManager() ;
const informationInformationIconCopy = { "en": { "INFORMATIONICON": {} }, "kr": { "INFORMATIONICON": {} }, "ch": { "INFORMATIONICON": {} }, "jp": { "INFORMATIONICON": {} } } export default informationInformationIconCopy;
import { combineReducers } from 'redux'; import { pruebaReducer } from './pruebaReducer'; import { userReducer } from './userReducer'; /*const reducer = (state= {}, action) => { switch (action.type) { case 'USER_DATA': console.log('hola',action.payload); console.log(...state, 'hola'); state = { ...state, user: action.payload } return state; default: return state; } } */ export default combineReducers({ userReducer, pruebaReducer })
var fullscreenMenu = document.querySelector('#menu__fullscreen'); var targetLink ; var activeHref; var activeSectionPos; var activeSection ; var menuIcon = document.querySelector('.menu'); var closeMenuIcon = document.querySelector('#closeFullscreenMenu'); var element,className; /*SHOW/HIDE menu when XS*/ fullscreenMenu.classList.add('hidden-responsive-menu'); menuIcon.addEventListener('click',function(e){ e.preventDefault(); hideMenuIcon(); activateCurrentSection(); hideContainer(); // scroll to target $('html, body').animate({ scrollTop: 0 }, 200); //reset the styling class for all the links var links = document.querySelectorAll('.menu__fullscreen__inner__nav__item a'); links.forEach(function(li){ li.classList.add('menu__fullscreen__inner__nav__link'); }) // console.log('link was active :'+link); targetLink.classList.remove('menu__fullscreen__inner__nav__link'); targetLink.classList.add('highlight-link'); }) ; closeMenuIcon.addEventListener('click',function(e){ e.preventDefault(); // setInterval(scrollToSection(activeSectionId),3000); showMenuIcon(); hideMenu(); // console.log('link beeing activated before close '+tergetLink); setInterval(scrollToSection(targetLink),2000); }); //remove / add classes function function addClassToElement(element,className){ document.querySelector(element).classList.add(className); } function removeClassFromElement(element,className){ document.querySelector(element).classList.remove(className); } //make xs menu navigation works //Add event listener fullscreenMenu.addEventListener('click',getLink); //getLink function function getLink(e){ //get the parent of links if(e.target.classList.contains('menu__fullscreen__inner__nav__link')){ hideMenu(); //go link setInterval(scrollToSection(e.target),3000); console.log(e.target); targetLink=e.target; showMenuIcon(); e.preventDefault(); } } //hide menu fisrt function hideMenu(){ //hide menu and bring the body back removeClassFromElement('#menu__fullscreen','shown-responsive-menu'); addClassToElement('#menu__fullscreen','hidden-responsive-menu'); } //hide container function hideContainer(){ removeClassFromElement('#menu__fullscreen','hidden-responsive-menu'); addClassToElement('#menu__fullscreen','shown-responsive-menu'); $('a[href="#about"]').addClass('scroll-to-menu'); } //hide mneu icon function hideMenuIcon(){ addClassToElement('#iconMenu','hide-icon-menu'); // removeClassToElement('#iconMenu','menu'); } function showMenuIcon(){ removeClassFromElement('#iconMenu','hide-icon-menu'); // removeClassToElement('#iconMenu','menu'); } /* JQUERY PARTS*/ document.addEventListener('scroll',activateCurrentSection); /** * TODO: * add when click links in menu fullscreen scroling must go from the active section to the selected section (that means from top to bottom or bottom to top) **/
export default { url: "/", baseURL: "", timeout: 60 * 1000, withCredentials: false // default };
export let contactRowBp = { tag: "div", classes: ["row", "justify-content-between", "mt-3"], props: { blueprint: "contactRow", }, states: {}, };
import ApiError from '../../ApiError'; import { general } from '../../core/error/MessageProperties'; export default class GetUserUseCase { constructor({database, logger}) { this.userDao = database.userDao(); this.logger = logger; } async execute(param) { const user = await this.userDao.getUserById(param.id); if (user) { return user } else { throw new ApiError('User not found', general.dataNotFound) } } }
import User from './components/component/User' import Home from './components/component/Home' export default function (router) { router.redirect({ '/': '/user' }) router.map({ '/user': { component: User }, '/home': { component: Home // subRoutes: { // '/deviceGroupingData': { // component: DeviceGroupingData // }, // '/posterGroupingData': { // component: PosterGroupingData // } // } } }) }
var apikey = 'IocJBYsIrONghsgpncPDM9P435h5zKrP0eEjNqGqe9Q';
import { all } from "redux-saga/effects"; import { authSaga } from "./Auth/saga"; import { boardSaga } from "./Board/saga"; import { gameCreateSaga } from "./GameCreate/saga"; import { profileSaga } from "./Profile/saga"; export function* storyStart() { yield all([authSaga(), profileSaga(), boardSaga(), gameCreateSaga()]); }
const baseurl = 'https://www.apitutor.org/spotify/simple/v1/search'; // Note: AudioPlayer is defined in audio-player.js const audioFile = 'https://p.scdn.co/mp3-preview/bfead324ff26bdd67bb793114f7ad3a7b328a48e?cid=9697a3a271d24deea38f8b7fbfa0e13c'; const audioPlayer = AudioPlayer('.player', audioFile); const search = (ev) => { const term = document.querySelector('#search').value; console.log('search for:', term); // issue three Spotify queries at once... getTracks(term); getAlbums(term); getArtist(term); if (ev) { ev.preventDefault(); } } const attachTrackHandlers = () => { const tracks = document .getElementById("tracks") .querySelectorAll(".track-item"); console.log(tracks.length); tracks.forEach((track) => { track.addEventListener("click", (event) => { const trackPreviewContainer = document .querySelector("footer") .getElementsByClassName("track-item")[0]; trackPreviewContainer.innerHTML = `${event.currentTarget.innerHTML}`; const songUrl = event.currentTarget.getAttribute("data-preview-track"); audioPlayer.setAudioFile(songUrl); audioPlayer.play(); }); }); }; const getTracks = (term) => { console.log(` get tracks from spotify based on the search term "${term}" and load them into the #tracks section of the DOM...`); fetch( `https://www.apitutor.org/spotify/simple/v1/search?type=track&q=${term}` ) .then((response) => response.json()) .then((data) => { const size = 5; const items = data.slice(0, size).map((i) => { return `<section class="track-item preview" data-preview-track="${i.preview_url}"> <img src="${i.album.image_url}"> <i class="fas play-track fa-play" aria-hidden="true"></i> <div class="label"> <h3>${i.album.name}</h3> <p> ${i.name} </p> </div> </section>`; }); document.getElementById("tracks").innerHTML = items.length > 0 ? `${items.join(" ")}` : `<p>No tracks found</p>`; }) .then(() => { attachTrackHandlers(); }); }; const getAlbums = (term) => { console.log(` get albums from spotify based on the search term "${term}" and load them into the #albums section of the DOM...`); fetch( `https://www.apitutor.org/spotify/simple/v1/search?type=album&q=${term}` ) .then((response) => response.json()) .then((data) => { const items = data.map((i) => { return `<section class="album-card" id="${i.id}"> <div> <img src="${i.image_url}"> <h3>${i.name}</h3> <div class="footer"> <a href="${i.spotify_url}" target="_blank"> view on spotify </a> </div> </div> </section>`; }); document.getElementById("albums").innerHTML = items.length > 0 ? `${items.join(" ")}` : `<p>No albums found</p>`; }); }; const getArtist = (term) => { console.log(` get artists from spotify based on the search term "${term}" and load the first artist into the #artist section of the DOM...`); fetch( `https://www.apitutor.org/spotify/simple/v1/search?type=artist&q=${term}` ) .then((response) => response.json()) .then((data) => { if (data.length > 0) { const elem = data[0]; document.getElementById("artist").innerHTML = ` <section class="artist-card" id="${elem.id}"> <div> <img src="${elem.image_url}"> <h3>${elem.name}</h3> <div class="footer"> <a href="${elem.spotify_url}" target="_blank"> view on spotify </a> </div> </div> </section> `; } else { document.getElementById("artist").innerHTML = ` <section class="artist-card" id=""> <div> <h3>No artist with the name ${term} found.</h3> </section> `; } }); }; document.querySelector("#search").onkeyup = (ev) => { // Number 13 is the "Enter" key on the keyboard console.log(ev.keyCode); if (ev.keyCode === 13) { ev.preventDefault(); search(); } };
const express = require("express"); const router = express.Router(); const { createContact, deleteContact, getContact, updateContact, } = require("../controllers/contactController"); router.post("/create", createContact); router.delete("/delete/:id", deleteContact); router.get("/contacts", getContact); router.patch("/update/:id", updateContact); module.exports = router;
import React, { useState, useEffect } from "react"; import { Button, Input } from "antd"; import { LockOutlined, ExclamationCircleTwoTone, CheckCircleTwoTone, } from "@ant-design/icons"; import axios from "axios"; import { useRouter } from "next/router"; import { Container, Title, Subtitle, TextTitle, InputWrapper, SuccessMessage, ErrorMessage, } from "./style"; import baseUrl from "../../../utils/baseUrl"; const index = () => { const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [isLoading, setLoading] = useState(false); const [isSuccess, setSuccess] = useState(null); const [isDisabled, setDisabled] = useState(true); const router = useRouter(); //disable reset password button if passwords dont match criteria useEffect(() => { if (password.length >= 6 && password === confirmPassword) { setDisabled(false); } else { setDisabled(true); } }, [password, confirmPassword]); //handle submit function const handleSubmit = async () => { setLoading(true); setSuccess(null); try { //set headers for request const config = { headers: { "Content-Type": "application/json", }, }; //stringify the form items const data = { token: router.query.token, password: password }; const body = JSON.stringify(data); //send request const url = `${baseUrl}/api/verification/authenticate/forgotPassword`; await axios.patch(url, body, config); setSuccess(true); setTimeout(() => { router.push("/"); }, 3000); } catch (err) { setSuccess(false); } finally { setLoading(false); } }; return ( <Container> <Title>Password Reset</Title> <Subtitle>Password must be at least 6 characters</Subtitle> <TextTitle>New Password:</TextTitle> <InputWrapper> <Input.Password placeholder='Password' prefix={<LockOutlined style={{ color: "rgba(0,0,0,.25)" }} />} size='large' name='password' value={password} onChange={(e) => setPassword(e.target.value)} type='password' style={{ marginRight: "1em" }} /> <div style={{ fontSize: "1.5rem" }}> {password.length >= 6 ? ( <CheckCircleTwoTone twoToneColor='#52c41a' /> ) : ( <ExclamationCircleTwoTone twoToneColor='#fcbe03' /> )} </div> </InputWrapper> <TextTitle>Confirm New Password:</TextTitle> <InputWrapper> <Input.Password placeholder='Password' prefix={<LockOutlined style={{ color: "rgba(0,0,0,.25)" }} />} size='large' name='password' value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} type='password' style={{ marginRight: "1em" }} /> <div style={{ fontSize: "1.5rem" }}> {password === confirmPassword && password.length >= 6 ? ( <CheckCircleTwoTone twoToneColor='#52c41a' /> ) : ( <ExclamationCircleTwoTone twoToneColor='#fcbe03' /> )} </div> </InputWrapper> <Button type='primary' htmlType='submit' loading={isLoading} size='large' disabled={isDisabled} onClick={handleSubmit} > Reset Password </Button> {isSuccess && ( <SuccessMessage> <CheckCircleTwoTone twoToneColor='#52c41a' /> Password Successfully Changed! </SuccessMessage> )} {isSuccess === false && ( <ErrorMessage> <ExclamationCircleTwoTone twoToneColor='#fcbe03' /> Could Not Reset Password </ErrorMessage> )} </Container> ); }; export default index;
var validator = require('validator'); var getModelValidator = require('./modelValidator'); var notEmpty = function(string) { return !validator.isNull(string); }; var schema = [ { property: 'name', test: notEmpty, message: 'Tilauksen nimi ei saa olla tyhjä', }, { property: 'costcenterId', test: notEmpty, message: 'Valitse kustannuspaikka', }, ]; module.exports = getModelValidator(schema);
angular.module('signupCtrls', []).controller('signupCtrl', ['$scope', '$stateParams', '$document', '$state', 'usuarioService', function ($scope, $stateParams, $document, $state, usuarioService) { $scope.doSignup = function (userSignup) { if ($document[0].getElementById("cuser_name").value != "" && $document[0].getElementById("cuser_pass").value != "") { firebase.auth().createUserWithEmailAndPassword(userSignup.cusername, userSignup.cpassword).then(function () { //console.log("Signup successful"); var user = firebase.auth().currentUser; user.sendEmailVerification().then(function (result) { console.log(result) }, function (error) { console.log(error) }) name = userSignup.displayName; email = userSignup.email; photoUrl = userSignup.photoURL; uid = userSignup.uid; state = userSignup.state; usuarioService.setUser({ "displayName": userSignup.displayname, "email": user.email, "imageUrl": user.photoURL, "userId": user.uid, "state": userSignup.state }); user.updateProfile({ displayName: userSignup.displayname, photoURL: userSignup.photoprofile, state : userSignup.state }).then(function () { // Update successful. $state.go("login"); }, function (error) { // An error happened. console.log(error); }); alert("Sucesso,verifique seu email e confirme") return false; }, function (error) { // An error happened. var errorCode = error.code; var errorMessage = error.message; console.log(errorCode); if (errorCode === 'auth/weak-password') { alert('Senha está fraca, escolha uma senha mais segura.'); return false; } else if (errorCode === 'auth/email-already-in-use') { alert('O email já está sendo usado.'); return false; } }); } else { alert('Entre com email e senha'); return false; }//end check client username password };// end $scope.doSignup() }]);
var express = require('express'); var router = express.Router(); var mongodb = require('mongodb'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router; router.get('/thelist', function(req, res){ var MongoClient = mongodb.MongoClient; var url = 'mongodb://localhost:27017/gradebook'; // Define where the MongoDB server is MongoClient.connect(url, function (err, db) {// Connect to the server if (err) { console.log('Unable to connect to the Server', err); } else { // We are connected console.log('Connection established to', url); //Get the documents collection var collection = db.collection('students'); collection.find({}).toArray(function (err, result) {// Find all students if (err) { res.send(err); } else if (result.length) { res.render('studentlist',{ // Pass the returned database documents to Jade "studentlist" : result }); } else { res.send('No documents found'); } db.close(); //Close connection }); } }); }); // Route to the page we can add students from using newstudent.jade router.get('/newstudent', function(req, res){ res.render('newstudent', {title: 'Add Student' }); }); router.post('/addstudent', function(req, res){ var MongoClient = mongodb.MongoClient; var url = 'mongodb://localhost:27017/gradebook'; MongoClient.connect(url, function(err, db){ // Connect to the server if (err) { console.log('Unable to connect to the Server:', err); } else { console.log('Connected to Server'); var collection = db.collection('students'); // Get the documents collection var student1 = {firstname: req.body.firstname, lastname: req.body.lastname, // Get the student data email: req.body.email}; collection.insert([student1], function (err, result){ if (err) { console.log(err); } else { res.redirect("thelist"); } db.close(); }); } }); }); router.get('/course', function(req, res){ res.render('course', {title: 'course' }); }); module.exports = router; router.get('/studentsregister', function(req, res){ res.render('studentsregister', {title: 'studentsregister' }); console.log('A'); }); router.get('/studenthome', function(req, res){ res.render('studenthome', {title: 'studenthome'}); console.log('D'); }); router.post('/studentsregister', function(req, res){ console.log('B'); var MongoClient = mongodb.MongoClient; var url = 'mongodb://localhost:27017/gradebook'; MongoClient.connect(url, function(err, db){ // Connect to the server if (err) { console.log('Unable to connect to the Server:', err); } else { console.log('Connected to Server'); var collection = db.collection('students'); // Get the documents collection var student1 = {firstname: req.body.firstname, lastname: req.body.lastname, // Get the student data password: req.body.password, confirmpassword: req.body.confirmpassword, gender: req.body.gender, email: req.body.email, answer:req.body.answer}; collection.insert([student1], function (err, result){ if (err) { console.log("blahhhhhh"); console.log(err); } else { // res.redirect('/studenthome'); res.render('studenthome'); //es.render('/', {title: 'studentsregister' }); console.log('C'); } db.close(); }); } }); }); module.exports = router; router.get('/teachersregister', function(req, res){ res.render('teachersregister', {title: 'teachersregister' }); }); router.get('/teacherhome', function(req, res){ res.render('teacherhome', {title: 'teacherhome' }); console.log('D'); }); router.post('/registerteacher', function(req, res){ var MongoClient = mongodb.MongoClient; var url = 'mongodb://localhost:27017/gradebook'; MongoClient.connect(url, function(err, db){ // Connect to the server if (err) { console.log('Unable to connect to the Server:', err); } else { console.log('Connected to Server'); var collection = db.collection('teachers'); // Get the documents collection var teacher1 = {firstname: req.body.firstname, lastname: req.body.lastname, // Get the student data password: req.body.password, email: req.body.email, securityanswer: req.body.answer}; collection.insert([teacher1], function (err, result){ if (err) { console.log(err); } else { res.redirect("teacher"); } db.close(); }); } }); }); module.exports = router; router.get('/teacher', function(req, res){ res.render('teacher', {title: 'Teacher' }); }); router.post('/teacher', function(req, res){ var MongoClient = mongodb.MongoClient; var url = 'mongodb://localhost:27017/gradebook'; MongoClient.connect(url, function(err, db){ // Connect to the server if (err) { console.log('Unable to connect to the Server:', err); } else { console.log('Connected to Server'); var collection = db.collection('teachers'); // Get the documents collection var teacher1 = {teacher: req.body.teacher, street: req.body.street, // Get the student data city: req.body.city, state: req.body.state, sex: req.body.sex, gpa: req.body.gpa}; collection.insert([teacher1], function (err, result){ if (err) { console.log(err); } else { res.redirect('/studenthome'); //res.render('studenthome', {title: 'studenthome' }); } db.close(); }); } }); }); module.exports = router; router.get('/teacherlogin', function(req, res){ res.render('teacherlogin', {title: 'teacherlogin' }); }); router.post('/teacherlogin', function(req, res){ // Get a Mongo client to work with the Mongo server var MongoClient = mongodb.MongoClient; // Define where the MongoDB server is var url = 'mongodb://localhost:27017/gradebook'; // Connect to the server MongoClient.connect(url, function(err, db){ if (err) { console.log('Unable to connect to the Server:', err); } else { console.log('Connected to Server'); var collection = db.collection('teachers'); var login1 = req.body.username; var login2 = req.body.password; console.log(req.body); console.log(login1); console.log(login2); collection.find({"email": login1,"pass": login2}).toArray(function (err, result) { console.log(result); if (err) { res.send("hi" + err); console.log("B"); } else if (result.length) { console.log("Logged In"); res.render('teacherhome', { "userData" : result }); } else { res.redirect('/'); } db.close(); }); } //db.close(); }); }); module.exports = router; router.get('/studentlogin', function(req, res){ res.render('studentlogin', {title: 'studentlogin' }); }); router.post('/studentlogin', function(req, res){ var MongoClient = mongodb.MongoClient; var url = 'mongodb://localhost:27017/gradebook'; MongoClient.connect(url, function(err, db) { // Connect to the server if (err) { console.log('Unable to connect to the Server:', err); } else { console.log('Connected to Server'); var collection = db.collection('studnets'); // Get the documents collection var user=req.body.username; var password=req.body.password; collection.find(user); if (err) { console.log(err); } else { res.redirect('/studenthome'); //res.render('studenthome', {title: 'studenthome' }); } db.close(); } }); }); // });
import React from 'react'; import PropTypes from 'prop-types'; import Typography from '@material-ui/core/Typography'; import DSASelect from '../controls/DSASelect'; import DSAItemList from '../controls/DSAItemList'; import DSAStepContent from '../controls/DSAStepContent'; import {CraftingObjects} from '../data/DSAObjects'; import {GetObject} from './DSASummaryObject'; const ID = "object" export default class DSAObjectChooser extends React.Component { handleChange = (value) => { // find the right cost object: const o = CraftingObjects.find((c) => c.name === value.value); this.props.onChange(ID, o); } handleBack = () => { this.props.stepper.back(ID); } getOptions() { const {objecttype, talent} = this.props; return CraftingObjects.filter((c) => { return c.type === objecttype.name && c.talent === talent.name; }).map((c) => ({value: c.name, label: c.name})); } render() { const {stepper, object} = this.props const active = object !== undefined; return <DSAStepContent active={active} handleNext={stepper.next} handleBack={this.handleBack}> <Typography>Wähle einen Gegenstand.</Typography> <form> <DSASelect options={this.getOptions()} value={active ? object.name : ""} onChange={this.handleChange} label="Wähle" /> </form> {active && <DSAItemList items={GetObject(object)}/>} </DSAStepContent> } } DSAObjectChooser.propTypes = { stepper: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, objecttype: PropTypes.object.isRequired };
//for checking the status of the user i.e whether he is logged in or not auth.onAuthStateChanged(user =>{ if(user) { console.log('User Logged In: ', user); console.log("Opened: "+window.location.href); var path = window.location.href; var split = path.split("/"); var x = split.slice(0, split.length - 1).join("/") + "/"; console.log("To be replaced with : "+ x+"loggedin.html"); window.location.replace(x+"loggedin.html"); document.getElementById('loginnav').style.display = 'none'; document.getElementById('signupnav').style.display = 'none'; document.getElementById('logoutnav').style.display = 'inline-block'; document.getElementById('container').style.display = 'none'; } else{ console.log('User Logged Out'); document.getElementById('loginnav').style.display = 'inline-block'; document.getElementById('signupnav').style.display = 'inline-block'; document.getElementById('logoutnav').style.display = 'none'; document.getElementById('container').style.display = 'none'; } }); //signup const signupform = document.querySelector('#signup-form'); signupform.addEventListener('submit', (e) =>{ e.preventDefault(); // to prevent it from going back, i.e. does not refreshes the page document.getElementById('errors1').style.display='none'; //get user info const email = signupform['signup-email'].value; const password = signupform['signup-password'].value; const repassword = signupform['signup-repassword'].value; // console.log(email, password) const uName=signupform['signup-name'].value; //signup the user if(password == repassword) { auth.createUserWithEmailAndPassword(email, password).then(cred => { console.log(cred.user); const modal = document.querySelector('#modal-signup'); signupform.reset(); var par = document.getElementById("error1"); var ta = document.createTextNode(""); par.appendChild(ta); var user = firebase.auth().currentUser; if (user) { // User is signed in. console.log("Hi"); firebase.database().ref('users/' + user.uid).set({ username: uName, email: email, }, function(error) { if (error) { console.log("//The write failed"); } else { console.log("//Data saved successfully"); return result.user.updateProfile({ displayName: uName }) } }); } else { console.log("Bye"); // No user is signed in. } }).catch(err => { document.getElementById('errors1').style.display='block'; var para = document.getElementById("error1"); para.innerHTML= err.message; }); } else { alert("The passwords do not match"); } }); //logout const logout = document.querySelector('#logout'); logout.addEventListener('click',(e) => { e.preventDefault(); auth.signOut().then(() =>{ //console.log('User Signed Out'); }); }); const forgot = document.querySelector("#forgot-button"); forgot.addEventListener('click',(e) => { var auth = firebase.auth(); //const loginforms = document.querySelector('#login-form'); const emailAddress = document.getElementById("forgot-email").value; e.preventDefault(); auth.sendPasswordResetEmail(emailAddress).then(() =>{ // Email sent. alert("Email Sent") }).catch(function(error) { // An error happened. alert("Email Not sent") }); }) // Login Form const loginform = document.querySelector('#login-form'); const loginButton = document.querySelector('#login-button'); loginform.addEventListener('submit', (e) =>{ e.preventDefault(); //get User info const email = loginform['login-email'].value; const password = loginform['login-password'].value; auth.signInWithEmailAndPassword(email, password).then(cred =>{ //console.log(cred.user) //not needed really const modal = document.querySelector('#modal-login'); //to get the login form in work loginform.reset(); var par = document.getElementById("error2"); var ta = document.createTextNode(""); par.appendChild(ta); }).catch(err => { document.getElementById('errors2').style.display='block'; var para = document.getElementById("error2"); para.innerHTML= err.message; }); });
/*jshint esversion:6 */ import 'babel-polyfill'; import * as tf from '@tensorflow/tfjs'; import {learnLinear} from './learnLinear'; import {run} from './run'; run(); //learnLinear();
import styles from '../../Global/styles/adminHousestyle.module.css' import firebase from '../../../../../db/firebase' import { useDocumentDataOnce } from 'react-firebase-hooks/firestore' const ImageEdit = ({ index }) => { const [ images ] = useDocumentDataOnce(firebase.firestore().collection('media').doc('images')) return ( <> <h1>Photo Gallery</h1> <h2>Edit the detials for this image</h2> <div className={styles.userInterface}> { !images ? 'Loading image data...' : <> <h3>{images.gallery[index].title}</h3> </> } </div> </> ) } export default ImageEdit
import React, {Component} from "react"; import Axios from "axios"; //import CSS file import "./recipeContent.css"; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import Favorite from '@material-ui/icons/Favorite'; import FavoriteBorder from '@material-ui/icons/FavoriteBorder'; class RecipeContent extends Component{ constructor(props){ super(props); this.state={ meal: [], }; } componentDidMount(){ console.log( "https://www.themealdb.com/api/json/v1/1/search.php?s=" + this.props.recipe ); if(this.props.recipe==="") alert("ENTER A VALID VALUE!!"); else { Axios.get( "https://www.themealdb.com/api/json/v1/1/search.php?s=" + this.props.recipe ).then((resolve) => { console.log(resolve.data.meals); this.setState({ meal: resolve.data.meals, }); }); } } componentDidUpdate(prevProps) { if (this.props.recipe !== prevProps.recipe) { if (this.props.recipe === "") alert("Enter a Dish!!"); else { Axios.get( "https://www.themealdb.com/api/json/v1/1/search.php?s=" + this.props.recipe ).then((resolve) => { console.log(resolve.data.meals); this.setState({ meal: resolve.data.meals, }); }); } } } render(){ const{meal} = this.state; if(meal !== null && meal.length>0){ var list = []; let i = 1; while (meal[0]["strIngredient"+i]!==""){ list.push( <li key={i}> {meal[0]["strIngredient" + i] + "----" + meal[0]["strMeasure" + i]} </li> ); i++; } console.log(list); } const id = meal !== null && meal.length > 0 ? ( <div className="recipeContainer"> <div className="title"> <h1>{meal[0].strMeal}</h1> <FormControlLabel control={<Checkbox icon={<FavoriteBorder />} checkedIcon={<Favorite />} name="checkedH" />}/> </div> <div className="recipeData"> <img src={meal[0].strMealThumb} alt={"Your meal for " + meal[0].strMeal} /> <div className="textInfo"> <p> <em>Category of Meal:</em> {meal[0].strCategory}{" "} </p> <p> <em>Area of the Meal:</em> {meal[0].strArea}{" "} </p> <h3> Ingredients<style></style></h3> <ul className="ingredients">{list}</ul> <h3>Recipes</h3> <div className="recipes">{meal[0].strInstructions}</div> </div> </div> </div> ) : ( <div className="nada">No Data has been received</div> ); return <div>{id}</div>; } } export default RecipeContent;
import Firebase from './index'; import { timestampData } from './dataWrapper'; export default class FBProposals { static Collection = 'proposals'; static getCollection() { const { db } = Firebase; return db.collection(FBProposals.Collection); } static add(document) { const collection = this.getCollection(); return collection.add(timestampData(document)); } }
var interface_c1_connector_complete_session_service = [ [ "createCompleteSessionWithOptions:usingBlock:", "interface_c1_connector_complete_session_service.html#a0fc2d913ecd06bbf6ec9932700ba7bca", null ] ];
var connection; var websocket_open=false; var control=['T','P','R','Y','1','2']; var can_send_controll=false; var debug=false; var canvas; var limitSize = 64; var inputSize = 36; var lastTime; var sticks; var context; var WIDTH var HEIGHT; var threshold; var point; function debugc(message){ if ( debug ) console.log(message); } function send_rc(channel,value) { sendBuffer=new Int8Array(4); if (websocket_open) { sendBuffer[0]='S'.charCodeAt(0); sendBuffer[1]=channel.charCodeAt(0); val=parseInt(value); sendBuffer[2]=val & 0x00ff; sendBuffer[3]=(val &0x0000ff00) >>8; connection.send(sendBuffer); } } function manage_rc(e){ debugc("message received"); var dv=new DataView(e.data); var cmd=dv.getUint8(0); var sendBuffer= new Int8Array(2); if (cmd == 'G'.charCodeAt(0)){ var controller = dv.getUint8(1); var value= dv.getUint16(2); sendBuffer[0]='G'.charCodeAt(0); switch (controller){ // 'T' case 84: $("#throttle-range").val(value.toString()).slider("refresh"); sendBuffer[1]='Y'.charCodeAt(0); break; // 'Y' case 89: $("#yaw-range").val(value.toString()).slider("refresh"); sendBuffer[1]='P'.charCodeAt(0); break; // 'P' case 80: $("#pitch-range").val(value.toString()).slider("refresh"); sendBuffer[1]='R'.charCodeAt(0); break; // 'R' case 82: $("#roll-range").val(value.toString()).slider("refresh"); sendBuffer[1]='1'.charCodeAt(0); break; // '1' case 49: $("#aux1-range").val(value.toString()).slider("refresh"); sendBuffer[1]='2'.charCodeAt(0); break; // '2' case 50: $("#aux2-range").val(value.toString()).slider("refresh"); can_send_controll = true; break; } connection.send(sendBuffer); } } function closeWS(){ connection.close(); websocket_open=false; } function createWS(){ if (websocket_open) closeWS(); connection = new WebSocket("ws://"+window.location.hostname+":8080") connection.binaryType="arraybuffer" connection.onopen = function () { debugc("Connection opened") $("#connected").css("color","green"); websocket_open=true; sendBuffer= new Int8Array(2); sendBuffer[0]='G'.charCodeAt(0); sendBuffer[1]='T'.charCodeAt(0); connection.send(sendBuffer); } connection.onclose = function () { debugc("Connection closed") $("#connected").css("color","red"); websocket_open=false; } connection.onerror = function (e) { debugc("Connection error:"+ev.data) } connection.onmessage = function (event) { debugc("message"); manage_rc(event); } } $(document).ready(function(e) { $("#esp8266remote").bind("pagecreate", function(e) { debugc("page created"); }); $("#connect").bind("vclick", function(e) { debugc("connect"); createWS(); }); $("#disconnect").bind("vclick", function(e) { debugc("disconnect"); closeWS(); can_send_controll=false; update_cnt=0; }); $("#throttle").bind("change", function(e) { debugc("throttle update"); if( can_send_controll ) send_rc('T',$("#throttle-range").val()); }); $("#yaw").bind("change", function(e) { debugc("yaw update"); if( can_send_controll ) send_rc('Y',$("#yaw-range").val()); }); $("#pitch").bind("change", function(e) { debugc("pitch update"); if( can_send_controll ) send_rc('P',$("#pitch-range").val()); }); $("#roll").bind("change", function(e) { debugc("roll update"); if( can_send_controll ) send_rc('R',$("#roll-range").val()); }); $("#aux1").bind("change", function(e) { debugc("aux1 update"); if( can_send_controll ) send_rc('1',$("#aux1-range").val()); }); $("#aux2").bind("change", function(e) { debugc("aux2 update"); if( can_send_controll ) send_rc('2',$("#aux2-range").val()); }); canvas = document.getElementById("stage"); context = canvas.getContext("2d"); WIDTH = canvas.offsetWidth; HEIGHT = canvas.offsetHeight; lastTime = Date.now(); sticks = [new Stick(inputSize), new Stick(inputSize)]; threshold = 4; point = { radius: 20, speed: 10, x: (WIDTH / 2), y: (HEIGHT / 2)} init(); });
/* * After add to cart tests, complete checkout * * @package: Blueacorn 6_completeCheckout.js * @version: 1.0 * @Author: Luke Fitzgerald * @Copyright: Copyright 2015-09-04 13:12:42 Blue Acorn, Inc. */ 'use strict'; casper.userAgent('Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1') //local testing phantom.injectJs('../../data/Data.js'); phantom.injectJs('../../utilities/Start.js'); phantom.injectJs('../../utilities/Run.js'); phantom.injectJs('../../utilities/Screenshot.js'); phantom.injectJs('../../utilities/CommonTests.js'); phantom.injectJs('../../pos/SimpleProductPage.js'); phantom.injectJs('../../pos/Checkout.js'); phantom.injectJs('../../pos/Header.js'); phantom.injectJs('../../pos/OrderSuccessPage.js'); //product page suite testing /*phantom.injectJs('../data/Data.js'); phantom.injectJs('../utilities/Start.js'); phantom.injectJs('../utilities/Run.js'); phantom.injectJs('../utilities/Screenshot.js'); phantom.injectJs('../utilities/CommonTests.js'); phantom.injectJs('../pos/SimpleProductPage.js'); phantom.injectJs('../pos/Checkout.js'); phantom.injectJs('../pos/Header.js'); phantom.injectJs('../pos/OrderSuccessPage.js');*/ var d = new Data(); var start = new Start(); var run = new Run(); var screenshot = new Screenshot(); var ct = new CommonTests(); var checkout = new Checkout(); var spp = new SimpleProductPage(); var header = new Header(); var osp = new OrderSuccessPage(); casper.test.begin('Add simple product to cart', 13, function(test) { var productName; var orderNum; casper.options.viewportSize = {width:d.getDesktopBrowserWidth(), height:d.getBrowserHeight()}; casper.options.waitTimeout = 10000; //start.startWithCreds(d.getStagingDomain() + checkout.getUrl(), d.getHttpUn(), d.getHttpPw()); start.startWithCreds(d.getStagingDomain() + d.getSimpleProd3(), d.getHttpUn(), d.getHttpPw()); ct.testHttpStatus(); //starting on product page for testing purposes only casper.then(function() { //get product name, assert mini cart is closed, assert add to cart button exists productName = this.fetchText(spp.getProductName()); ct.assertExists(header.getClosedMiniCart()); ct.assertExists(spp.getAddToCartButton()); }); casper.then(function() { //add product to cart this.click(spp.getAddToCartButton()); }); casper.waitForSelector(header.getOpenMiniCart(), function() { casper.waitForText('Recently added items', function() { this.echo(this.fetchText(header.getMiniCartSuccessMessage())); }); }); casper.then(function() { ct.assertExists(header.getMiniCartProducts() + ':nth-child(1)'); ct.assertEquals(productName, this.fetchText(header.getMiniCartProducts() + ':nth-child(1) > div > div > p.product-name > a'), 'Product name in mini cart matches product name on page!'); //advance to checkout this.click(header.getMiniCartCheckoutButton()); }); casper.wait(1000); casper.waitUntilVisible(checkout.getCheckoutHeading(), function() { this.click(checkout.getGuestCheckoutButton()); }); //start of checkout page testing casper.then(function() { //click guest checkout button this.click(checkout.getGuestCheckoutButton()); }); casper.waitUntilVisible(checkout.getBillingStepTitle(), function() { ct.assertVisible(checkout.getBillingForm()); //once form is visible, fill it out this.sendKeys(checkout.getBillingFirstName(), d.getFn()); this.sendKeys(checkout.getBillingLastName(), d.getLn()); this.sendKeys(checkout.getBillingEmail(), d.getEmail()); this.sendKeys(checkout.getBillingAddress(), d.getAddress()); this.sendKeys(checkout.getBillingCity(), d.getCity()); this.sendKeys(checkout.getBillingZip(), d.getZip()); this.sendKeys(checkout.getBillingPhone(), d.getPhone()); this.evaluate(function() { $('billing:region_id').value = 54; }); }); casper.then(function() { //assert ship to this address radio button is checked (default) ct.assertExists(checkout.getBillingShipToThisAddressRadioButtonLabel() + '.checked'); ct.assertExists(checkout.getBillingShipToAnotherAddressRadioButtonLabel() + ':not(.checked)'); }); casper.then(function() { this.click(checkout.getBillingContinueButton()); }); casper.waitUntilVisible(checkout.getShippingMethodSubheading(), function() { //assert shipping methods form is displayed ct.assertVisible(checkout.getShippingMethodForm()); //assert first shipping method radio button is checked (default) ct.assertExists(checkout.getShippingMethodRadioButtonLabel() + '.checked'); }); casper.then(function() { this.click(checkout.getShippingMethodContinueButton()); }); casper.waitUntilVisible(checkout.getPaymentInfoForm(), function() { //assert payment info form is visible ct.assertVisible(checkout.getPaymentInfoForm()); //assert first payment option (braintree) is selected (default) ct.assertExists(checkout.getPaymentOptionLabel() + '.checked'); //fill out CC form this.sendKeys(checkout.getCcNum(), d.getCcNum()); this.sendKeys(checkout.getCcvNum(), d.getCcvNum()); //entire cc expiration date this.evaluate(function() { $('#braintree_expiration').value = d.getCCExpMonth; }); this.evaluate(function() { $('#braintree_expiration_yr').value = d.getCCExpYear; }); }); //casper.wait(5000); casper.then(function() { this.click(checkout.getPaymentInfoContinueButton()); }); casper.wait(1000); casper.waitUntilVisible(checkout.getOrderReviewBlock(), function() { //assert order review table is displayed ct.assertVisible(checkout.getOrderReviewBlock()); }); //this scroll was for testing purposes only casper.then(function() { //scroll down page, just to see what is happening this.scrollTo(0, 500); }); casper.then(function() { this.click(checkout.getSubmitOrderButton()); }); casper.wait(5000); // //Order Success Page tests // casper.waitUntilVisible(osp.getHeading(), function() { casper.waitForText('THANK YOU FOR YOUR PURCHASE!', function() { this.echo(this.fetchText(osp.getOrderNum())); orderNum = this.fetchText(osp.getOrderNum()); }); }); casper.wait(5000); ct.clearCookies(); run.run(); });
import { useEffect } from "react"; export default function useOnClickOutside(ref, handleEvent) { useEffect(() => { const eventListener = e => { if (!ref.current.contains(e.target)) { handleEvent(e); } }; document.addEventListener("click", eventListener); return () => document.removeEventListener("click", eventListener); }, [ref, handleEvent]); }
$("#text").html("konexion");
'use strict'; import React, {Component} from 'react'; import { View, ScrollView, SafeAreaView, StatusBar, Image, AsyncStorage, StyleSheet,} from 'react-native'; import {DisplayText, } from '../../components'; import styles from './styles'; export default class Profile extends Component { constructor(props) { super(props); this.state ={ overflowModalVisible: false, data : '', phone : 0, token : '', profile_id : '', showAlert : false, message : '', refreshing: false, gender: '', } } render () { return( <SafeAreaView style={styles.container}> <StatusBar barStyle="default" /> <View style = {styles.subscribtionView}> <View style = {styles.subPlanView}> </View> </View> </SafeAreaView> ) } }
define(['angular'], function (angular) { 'use strict'; /** * @ngdoc function * @name kvmApp.controller:CookiesCtrl * @description * # CookiesCtrl * Controller of the kvmApp */ angular.module('kvmApp.controllers.CookiesCtrl', ['ngCookies']) .controller('CookiesCtrl', function ($scope, $http, $cookieStore) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; $scope.initPage = function(number) { $http.get('/api/v2/getinfo/' +number). success(function (data) { $scope.username = data.username; $scope.defaults = data.defaults; $scope.projects = data.projects; $scope.results = data.results; }); }; $scope.initPage(1); }); });
import { StyleSheet } from 'react-native' export const styles = StyleSheet.create({ container: { flex:1, padding:10, backgroundColor:'#111', //justifyContent:'center', //alignItems:'center' }, containerTxtTop: { justifyContent:'center', alignItems:'center', height:'15%' }, txtTop: { fontSize:18, fontWeight:'bold', letterSpacing:2.8, color:'#e9e9e9' }, containerItem: { width: '100%', height: 70, backgroundColor: '#111', padding: 5, paddingLeft: 10, flexDirection: 'row', marginBottom: 1, }, containerImage: { borderRadius: 24 }, picture: { height: 60, width: 60, resizeMode: "cover", borderRadius: 30, borderColor: '#aaa', borderWidth: 1, }, containerInfos: { flex: 1, flexDirection: 'column', paddingLeft: 10, backgroundColor: '#111' }, name: { fontWeight: 'bold', fontSize: 16, marginBottom: 2, color: '#aaa' }, phone: { //paddingLeft:10, fontSize: 12, paddingLeft: 5, color: '#aaa' }, address: { //paddingLeft:10, fontSize: 11, paddingLeft: 5, color: '#aaa' }, })
import KbcAccess from './app/KbcAccess'; import Projects from './app/Projects'; import Services from './lib/Services'; import Users from './app/Users'; require('source-map-support').install(); const _ = require('lodash'); const createError = require('http-errors'); const { RequestHandler } = require('@keboola/serverless-request-handler'); let services; function initStorage(event) { const token = _.find(event.headers, (header, index) => _.toLower(index) === 'x-storageapi-token'); if (!token) { throw createError(401, 'Storage token is missing from request headers'); } return services.getStorage(process.env.KBC_URL, token); } function initKbcAccessApp(event) { return new KbcAccess(services.getDb(), initStorage(event), services); } function initProjectsApp(event) { return new Projects(services.getDb(), initStorage(event), services.getValidation(), services); } function initUsersApp(event) { return new Users(services.getDb(), initStorage(event), services.getValidation(), services); } const resourceMap = { '/': { GET: { handler: () => Promise.resolve({ api: 'gooddata-provisioning', documentation: 'https://keboolagooddataprovisioning.docs.apiary.io', }), code: 200, }, }, '/projects': { GET: { handler: event => initProjectsApp(event).list(event), code: 200, }, POST: { handler: event => initProjectsApp(event).create(event), code: 201, }, }, '/projects/{pid}': { GET: { handler: event => initProjectsApp(event).get(event), code: 200, }, DELETE: { handler: event => initProjectsApp(event).delete(event), code: 204, }, }, '/users': { GET: { handler: event => initUsersApp(event).list(event), code: 200, }, POST: { handler: event => initUsersApp(event).create(event), code: 201, }, }, '/users/{login}': { DELETE: { handler: event => initUsersApp(event).delete(event), code: 204, }, }, '/users/{login}/sso': { GET: { handler: event => initUsersApp(event).sso(event), code: 200, }, }, '/projects/{pid}/users/{login}': { POST: { handler: event => initProjectsApp(event).addUser(event), code: 204, }, DELETE: { handler: event => initProjectsApp(event).removeUser(event), code: 204, }, }, '/projects/{pid}/access': { GET: { handler: event => initKbcAccessApp(event).sso(event), code: 200, }, POST: { handler: event => initKbcAccessApp(event).create(event), code: 204, }, DELETE: { handler: event => initKbcAccessApp(event).remove(event), code: 204, }, }, }; module.exports.handler = (event, context, callback) => RequestHandler.handler(() => { process.env.AWS_REQUEST_ID = context.awsRequestId; if (!_.has(event, 'httpMethod') || !_.has(event, 'resource')) { throw createError(400, 'Bad Request'); } if (!_.has(resourceMap, event.resource)) { throw createError(404, 'Route Not Found'); } const resource = resourceMap[event.resource]; if (!_.has(resource, event.httpMethod)) { throw createError(405, 'Method Not Allowed'); } const resourceMethod = resource && resource[event.httpMethod]; services = new Services(process.env); return resourceMethod.handler(event) .then(res => RequestHandler.response(null, res, event, context, callback, resourceMethod.code)) .catch((err) => { if (err.statusCode && _.get(err, 'statusCode') < 500) { const response = RequestHandler.getResponseBody(err, null, context); RequestHandler.logRequest(context, err, event, response); response.body = response.body ? JSON.stringify(response.body) : ''; callback(null, response); } return RequestHandler.response(err, null, event, context, callback); }); }, event, context, callback);
// <!-firebase chat history start Gk--> var chatHistory = "chatHistory"; var database = firebase.database().ref(); ref = database.child(chatHistory).child(firebaseId); ref.on("value",gotData); function gotData(data){ var scores = data.val(); if(scores==null){ $("#chatHistory").html('No chat history'); }else{ var keys = Object.keys(scores); dataShow(keys,scores); } } function dataShow(keys,scores){ a = 0; $("#chatHistory").html(""); if(keys.length==0){ $("#chatHistory").html('<div class="chatList">No chat history </div>'); }else{ for (var i = 0; i < keys.length; i++) { var k = keys[i]; var res = k.split("+"); database.child("users").child(res[1]).once('value').then(function(snapshot) { var d = keys[a]; a++; var name = snapshot.val().name; var uImage = snapshot.val().image; var productId = scores[d].productId; var productImage = scores[d].productImage; var RreceiverId = scores[d].receiverId; var dt = new Date(scores[d].time); var RsenderId = scores[d].senderId; var Userid = scores[d].opponentId; var message = scores[d].message; userId = RsenderId; if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(message)){ var msg = "Send image"; } else { var msg = message; } var month = dt.getMonth()+1; var day = dt.getDate(); var output = (month<10 ? '0' : '') + month + '/' + (day<10 ? '0' : '') + day + '/' + dt.getFullYear() ; console.log(output); console.log(output); var hours = dt.getHours(); var minutes = dt.getMinutes(); var timeString = hours + ":" + (minutes<10 ? '0' : '')+ minutes + ":" + dt.getSeconds(); var H = +timeString.substr(0, 2); var h = (hours<10 ? '0' : '')+(H % 12) || 12; var ampm = H < 12 ? "AM" : "PM"; postTime = output+" "+h + timeString.substr(2, 3) + ampm; if (msg.length > 50) { msg = msg.substr(0, 50)+'...'; } $("#chatHistory").append('<div class="chatList"><div class="chatuserImg"><a href="'+base_url+'chat/index/'+Userid+'/'+productId+'"><img src="'+uImage+'"><div class="userInfo"><h3>'+name+'</h3><p>'+msg+'</p></div></a></div><div class="chatPr"><a href="'+base_url+"products/viewProduct/"+productId+'"><img src="'+productImage+'"></a><p>'+postTime+'</p></div></div>'); }); /* $.ajax({ url:base_url+'user/profilegetByChatId', type:'post', data: {'chatId':res[1]}, success:function(resp){ udata = $.parseJSON(resp); var uImage = udata.image; if(name!=""){ var name = udata.name; var d = keys[a]; console.log(name); console.log(scores[d].message); var productId = scores[d].productId; var productImage = scores[d].productImage; var RreceiverId = scores[d].receiverId; var dt = new Date(scores[d].time); var RsenderId = scores[d].senderId; var Userid = scores[d].opponentId; var message = scores[d].message; userId = RsenderId; if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(message)){ var msg = "Send image"; } else { var msg = message; } var month = dt.getMonth()+1; var day = dt.getDate(); var output = (day<10 ? '0' : '') + day + '/' + (month<10 ? '0' : '') + month + '/' + dt.getFullYear() ; var timeString = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); var H = +timeString.substr(0, 2); var h = (H % 12) || 12; var ampm = H < 12 ? "AM" : "PM"; postTime = output+" "+h + timeString.substr(2, 3) + ampm; $("#chatHistory").append('<div class="chatList"><a href="'+base_url+'chat/index/'+Userid+'/'+productId+'"><div class="chatuserImg"><img src="'+uImage+'"><div class="userInfo"><h3>'+name+'</h3><p>'+msg+'</p></div></div><div class="chatPr"><img src="'+productImage+'"><p>'+postTime+'</p></div></a></div>'); a++; } } });*/ } } } function dataSort(array){ array.sort(function(a,b){ // Turn your strings into dates, and then subtract them // to get a value that is either negative, positive, or zero. return new Date(b.time) - new Date(a.time); }); } // <!-firebase chat history end Gk-->
var libs = { portal: require('/lib/xp/portal'), // Import the portal functions thymeleaf: require('/lib/xp/thymeleaf'), // Import the Thymeleaf rendering function util: require('/lib/enonic/util') }; // Specify the view file to use var conf = { view: resolve('country.html') }; // Handle the GET request exports.get = function(req) { libs.util.log(req); // Get the country content and extract the needed data from the JSON var content = libs.portal.getContent(); // Prepare the model object with the needed data extracted from the content var model = { name: content.displayName, isEUCountry : content.member, description: content.data.description, population: content.data.population }; // Return the merged view and model in the response object return { body: libs.thymeleaf.render(conf.view, model) } };
import React from 'react'; import './ResetButton.css'; const ResetButton = ({ children, setInitialStates }) => ( <button type="reset" onClick={() => setInitialStates()}>{children}</button> ) export default ResetButton;
import React from "react"; import { View, Text, StyleSheet, Button, ActivityIndicator } from "react-native"; import axios from "axios"; import Header from "../components/Header"; import QuizList from "../components/QuizList"; class QuizScreen extends React.Component { state = { loading: false }; static navigationOptions = { header: null }; startQuiz = () => { const { loading } = this.state; const { navigation } = this.props; this.setState({ loading: !loading }); fetch( "https://opentdb.com/api.php?amount=10&category=18&difficulty=easy&type=multiple&encode=base64" ) .then(response => response.json()) .then(({ results }) => { this.setState({ loading: false }); navigation.navigate("Questions", { questions: results }); }) .catch(err => { console.log("ERR->", err); alert(`ERROR: ${err.message}. Try again`); this.setState({ loading: false }); }); }; render() { const { loading } = this.state; return ( <View style={styles.container}> {loading ? ( <ActivityIndicator size="large" color="#008080" /> ) : ( <Button onPress={() => this.startQuiz()} title="Start Quiz" color="#008080" /> )} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#F5F5F5" }, button: { padding: 25, color: "white", alignItems: "center", backgroundColor: "#e74c3c", borderRadius: 5 } }); export default QuizScreen;
const apiKey = "AIzaSyCPGprQ3b1CTpBQUxtOckThjtLm3AYEQrQ"; module.exports = apiKey;
app.controller("contractCtrl", ['ContractService', 'ContractAttachService', 'ContractReceiptService', 'ModalProvider', '$scope', '$rootScope', '$state', '$timeout', '$uibModal', function (ContractService, ContractAttachService, ContractReceiptService, ModalProvider, $scope, $rootScope, $state, $timeout, $uibModal) { /************************************************************** * * * Contract * * * *************************************************************/ $scope.selected = {}; $scope.contracts = []; $scope.param = {}; $scope.items = []; $scope.items.push( {'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu'}, {'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'العقود' : 'Contracts'} ); $scope.filter = function () { var search = []; if ($scope.param.code) { search.push('code='); search.push($scope.param.code); search.push('&'); } // if ($scope.param.customerName) { search.push('customerName='); search.push($scope.param.customerName); search.push('&'); } if ($scope.param.customerMobile) { search.push('customerMobile='); search.push($scope.param.customerMobile); search.push('&'); } if ($scope.param.customerIdentityNumber) { search.push('customerIdentityNumber='); search.push($scope.param.customerIdentityNumber); search.push('&'); } // if ($scope.param.supplierName) { search.push('supplierName='); search.push($scope.param.supplierName); search.push('&'); } if ($scope.param.supplierMobile) { search.push('supplierMobile='); search.push($scope.param.supplierMobile); search.push('&'); } if ($scope.param.supplierIdentityNumber) { search.push('supplierIdentityNumber='); search.push($scope.param.supplierIdentityNumber); search.push('&'); } // if ($scope.param.amountFrom) { search.push('amountFrom='); search.push($scope.param.amountFrom); search.push('&'); } if ($scope.param.amountTo) { search.push('amountTo='); search.push($scope.param.amountTo); search.push('&'); } // if ($scope.param.registerDateFrom) { search.push('registerDateFrom='); search.push($scope.param.registerDateFrom.getTime()); search.push('&'); } if ($scope.param.registerDateTo) { search.push('registerDateTo='); search.push($scope.param.registerDateTo.getTime()); search.push('&'); } // ContractService.filter(search.join("")).then(function (data) { $scope.contracts = data; $scope.setSelected(data[0]); $scope.totalAmount = 0; $scope.totalPayments = 0; $scope.totalRemain = 0; angular.forEach(data, function (contract) { $scope.totalAmount+=contract.amount; $scope.totalPayments+=contract.paid; $scope.totalRemain+=contract.remain; }); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findAllContracts = function () { ContractService.findAll().then(function (data) { $scope.contracts = data; $scope.setSelected(data[0]); $scope.totalAmount = 0; $scope.totalPayments = 0; $scope.totalRemain = 0; angular.forEach(data, function (contract) { $scope.totalAmount+=contract.amount; $scope.totalPayments+=contract.paid; $scope.totalRemain+=contract.remain; }); $scope.items = []; $scope.items.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'العقود' : 'Contracts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'كل العقود' : 'All Contracts'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsByToday = function () { ContractService.findByToday().then(function (data) { $scope.contracts = data; $scope.setSelected(data[0]); $scope.totalAmount = 0; $scope.totalPayments = 0; $scope.totalRemain = 0; angular.forEach(data, function (contract) { $scope.totalAmount+=contract.amount; $scope.totalPayments+=contract.paid; $scope.totalRemain+=contract.remain; }); $scope.items = []; $scope.items.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'العقود' : 'Contracts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'عقود اليوم' : 'Contracts For Today'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsByWeek = function () { ContractService.findByWeek().then(function (data) { $scope.contracts = data; $scope.setSelected(data[0]); $scope.totalAmount = 0; $scope.totalPayments = 0; $scope.totalRemain = 0; angular.forEach(data, function (contract) { $scope.totalAmount+=contract.amount; $scope.totalPayments+=contract.paid; $scope.totalRemain+=contract.remain; }); $scope.items = []; $scope.items.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'العقود' : 'Contracts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'عقود الاسبوع' : 'Contracts For Week'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsByMonth = function () { ContractService.findByMonth().then(function (data) { $scope.contracts = data; $scope.setSelected(data[0]); $scope.totalAmount = 0; $scope.totalPayments = 0; $scope.totalRemain = 0; angular.forEach(data, function (contract) { $scope.totalAmount+=contract.amount; $scope.totalPayments+=contract.paid; $scope.totalRemain+=contract.remain; }); $scope.items = []; $scope.items.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'العقود' : 'Contracts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'عقود الشهر' : 'Contracts For Month'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsByYear = function () { ContractService.findByYear().then(function (data) { $scope.contracts = data; $scope.setSelected(data[0]); $scope.totalAmount = 0; $scope.totalPayments = 0; $scope.totalRemain = 0; angular.forEach(data, function (contract) { $scope.totalAmount+=contract.amount; $scope.totalPayments+=contract.paid; $scope.totalRemain+=contract.remain; }); $scope.items = []; $scope.items.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'العقود' : 'Contracts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'عقود العام' : 'Contracts For Year'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.setSelected = function (object) { if (object) { angular.forEach($scope.contracts, function (contract) { if (object.id == contract.id) { $scope.selected = contract; return contract.isSelected = true; } else { return contract.isSelected = false; } }); } }; $scope.delete = function (contract) { if (contract) { $rootScope.showConfirmNotify("حذف البيانات", "هل تود حذف العقد وكل ما يتعلق به من حسابات فعلاً؟", "error", "fa-trash", function () { ContractService.remove(contract.id).then(function () { var index = $scope.contracts.indexOf(contract); $scope.contracts.splice(index, 1); $scope.setSelected($scope.contracts[0]); }); }); return; } $rootScope.showConfirmNotify("حذف البيانات", "هل تود حذف العقد وكل ما يتعلق به من حسابات فعلاً؟", "error", "fa-trash", function () { ContractService.remove($scope.selected.id).then(function () { var index = $scope.contracts.indexOf($scope.selected); $scope.contracts.splice(index, 1); $scope.setSelected($scope.contracts[0]); }); }); }; $scope.newContract = function () { ModalProvider.openContractCreateModel().result.then(function (data) { $scope.contracts.splice(0, 0, data); }, function () { console.info('ContractCreateModel Closed.'); }); }; $scope.newContractReceipt = function (contract) { ModalProvider.openReceiptCreateByContractModel(contract).result.then(function (data) { if (contract.contractReceipts) { return contract.contractReceipts.splice(0, 0, data); } }, function () { console.info('ContractReceiptCreateModel Closed.'); }); }; $scope.rowMenu = [ { html: '<div class="drop-menu">انشاء تاجر جديد<span class="fa fa-pencil fa-lg"></span></div>', enabled: function () { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_CREATE']); }, click: function ($itemScope, $event, value) { $scope.newContract(); } }, { html: '<div class="drop-menu">تعديل بيانات العقد<span class="fa fa-edit fa-lg"></span></div>', enabled: function () { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_UPDATE']); }, click: function ($itemScope, $event, value) { ModalProvider.openContractUpdateModel($itemScope.contract); } }, { html: '<div class="drop-menu">حذف العقد<span class="fa fa-trash fa-lg"></span></div>', enabled: function () { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_DELETE']); }, click: function ($itemScope, $event, value) { $scope.delete($itemScope.contract); } }, { html: '<div class="drop-menu">تسديد دفعة<span class="fa fa-money fa-lg"></span></div>', enabled: function ($itemScope) { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_RECEIPT_CREATE']); }, click: function ($itemScope, $event, value) { $scope.newContractReceipt($itemScope.contract); } }, { html: '<div class="drop-menu">فحص ملف<span class="fa fa-money fa-lg"></span></div>', enabled: function ($itemScope) { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_CREATE']); }, click: function ($itemScope, $event, value) { $scope.scanToJpg($itemScope.contract); } }, { html: '<div class="drop-menu">مرفق جديد<span class="fa fa-link fa-lg"></span></div>', enabled: function ($itemScope) { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_CREATE']); }, click: function ($itemScope, $event, value) { $scope.uploadFiles($itemScope.contract); } } ]; /*********************************** * * * START FILE UPLOADER * * * **********************************/ $scope.contractForUpload = {}; $scope.uploadFiles = function (contract) { $scope.contractForUpload = contract; document.getElementById('uploader').click(); }; $scope.initFiles = function (files) { $scope.wrappers = []; angular.forEach(files, function (file) { var wrapper = {}; wrapper.src = file; wrapper.name = file.name.substr(0, file.name.lastIndexOf('.')) || file.name; wrapper.mimeType = file.name.split('.').pop(); wrapper.size = file.size; $scope.wrappers.push(wrapper); }); var modalInstance = $uibModal.open({ animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body', templateUrl: '/ui/partials/contract/contractAttachUpload.html', controller: 'contractAttachUploadCtrl', scope: $scope, backdrop: 'static', keyboard: false }); modalInstance.result.then(function () { angular.forEach($scope.wrappers, function (wrapper) { ContractAttachService.upload($scope.contractForUpload, wrapper.name, wrapper.mimeType, wrapper.description, wrapper.src).then(function (data) { if ($scope.contractForUpload.contractAttaches) { return $scope.contractForUpload.contractAttaches.splice(0, 0, data); } }); }); }, function () { }); }; /*********************************** * * * END FILE UPLOADER * * * **********************************/ /*********************************** * * * START SCAN MANAGER * * * **********************************/ $scope.scanToJpg = function (contract) { $scope.contractForUpload = contract; scanner.scan(displayImagesOnPage, { "output_settings": [ { "type": "return-base64", "format": "jpg" } ] } ); }; function dataURItoBlob(dataURI) { // convert base64/URLEncoded data component to raw binary data held in a string var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]); else byteString = unescape(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], {type: mimeString}); } function displayImagesOnPage(successful, mesg, response) { var scannedImages = scanner.getScannedImages(response, true, false); // returns an array of ScannedImage var files = []; for (var i = 0; (scannedImages instanceof Array) && i < scannedImages.length; i++) { var blob = dataURItoBlob(scannedImages[i].src); var file = new File([blob], wrapper.name + '.jpg'); files.push(file); } $scope.initFiles(files); } /*********************************** * * * END SCAN MANAGER * * * **********************************/ /************************************************************** * * * Contract Receipt In * * * *************************************************************/ $scope.selectedIn = {}; $scope.contractReceiptsIn = []; $scope.itemsIn = []; $scope.itemsIn.push( {'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu'}, {'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts'} ); $scope.paramIn = {}; $scope.setSelectedIn = function (object) { if (object) { angular.forEach($scope.contractReceiptsIn, function (contractReceipt) { if (object.id == contractReceipt.id) { $scope.selectedIn = contractReceipt; return contractReceipt.isSelected = true; } else { return contractReceipt.isSelected = false; } }); } }; $scope.filterIn = function () { var search = []; if ($scope.paramIn.contractCodeFrom) { search.push('contractCodeFrom='); search.push($scope.paramIn.contractCodeFrom); search.push('&'); } if ($scope.paramIn.contractCodeTo) { search.push('contractCodeTo='); search.push($scope.paramIn.contractCodeTo); search.push('&'); } // if ($scope.paramIn.contractCustomerName) { search.push('contractCustomerName='); search.push($scope.paramIn.contractCustomerName); search.push('&'); } if ($scope.paramIn.contractCustomerMobile) { search.push('contractCustomerMobile='); search.push($scope.paramIn.contractCustomerMobile); search.push('&'); } if ($scope.paramIn.contractCustomerIdentityNumber) { search.push('contractCustomerIdentityNumber='); search.push($scope.paramIn.contractCustomerIdentityNumber); search.push('&'); } // if ($scope.paramIn.contractSupplierName) { search.push('contractSupplierName='); search.push($scope.paramIn.contractSupplierName); search.push('&'); } if ($scope.paramIn.contractSupplierMobile) { search.push('contractSupplierMobile='); search.push($scope.paramIn.contractSupplierMobile); search.push('&'); } if ($scope.paramIn.contractSupplierIdentityNumber) { search.push('contractSupplierIdentityNumber='); search.push($scope.paramIn.contractSupplierIdentityNumber); search.push('&'); } // if ($scope.paramIn.contractAmountFrom) { search.push('contractAmountFrom='); search.push($scope.paramIn.contractAmountFrom); search.push('&'); } if ($scope.paramIn.contractAmountTo) { search.push('contractAmountTo='); search.push($scope.paramIn.contractAmountTo); search.push('&'); } // if ($scope.paramIn.contractRegisterDateFrom) { search.push('contractRegisterDateFrom='); search.push($scope.paramIn.contractRegisterDateFrom.getTime()); search.push('&'); } if ($scope.paramIn.contractRegisterDateTo) { search.push('contractRegisterDateTo='); search.push($scope.paramIn.contractRegisterDateTo.getTime()); search.push('&'); } // // if ($scope.paramIn.receiptCodeFrom) { search.push('receiptCodeFrom='); search.push($scope.paramIn.receiptCodeFrom); search.push('&'); } if ($scope.paramIn.receiptCodeTo) { search.push('receiptCodeTo='); search.push($scope.paramIn.receiptCodeTo); search.push('&'); } // if ($scope.paramIn.receiptDateFrom) { search.push('receiptDateFrom='); search.push($scope.paramIn.receiptDateFrom.getTime()); search.push('&'); } if ($scope.paramIn.receiptDateTo) { search.push('receiptDateTo='); search.push($scope.paramIn.receiptDateTo.getTime()); search.push('&'); } // search.push('receiptType=In'); search.push('&'); // ContractReceiptService.filter(search.join("")).then(function (data) { $scope.contractReceiptsIn = data; $scope.setSelectedIn(data[0]); $scope.totalAmount = 0; angular.forEach(data, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); $scope.itemsIn = []; $scope.itemsIn.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'بحث مخصص' : 'Custom Filters'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findAllContractsReceiptsIn = function () { ContractReceiptService.findAllIn().then(function (data) { $scope.contractReceiptsIn = data; $scope.setSelectedIn(data[0]); $scope.totalAmount = 0; angular.forEach(data, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); $scope.itemsIn = []; $scope.itemsIn.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'كل الايرادات' : 'All Contract Incomes'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsReceiptsInByToday = function () { ContractReceiptService.findByTodayIn().then(function (data) { $scope.contractReceiptsIn = data; $scope.setSelectedIn(data[0]); $scope.totalAmount = 0; angular.forEach(data, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); $scope.itemsIn = []; $scope.itemsIn.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات اليوم' : 'Contract Incomes For Today'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsReceiptsInByWeek = function () { ContractReceiptService.findByWeekIn().then(function (data) { $scope.contractReceiptsIn = data; $scope.setSelectedIn(data[0]); $scope.totalAmount = 0; angular.forEach(data, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); $scope.itemsIn = []; $scope.itemsIn.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات الاسبوع' : 'Contract Incomes For Week'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsReceiptsInByMonth = function () { ContractReceiptService.findByMonthIn().then(function (data) { $scope.contractReceiptsIn = data; $scope.setSelectedIn(data[0]); $scope.totalAmount = 0; angular.forEach(data, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); $scope.itemsIn = []; $scope.itemsIn.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات الشهر' : 'Contract Incomes For Month'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.findContractsReceiptsInByYear = function () { ContractReceiptService.findByYearIn().then(function (data) { $scope.contractReceiptsIn = data; $scope.setSelectedIn(data[0]); $scope.totalAmount = 0; angular.forEach(data, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); $scope.itemsIn = []; $scope.itemsIn.push( { 'id': 1, 'type': 'link', 'name': $rootScope.lang === 'AR' ? 'البرامج' : 'Application', 'link': 'menu' }, { 'id': 2, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العقود' : 'Contract Receipts' }, {'id': 3, 'type': 'title', 'name': $rootScope.lang === 'AR' ? 'ايرادات العام' : 'Contract Incomes For Year'} ); $timeout(function () { window.componentHandler.upgradeAllRegistered(); }, 500); }); }; $scope.deleteIn = function (contractReceipt) { if (contractReceipt) { $rootScope.showConfirmNotify("حذف البيانات", "هل تود حذف السند وكل ما يتعلق به من حسابات فعلاً؟", "error", "fa-trash", function () { ContractReceiptService.remove(contractReceipt.id).then(function () { var index = $scope.contractReceiptsIn.indexOf(contractReceipt); $scope.contractReceiptsIn.splice(index, 1); $scope.setSelectedIn($scope.contractReceiptsIn[0]); $scope.totalAmount = 0; angular.forEach($scope.contractReceiptsIn, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); }); }); return; } $rootScope.showConfirmNotify("حذف البيانات", "هل تود حذف السند وكل ما يتعلق به من حسابات فعلاً؟", "error", "fa-trash", function () { ContractReceiptService.remove($scope.selectedIn.id).then(function () { var index = $scope.contractReceiptsIn.indexOf($scope.selectedIn); $scope.contractReceiptsIn.splice(index, 1); $scope.setSelectedIn($scope.contractReceiptsIn[0]); $scope.totalAmount = 0; angular.forEach($scope.contractReceiptsIn, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); }); }); }; $scope.newContractReceiptIn = function () { ModalProvider.openContractReceiptInCreateModel().result.then(function (data) { $scope.contractReceiptsIn.splice(0, 0, data); $scope.totalAmount = 0; angular.forEach($scope.contractReceiptsIn, function (contractReceipt) { $scope.totalAmount+=contractReceipt.receipt.amountNumber; }); }, function () { console.info('ContractReceiptCreateModel Closed.'); }); }; $scope.rowMenuIn = [ { html: '<div class="drop-menu">انشاء سند جديد<span class="fa fa-pencil fa-lg"></span></div>', enabled: function () { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_RECEIPT_IN_CREATE']); }, click: function ($itemScope, $event, value) { $scope.newContractReceiptIn(); } }, { html: '<div class="drop-menu">حذف السند<span class="fa fa-trash fa-lg"></span></div>', enabled: function () { return $rootScope.contains($rootScope.me.team.authorities, ['ROLE_CONTRACT_RECEIPT_IN_DELETE']); }, click: function ($itemScope, $event, value) { $scope.deleteIn($itemScope.contractReceipt); } } ]; $timeout(function () { $scope.findContractsByWeek(); $scope.findContractsReceiptsInByWeek(); window.componentHandler.upgradeAllRegistered(); }, 1500); }]);
$(document).ready(function(){ var history = []; var storedData = localStorage.getItem("history"); if (storedData){ history = JSON.parse(storedData); console.log("restored",history); retrieveHistory(history); var userInput = history[0]; console.log("userInput:",userInput); startSearch(userInput); }; function startSearch (userInput){ console.log("search started"); var APIKey = "9f7d706ef6d3f4a96f60c4354887012e"; var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + userInput + "&appid=" + APIKey; console.log(queryURL); $.ajax({ url: queryURL, method: "GET" }).then(function(response){ $.ajax({ url: queryURL, method: "GET" }); var tempFahrenheit = Math.round(((response.main.temp) - 273.15) * 1.80 + 32); console.log(tempFahrenheit) var windSpeed = response.wind.speed; console.log(windSpeed); var humidity = response.main.humidity; var windSpeed = response.wind.speed; var lat = response.coord.lat; var lon = response.coord.lon; console.log(lat, lon); var weatherIcon = response.weather[0].icon; console.log(weatherIcon); $("#cityName").html(`${response.name}`); $("#currentDay").html(moment().format('(MM/DD/YYYY)'));//refactoring later to make getting time from API $("#weatherIcon").empty().append(`<img src = "https://openweathermap.org/img/wn/${weatherIcon}@2x.png">`); $("#temperature").html(`Temperature: ${tempFahrenheit} &degF`); $("#humidity").html(`Humidity: ${humidity} %`); $("#windSpeed").html(`Wind Speed: ${windSpeed} MPH`); var queryURLuv = "https://api.openweathermap.org/data/2.5/uvi?appid=" + APIKey + "&lat=" + lat + "&lon=" + lon; $.ajax({ url: queryURLuv, method: "GET" }).then(function(response){ $.ajax({ url: queryURLuv, method: 'GET' }); var uvlIndex = response.value; $("#uvl-display").html(`UV Index: <span id="UV">${uvlIndex}</span>`); if (uvlIndex <=2){ console.log("UV green"); $("#UV").addClass("greenUV"); } else if (uvlIndex <=7){ console.log("UV orange"); $("#UV").addClass("orangeUV"); } else { console.log("UV red"); $("#UV").addClass("redUV"); }; }); var queryURLforecast = "https://api.openweathermap.org/data/2.5/forecast?q=" + userInput + "&appid=" + APIKey; $.ajax({ url: queryURLforecast, method: "GET" }).then(function(response){ $.ajax({ url: queryURLuv, method: 'GET' }); console.log("5days", response); // day 1st var tempFahrenheit1 = Math.round(((response.list[4].main.temp) - 273.15) * 1.80 + 32); console.log(tempFahrenheit1); var humidity1 = response.list[4].main.humidity; console.log(humidity1); var weatherIcon1 = response.list[4].weather[0].icon; console.log(weatherIcon1); var getdate1 = response.list[4].dt; console.log(getdate1); var newdate1 = new Date(getdate1*1000); var date1 = newdate1.getDate(); var year1 = newdate1.getFullYear(); var month1 = newdate1.getMonth()+1; console.log(month1, "/", date1, "/", year1); $("#day1").empty().append(`<div class="card text-white bg-primary fcard" style="max-width: 18rem;"> <div class="card-header date">${month1}/${date1}/${year1}</div> <div class="card-body"> <p class="card-text icon"><img src = "https://openweathermap.org/img/wn/${weatherIcon1}.png"></p> <p class="card-text temp">Temp: ${tempFahrenheit1} &degF</p> <p class="card-text hum">Humidity: ${humidity1} %</p> </div> </div>`); // day 2nd var tempFahrenheit2 = Math.round(((response.list[12].main.temp) - 273.15) * 1.80 + 32); console.log(tempFahrenheit2); var humidity2 = response.list[12].main.humidity; console.log(humidity2); var weatherIcon2 = response.list[12].weather[0].icon; console.log(weatherIcon2); var getdate2 = response.list[12].dt; console.log(getdate2); var newdate2 = new Date(getdate2*1000); var date2 = newdate2.getDate(); var year2 = newdate2.getFullYear(); var month2 = newdate2.getMonth()+1; console.log(month2, "/", date2, "/", year2); $("#day2").empty().append(`<div class="card text-white bg-primary fcard" style="max-width: 18rem;"> <div class="card-header date">${month2}/${date2}/${year2}</div> <div class="card-body"> <p class="card-text icon"><img src = "https://openweathermap.org/img/wn/${weatherIcon2}.png"></p> <p class="card-text temp">Temp: ${tempFahrenheit2} &degF</p> <p class="card-text hum">Humidity: ${humidity2} %</p> </div> </div>`); // day 3d var tempFahrenheit3 = Math.round(((response.list[20].main.temp) - 273.15) * 1.80 + 32); console.log(tempFahrenheit3); var humidity3 = response.list[20].main.humidity; console.log(humidity3); var weatherIcon3 = response.list[20].weather[0].icon; console.log(weatherIcon3); var getdate3 = response.list[20].dt; console.log(getdate3); var newdate3 = new Date(getdate3*1000); var date3 = newdate3.getDate(); var year3 = newdate3.getFullYear(); var month3 = newdate3.getMonth()+1; console.log(month3, "/", date3, "/", year3); $("#day3").empty().append(`<div class="card text-white bg-primary fcard" style="max-width: 18rem;"> <div class="card-header date">${month3}/${date3}/${year3}</div> <div class="card-body"> <p class="card-text icon"><img src = "https://openweathermap.org/img/wn/${weatherIcon3}.png"></p> <p class="card-text temp">Temp: ${tempFahrenheit3} &degF</p> <p class="card-text hum">Humidity: ${humidity3} %</p> </div> </div>`); // day 4s var tempFahrenheit4 = Math.round(((response.list[28].main.temp) - 273.15) * 1.80 + 32); console.log(tempFahrenheit4); var humidity4 = response.list[28].main.humidity; console.log(humidity4); var weatherIcon4 = response.list[28].weather[0].icon; console.log(weatherIcon4); var getdate4 = response.list[28].dt; console.log(getdate4); var newdate4 = new Date(getdate4*1000); var date4 = newdate4.getDate(); var year4 = newdate4.getFullYear(); var month4 = newdate4.getMonth()+1; console.log(month4, "/", date4, "/", year4); $("#day4").empty().append(`<div class="card text-white bg-primary fcard" style="max-width: 18rem;"> <div class="card-header date">${month4}/${date4}/${year4}</div> <div class="card-body"> <p class="card-text icon"><img src = "https://openweathermap.org/img/wn/${weatherIcon4}.png"></p> <p class="card-text temp">Temp: ${tempFahrenheit4} &degF</p> <p class="card-text hum">Humidity: ${humidity4} %</p> </div> </div>`); // day 5s var tempFahrenheit5 = Math.round(((response.list[36].main.temp) - 273.15) * 1.80 + 32); console.log(tempFahrenheit5); var humidity5 = response.list[36].main.humidity; console.log(humidity5); var weatherIcon5 = response.list[36].weather[0].icon; console.log(weatherIcon5); var getdate5 = response.list[36].dt; console.log(getdate5); var newdate5 = new Date(getdate5*1000); var date5 = newdate5.getDate(); var year5 = newdate5.getFullYear(); var month5 = newdate5.getMonth()+1; console.log(month5, "/", date5, "/", year5); $("#day5").empty().append(`<div class="card text-white bg-primary fcard" style="max-width: 18rem;"> <div class="card-header date">${month5}/${date5}/${year5}</div> <div class="card-body"> <p class="card-text icon"><img src = "https://openweathermap.org/img/wn/${weatherIcon5}.png"></p> <p class="card-text temp">Temp: ${tempFahrenheit5} &degF</p> <p class="card-text hum">Humidity: ${humidity5} %</p> </div> </div>`); }); }); }; function retrieveHistory (history){ history.forEach(element => $("#searchHistory").prepend(`<tr><th class="cityInHistory" scope="row">${element}</th></tr>`) ); }; var addToHistory = function(userInput){ if (userInput!=0 && history.length <10){ $("#searchHistory").prepend(`<tr><th class="cityInHistory" scope="row">${userInput}</th></tr>`) history.push(userInput); console.log(history); localStorage.setItem("history", JSON.stringify(history)); // code in process // } else { // $("#searchHistory").html(`<tr><th class="cityInHistory" scope="row">${userInput}</th></tr>`) }; }; function cleaningInputgroup(){ var cleanInputgroup = $( `<input type="text" class="form-control" placeholder="City" id="cityInput"> <div class="input-group-append"> <button type="submit" class="btn btn-primary" id="searchBtn"><i class="fas fa-search"></i></button> </div>` ); $(".input-group").html(cleanInputgroup); }; $(document).on("click",".btn", function(){ event.preventDefault(); var userInput = $("#cityInput").val(); console.log(userInput); startSearch(userInput); addToHistory(userInput); cleaningInputgroup() }); $(document).on('click','.cityInHistory', function(){ console.log("TH BEEN HITED"); var userInput = $(this).text(); console.log(userInput); startSearch(userInput); }); });
angular.module('eatery').controller('donateCtrl', [ '$scope', '$http', function($scope, $http){ $scope.data = ''; function getFoodbanks(){ $http.get('/api/foodbanks') .then( function(data){ $scope.data = data.data; }, function(errData){ alert(JSON.stringify(errData.data)); } ); } getFoodbanks(); }]);
var cfg = require("../../utils/cfg.js"); var app = getApp(); Page({ data:{ money:'' }, onLoad: function () { var that=this wx.setNavigationBarTitle({ title: app.language('validator.widthdrawcashtitle') }); wx.getStorage({ key: 'langIndex', success: function(res) { that.setData({ langIndex: res.data }) } }); this.setLang(); wx.getStorage({ key: 'integral', success: function(res) { that.setData({ integral: res.data }) } }); }, setLang() { const set = wx.T._ this.setData({ widthdraw_cash: set('widthdraw_cash'), }) }, bindIntegralName:function(e){ this.setData({ points:e.detail.value, money:(e.detail.value)/100 }); console.log(e.detail.value) console.log(this.data.integral) if(this.data.integral<e.detail.value){ this.setData({ points:this.data.integral, money:(this.data.integral)/100 }); } }, realnme_auth: function (e) { var integralreg = /^[1-9]+[0-9]*]*$/; if (e.detail.value.alipayname === '') { wx.showToast({ title: app.language('validator.alipaynamenot'), icon: "none", duration: 1000 }); } else if (e.detail.value.alipayaccount === '') { wx.showToast({ title: app.language('validator.alipayaccountnot'), icon: "none", duration: 1000 }); } else if (e.detail.value.points === '') { wx.showToast({ title: app.language('validator.integralnot'), icon: "none", duration: 1000 }); } else if (this.data.integral < e.detail.value.points) { wx.showToast({ title: app.language('validator.integralnotenough'), icon: "none", duration: 1000 }); } else if (!integralreg.test(e.detail.value.points)) { wx.showToast({ title: app.language('validator.integralnumber'), icon: "none", duration: 1000 }); } else if ((e.detail.value.points) % 100 !== 0) { if(this.data.integral<e.detail.value.points){ this.setData({ points:this.data.integral, }); if((e.detail.value.points) % 100 !== 0){ wx.showToast({ title: app.language('validator.integralmultiple'), icon: "none", duration: 1000 }); } }else{ wx.showToast({ title: app.language('validator.integralmultiple'), icon: "none", duration: 1000 }); } } else { wx.request({ url: cfg.getAPIURL() + '/api/user/balance/withdraw', method: 'POST', data:{ account:e.detail.value.alipayaccount, name:e.detail.value.alipayname, points:Number(e.detail.value.points) }, header: app.globalData.header, success: function(response) { console.log(response) if(response.data.code===0){ wx.showToast({ title:response.data.message, icon:'none', duration:1000 }); wx.navigateTo({ url:'/pages/usermoney/index' }) }else{ wx.showToast({ title:response.data.message, icon:'none', duration:1000 }) } }, fail: function(response) { wx.showToast({ title: response.data.message, }) } }) } }, });
var isMAC = /Mac OS/.test(navigator.userAgent), oModifierKeys = { sCtrlKeyLabel: isMAC ? "Cmd" : "Ctrl", sAltKeyLabel: isMAC ? "Opt" : "Alt", sShiftKeyLabel: "Shift" }, aSavedShortcuts = [], oOptionsSaveButton = null, oOptionsResetButton = null, oShortcutsSaveButton = null, oShortcutsResetButton = null; function init() { for (var a = 0, b = 0, c = 0, g = null, d = null, e = null, f = document.getElementsByTagName("nav")[0].getElementsByTagName("li"), h = document.getElementsByTagName("section"), a = 0, c = f.length; a < c; a++)f[a].onclick = function () { b = 0; for (c = f.length; b < c; b++)f[b].className = ""; for (b = 0; g = h[b]; b++)g.className = ""; this.className = "current"; getElem("box-" + this.id).className = "current" }; oOptionsSaveButton = getElem("accessibility-save-button"); oOptionsResetButton = getElem("accessibility-reset-button"); oShortcutsSaveButton = getElem("shortcuts-save-button"); oShortcutsResetButton = getElem("shortcuts-reset-button"); oOptionsSaveButton.addEventListener("click", saveOptions, !1); oOptionsResetButton.addEventListener("click", resetOptions, !1); oShortcutsSaveButton.addEventListener("click", saveShortcuts, !1); oShortcutsResetButton.addEventListener("click", resetShortcuts, !1); e = getElem("box-options").getElementsByTagName("input"); for (a = 0; d = e[a]; a++)d.addEventListener("input", optionChanged, !1), d.addEventListener("change", optionChanged, !1); e = getElem("box-keyboard-shortcuts").getElementsByTagName("input"); for (a = 0; d = e[a]; a++)d.addEventListener("keydown", filterKey, !1); retrieveOptions(); retrieveShortcuts() } function optionChanged() { oOptionsSaveButton.disabled = !1; oOptionsResetButton.disabled = !1 } function filterKey(a) { var b = [], c = a.keyIdentifier; isMAC && a.metaKey && b.push(oModifierKeys.sCtrlKeyLabel); !isMAC && a.ctrlKey && b.push(oModifierKeys.sCtrlKeyLabel); a.altKey && b.push(oModifierKeys.sAltKeyLabel); a.shiftKey && b.push(oModifierKeys.sShiftKeyLabel); if (c !== "U+0009") this.className = "", (a.which > 96 && a.which < 123 || a.which > 64 && a.which < 91) && c.substring(0, 2) === "U+" ? b.push(String.fromCharCode(a.which).toUpperCase()) : c === "Alt" || c === "Meta" || c === "Control" || c === "Shift" ? (b.push(""), this.className = "invalid") : c.substring(0, 2) !== "U+" && b.push(c), aSavedShortcuts[this.id] = { ctrl: isMAC ? a.metaKey : a.ctrlKey, alt: a.altKey, shift: a.shiftKey, code: a.keyCode, identifier: a.keyIdentifier }, this.value = b.join("-"), a.preventDefault(); oShortcutsSaveButton.disabled = !1; oShortcutsResetButton.disabled = !1 } function saveOptions() { var a = { url_validate_html: getElem("validate-html").value, url_validate_css: getElem("validate-css").value, url_validate_links: getElem("validate-links").value, url_validate_feed: getElem("validate-feed").value, url_validate_accessibility: getElem("validate-accessibility").value, mode_validate_local_html: { show_source: getElem("show-source").checked, show_outline: getElem("show-outline").checked, verbose_output: getElem("verbose-output").checked }, mode_validate_local_css: getElem("css2").checked ? "css2" : "css3" }; window.localStorage.options = JSON.stringify(a); var b = getElem("accessibility-save-status"); b.style.setProperty("-webkit-transition", "opacity 0s ease-in"); b.style.opacity = 1; setTimeout(function () { b.style.setProperty("-webkit-transition", "opacity 1s ease-in"); b.style.opacity = 0 }, 1E3); oOptionsSaveButton.disabled = !0; oOptionsResetButton.disabled = !0 } function resetOptions() { retrieveOptions() } function saveShortcuts() { var a = null, b = !1; oInputs = getElem("box-keyboard-shortcuts").getElementsByTagName("input"); for (var c = 0; oInput = oInputs[c]; c++)if (oInput.className === "invalid") a = getElem("invalid-shortcut-" + oInput.id), a.style.setProperty("-webkit-transition", "opacity 0s ease-in"), a.style.opacity = 1, b = !0; b ? setTimeout(function () { for (c = 0; oInput = oInputs[c]; c++)a = getElem("invalid-shortcut-" + oInput.id), a.style.setProperty("-webkit-transition", "opacity 1s ease-in"), a.style.opacity = 0 }, 1E3) : (window.localStorage.shortcuts = JSON.stringify({ view_all_styles: aSavedShortcuts["view-all-styles"], reload_css: aSavedShortcuts["reload-css"], disable_all_styles: aSavedShortcuts["disable-all-styles"], view_javascript: aSavedShortcuts["view-javascript"], view_generated_source: aSavedShortcuts["view-generated-source"], display_ruler: aSavedShortcuts["display-ruler"], display_color_picker: aSavedShortcuts["display-color-picker"] }), a = getElem("shortcuts-save-status"), a.style.setProperty("-webkit-transition", "opacity 0s ease-in"), a.style.opacity = 1, setTimeout(function () { a.style.setProperty("-webkit-transition", "opacity 1s ease-in"); a.style.opacity = 0 }, 1E3), oShortcutsSaveButton.disabled = !0, oShortcutsResetButton.disabled = !0) } function resetShortcuts() { for (var a = getElem("box-keyboard-shortcuts").getElementsByTagName("input"), b = 0, c; c = a[b]; b++)c.className = ""; retrieveShortcuts() } function retrieveOptions() { oOptionsSaveButton.disabled = !0; oOptionsResetButton.disabled = !0; if (!window.localStorage.options || !JSON.parse(window.localStorage.options).url_validate_html) { var a = getDefaultOptions(); window.localStorage.options = JSON.stringify(a) } a = JSON.parse(window.localStorage.options); getElem("validate-html").value = a.url_validate_html; getElem("validate-css").value = a.url_validate_css; getElem("validate-links").value = a.url_validate_links; getElem("validate-feed").value = a.url_validate_feed; getElem("validate-accessibility").value = a.url_validate_accessibility; getElem("show-source").checked = a.mode_validate_local_html.show_source; getElem("show-outline").checked = a.mode_validate_local_html.show_outline; getElem("verbose-output").checked = a.mode_validate_local_html.verbose_output; getElem(a.mode_validate_local_css).checked = !0 } function retrieveShortcuts() { oShortcutsSaveButton.disabled = !0; oShortcutsResetButton.disabled = !0; if (!window.localStorage.shortcuts) { var a = getDefaultShortcuts(); window.localStorage.shortcuts = JSON.stringify(a) } a = JSON.parse(window.localStorage.shortcuts); getElem("view-all-styles").value = getHumanReadableShortcut(a.view_all_styles); getElem("reload-css").value = getHumanReadableShortcut(a.reload_css); getElem("disable-all-styles").value = getHumanReadableShortcut(a.disable_all_styles); getElem("view-javascript").value = getHumanReadableShortcut(a.view_javascript); getElem("view-generated-source").value = getHumanReadableShortcut(a.view_generated_source); getElem("display-ruler").value = getHumanReadableShortcut(a.display_ruler); getElem("display-color-picker").value = getHumanReadableShortcut(a.display_color_picker); aSavedShortcuts["view-all-styles"] = a.view_all_styles; aSavedShortcuts["reload-css"] = a.reload_css; aSavedShortcuts["disable-all-styles"] = a.disable_all_styles; aSavedShortcuts["view-javascript"] = a.view_javascript; aSavedShortcuts["view-generated-source"] = a.view_generated_source; aSavedShortcuts["display-ruler"] = a.display_ruler; aSavedShortcuts["display-color-picker"] = a.display_color_picker } function getHumanReadableShortcut(a) { var b = []; a.ctrl && b.push(oModifierKeys.sCtrlKeyLabel); a.alt && b.push(oModifierKeys.sAltKeyLabel); a.shift && b.push(oModifierKeys.sShiftKeyLabel); a.identifier.substring(0, 2) === "U+" ? b.push(String.fromCharCode(a.code).toUpperCase()) : b.push(a.identifier); return b.join("-") } function getDefaultOptions() { return { url_validate_html: "http://validator.w3.org/check?verbose=1&uri=", url_validate_css: "http://jigsaw.w3.org/css-validator/validator?profile=css21&uri=", url_validate_links: "http://validator.w3.org/checklink?check=Check&hide_type=all&summary=on&uri=", url_validate_links: "http://validator.w3.org/checklink?uri=", url_validate_feed: "http://validator.w3.org/feed/check.cgi?url=", url_validate_accessibility: "http://wave.webaim.org/report#/", url_validate_accessibility: "http://achecker.ca/checkacc.php?id=2f4149673d93b7f37eb27506905f19d63fbdfe2d&guide=WCAG2-L2&output=html&uri=", mode_validate_local_html: { show_source: !0, show_outline: !1, verbose_output: !0 }, mode_validate_local_css: "css2" } } function getDefaultShortcuts() { return { view_all_styles: {ctrl: !1, alt: !1, shift: !1, code: 113, identifier: "F2"}, reload_css: {ctrl: !1, alt: !1, shift: !1, code: 120, identifier: "F9"}, disable_all_styles: {ctrl: !0, alt: !1, shift: !0, code: 83, identifier: "U+0053"}, view_javascript: {ctrl: !1, alt: !1, shift: !1, code: 115, identifier: "F4"}, view_generated_source: {ctrl: !0, alt: !1, shift: !0, code: 85, identifier: "U+0055"}, display_ruler: {ctrl: !1, alt: !1, shift: !1, code: 118, identifier: "F7"}, display_color_picker: { ctrl: !1, alt: !1, shift: !1, code: 119, identifier: "F8" } } } function getElem(a) { return document.getElementById(a) } function i18n() { var $key = arguments[0]; var msg = chrome.i18n.getMessage($key); if (arguments.length > 1) { } for (var i = 1; i < arguments.length; i++) { msg = msg.replace("%" + i, arguments[i]); } return msg; } $(function(){ var newBody = Mustache.to_html($('body').html(), chrome.i18n.getMessage); $('body').html($(newBody)); init(); });
import React, { Component } from "react"; import { connect } from 'react-redux'; import _ from 'lodash'; import "./index.css"; class Chat extends Component { render() { const { streaming } = this.props; const channel = streaming.substring(streaming.lastIndexOf('=') + 1); return ( <iframe frameborder="0" scrolling="no" id="chat_embed" src={`https://www.twitch.tv/embed/${channel}/chat?parent=${window.location.hostname}&te-theme=dark&darkpopout`} height="500" width="100%"> </iframe> ); } } function mapStateToProps(state){ return { profile : state.profile, ln: state.language }; } export default connect(mapStateToProps)(Chat);
var express = require('express'); var app = express(); var router = express.Router(); var discipline = require('../models/discipline'); var media = require('../models/media'); var course = require('../models/course'); var date = require('../custom_modules/date').timezone(-180); var utils = require('../custom_modules/utils'); var session = require('express-session'); var path = require('path'); //var fileUpload = require('express-fileupload'); var multer = require("multer"); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './public/uploads') }, filename: function (req, file, cb) { console.log(file); var file_name = path.basename(file.originalname, path.extname(file.originalname)); cb(null, utils.removeaccents(file_name, "-", true)+'-'+Date.now()+path.extname(file.originalname)); } }); var upload = multer({ storage: storage }); var bodyParser = require("body-parser"); router.use(session({ /* genid: function(req) { return expiryDate; // use UUIDs for session IDs },*/ secret: 'integro', resave: false, saveUninitialized: true, cookie: {maxAge: null, secure: false} })); //router.use(fileUpload()); router.use(bodyParser.json()); router.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); router.get('/', function (req, res, next) { var data = {}; res.render('sys/media', data); }); router.get('/list', function (req, res, next) { res.render('sys/listmedia'); }); router.get('/create', function (req, res, next){ res.render('sys/forms/media'); }); router.get('/find/:id', function (req, res, next){ var id = req.params.id; media.where({ id : id }).fetch().then(function(mediadata){ var jdata = mediadata.toJSON(); res.json(jdata); }); }); router.post('/save', function (req, res, next){ var m = new media({ id: req.body.id, user_id: req.body.user_id, title: req.body.title, url: req.body.url, details: req.body.details, metatitle: req.body.title, /*format: file.format, size: file.size,*/ timecreated: Date.now() }); /* console.log(m); */ m.save() .then(function(model){/* console.log('saved'); console.log(model); */ res.status(200); }); }); router.get('/inputfile', function(req, res) { res.render('sys/uploader'); }); router.post('/upload', upload.array('file_up', 5), function(req, res) { console.log(req.files); var data = { files : [] }; for(var c = 0; c < req.files.length; c++){ data.files[c] = {}; data.files[c].path = req.files[c].path; } res.json(data); }); router.delete('/delete', function (req, res){ new media({ id: req.query.id }).destroy().then(function(model){ return res.status(200); }); }); /* JSON */ router.get('/bycourse/:courseid', function (req, res, next) { course.where({id: req.params.courseid }).fetch({withRelated: ['disciplines.media.user', 'disciplines.media.categories']}) .then(function (coursedata) { var data = coursedata.toJSON(); data.user = req.session.access.user; for(var c = 0; c < data.disciplines.length; c++){ for(var x = 0; x < data.disciplines[c].media.length; x++){ data.disciplines[c].media[x].timecreated = date('(%a) :: %d de %B, %Hh:%Mm', new Date(data.disciplines[c].media[x].timecreated)); data.disciplines[c].categories = data.disciplines[c].categories; } } res.json(data); }); }); /* * ng click bind */ router.get('/bind/:id', function (req, res, next){ bind.forge({ user_id : req.session.access.user.id, instance_id : req.params.id, instance_type : 'media' }) .save() .then(success => res.status(200).send(success)) .catch(error => res.status(500).send(error.message)); }); /* * ng json query */ router.get('/search/:search', function (req, res, next) { media.query(function (qb) { qb.where('title', 'LIKE', '%' + req.params.search + '%') .orWhere('details', 'LIKE', '%' + req.params.search + '%') .orWhere('details', 'LIKE', '%' + req.params.search + '%') .orWhere('url', 'LIKE', '%' + req.params.search + '%'); }).fetchAll().then(function (mediadata) { res.json(mediadata.toJSON()); }); }); /* */ router.get('/edit/:id', function (req, res, next){ var id = req.params.id; media.where({ id : id }).fetch().then(function(mediadata){ var jdata = mediadata.toJSON(); return res.json(jdata); }); }); router.get('/home/redirected/:why', function (req, res, next) { var data = {}; res.render('index', data); }); module.exports = router;
import React from "react"; import axios from "axios"; import moment from "moment" export const GetSymInfo = (symList, nodejs) => { //axios making the request to the Server API send the stock code // it can be request more then on stock code, must be separeted by comma. return axios.get(nodejs + "/info/" + symList).then((data) => { data = data.data.quoteResponse.result; var list = data.map((item) => { let earnDate = "N/A"; //checking if there is a earning date for the specific stoc if(item.earningsTimestamp !== undefined) //formating into readeble data earnDate = moment(new Date(item.earningsTimestamp*1000)).format('ll') //checking if there is display name, if not display longName let name = item.displayName; if (name === undefined) name = item.longName; // formating the information in JSON Obejct let str = '{"name":"'+name+ // name of the stock '","price":'+item.regularMarketPrice.toFixed(2)+ // price of the stock | to fixed is a function to convert to 2 decimal ',"percent":"'+item.regularMarketChangePercent.toFixed(2)+ // change percentage '","sym":"'+item.symbol+'","change":"'+item.regularMarketChange.toFixed(2)+ // symbol and price change '","open":"'+item.regularMarketOpen+ // stock open price '","prevClose":"'+item.regularMarketPreviousClose+ // stock previous close '","exchangeOpen":"'+item.triggerable+ '","eps":"'+item.epsCurrentYear+ // eps value '","sharesOutstanding":"'+item.sharesOutstanding+ // shares outstanding '","marketCap":"'+item.marketCap+ // market cap '","earningsTimestamp":"'+earnDate+ //earning date '","marketState":"'+item.marketState+ //earning date '"}'; str = JSON.parse(str) //returning the json object return str; }) //returning the list return list; }) }
var width = 960, height = 600; var mapPath = "/cmdoptesc/raw/4714c586f69425043ae3/us.json"; var projection = d4.geoAlbersUsa() .scale(1280) .translate([width / 2, height / 2]); var path = d4.geoPath() .projection(projection); var svg, dataset; var policyCircleScale, stateCircleScale; stateCircleScale = d4.scaleLinear().range([5, 30]); d3.json("./data/us.json", function(error, us) { if (error) return console.error(error); svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); svg.append("path") .datum(topojson.feature(us, us.objects.land)) .attr("d", path) .attr("class", "land-boundary"); svg.append("path") .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; })) .attr("d", path) .attr("class", "state-boundary"); d3.csv("./data/policy_adoptions.csv") .row(function(d) { return { policy: d.policy_id, lat: parseFloat(d.lat), lng: parseFloat(d.long), state: d.state, state_name: d.state_name, value: d.adoption_case, adopted_year: new Date(d.adopted_year) }; }) .get(function(err, rows) { if (err) return console.error(err); dataset = rows; }); var displaySites = function(data) { //*** Calculate # of cumulative adoption cases for each policy // Output: array of adoption object itself... // # of adoption case will be the size of policy circle data.map(function(adoption){ var adopted_cases; // radius of policy circle adopted_cases = data.filter(function(d){ return (d.policy === adoption.policy) && (d.adopted_year < adoption.adopted_year); }); return Object.assign(adoption, { "value": adopted_cases.length+1 }); }); //*** Rescale the size of policy circle var policyCircleMin, policyCircleMax; // if(data.length <= 1000){ policyCircleMax = 10 } // else if(data.length <= 1000){ policyCircleMax = 4 - data.length/400 } // else if(data.length <= 5000){ policyCircleMax = 2 - data.length/2500 } // else { policyCircleMax = 1 } policyCircleMax = 4; policyCircleMin = policyCircleMax/3; policyCircleScale = d4.scaleLinear().range([policyCircleMin, policyCircleMax]); policyCircleScale.domain(d4.extent(data.map(function(d){ return d.value; }))); // Reassign the scaled policy circle size data.map(function(adoption){ return Object.assign(adoption, { "value": policyCircleScale(adoption.value) }); }) //*** Change the data structure grouped by state /* [ ... { state: 'WA', lat: 140.64, lng: 46.57, permalink: abc-def, adoptions: [ ... { }, ... ] } ... ] */ var dataGroupByState = _.groupBy(data, 'state'); dataGroupByState = Object.keys(dataGroupByState).map(function(state){ var state_obj = {}; var lat = dataGroupByState[state][0].lat, lng = dataGroupByState[state][0].lng, permalink = dataGroupByState[state][0].permalink, adoptions = dataGroupByState[state]; //*** Filter out some policy circles that have lower score than the threshold var maxScore = d3.max(adoptions, function(d){ return d.adopted_cases; }); // Filter out // adoptions.filter(function(d) { // return d.adopted_cases > (maxScore / 1.5); // }); if (adoptions.length > 20){ adoptions = adoptions.sort(function(a, b){ return d3.descending(a.adopted_cases, b.adopted_cases); }).slice(0, 19); } state_obj = { 'name': state, 'lat': lat, 'lng': lng, 'children': adoptions }; return state_obj; }); var states, stateCircles; // Define each state as root // Convert each state key to an object with functions and properties for hierarchical structure states = dataGroupByState.map(function (state){ return d4.hierarchy(state) .sum(function(d){ return d.value; }).sort(function(a, b){ return b.value - a.value; }); }); stateCircleScale.domain(d4.extent(states.map(function(d){ return d.value; }))); // Hook the dataset with objects svg.selectAll(".g_state") .data(states) .enter().append("g") .attr("class", function(d){ return "g_state g_state_" + d.data.name; }) .attr("transform", function(d){ return "translate(" + (projection([d.data.lng, d.data.lat])[0]) + "," + (projection([d.data.lng, d.data.lat])[1]) + ")" }); //*** Update circles with updated data states.forEach(function(state){ // Get an array of all nodes from the state data var pack, root_size, g_state, nodes, circles, innerCircleRadius; root_size = state.value, // Update the size of root circle according to the summed value pack = d4.pack().size([root_size, root_size]).padding(2), g_state = svg.selectAll(".g_state_" + state.data.name) // .attr("transform", function(d){ // return "translate(" + // (projection([d.data.lng, d.data.lat])[0]-d.value*3) + "," + (projection([d.data.lng, d.data.lat])[1]-d.value*3) + ")" // }), root_node = pack(state), nodes = root_node.descendants(), circles = g_state.selectAll(".circle") .data(nodes); circles.style("fill", "white"); // state.x = projection([state.data.lng, state.data.lat])[0]; // state.y = projection([state.data.lng, state.data.lat])[1]; // Set the state circles to the fixed coordinate with summed radius // circles.enter() // .append("circle") // .attr("class", function(d) { return d.parent ? ("circle circle_policy circle_policy_" + d.parent.data.name) // : ("circle circle_state circle_state_" + d.data.name); // }) // .style("fill", "red") // .style("stroke", "black") // .transition().delay(400) // .attr("r", function(d){ // if (d3.select(this).attr("class") === "circle circle_state circle_state_" + d.data.name) { // innerCircleRadius = d.r; // } // //console.log(d3.select(this).attr("class"), innerCircleRadius, d.r); // return d.r; // }) // .attr("cx", function(d){ // if (d3.select(this).attr("class") === "circle circle_state circle_state_" + d.data.name) // return d.x - innerCircleRadius; // return d.x - innerCircleRadius; // }) // .attr("cy", function(d){ // if (d3.select(this).attr("class") === "circle circle_state circle_state_" + d.data.name) // return d.y - innerCircleRadius; // return d.y - innerCircleRadius; // }); // //console.log(d3.select(".circle_state_" + state.data.name), state.data.children.length, innerCircleRadius); // circles.transition().duration(400) // .attr("r", function(d){ // if (d3.select(this).attr("class") === "circle circle_state circle_state_" + d.data.name) { // //console.log(d3.select(this).attr("class"), innerCircleRadius, d.r); // innerCircleRadius = d.r; // } // return d.r; // }) // .attr("cx", function(d){ // if (d3.select(this).attr("class") === "circle circle_state circle_state_" + d.data.name) // return d.x - innerCircleRadius; // return d.x - innerCircleRadius; // }) // .attr("cy", function(d){ // if (d3.select(this).attr("class") === "circle circle_state circle_state_" + d.data.name) // return d.y - innerCircleRadius; // return d.y - innerCircleRadius; // }); // circles.exit() // .attr("r", function(d){ // return 0; // }) // .transition().duration(200) // .remove(); }); //*** Control outer circles states.forEach(function(d){ d.x = projection([d.data.lng, d.data.lat])[0]; d.y = projection([d.data.lng, d.data.lat])[1]; }) stateCircles = svg.selectAll(".outer_circle_state") .data(states); stateCircles.enter().append("circle") .attr("class", function(d){ return "outer_circle_state outer_circle_state_" + d.data.name; }) // .attr("transform", function(d){ // return "translate(" + // (projection([d.data.lng, d.data.lat])[0]-d.value) + "," + (projection([d.data.lng, d.data.lat])[1]-d.value) + ")" // }) .transition().delay(400) // .attr("cx", function(d){ // return projection([d.data.lng, d.data.lat])[0]; // }) // .attr("cy", function(d){ // return projection([d.data.lng, d.data.lat])[1]; // }) .attr("r", function(d){ //console.log(d.x, d.y); return d.r + 3; }) .style("fill", "none") .style("stroke", "black"); stateCircles .transition().duration(300) // .attr("cx", function(d){ // return projection([d.data.lng, d.data.lat])[0]; // }) // .attr("cy", function(d){ // return projection([d.data.lng, d.data.lat])[1]; // }) .attr("r", function(d){ return d.r + 3; }) .style("fill", "none") .style("stroke", "black"); stateCircles.exit() // .attr("cx", function(d){ // return projection([d.data.lng, d.data.lat])[0]; // }) // .attr("cy", function(d){ // return projection([d.data.lng, d.data.lat])[1]; // }) .attr("r", function(d){ return 0; }) .remove(); //stateCircles.forEach(function(circle, index, wholeCircles){ console.log(collide(circle, wholeCircles)); }); //force().gravity(3.0).size([800,600]).charge(-1).nodes(forceNodes); var simulation = d4.forceSimulation(states) // .force("gravity", d4.forceManyBody(30).distanceMin(2)) // .force('charge', d4.forceManyBody().strength(0)) //.size([800,600]) //.charge(-1).nodes(states) //.velocityDecay(1) //.force('charge', d4.forceManyBody().strength(-10)) // .force("forceX", d4.forceX().strength(.1).x(100 * .5)) // .force("forceY", d4.forceY().strength(.1).y(100 * .5)) .force('collision', d4.forceCollide().strength(1).iterations(12) // strength should be closer to 1 .radius(function(d) { return d.r*1.05; })) .on("tick", tick); function tick (){ stateCircles .attr("cx", function(d){ return d.x; }) .attr("cy", function(d){ return d.y; }) // .attr( // "transform", // function(d) { return "translate(" + d.x + "," + d.y + ")"; } // ) } }; var minDateUnix = new Date('1800-01-01').getYear() + 1900; var maxDateUnix = new Date('2017-12-31').getYear() + 1900; var step = 60*60*24; d3.select('#slider3').call(d3.slider() .axis(true).min(minDateUnix).max(maxDateUnix) .on("slide", function(evt, value) { var newValue = value; d3.select("#current_year").transition() .tween("text", function(d) { var self = this; var i = d3.interpolateRound(Math.floor(d3.select(this).text()), Math.floor(newValue)); return function(t) { d3.select(this).text(i(t)); }; }); var newData = _(dataset).filter( function(site) { //console.log("current silder time:", site.created_at, value); var adopted_year = site.adopted_year.getYear() + 1900; return adopted_year < value; }) // console.log("New set size ", newData.length); displaySites(newData); }) ); // svg // .style("background", color(-1)) // .on("click", function() { zoom(root); }); // zoomTo([width / 2, height / 2, root.r * 2 + margin]); }); function zoom(d) { var focus0 = focus; focus = d; var transition = d3.transition() .duration(d3.event.altKey ? 7500 : 750) .tween("zoom", function(d) { var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]); return function(t) { zoomTo(i(t)); }; }); transition.selectAll("text") .filter(function(d) { return d.parent === focus || this.style.display === "inline"; }) .style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; }) .on("start", function(d) { if (d.parent === focus) this.style.display = "inline"; }) .on("end", function(d) { if (d.parent !== focus) this.style.display = "none"; }); } function zoomTo(v) { var diameter = height, k = diameter / v[2], view = v; node.attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; }); circle.attr("r", function(d) { return d.r * k; }); }
import React from 'react' const MessageForm = ({onSendMessage,onChange,message,placeholder})=> { return ( <form onSubmit={onSendMessage} className="send-message-form"> <input onChange={onChange} value={message} placeholder={placeholder} type="text" /> </form> ) } export default MessageForm
import React, { useState, useContext } from "react"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import { makeStyles } from "@material-ui/core/styles"; import axios from "axios"; import { Redirect } from "react-router-dom"; import UserContext from "../Contexts/UserContext"; const useStyles = makeStyles(theme => ({ root: { width: 300 } })); const FormRegister = () => { // STYLE : const classes = useStyles(); // Use of the context. const { setUser, setIsLogged, isLogged} = useContext( UserContext ); const [error, hasError] = useState(false); const [errorMessage, setNewMessageError] = useState(); const [pseudonyme, setPseudonyme] = useState(); const [password, setPassword] = useState(); const [confirmationPassword, setConfirmationPassword] = useState(); const [name, setName] = useState(); const [firstname, setFirstname] = useState(); const [email, setEmail] = useState(); const handleInputNameChange = event => { setName(event.target.value); }; const handleInputFirstnameChange = event => { setFirstname(event.target.value); }; const handleInputPseudonymeChange = event => { setPseudonyme(event.target.value); }; const handleInputPasswordChange = event => { setPassword(event.target.value); }; const handleInputConfirmationPasswordChange = event => { setConfirmationPassword(event.target.value); }; const handleBlurForm = (event) => { if (password !== confirmationPassword) { hasError(true); setNewMessageError("you must enter the same password"); } } const handleInputEmailChange = event => { setEmail(event.target.value); }; const handleChangeForm = (event) => { hasError(false) } const handleSubmit = event => { event.preventDefault(); hasError(false); const userData = { pseudonyme, password, email, name, firstname }; if (!error) { axios .post("/users/register", userData) .then(response => { hasError(response.data.error); setNewMessageError(response.data.errorMessage); setUser(response.data.userData) setIsLogged(response.data.isLogged); }) .catch(err => { console.error(err); }); } }; return ( <> {isLogged && ( <> <Redirect to={"/profil"} /> </> )} <form onSubmit={handleSubmit} onChange={handleChangeForm} className={classes.root} autoComplete="off" onBlur={handleBlurForm} > <div> <TextField style={{ width: "300px" }} id="registerPseudonyme" label="Pseudonyme" onChange={handleInputPseudonymeChange} required /> <TextField style={{ width: "300px" }} id="registerFirstname" label="Firstname" onChange={handleInputFirstnameChange} required /> <TextField style={{ width: "300px" }} id="registerName" label="Name" onChange={handleInputNameChange} required /> <TextField style={{ width: "300px" }} id="registerPassword" type="password" label="Password" onChange={handleInputPasswordChange} required /> <TextField style={{ width: "300px" }} id="registerPasswordConfirmation" type="password" label="Password confirmation" onChange={handleInputConfirmationPasswordChange} required /> <TextField style={{ width: "300px" }} id="registerEmail" label="Email" type="email" onChange={handleInputEmailChange} required /> <Button style={{ margin: "20px 0 0 110px" }} variant="contained" color="primary" type="submit" > Envoyer </Button> {error && <div style={{ color: "red" }}> {errorMessage} </div>} </div> </form> </> ); }; export default FormRegister;
import React from 'react' //component responsible for simply allowing the user to navigate through pages const selector = (props) =>{ var actualPg = props.page; var leftPg = actualPg; var rightPg = actualPg; if (actualPg > 1) leftPg = actualPg -1; if (actualPg < 9) rightPg = actualPg +1; return( <div className = "page-selector"> <button className = "pgleft" onClick = {() => props.onPageSelect(leftPg)}> &lt; </button> <button className = "pgright" onClick = {() => props.onPageSelect(rightPg)}> &gt; </button> </div> ); } export default selector;
import React from 'react'; function Controls(props) { function clickWall() { return props.clicked('wall'); } function clickStart() { return props.clicked('start'); } function clickEnd() { return props.clicked('end'); } return ( <div className="Controls"> <button className={props.mode === 'wall' ? "activated" : ""} onClick={clickWall}>Place Walls</button> <button className={props.mode === 'start' ? "activated" : ""} onClick={clickStart}>Place Start</button> <button className={props.mode === 'end' ? "activated" : ""} onClick={clickEnd}>Place End</button> </div> ); } export default Controls;
import React, { Component } from 'react' import firebase from 'firebase/app' ; import 'firebase/auth' class signup extends Component { state={ email:"", password:"" } handleChange = event =>{ this.setState({ [event.target.name]:[event.target.value] }) } handleSubmit = (event)=>{ event.preventDefault(); let email = String(this.state.email); let password = String(this.state.password); console.log(email,password); firebase.auth().createUserWithEmailAndPassword(email,password).then((user)=>{ console.log(user); }).catch(err=>{ console.log(err); }) } render() { return ( <div className="section"> <div className="title has-text-centered" style={{marginTop:"0 auto"}}>Sign Up</div> <form className="container" action="/login"> <div className="field"> <div className="control"> <input className="input" type="email" placeholder="Email" name="email" onChange={this.handleChange}/> </div> </div> <div className="field"> <div className="control"> <input className="input" type="password" placeholder="Password" name="password" onChange={this.handleChange}/> </div> </div> <div className="field"> <div className="control"> <input className="input" type="password" placeholder="Confirm Password" /> </div> </div> <div className="field is-grouped is-grouped-centered" > <div className="control"> <input className="button is-link" type="submit" onClick={this.handleSubmit}/> </div> </div> </form> </div> ) } } export default signup
// // Controls are views which respond to user input import View from './View.js' export default class Control extends View { /** Constructor */ constructor() { super() // Bind handler functions this.onMouseMove = this.onMouseMove.bind(this) this.onMouseDown = this.onMouseDown.bind(this) } /** Called when the overlay is added to the screen */ onVisible() { // Add listener Controller.mouseMoveEvent.connect(this.onMouseMove) Controller.mousePressEvent.connect(this.onMouseDown) } /** Called when the overlay is removed from the screen */ onHidden() { // Add listener Controller.mouseMoveEvent.disconnect(this.onMouseMove) Controller.mousePressEvent.disconnect(this.onMouseDown) } /** Called when the mouse moves */ onMouseMove(event) { // Check if within our bounds var within = event.x >= this.options.x && event.x < this.options.x + this.options.width && event.y >= this.options.y && event.y < this.options.y + this.options.height // Send events if (this.wasWithin && !within) this.onMouseLeave(event) else if (!this.wasWithin && within) this.onMouseEnter(event) this.wasWithin = within } /** Called when the mouse button is pressed */ onMouseDown(event) { // If pointer is within the view, call event if (this.wasWithin) this.onMouseDownInside(event) } /** Called when the mouse button is pressed inside the view */ onMouseDownInside(event) { } /** Called when the mouse enters the view */ onMouseEnter(event) { } /** Called when the mouse exits the view */ onMouseLeave(event) { } }
document.write('It works I promise');
export const SET_ERROR_TEXT = 'user/SET_ERROR_TEXT' export const SET_USERNAME = 'user/SET_USERNAME' export const CREATE_USER = 'user/CREATE_USER' export const SHOW_USERNAME_MODAL = 'user/SHOW_USERNAME_MODAL' export const CLOSE_USERNAME_MODAL = 'user/CLOSE_USERNAME_MODAL'
import React, {Component} from 'react'; import { View, StyleSheet, StatusBar, ScrollView, Text, TouchableOpacity, KeyboardAvoidingView, Keyboard, TextInput, ActivityIndicator, FlatList, AsyncStorage, Image, Alert, Dimensions, } from 'react-native'; import {Input, InputProps, Button} from 'react-native-ui-kitten'; import AntIcon from 'react-native-vector-icons/AntDesign'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import ReceiveMessageLayout from './ReceiveMessageLayout'; import axios from 'axios'; import {withNavigation, DrawerActions} from 'react-navigation'; import * as CONSTANT from '../../Constants/Constant'; import HTML from 'react-native-render-html'; import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'; const Entities = require('html-entities').XmlEntities; const entities = new Entities(); class MessageDetailLayout extends Component { state = { data: [], isLoading: true, fetchMessageDetail: [], message: '', }; componentDidMount() { this.fetchMessages(); } fetchMessages = async () => { const Pid = await AsyncStorage.getItem('projectUid'); const {params} = this.props.navigation.state; const response = await fetch( CONSTANT.BaseUrl + 'chat/list_user_messages/?reciver_id=' + Pid + '&current_id=' + params.receiver_id, ); const json = await response.json(); if ( Array.isArray(json) && json[0] && json[0].type && json[0].type === 'error' ) { this.setState({fetchMessageDetail: [], isLoading: false}); // empty data set } else { this.setState({fetchMessageDetail: json.chat_sidebar, isLoading: false}); this.setState({fetchMessageList: json.chat_nodes, isLoading: false}); } }; SendMessage = async () => { this.setState({ message: '', }); const {message} = this.state; const {params} = this.props.navigation.state; const Uid = await AsyncStorage.getItem('projectUid'); if (message == '') { //alert("Please enter Email address"); this.setState({email: 'Por favor agregue mensaje.'}); Alert.alert("Oops" , "Por favor agregue mensaje.") } else { axios .post(CONSTANT.BaseUrl + 'chat/sendUserMessage', { sender_id: Uid, receiver_id: params.receiver_id, message: message, }) .then(async response => { if (response.status == 200) { this.setState({ message: '', }); this.fetchMessages(); } else if (response.status == 203) { this.setState({ message: '', }); Alert.alert(response.type); } }) .catch(error => { this.setState({ message: '', }); console.log(error); }); } Keyboard.dismiss(); }; render() { const {isLoading} = this.state; return ( <View style={styles.container}> <StatusBar backgroundColor="#fff" barStyle="dark-content" /> {isLoading && ( <View style={styles.messageDetailActivityIndicatorArea}> <ActivityIndicator size="small" color={CONSTANT.primaryColor} style={styles.messageDetailActivityIndicatorStyle} /> </View> )} {this.state.fetchMessageDetail && ( <View style={styles.messageDetailFetchStyle}> <TouchableOpacity onPress={() => this.props.navigation.goBack(null)} style={styles.messageDetailTouchableStyle}> <AntIcon name="back" size={25} color={'#fff'} /> </TouchableOpacity> <View style={styles.messageDetailTopRatedArea}> <View style={styles.messageDetailTopRated}> <View style={styles.MainTopRatedStyle}> <View style={styles.ImageLayoutStyle}> <Image resizeMode="contain" style={styles.ImageStyle} source={{uri: `${this.state.fetchMessageDetail.avatar}`}} /> </View> <View style={styles.docContentstyle}> <View style={styles.messageDetailTopRated}> {this.state.fetchMessageDetail && ( <Text numberOfLines={1} style={styles.DocName}> {this.state.fetchMessageDetail.username} </Text> )} </View> {this.state.fetchMessageDetail && ( <HTML html={this.state.fetchMessageDetail.user_register} containerStyle={styles.titleStyle} imagesMaxWidth={Dimensions.get('window').width} /> // <Text // numberOfLines={1} // style={styles.titleStyle}>{`${entities.decode( // this.state.fetchMessageDetail.user_register, // )}`}</Text> )} </View> </View> </View> </View> </View> )} <KeyboardAvoidingView behavior={ Platform.OS === 'ios' ? 'padding' : undefined } style={{ flex: 1, flexDirection: 'column',justifyContent: 'center',}} behavior="padding:1000" enabled keyboardVerticalOffset={100}> <ScrollView> {this.state.fetchMessageList ? ( <FlatList style={styles.messageDetailListStyle} data={this.state.fetchMessageList} keyExtractor={(a, b) => b.toString()} renderItem={({item}) => ( <TouchableOpacity> {item.chat_is_sender == 'yes' ? ( <View style={styles.messageDetailListTouchableArea}> <View style={styles.messageDetailListTouchableTextArea}> <Text style={styles.messageDetailListTouchableMessageText}> {item.chat_message} </Text> </View> <Text style={styles.messageDetailListTouchableDateText}> {item.chat_date} </Text> </View> ) : item.chat_is_sender == 'no' ? ( <View style={styles.messageDetailListTouchableChatArea}> <View style={styles.messageDetailListTouchableChatMessageStyle}> <Text style={styles.messageDetailListTouchableChatMessageText}> {item.chat_message} </Text> </View> <View style={styles.messageDetailListTouchableChatDateStyle}> <Text style={styles.messageDetailListTouchableChatDateText}> {item.chat_date} </Text> <AntIcon style={styles.messageDetailListTouchableChatDateIcon} name="check" size={13} color={'#4B8B3B'} /> </View> </View> ) : null} </TouchableOpacity> )} keyExtractor={(item, index) => index} /> ) : null} </ScrollView> </KeyboardAvoidingView> <View style={styles.messageDetailTextInputArea}> <TextInput multiline={true} placeholder={CONSTANT.MessagesTypehere} underlineColorAndroid="transparent" placeholderTextColor="#7F7F7F" style={styles.TextInputLayout} onChangeText={message => this.setState({message})}></TextInput> <TouchableOpacity onPress={this.SendMessage} style={styles.messageDetailTextInputStyle}> <FontAwesome name="send" size={25} color={CONSTANT.primaryColor} /> </TouchableOpacity> </View> </View> ); } } export default withNavigation(MessageDetailLayout); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f7f7f7', }, searchText: { marginTop: 15, marginLeft: 10, marginBottom: 5, fontSize: 15, }, searchTextBold: { color: '#3d4461', marginLeft: 10, fontWeight: '900', fontSize: 20, marginTop: -8, }, MainTopRatedStyle: { marginLeft: 20, flexDirection: 'row', alignItems: 'center', }, ImageStyle: { height: 40, width: 40, position: 'relative', top: 0, left: 0, bottom: 0, right: 0, borderRadius: 20, }, docContentstyle: { flexDirection: 'column', marginLeft: 10, }, titleStyle: { color: '#fff', fontSize: 13, fontFamily:CONSTANT.PoppinsRegular }, ImageLayoutStyle: { elevation: 4, shadowColor: '#000', borderRadius: 4, overflow: 'hidden', width: 40, height: 40, borderRadius: 20, }, DocName: { color: '#fff', fontSize: 15, fontFamily:CONSTANT.PoppinsBold }, container: { flex: 1, backgroundColor: '#f7f7f7', }, TextInputLayout: { height: 51, width: '80%', color: '#323232', paddingLeft: 10, paddingRight: 10, borderRadius: 8, borderWidth: 1, borderColor: '#dddddd', marginLeft: 10, marginBottom:5, marginTop:5, marginTop:5, shadowOffset: {width: 0, height: 2}, shadowOpacity: 0.2, shadowColor: '#000', fontFamily:CONSTANT.PoppinsRegular }, messageDetailActivityIndicatorArea: {justifyContent: 'center', height: '100%'}, messageDetailActivityIndicatorStyle: { height: 30, width: 30, borderRadius: 60, alignContent: 'center', alignSelf: 'center', justifyContent: 'center', backgroundColor: '#fff', elevation: 5, }, messageDetailFetchStyle: { height: 60, paddingLeft: 15, paddingRight: 15, width: '100%', backgroundColor: '#3d4461', flexDirection: 'row', shadowOffset: {width: 0, height: 2}, shadowColor: '#000', shadowOpacity: 0.2, shadowRadius: 2, elevation: 10, }, messageDetailTouchableStyle: { flexDirection: 'column', display: 'flex', alignContent: 'center', alignSelf: 'center', justifyContent: 'center', }, messageDetailTopRatedArea: { flexDirection: 'column', display: 'flex', alignContent: 'center', alignSelf: 'center', justifyContent: 'center', }, messageDetailTopRated: {flexDirection: 'row'}, messageDetailListStyle: {height: '80%', marginBottom: 15, marginTop: 15}, messageDetailListTouchableArea: { flexDirection: 'column', margin: 5, width: '100%', paddingLeft: 10, }, messageDetailListTouchableTextArea: { alignSelf: 'flex-start', maxWidth: '80%', backgroundColor: '#fff', borderWidth: 0.6, borderRadius: 6, borderColor: '#dddddd', }, messageDetailListTouchableMessageText: { color: '#000', fontSize: 13, color: '#323232', padding: 10, fontFamily:CONSTANT.PoppinsRegular }, messageDetailListTouchableDateText: { color: '#767676', fontSize: 10, marginTop: 2, marginLeft: 5, fontFamily:CONSTANT.PoppinsRegular }, messageDetailListTouchableChatArea: { flexDirection: 'column', margin: 5, width: '100%', paddingRight: 15, }, messageDetailListTouchableChatMessageStyle: { alignSelf: 'flex-end', maxWidth: '80%', backgroundColor: CONSTANT.primaryColor, alignItems: 'flex-end', justifyContent: 'flex-end', borderWidth: 0.6, borderRadius: 6, borderColor: '#dddddd', }, messageDetailListTouchableChatMessageText: { color: '#000', fontSize: 13, padding: 10, color: '#fff', fontFamily:CONSTANT.PoppinsRegular }, messageDetailListTouchableChatDateStyle: { flexDirection: 'row', alignSelf: 'flex-end', alignItems: 'flex-end', justifyContent: 'flex-end', }, messageDetailListTouchableChatDateText: { color: '#767676', fontSize: 10, marginTop: 2, marginLeft: 10, fontFamily:CONSTANT.PoppinsRegular }, messageDetailListTouchableChatDateIcon: {marginLeft: 5}, messageDetailTextInputArea: {flexDirection: 'row'}, messageDetailTextInputStyle: { backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center', alignContent: 'center', height: 51, borderRadius:25.5, marginLeft:10, width: 51, elevation: 4, marginTop:5, shadowOffset: {width: 0, height: 2}, shadowOpacity: 0.2, shadowColor: '#000', } });
import style from './css/dictionary.module.css'; import React from 'react'; import SoundBtn from './soundBtn'; import CartBtn from './cartBtn'; import CloseBtn from '../../../buttons/closeBtn'; const Dictionary = ({ name, words = 0, repeat = null, id, onDictChange, onRemoveDict, groupId, list }) => { return ( <div className={style.dictionary}> <div className={style.name}> <h2 className={style.name_h2}> {name} </h2> </div> <CloseBtn onBtnClick={() => { onRemoveDict(id, groupId); }} absolute={{position: 'absolute', top: '-10px', right: 0}}> x </CloseBtn> <div className={style.body}> <div className={style.body_left}> <h2 className={style.counter} onClick={() => { onDictChange(id, 'CHANGE', name, repeat, list); }}> {words} - words </h2> </div> <div className={style.body_right}> <CartBtn /> <SoundBtn /> </div> </div> <div className={style.repeat}> <h4 className={style.repeat_h4}> {repeat} </h4> </div> </div> ) } export default Dictionary;
var searchData= [ ['urlscheme',['UrlScheme',['../url_8h.html#a10b37ccf31f8e23024ff3ba628aa4243',1,'url.h']]], ['userhdrsoverrideidx',['UserHdrsOverrideIdx',['../header_8c.html#ab53860ce4ae55a975e85479ed7424644',1,'header.c']]] ];
function addUser() { window.location = "kwitter_room.html"; }
export default { label: 'Largest, Tallest, Longest etc', id: 'largest', list: [ { id: 'reading', type: 'passage', label: 'World: Largest, Tallest, Longest', data: { title: 'World: Largest, Tallest, Longest, Smallest etc', text: [ `# Largest...`, { type: 'hilight', text: `Continent − Asia Ocean − Pacific River − Amazon Desert − Sahara Peninsula − Arabian Forest − Amazon Rain Forest Island − Greenland Country (area) − Russia Country (population) − China City (population) − Tokyo Animal − Blue Whale Animal (land) − Elephant Bird − Ostrich Sea Bird − Albatross` }, `# Tallest...`, { type: 'hilight', text: `Animal − Giraffe Building − Burj Khalifa Mountain Peak − Everest Mountain Range − Himalayas WaterFalls − Angel Falls Statue − Statue of Unity` }, `# Longest...`, { type: 'hilight', text: `River − Nile Bone − Femur Railway − Trans-Siberian Railway Railway Platform − Gorakhpur River Dam − Hirakud Dam Wall − Great Wall of China` }, `# Smallest...`, { type: 'hilight', text: `Bird − Humming Bird Continent − Australia Planet − Mercury Country − Vatican City Ocean − Arctic Ocean` }, `# More`, { type: 'hilight', text: `Fastest bird − Peregrine Falcon Fastest animal − Cheetah Hardest metal − Tungsten Brightest Planet − Venus` } ] } }, { id: 'mcq', label: 'Multiple Choice Questions', type: 'mcq', commonData: { title: 'Multiple Choice Questions' }, data: [ { questions: [ { qText: 'What is the tallest statue in the world?', options: 'Statue of Unity, Statue of Liberty, Statue of Diversity' }, { qText: 'What is the tallest waterfall in the world?', options: 'Angel Falls, Niagara Falls, Jog Falls' }, { qText: 'What is the longest bone in our human body?', options: 'Femur, Leg Bone, Back Bone, Ribs' }, { qText: 'What is the longest river in the world?', options: 'Nile, Amazon, Brahmaputra' }, { qText: 'Where is the longest railway platform present?', options: 'Gorakhpur, Jaipur, New Delhi, Siberia' } ] }, { questions: [ { qText: 'What is the highly populated country?', options: 'China, Russia, India, England' }, { qText: 'What is the longest wall?', options: 'Great wall of China, Great wall of America, Great wall of India' }, { qText: 'What is the smallest planet in our Solar System?', options: 'Mercury, Venus, Pluto' }, { qText: 'What is the biggest animal?', options: 'Blue Whale, Shark, Elephant, Giraffe' }, { qText: 'What is the biggest bird?', options: 'Ostrich, Albatross, Falcon, Humming Bird' } ] }, { questions: [ { qText: 'What is the biggest desert?', options: 'Sahara Desert, Thar Desert, Gobi Desert ' }, { qText: 'What is the highest mountain range in the world?', options: 'Himalayas, Everest, Alps' }, { qText: 'What is the smallest ocean?', options: 'Arctic Ocean, Southern Ocean, Indian Ocean' }, { qText: 'What is the hardest metal?', options: 'Tungsten, Copper, Iron, Gold' }, { qText: 'What is the smallest continent?', options: 'Australia, Asia, South America' } ] } ] }, { type: 'match', label: 'Match', id: 'match', commonData: { title: 'Match the following' }, data: [ `Largest Continent, Asia Smallest Continent, Australia Largest Country, Russia Smallest Country, Vatican City Largest Ocean , Pacific Smallest Ocean , Arctic`, `Largest Bird, Ostrich Largest sea Bird, Albatross Smallest Bird , Humming Bird Fastest bird, Peregrine Falcon Tallest Animal, Giraffe Largest Animal, Blue Whale`, `Tallest Peak, Everest Tallest Mountain Range, Himalayas Tallest Building, Burj Khalifa Largely Populated city, Tokyo Smallest Country, Vatican City Largest Island, Greenland` ] }, { type: 'completeWord', label: 'Answer It', id: 'complete', commonData: { lang: 'en', title: 'Type the right answer.' }, data: [ `Largest Continent, Asia Largest Animal, Blue Whale Largest animal living in land, Elephant Largest desert in the world, Sahara Largest Island, Greenland Largest Sea Bird, Albatross Tallest Animal, Giraffe Tallest Building, Burj Khalifa Tallest Mountain Peak, Everest Tallest Mountain Range, Himalayas`, `Largest River, Amazon Longest River, Nile Largest Ocean, Pacific Largest Country by area, Russia Largest Country by population , China Largest Peninsula, Arabian Tallest Waterfall, Angel Smallest Ocean, Arctic Smallest Planet, Mercury Smallest Bird, Humming Bird`, `Fastest bird is Peregrine _____, Falcon Fastest Animal, Cheetah Hardest Metal, tungsten Brightest Planet, venus Largest Forest is ______ Rain Forest. , Amazon Longest Human Bone, Femur Longest Railway Platform, Gorakhpur Smallest Country, Vatican City` ] }, { id: 'reading-2', type: 'passage', style: 'big', label: 'India : Largest, Longest, Tallest', data: { title: 'India : Largest, Longest, Tallest', text: [ `# Largest...`, { type: 'hilight', text: `Desert − Thar Desert Lake − Vembanad Lake Fresh Water Lake − Wular State (area) − Rajasthan State (population) - Uttar Pradesh Forest (state) − Madhya Pradesh Port − Mumbai City (population) − Mumbai` }, `# Longest ...`, { type: 'hilight', text: `River − Ganga Dam − Hirakud Beach − Marina Beach Road − NH44 (Srinagar to Kanyakumari) Railway Platform − Gorakhpur Coastline (state) − Gujarat Tunnel − Atal Tunnel` }, `# Others...`, { type: 'hilight', text: `Tallest Peak − Kanchenjunga Smallest State − Goa Smallest State (population) − Sikkim Highest Waterfall − Kunchikal Falls` } ] } }, { id: 'mcq-2', label: 'Multiple Choice Questions', type: 'mcq', commonData: { title: 'Multiple Choice Questions' }, data: [ { questions: [ { qText: 'What is the largest port in India?', options: 'Mumbai, Chennai, Kolkata' }, { qText: 'Which state has the largest forest cover?', options: 'Madhya Pradesh, Uttar Pradesh, Kerala' }, { qText: 'Which is the largest state?', options: 'Rajasthan, Gujarat, Tamil Nadu, Madhya Pradesh' }, { qText: 'Which is the largest state in population?', options: ' Uttar Pradesh, Madhya Pradesh, Rajasthan' }, { qText: 'Which is the biggest fresh water lake in India?', options: 'Wular Lake, Vembanad Lake, Pulicat Lake' } ] }, { questions: [ { qText: 'Which is the longest river that flows in India?', options: 'Ganga, Brahmaputra, Yamuna' }, { qText: 'Which is the longest Beach in India?', options: 'Marina Beach, Kovalam Beach, Juhu Beach' }, { qText: 'Which state has the longest coastline?', options: 'Gujarat, Maharashtra, Andhra Pradesh' }, { qText: 'Which is the longest dam in India?', options: 'Hirakud Dam, Mettur Dam, Bhakra Nangal Dam' }, { qText: 'Which is the largest city in population?', options: 'Mumbai, New Delhi, Banglore, Chennai' } ] }, { questions: [ { qText: 'Which is the longest highway road in India?', options: 'NH 44, NH 50, NH 43' }, { qText: 'NH 44 connects Srinagar and _________.', options: 'Kanyakumari, Chennai, Thiruvananthapuram' }, { qText: 'Which is the tallest peak in India?', options: 'Kanchenjunga, Mount Everest, Doddabetta' }, { qText: 'Which is the smallest state in India?', options: 'Goa, Haryana, Telangana' }, { qText: 'Which is the highest waterfall in India?', options: 'Kunchikal Falls, Jog Falls, Athirappilly Falls' } ] } ] }, { type: 'match', label: 'Match', id: 'match-2', commonData: { title: 'Match the following. (In India)' }, data: [ `Highest Waterfall, Kunchikal Tallest Peak, Kanchenjunga Longest Dam, Hirakud Longest Tunnel, Atal Longest Beach, Marina`, `Smallest State (area), Goa Smallest State (population), Sikkim Largest State (area), Rajasthan Largest State (population), Uttar Pradesh Longest Coastline, Gujarat`, `Largest Lake, Vembanad Fresh water Lake, Wular Largest Desert, Thar Largest Port, Mumbai Longest Railway Platform, Gorakhpur` ] }, { type: 'completeWord', label: 'Write It', id: 'complete-2', commonData: { lang: 'en', title: 'Write the following with respect to India.' }, data: [ `Longest River, Ganga State with longest coastline, Gujarat Longest Dam, Hirakud Longest Beach, Marina Longest Road, NH 44, __ 44 Longest Railway Platform, Gorakhpur`, `Largest Desert, Thar Largest State (area), Rajasthan Largest State (population), Uttar Pradesh State with Largest forest, Madhya Pradesh Largest Port, Mumbai Highly populated city, Mumbai`, `Largest Lake, Vembanad Largest Fresh Water Lake, Wular Longest Tunnel, Atal Tunnel, ____ Tunnel Tallest Peak, Kanchenjunga Smallest State, Goa, ___ Smallest State (population), Sikkim Highest Waterfall, Kunchikal` ] } ] };
export const options = { role: "main", selectorsWithImplicitRole: ["main"] };
#!/usr/bin/env node const Web3 = require("web3"); const rlay = require("@rlay/web3-rlay"); const redis = require("redis"); const JsonRPC = require("simple-jsonrpc-js"); const WebSocket = require("ws"); const pLimit = require("p-limit"); const mainWithConfig = async () => { const program = require("yargs") .env() .option("index", { demandOption: true, describe: "Name of the redisearch index" }) .option("rpc-url", { describe: "URL of JSON-RPC endpoint" }) .default("rpc-url", "http://localhost:8546") .option("ws-rpc-url", { describe: "URL of JSON-RPC Websocket endpoint" }) .default("ws-rpc-url", "ws://localhost:8547"); const config = program.argv; const web3 = new Web3(config.rpcUrl); rlay.extendWeb3WithRlay(web3); const client = redis.createClient(); const retrieveLimit = pLimit(50); const retrieve = cid => { return retrieveLimit(() => rlay.retrieve(web3, cid)); }; const getLabel = async entity => { const annotations = await Promise.all(entity.annotations.map(retrieve)); const annotationLabel = annotations.find( n => n.property === rlay.builtins.labelAnnotationProperty ); if (!annotationLabel) { return null; } return rlay.decodeValue(annotationLabel.value); }; const enrichedEntity = async entity => { const labelPr = getLabel(entity).then(label => (entity.label = label)); return Promise.all([labelPr]).then(() => entity); }; const processIncomingEntity = entity => { enrichedEntity(entity).then(entity => { client.send_command("FT.ADD", [ config.index, entity.cid, "1.0", "REPLACE", "FIELDS", ...(entity.label ? ["label", entity.label] : []), ...["cid", entity.cid], ...["type", entity.type] ]); }); }; const startJsonRpc = () => { const jrpc = new JsonRPC(); const socket = new WebSocket(config.wsRpcUrl); jrpc.on("rlay_subscribeEntities", ["entity"], processIncomingEntity); socket.onmessage = function(event) { jrpc.messageHandler(event.data); }; jrpc.toStream = function(_msg) { console.log("_msg", _msg); socket.send(_msg); }; socket.onerror = function(error) { console.error("Error: " + error.message); }; socket.onopen = function() { //calls jrpc .call("rlay_subscribeEntities", [{ fromBlock: 0 }]) .then(function(result) { console.log("open", result); }); }; }; const main = async () => { await new Promise((resolve, reject) => { client.send_command("FT.DROP", [config.index], (err, res) => { if (err) { return reject(err); } return resolve(res); }); }).catch(err => { console.log("ERROR during index creation:", err); }); await new Promise((resolve, reject) => { client.send_command( "FT.CREATE", [ config.index, "SCHEMA", ...["label", "TEXT", "WEIGHT", "3.0"], ...["cid", "TEXT"], ...["type", "TEXT", "WEIGHT", "1.0"] ], (err, res) => { if (err) { return reject(err); } return resolve(res); } ); }); startJsonRpc(); }; await main(); }; mainWithConfig();
import React, { Component } from 'react' import './tour.css' export default class Tour extends Component { state = { infoToggle : false } toggleInfo = ()=>{ this.setState({ infoToggle : !this.state.infoToggle }) } render() { const {img,name,city,id,info} = this.props.info return ( <article className="tour"> <div className="imageContainer"> <img src={img} alt="city" /> <span className="closebtn" onClick={()=>this.props.removeTour(id)}>&times;</span> </div> <div className="info"> <h3>City : {city}</h3> <h4>Name : {name}</h4> <h5 onClick={this.toggleInfo}>info {" "}</h5> {this.state.infoToggle && <p>{info}</p> } </div> </article> ) } }
const u = void 0; exports.isUndefined = (value) => { return value === u && typeof value === 'undefined'; } exports.isObject = (value) => { return Object.prototype.toString.call(value) === '[object Object]'; } exports.isString = (value) => { return Object.prototype.toString.call(value) === '[object String]'; } exports.isArray = (value) => { return Object.prototype.toString.call(value) === '[object Array]'; } exports.isNumber = (value) => { return Object.prototype.toString.call(value) === '[object Number]'; }
define(['frame'], function (ngApp) { 'use strict'; ngApp.provider.controller('ctrlCoin', ['$scope', 'http2', function ($scope, http2) { function fetchRules() { var url; url = '/rest/pl/fe/matter/mission/coin/rules?site=' + _oMission.siteid + '&mission=' + _oMission.id; http2.get(url).then(function (rsp) { rsp.data.forEach(function (oRule) { var oRuleData; if ($scope.rules[oRule.act]) { oRuleData = $scope.rules[oRule.act].data; oRuleData.id = oRule.id; oRuleData.actor_delta = oRule.actor_delta; oRuleData.actor_overlap = oRule.actor_overlap; } }); }); } var _oMission, _aDefaultActions; _aDefaultActions = [{ data: { act: 'site.matter.enroll.submit', matter_type: 'enroll' }, desc: '记录活动————用户A提交新填写记录', }, { data: { act: 'site.matter.enroll.cowork.get.submit', matter_type: 'enroll' }, desc: '记录活动————用户A提交的填写记录获得新协作填写数据', }, { data: { act: 'site.matter.enroll.cowork.do.submit', matter_type: 'enroll' }, desc: '记录活动————用户A提交新协作填写数据', }, { data: { act: 'site.matter.enroll.share.friend', matter_type: 'enroll' }, desc: '记录活动————用户A分享活动给微信好友', }, { data: { act: 'site.matter.enroll.share.timeline', matter_type: 'enroll' }, desc: '记录活动————用户A分享活动至朋友圈', }, { data: { act: 'site.matter.enroll.data.get.like', matter_type: 'enroll' }, desc: '记录活动————用户A填写数据获得赞同', }, { data: { act: 'site.matter.enroll.cowork.get.like', matter_type: 'enroll' }, desc: '记录活动————用户A填写的协作数据获得赞同', }, { data: { act: 'site.matter.enroll.data.get.remark', matter_type: 'enroll' }, desc: '记录活动————用户A填写数据获得留言', }, { data: { act: 'site.matter.enroll.cowork.get.remark', matter_type: 'enroll' }, desc: '记录活动————用户A填写协作数据获得留言', }, { data: { act: 'site.matter.enroll.do.remark', matter_type: 'enroll' }, desc: '记录活动————用户A发表留言', }, { data: { act: 'site.matter.enroll.remark.get.like', matter_type: 'enroll' }, desc: '记录活动————用户A发表的留言获得赞同', }, { data: { act: 'site.matter.enroll.data.get.agree', matter_type: 'enroll' }, desc: '记录活动————用户A填写的数据获得推荐', }, { data: { act: 'site.matter.enroll.cowork.get.agree', matter_type: 'enroll' }, desc: '记录活动————用户A发表的协作填写记录获得推荐', }, { data: { act: 'site.matter.enroll.remark.get.agree', matter_type: 'enroll' }, desc: '记录活动————用户A发表的留言获得推荐', }]; $scope.rules = {}; _aDefaultActions.forEach(function (oRule) { oRule.data.actor_delta = 0; oRule.data.actor_overlap = 'A'; $scope.rules[oRule.data.act] = oRule; }); $scope.rulesModified = false; $scope.changeRules = function () { $scope.rulesModified = true; }; $scope.save = function () { var oRule, aPostRules, url; aPostRules = []; for (var act in $scope.rules) { oRule = $scope.rules[act]; if (oRule.id || oRule.actor_delta != 0) { aPostRules.push(oRule.data); } } url = '/rest/pl/fe/matter/mission/coin/saveRules?site=' + _oMission.siteid + '&mission=' + _oMission.id; http2.post(url, aPostRules).then(function (rsp) { for (var k in rsp.data) { $scope.rules[k].id = rsp.data[k]; } $scope.rulesModified = false; }); }; $scope.$watch('mission', function (oMission) { if (oMission) { _oMission = oMission; fetchRules(); } }); }]); });
import React from 'react'; import Budget from './components/Budget'; import Balance from './components/Balance'; import Expenses from './components/Expenses'; import ExpensesList from './components/ExpensesList'; import ExpenseForm from './components/ExpenseForm'; import { AppProvider} from './Context/Context'; function App() { return ( <AppProvider> <div className="container mx-auto pb-6 px-8 bg-blue-800"> <h1 className="mt-4 text-white text-center text-3xl p-4">My Budget Planner</h1> <div className="bg-gray-200 p-4"> <div className="block px-4 py-2 text-center text-white text-2xl bg-green-500"> <Budget/> </div> <div className="block px-4 py-2 text-center text-white text-2xl bg-blue-600 mt-3"> <Balance/> </div> <div className="block px-4 py-2 text-center text-white text-2xl bg-blue-900 mt-3"> <Expenses/> </div> </div> <h2 className="mt-3 text-white text-center text-3xl p-2">Expenses</h2> <div className="row mt-3"> <div className="col-sm"> <ExpensesList/> </div> </div> <h2 className="text-white text-center text-2xl p-2">Add Your Expense</h2> <div className='mt-3'> <div className='col-sm'> <ExpenseForm/> </div> </div> </div> </AppProvider> ); } export default App;
import React, { useState } from "react"; import { Link } from "react-router-dom"; import People from "./People"; import "./searchinfo.css"; const SearchInfo = () => { const [showPeople, setShowPeople] = useState(false); const [adult, setAdult] = useState(2); const [children, setChildren] = useState(0); const [room, setRoom] = useState(0); const decreaseRoom = () => { if (room <= 0) { setRoom(0); } else { setRoom(room - 1); } }; const increaseRoom = () => { setRoom(room + 1); }; const decreaseAdult = () => { if (adult <= 0) { setAdult(0); } else { setAdult(adult - 1); } }; const increaseAdult = () => { setAdult(adult + 1); }; const decreaseChildren = () => { if (children <= 0) { setChildren(0); } else { setChildren(children - 1); } }; const increaseChildren = () => { setChildren(children + 1); }; return ( <div className="search-info-background"> <Link to="" target="_blank"></Link> <div className="grid wide"> <h1>Trải nghiệm kỳ nghỉ tuyệt vời</h1> <h2>Combo khách sạn - vé máy bay - đưa đón sân bay giá tốt nhất </h2> <div className="search-form"> <div className="search-input"> <i className="fas fa-map-marker-alt"></i> <input type="text" name="" id="" placeholder="Bạn muốn đi đâu?" /> </div> <div className="search"> <div className="search-quantitypeople" onClick={() => setShowPeople(!showPeople)} > <i className="fas fa-user-plus"></i> <div> <p> {adult} người lớn, {children} trẻ em </p> <p>{room} Phòng</p> </div> </div> <div className="quantitypeople" style={{ display: `${showPeople ? "block" : "none"}` }} > <People decreaseRoom={decreaseRoom} increaseRoom={increaseRoom} decreaseAdult={decreaseAdult} increaseAdult={increaseAdult} decreaseChildren={decreaseChildren} increaseChildren={increaseChildren} adult={adult} children={children} room={room} /> </div> <div className="search-btn"> <button>Tìm</button> </div> </div> </div> </div> </div> ); }; export default SearchInfo;
import React from 'react' import { NavHashLink } from 'react-router-hash-link' const ruleRegex = new RegExp(/(in|rule|rules)\s((\d{3}\.\d{1,2}\w)|(\d{3}\.\d{1,2})|(\d{3}))/, 'gi') const parseLink = (rule, index, ruleIndex) => { const currRule = rule[index] const ruleMatch = currRule.topic.match(ruleRegex) if (ruleMatch) { const cleanedArray = currRule.topic.split(ruleRegex).filter((entry) => entry !== undefined) const splitTopic = Array.from(new Set(cleanedArray)).map((entry) => { if (ruleIndex.has(entry)) { const root = entry.match(/\d{1}/) const target = entry.match(/\d{3}/) const key = Math.random().toString(36).substr(2, 5) const link = `/${root}/${target}#${entry}` if (process.env.NODE_ENV === 'test') { return link } return [' ', <NavHashLink key={key} className="refLink" to={link}>{entry}</NavHashLink>] } return entry }) return splitTopic } return [rule[index].topic] } export default parseLink
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const checkAuth = require('../middleware/check-auth'); const User = require('../../models/User'); router.post('/signup', (req, res, next) => { User.find({ email: req.body.email }) .exec() .then(user => { if (user.length >= 1) { return res.status(409).json({ message: 'Email Exists' }); } else { bcrypt.hash(req.body.password, 10, (err, hash) => { if (err) { return res.status(500).json({ error: err, message: err }); } else { const user = new User({ _id: new mongoose.Types.ObjectId(), email: req.body.email, password: hash, firstName: req.body.firstName, lastName: req.body.lastName }); user.save() .then(result => { console.log(result); res.status(201).json({ message: 'User Created' }); }) .catch(err => { console.log(err); res.status(500).json({ error: err, message: err }); }); } }) } }) }); router.post('/login', (req, res, next) => { User.find({ email: req.body.email}) .exec() .then(user => { if (user.length < 1) { return res.status(401).json({ message: 'Auth Failed 1' }); } bcrypt.compare(req.body.password, user[0].password, (err, result) => { if (err) { return res.status(401).json({ message: 'Auth Failed 2' }); } if (result) { console.log('Environment:', process.env.JWT_KEY); const token = jwt.sign( { email: user[0].email, userId: user[0]._id }, process.env.JWT_KEY, { expiresIn: "1h" } ); return res.status(200).json({ message: 'Auth Successful', token: token, userName: user[0].userName, firstName: user[0].firstName }); } res.status(401).json({ message: 'Auth Failed 3' }); }); }) .catch(err => { console.log(err); res.status(500).json({ error: err, message: err }); }); }); router.get('/user/:userId', checkAuth, (req,res,next) => { User.findById({_id: req.params.userId}) .exec() .then(result => { if (req.params.userId != req.userData.userId) { return res.status(401).json({ message: 'Auth Failed 5' }); } else { return res.status(200).json({ message: 'User GET', userName: result.userName, firstName: result.firstName, lastName: result.lastName, email: result.email, streetAddress: result.streetAddress, city: result.city, state: result.state, zip: result.zip }); } }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }) router.delete('/:userId', checkAuth, (req, res, next) => { if (req.params.userId != req.userData.userId) { return res.status(401).json({ message: 'Auth Failed 5' }); } else { User.remove({_id: req.params.userId}) .exec() .then(result => { if (req.params.userId != req.userData.userId) { return res.status(401).json({ message: 'Auth Failed 5' }); } else { res.status(200).json({ message: 'User Deleted' }); } }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }) } }); router.patch('/edit/:userId', checkAuth, (req, res, next) => { if (req.params.userId != req.userData.userId) { return res.status(401).json({ message: 'Auth Failed 5' }); } else { User.update({_id: req.params.userId}, {$set: { userName: req.body.userName, firstName: req.body.firstName, lastName: req.body.lastName, streetAddress: req.body.streetAddress, city: req.body.city, state: req.body.state, zip: req.body.zip }}) .exec() .then(result => { res.status(200).json({ message: 'User Updated!', request: { type: 'PATCH', url: '/user/' + req.params.userId } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); } }); //Verify user router.get('/verify/:token', (req, res, next) => { const token = req.params.token; if (!token) { return res.status(401).json({message: 'Must Pass Token'}); } jwt.verify(token, process.env.JWT_KEY, (err, user) => { if (err) { return res.status(401).json({ message: 'Auth Failed 51' }); } User.findById({_id: user.userId}) .exec() .then(result => { console.log('Verifying'); console.log(result); return res.status(200).json({ message: 'User Verified', user: user, token: token, userName: result.userName, firstName: result.firstName, userId: result._id, email: result.email, }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); }) module.exports = router;
class UserModel { constructor(user_arr) { this.nickname = user_arr.nickname ? user_arr.nickname : "NoName"; this.email = user_arr.email ? user_arr.email : undefined; this.id = this.getNewId(user_arr.id) } getNewId(id = null) { return id ? id : 'user_' + (Math.floor(Math.random() * (1000001)) + 1000000); } } module.exports = UserModel;
let express = require('express'), bodyParser = require('body-parser'), port = process.env.PORT || 3000, app = express(); let alexaVerifier = require('alexa-verifier'); let mongoose = require('mongoose'); var mailer = require("nodemailer"); const VrmReg = require('./models/vrmReg.model.js'); const Master = require('./models/master.model.js'); const Product = require('./models/product.model.js') var async = require('async'); var request = require('request'); const SKILL_NAME = 'Compare the car part'; const HELP_REPROMPT = 'How can I help you with?'; const STOP_MESSAGE = 'Thanks for visiting compare the car part Enjoy the day...Goodbye!'; const MORE_MESSAGE = 'which category would you like?' const MORE_MESSAGE1 = 'what would you like?' const PAUSE = '<break time="0.3s" />' const WHISPER = '<amazon:effect name="whispered"/>' let dbURL = 'mongodb+srv://myiqisltd:Rookery12@ds151834.4wuxx.mongodb.net/carpartdb?retryWrites=true&w=majority'; //let dbURL = 'mongodb://myiqisltd:ALAN2889@ds151834-a0.mlab.com:51834,ds151834-a1.mlab.com:51834/carpartdb?replicaSet=rs-ds151834'; var ktype; var masterData; var email; var name; var productLink; var category; var brand; app.use(bodyParser.json({ verify: function getRawBody(req, res, buf) { req.rawBody = buf.toString(); } })); function requestVerifier(req, res, next) { alexaVerifier( req.headers.signaturecertchainurl, req.headers.signature, req.rawBody, function verificationCallback(err) { if (err) { res.status(401).json({ message: 'Verification Failure', error: err }); } else { next(); } } ); } function log() { if (true) { console.log.apply(console, arguments); } } app.post('/comparethecarpart', requestVerifier, function (req, res) { if (req.body.request.type === 'SessionEndedRequest') { if (req.body.request.reason === 'USER_INITIATED') { res.json(stopAndExit()); } else { const speechOutput = 'There was a problem with the requested skills response please try again' var jsonObj = buildResponse(speechOutput, true, ""); return jsonObj; } } else if (req.body.request.type === 'LaunchRequest') { getWelcomeMsg(req.body).then(result => res.json(result)); isFisrtTime = false } else if (req.body.request.type === 'IntentRequest') { switch (req.body.request.intent.name) { case 'VehicleDetailsIntent': getRegDetails(req.body.request.intent).then(result => res.json(result)) break; case 'CategoryDetailsIntent': getCategoryDetails(req.body.request.intent).then(result => res.json(result)) break; case 'PositionDetailsIntent': getPositionDetails(req.body.request.intent).then(result => { res.json(result) }); break; case 'VariantDetailsIntent': getVariantDetails(req.body.request.intent).then(result => { res.json(result) }); break; case 'AMAZON.YesIntent': yesDetails(req.body).then(result => { res.json(result) }); break; case 'AMAZON.NoIntent': res.json(stopAndExit()); break; case 'AMAZON.CancelIntent': res.json(stopAndExit()); break; case 'AMAZON.StopIntent': res.json(stopAndExit()); break; case 'AMAZON.HelpIntent': res.json(help()); break; case 'Unhandled': res.json(stopAndExit()); break; default: } } }); function handleDataMissing() { return buildResponse(MISSING_DETAILS, true, null) } function stopAndExit() { const speechOutput = STOP_MESSAGE var jsonObj = buildResponse(speechOutput, true, ""); return jsonObj; } function help() { const speechOutput = 'You can say ' + PAUSE + ' Registration number is ' + PAUSE + 'l' + PAUSE + 'x' + PAUSE + 'five' + PAUSE + 'two' + PAUSE + 'h' + PAUSE + 'r' + PAUSE + 'm' + PAUSE + ' or ' + PAUSE + 'You can say ' + PAUSE + 'category is air filters' + ' or ' + PAUSE + 'You can say ' + PAUSE + 'Exit' + PAUSE + ' How can I help you with?'; const reprompt = HELP_REPROMPT var jsonObj = buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", reprompt); return jsonObj; } async function getWelcomeMsg(re) { ktype = ''; masterData = []; email = ''; name = ''; productLink = ''; category = ''; brand = ''; let promise = new Promise((resolve, reject) => { request.get({ url: re.context.System.apiEndpoint + "/v2/accounts/~current/settings/Profile.email", headers: { "Authorization": "Bearer " + re.context.System.apiAccessToken, "Accept": "application/json" } }, function (error, response, body) { if (error) { resolve(false); } else { resolve(response); } }); }); let result = await promise; if (result == false) { var welcomeSpeechOutput = 'In order to email you lowest price part details, compare the car part will need access to your email address and full name. Go to the home screen in your Alexa app and grant me permissions and try again. <break time="0.3s" />' const speechOutput = welcomeSpeechOutput; const more = welcomeSpeechOutput; return buildResponseWithPermission(speechOutput, true, "Over 1 million car parts available", more); } else { let jres = JSON.parse(result.body); if (jres.code == "ACCESS_DENIED") { var welcomeSpeechOutput = 'In order to email you lowest price part details, compare the car part will need access to your email address and full name. Go to the home screen in your Alexa app and grant me permissions and try again. <break time="0.3s" />' const speechOutput = welcomeSpeechOutput; const more = welcomeSpeechOutput; return buildResponseWithPermission(speechOutput, true, "Over 1 million car parts available", more); } else { email = result.body; let promise1 = new Promise((resolve, reject) => { request.get({ url: re.context.System.apiEndpoint + "/v2/accounts/~current/settings/Profile.name", headers: { "Authorization": "Bearer " + re.context.System.apiAccessToken, "Accept": "application/json" } }, function (error, response, body) { if (error) { resolve(false); } else { resolve(response); } }); }); let result1 = await promise1; name = result1 == false ? 'Guest' : result1.body.toString().replace(/"/g, ""); var welcomeSpeechOutput = 'Welcome ' + name + ' to compare the car part dot com <break time="0.3s" />' const tempOutput = WHISPER + "Please tell me your vehicle registration number" + PAUSE + ' you can say ' + PAUSE + WHISPER + ' Registration number is ' + PAUSE + 'l' + PAUSE + 'x' + PAUSE + 'five' + PAUSE + 'two' + PAUSE + 'h' + PAUSE + 'r' + PAUSE + 'm'; const speechOutput = welcomeSpeechOutput + tempOutput; const more = ' Registration number is l x five two h r m'; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", more); } } } async function getRegDetails(intentDetails) { let s = intentDetails.slots.registrationnumber.value.toString().split(' '); console.log(s) let finalS = ''; for (var i = 0; i < s.length; i++) { switch (s[i]) { case 'one': s[i] = 1; break; case 'two': s[i] = 2; break; case 'three': s[i] = 3; break; case 'four': s[i] = 4; break; case 'five': s[i] = 5; break; case 'six': s[i] = 6; break; case 'seven': s[i] = 7; break; case 'eight': s[i] = 8; break; case 'nine': s[i] = 9; break; case 'zero': s[i] = 0; break; default: } finalS += s[i]; } console.log(finalS) ktype = ''; let promise = new Promise((resolve, reject) => { VrmReg.find({ regno: { "$regex": finalS.toString(), "$options": "i" } }) .then(uni => { resolve(uni); }); }); let result = await promise; console.log(result) if (result.length > 0) { ktype = result[0].ktype; let promise1 = new Promise((resolve, reject) => { Master.find({ kType: result[0].ktype }).distinct('mainCategory') .then(uni => { resolve(uni); }); }); let result1 = await promise1; console.log(result1) var category = ''; for (var i = 0; i < result1.length; i++) { category += result1[i] + ',' + PAUSE; } var welcomeSpeechOutput = 'Your vehicle is <break time="0.3s" />' + WHISPER + result[0].model + ' ' + result[0].engine + PAUSE + WHISPER + ' We have the following parts available - ' + PAUSE + category + PAUSE + ' ' + PAUSE + ' you can say ' + PAUSE + WHISPER + ' Category is air filters' + PAUSE + MORE_MESSAGE; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE); } else { let promise2 = new Promise((resolve, reject) => { var username = "TC_myiqisltd"; var password = "R00k3ry8arn"; var auth = "Basic " + new Buffer(username + ":" + password).toString("base64"); console.log("https://www.cartell.ie/secure/xml/findvehicle?registration=" + finalS.toString() + "&servicename=XML_Cartell_MYIQIS&xmltype=soap12&readingtype=miles") request.get({ url: "https://www.cartell.ie/secure/xml/findvehicle?registration=" + finalS.toString() + "&servicename=XML_Cartell_MYIQIS&xmltype=soap12&readingtype=miles", headers: { "Authorization": auth } }, function (error, response, body) { console.log(body) if (error) { resolve(false) } else { var parseString = require('xml2js').parseString; var xml = body.toString(); parseString(xml, function (err, result) { resolve(result) }); } }); }); var res1 = await promise2; if (res1 == false) { var welcomeSpeechOutput = 'we cannot find this registration number. Please ensure you say each letter or number in a single form from a to z or numbers 0 to 9'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE); } else { if (res1) { let envelope = res1['soap:Envelope']['soap:Body']; if (envelope.length > 0) { let error = envelope[0]['soap:Fault']; if (error != undefined) { var welcomeSpeechOutput = 'we cannot find this registration number. Please ensure you say each letter or number in a single form from a to z or numbers 0 to 9'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE); } else { ktype = envelope[0].FindByRegistration[0].Vehicle[0].TecDoc_KTyp_No[0]; let promise1 = new Promise((resolve, reject) => { Master.find({ kType: ktype }).distinct('mainCategory') .then(uni => { resolve(uni); }); }); let result1 = await promise1; var category = ''; for (var i = 0; i < result1.length; i++) { category += result1[i] + ',' + PAUSE; } var welcomeSpeechOutput = 'Your vehicle is <break time="0.3s" />' + WHISPER + envelope[0].FindByRegistration[0].Vehicle[0].Model[0] + ' ' + envelope[0].FindByRegistration[0].Vehicle[0].FuelType[0] + ' ' + envelope[0].FindByRegistration[0].Vehicle[0].Power[0] + PAUSE + WHISPER + ' We have the following parts available - ' + PAUSE + category + PAUSE + ' ' + PAUSE + ' you can say ' + PAUSE + WHISPER + ' Category is air filters' + PAUSE + MORE_MESSAGE; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE); } } else { var welcomeSpeechOutput = 'we cannot find this registration number. Please ensure you say each letter or number in a single form from a to z or numbers 0 to 9'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE); } } } } } async function getCategoryDetails(intentDetails) { var cate = ''; category = ''; if (intentDetails.slots.categoryname.value.toString() == 'brake diks') cate = 'Brake Discs'; else cate = intentDetails.slots.categoryname.value.toString(); category = cate; if (ktype) { let promise = new Promise((resolve, reject) => { Master.find({ kType: ktype, mainCategory: { $regex: new RegExp(cate.replace(/[-[\]{}()*+?.,\\/^$|#\s]/g, "\\$&"), 'i') } }, { yinYangQ2: 1, location1: 1, lapArtId: 1 }) .then(uni => { resolve(uni); }); }); let result = await promise; masterData = result; var laparts = ''; if (result.length > 0) { var location = ''; var locationCheck = ''; for (var i = 0; i < result.length; i++) { if (result[i].location1.toString() != '') { if (location.toString().toLowerCase().indexOf(result[i].location1.toString().toLowerCase()) == -1) { if (i == 0) location += result[i].location1 + ' OR ' + PAUSE; else location += result[i].location1 + PAUSE; } locationCheck += result[i].location1; } laparts += result[i].lapArtId; } if (locationCheck == '') { let productData = []; var ean = laparts.toString().split('\n'); let uIndex = 0; productLink = ''; brand = ''; let promise = new Promise((resolve, reject) => { for (var i = 0; i < ean.length; i++) { Product.find({ lapArtId: ean[i] }, { supBrand: 1, "amazonData.UK.price": 1, "amazonData.UK.link": 1 }) .then(prod => { uIndex += prod[0] == undefined ? 1 : 0; let lowestPrice = getLowestPrice(prod[0]); prod[0].lowest = lowestPrice.price; productData.push(prod[0]); if (productData.length == (ean.length - uIndex)) { productData.sort((a, b) => (a.lowest == 'NA' ? 10000 : a.lowest) - (b.lowest == 'NA' ? 10000 : b.lowest)); productLink = productData[0].amazonData.UK.link; brand = productData[0].supBrand; var speechOutput; if (productData[0].lowest == 'NA') { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.categoryname.value + ' category ' + PAUSE + ' ' + 'you can say ' + PAUSE + 'category is' + PAUSE + 'air filters' + PAUSE + 'which other category would you like?'; speechOutput = welcomeSpeechOutput; } else { var welcomeSpeechOutput = 'The following ' + PAUSE + productData[0].supBrand + PAUSE + ' is available at the cheapest price at ' + PAUSE + productData[0].lowest + PAUSE + 'pounds ' + PAUSE + 'you can say ' + PAUSE + 'yes' + PAUSE + 'or' + PAUSE + 'no' + PAUSE + ' Would you like to buy?'; speechOutput = welcomeSpeechOutput; } resolve(speechOutput); } }).catch(err => { // resolve('Something wrong please try again') }); } }); let result = await promise; return buildResponseWithRepromt(result, false, "Over 1 million car parts available", 'Would you like to buy?'); } else { var welcomeSpeechOutput = 'In ' + intentDetails.slots.categoryname.value + ' category we have the following position available' + PAUSE + location + PAUSE + ' ' + ' you can say ' + PAUSE + 'front please ' + PAUSE + MORE_MESSAGE1; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE1); } } else { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.categoryname.value + ' category ' + PAUSE + ' ' + 'you can say ' + PAUSE + 'category is' + PAUSE + 'air filters' + PAUSE + 'which other category would you like?'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", 'which other category would you like?'); } } else { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.categoryname.value + ' category ' + PAUSE + ' ' + 'you can say ' + PAUSE + 'registration number is' + PAUSE + 'l' + PAUSE + 'x' + PAUSE + 'five' + PAUSE + 'two' + PAUSE + 'h' + PAUSE + 'r' + PAUSE + 'm'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", 'registration number is w one one one b o p'); } } async function getPositionDetails(intentDetails) { if (masterData.length > 0) { var variant = ''; var variantCheck = ''; var laparts = ''; let productData = []; for (var i = 0; i < masterData.length; i++) { if (masterData[i].location1.toString().toLowerCase().indexOf(intentDetails.slots.position.value.toString().toLowerCase()) != -1) { variant += masterData[i].yinYangQ2 + PAUSE + ' '; variantCheck += masterData[i].yinYangQ2; laparts += masterData[i].lapArtId; } } if (variantCheck == '') { var ean = laparts.toString().split('\n'); let uIndex = 0; productLink = ''; brand = ''; let promise = new Promise((resolve, reject) => { for (var i = 0; i < ean.length; i++) { Product.find({ lapArtId: ean[i] }, { supBrand: 1, "amazonData.UK.price": 1, "amazonData.UK.link": 1 }) .then(prod => { uIndex += prod[0] == undefined ? 1 : 0; let lowestPrice = getLowestPrice(prod[0]); prod[0].lowest = lowestPrice.price; productData.push(prod[0]); if (productData.length == (ean.length - uIndex)) { productData.sort((a, b) => (a.lowest == 'NA' ? 10000 : a.lowest) - (b.lowest == 'NA' ? 10000 : b.lowest)); productLink = productData[0].amazonData.UK.link; brand = productData[0].supBrand; var speechOutput; if (productData[0].lowest == 'NA') { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.position.value + ' position ' + PAUSE + 'category is ' + PAUSE + 'air filters ' + PAUSE + 'which other category would you like?';; speechOutput = welcomeSpeechOutput; } else { var welcomeSpeechOutput = 'The following ' + PAUSE + productData[0].supBrand + PAUSE + ' is available at the cheapest price at ' + PAUSE + productData[0].lowest + PAUSE + 'pounds ' + PAUSE + 'you can say ' + PAUSE + 'yes' + PAUSE + 'or' + PAUSE + 'no' + PAUSE + ' Would you like to buy?'; speechOutput = welcomeSpeechOutput; } resolve(speechOutput); } }).catch(err => { //resolve('Something wrong please try again') }); } }); let result = await promise; return buildResponseWithRepromt(result, false, "Over 1 million car parts available", 'Would you like to buy?'); } else { var welcomeSpeechOutput = intentDetails.slots.position.value.toString() + ' have the following variant available - ' + variant + PAUSE + ' ' + 'you can say ' + PAUSE + 'variant is' + PAUSE + 'solid' + PAUSE + MORE_MESSAGE1; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", MORE_MESSAGE1); } } else { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.position.value + ' position ' + PAUSE + 'you can say' + PAUSE + 'front please' + PAUSE + 'which other position would you like?'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", 'which other category would you like?'); } } async function getVariantDetails(intentDetails) { if (masterData.length > 0) { var laparts = ''; let productData = []; for (var i = 0; i < masterData.length; i++) { if (masterData[i].yinYangQ2.toString().toLowerCase().indexOf(intentDetails.slots.variantname.value.toString().toLowerCase()) != -1) { laparts += masterData[i].lapArtId; } } var ean = laparts.toString().split('\n'); let uIndex = 0; productLink = ''; brand = ''; let promise = new Promise((resolve, reject) => { for (var i = 0; i < ean.length; i++) { Product.find({ lapArtId: ean[i] }, { supBrand: 1, "amazonData.UK.price": 1, "amazonData.UK.link": 1 }) .then(prod => { uIndex += prod[0] == undefined ? 1 : 0; let lowestPrice = getLowestPrice(prod[0]); prod[0].lowest = lowestPrice.price; productData.push(prod[0]); if (productData.length == (ean.length - uIndex)) { productData.sort((a, b) => (a.lowest == 'NA' ? 10000 : a.lowest) - (b.lowest == 'NA' ? 10000 : b.lowest)); productLink = productData[0].amazonData.UK.link; brand = productData[0].supBrand; var speechOutput; if (productData[0].lowest == 'NA') { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.variantname.value + ' varient ' + PAUSE + 'variant is' + PAUSE + 'solid' + PAUSE + 'which other variant would you like?'; speechOutput = welcomeSpeechOutput; } else { var welcomeSpeechOutput = 'The following ' + PAUSE + productData[0].supBrand + PAUSE + ' is available at the cheapest price at ' + PAUSE + productData[0].lowest + PAUSE + 'pounds ' + PAUSE + 'you can say ' + PAUSE + 'yes' + PAUSE + 'or' + PAUSE + 'no' + PAUSE + ' Would you like to buy?'; speechOutput = welcomeSpeechOutput; } resolve(speechOutput); } }).catch(err => { //resolve('Something wrong please try again') }); } }); let result = await promise; return buildResponseWithRepromt(result, false, "Over 1 million car parts available", 'Would you like to buy?'); } else { var welcomeSpeechOutput = 'No parts available in ' + intentDetails.slots.variantname.value + ' varient ' + PAUSE + 'you can say' + PAUSE + 'variant is' + PAUSE + 'solid' + PAUSE + 'which other variant would you like?'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", 'which other variant would you like?'); } } function getLowestPrice(product) { let lowest = []; if (product.amazonData.UK.price != '') { lowest.push(parseFloat(product.amazonData.UK.price.toString().replace('£', ''))); } let i = lowest.length > 0 ? lowest.indexOf(Math.min(...lowest)) : ''; let p = { price: lowest.length > 0 ? Math.min(...lowest) : 'NA', } return p; } async function yesDetails(re) { if (masterData.length > 0) { // Use Smtp Protocol to send Email var smtpTransport = mailer.createTransport({ host: "smtp.zoho.com", port: 465, secure: true, //ssl auth: { user: "voice@comparethecarpart.com", pass: "Rookery12!" } }); var emailTemplate = '<!DOCTYPE html' + ' PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office"' + ' xmlns:v="urn:schemas-microsoft-com:vml">' + '' + '<head>' + ' <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />' + ' <meta content="width=device-width" name="viewport" />' + ' <meta content="IE=edge" http-equiv="X-UA-Compatible" />' + ' <title></title>' + ' <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css" />' + ' <style type="text/css">' + ' body {' + ' margin: 0;' + ' padding: 0;' + ' }' + '' + ' table,' + ' td,' + ' tr {' + ' vertical-align: top;' + ' border-collapse: collapse;' + ' }' + '' + ' * {' + ' line-height: inherit;' + ' }' + '' + ' a[x-apple-data-detectors=true] {' + ' color: inherit !important;' + ' text-decoration: none !important;' + ' }' + '' + ' .ie-browser table {' + ' table-layout: fixed;' + ' }' + '' + ' [owa] .img-container div,' + ' [owa] .img-container button {' + ' display: block !important;' + ' }' + '' + ' [owa] .fullwidth button {' + ' width: 100% !important;' + ' }' + '' + ' [owa] .block-grid .col {' + ' display: table-cell;' + ' float: none !important;' + ' vertical-align: top;' + ' }' + '' + ' .ie-browser .block-grid,' + ' .ie-browser .num12,' + ' [owa] .num12,' + ' [owa] .block-grid {' + ' width: 650px !important;' + ' }' + '' + ' .ie-browser .mixed-two-up .num4,' + ' [owa] .mixed-two-up .num4 {' + ' width: 216px !important;' + ' }' + '' + ' .ie-browser .mixed-two-up .num8,' + ' [owa] .mixed-two-up .num8 {' + ' width: 432px !important;' + ' }' + '' + ' .ie-browser .block-grid.two-up .col,' + ' [owa] .block-grid.two-up .col {' + ' width: 324px !important;' + ' }' + '' + ' .ie-browser .block-grid.three-up .col,' + ' [owa] .block-grid.three-up .col {' + ' width: 324px !important;' + ' }' + '' + ' .ie-browser .block-grid.four-up .col [owa] .block-grid.four-up .col {' + ' width: 162px !important;' + ' }' + '' + ' .ie-browser .block-grid.five-up .col [owa] .block-grid.five-up .col {' + ' width: 130px !important;' + ' }' + '' + ' .ie-browser .block-grid.six-up .col,' + ' [owa] .block-grid.six-up .col {' + ' width: 108px !important;' + ' }' + '' + ' .ie-browser .block-grid.seven-up .col,' + ' [owa] .block-grid.seven-up .col {' + ' width: 92px !important;' + ' }' + '' + ' .ie-browser .block-grid.eight-up .col,' + ' [owa] .block-grid.eight-up .col {' + ' width: 81px !important;' + ' }' + '' + ' .ie-browser .block-grid.nine-up .col,' + ' [owa] .block-grid.nine-up .col {' + ' width: 72px !important;' + ' }' + '' + ' .ie-browser .block-grid.ten-up .col,' + ' [owa] .block-grid.ten-up .col {' + ' width: 60px !important;' + ' }' + '' + ' .ie-browser .block-grid.eleven-up .col,' + ' [owa] .block-grid.eleven-up .col {' + ' width: 54px !important;' + ' }' + '' + ' .ie-browser .block-grid.twelve-up .col,' + ' [owa] .block-grid.twelve-up .col {' + ' width: 50px !important;' + ' }' + ' </style>' + ' <style id="media-query" type="text/css">' + ' @media only screen and (min-width: 670px) {' + ' .block-grid {' + ' width: 650px !important;' + ' }' + '' + ' .block-grid .col {' + ' vertical-align: top;' + ' }' + '' + ' .block-grid .col.num12 {' + ' width: 650px !important;' + ' }' + '' + ' .block-grid.mixed-two-up .col.num3 {' + ' width: 162px !important;' + ' }' + '' + ' .block-grid.mixed-two-up .col.num4 {' + ' width: 216px !important;' + ' }' + '' + ' .block-grid.mixed-two-up .col.num8 {' + ' width: 432px !important;' + ' }' + '' + ' .block-grid.mixed-two-up .col.num9 {' + ' width: 486px !important;' + ' }' + '' + ' .block-grid.two-up .col {' + ' width: 325px !important;' + ' }' + '' + ' .block-grid.three-up .col {' + ' width: 216px !important;' + ' }' + '' + ' .block-grid.four-up .col {' + ' width: 162px !important;' + ' }' + '' + ' .block-grid.five-up .col {' + ' width: 130px !important;' + ' }' + '' + ' .block-grid.six-up .col {' + ' width: 108px !important;' + ' }' + '' + ' .block-grid.seven-up .col {' + ' width: 92px !important;' + ' }' + '' + ' .block-grid.eight-up .col {' + ' width: 81px !important;' + ' }' + '' + ' .block-grid.nine-up .col {' + ' width: 72px !important;' + ' }' + '' + ' .block-grid.ten-up .col {' + ' width: 65px !important;' + ' }' + '' + ' .block-grid.eleven-up .col {' + ' width: 59px !important;' + ' }' + '' + ' .block-grid.twelve-up .col {' + ' width: 54px !important;' + ' }' + ' }' + '' + ' @media (max-width: 670px) {' + '' + ' .block-grid,' + ' .col {' + ' min-width: 320px !important;' + ' max-width: 100% !important;' + ' display: block !important;' + ' }' + '' + ' .block-grid {' + ' width: 100% !important;' + ' }' + '' + ' .col {' + ' width: 100% !important;' + ' }' + '' + ' .col>div {' + ' margin: 0 auto;' + ' }' + '' + ' img.fullwidth,' + ' img.fullwidthOnMobile {' + ' max-width: 100% !important;' + ' }' + '' + ' .no-stack .col {' + ' min-width: 0 !important;' + ' display: table-cell !important;' + ' }' + '' + ' .no-stack.two-up .col {' + ' width: 50% !important;' + ' }' + '' + ' .no-stack .col.num4 {' + ' width: 33% !important;' + ' }' + '' + ' .no-stack .col.num8 {' + ' width: 66% !important;' + ' }' + '' + ' .no-stack .col.num4 {' + ' width: 33% !important;' + ' }' + '' + ' .no-stack .col.num3 {' + ' width: 25% !important;' + ' }' + '' + ' .no-stack .col.num6 {' + ' width: 50% !important;' + ' }' + '' + ' .no-stack .col.num9 {' + ' width: 75% !important;' + ' }' + '' + ' .video-block {' + ' max-width: none !important;' + ' }' + '' + ' .mobile_hide {' + ' min-height: 0px;' + ' max-height: 0px;' + ' max-width: 0px;' + ' display: none;' + ' overflow: hidden;' + ' font-size: 0px;' + ' }' + '' + ' .desktop_hide {' + ' display: block !important;' + ' max-height: none !important;' + ' }' + ' }' + ' </style>' + '</head>' + '' + '<body class="clean-body" style="margin: 0; padding: 0; -webkit-text-size-adjust: 100%; background-color: #F5F5F5;">' + ' <style id="media-query-bodytag" type="text/css">' + ' @media (max-width: 670px) {' + ' .block-grid {' + ' min-width: 320px !important;' + ' max-width: 100% !important;' + ' width: 100% !important;' + ' display: block !important;' + ' }' + '' + ' .col {' + ' min-width: 320px !important;' + ' max-width: 100% !important;' + ' width: 100% !important;' + ' display: block !important;' + ' }' + '' + ' .col>div {' + ' margin: 0 auto;' + ' }' + '' + ' img.fullwidth {' + ' max-width: 100% !important;' + ' height: auto !important;' + ' }' + '' + ' img.fullwidthOnMobile {' + ' max-width: 100% !important;' + ' height: auto !important;' + ' }' + '' + ' .no-stack .col {' + ' min-width: 0 !important;' + ' display: table-cell !important;' + ' }' + '' + ' .no-stack.two-up .col {' + ' width: 50% !important;' + ' }' + '' + ' .no-stack.mixed-two-up .col.num4 {' + ' width: 33% !important;' + ' }' + '' + ' .no-stack.mixed-two-up .col.num8 {' + ' width: 66% !important;' + ' }' + '' + ' .no-stack.three-up .col.num4 {' + ' width: 33% !important' + ' }' + '' + ' .no-stack.four-up .col.num3 {' + ' width: 25% !important' + ' }' + ' }' + ' </style>' + ' <table bgcolor="#F5F5F5" cellpadding="0" cellspacing="0" class="nl-container" role="presentation"' + ' style="table-layout: fixed; vertical-align: top; min-width: 320px; Margin: 0 auto; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: #F5F5F5; width: 100%;"' + ' valign="top" width="100%">' + ' <tbody>' + ' <tr style="vertical-align: top;" valign="top">' + ' <td style="word-break: break-word; vertical-align: top; border-collapse: collapse;" valign="top">' + ' <div style="background-color:transparent;">' + ' <div class="block-grid"' + ' style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;;">' + ' <div' + ' style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">' + ' <div class="col num12"' + ' style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top;;">' + ' <div style="width:100% !important;">' + ' <div' + ' style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;">' + ' <table border="0" cellpadding="0" cellspacing="0" class="divider"' + ' role="presentation"' + ' style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;"' + ' valign="top" width="100%">' + ' <tbody>' + ' <tr style="vertical-align: top;" valign="top">' + ' <td class="divider_inner"' + ' style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; border-collapse: collapse;"' + ' valign="top">' + ' <table align="center" border="0" cellpadding="0"' + ' cellspacing="0" class="divider_content" height="10"' + ' role="presentation"' + ' style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; border-top: 0px solid transparent; height: 10px;"' + ' valign="top" width="100%">' + ' <tbody>' + ' <tr style="vertical-align: top;" valign="top">' + ' <td height="10"' + ' style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; border-collapse: collapse;"' + ' valign="top"><span></span></td>' + ' </tr>' + ' </tbody>' + ' </table>' + ' </td>' + ' </tr>' + ' </tbody>' + ' </table>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' <div style="background-color:transparent;">' + ' <div class="block-grid two-up no-stack"' + ' style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #2190E3;;">' + ' <div style="border-collapse: collapse;display: table;width: 100%;background-color:#2190E3;">' + ' <div class="col num6"' + ' style="min-width: 320px; max-width: 325px; display: table-cell; vertical-align: top;;">' + ' <div style="width:100% !important;">' + ' <div' + ' style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:25px; padding-bottom:25px; padding-right: 0px; padding-left: 25px;">' + ' <div align="left" class="img-container left fixedwidth"' + ' style="padding-right: 0px;padding-left: 0px;">' + ' <img alt="Image" border="0" class="left fixedwidth"' + ' src="https://www.comparethecarpart.com/assets/images/logo-ctcp-white.png"' + ' style="outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; clear: both; border: 0; height: auto; float: none; width: 100%; max-width: 195px; display: block;"' + ' title="Image" width="195" />' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' <div class="col num6"' + ' style="min-width: 320px; max-width: 325px; display: table-cell; vertical-align: top;;">' + ' <div style="width:100% !important;">' + ' <div' + ' style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:25px; padding-bottom:25px; padding-right: 25px; padding-left: 0px;">' + ' <div></div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' <div style="background-color:transparent;">' + ' <div class="block-grid"' + ' style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #D6E7F0;;">' + ' <div style="border-collapse: collapse;display: table;width: 100%;background-color:#D6E7F0;">' + ' <div class="col num12"' + ' style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top;;">' + ' <div style="width:100% !important;">' + ' <div' + ' style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:60px; padding-right: 25px; padding-left: 25px;">' + ' <div align="center" class="img-container center fixedwidth"' + ' style="padding-right: 0px;padding-left: 0px;">' + ' <div style="font-size:1px;line-height:45px"> </div><img align="center"' + ' alt="Image" border="0" class="center fixedwidth"' + ' src="https://s3.eu-west-2.amazonaws.com/carpart-images-large/comparethecarpart.png"' + ' style="outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; clear: both; border: 0; height: auto; float: none; width: 100%; max-width: 540px; display: block;"' + ' title="Image" width="540" />' + ' </div>' + ' <div' + ' style="color:#052d3d;font-family:\'Lato\', Tahoma, Verdana, Segoe, sans-serif;line-height:150%;padding-top:20px;padding-right:10px;padding-bottom:0px;padding-left:15px;">' + ' <div' + ' style="font-size: 12px; line-height: 18px; font-family: \'Lato\', Tahoma, Verdana, Segoe, sans-serif; color: #052d3d;">' + ' <p' + ' style="font-size: 14px; line-height: 75px; text-align: center; margin: 0;">' + ' <span style="font-size: 50px;"><strong><span' + ' style="line-height: 75px; font-size: 50px;"><span' + ' style="font-size: 38px; line-height: 57px;">WELCOME</span></span></strong></span>' + ' </p>' + ' <p' + ' style="font-size: 14px; line-height: 51px; text-align: center; margin: 0;">' + ' <span style="font-size: 34px;"><strong><span' + ' style="line-height: 51px; font-size: 34px;"><span' + ' style="color: #2190e3; line-height: 51px; font-size: 20px;">' + name + '</span></span></strong></span>' + ' </p>' + ' </div>' + ' </div>' + ' <div' + ' style="color:#555555;font-family:\'Lato\', Tahoma, Verdana, Segoe, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">' + ' <div' + ' style="font-size: 12px; line-height: 14px; color: #555555; font-family: \'Lato\', Tahoma, Verdana, Segoe, sans-serif;">' + ' <p' + ' style="font-size: 14px; line-height: 21px; text-align: center; margin: 0;">' + ' <span style="font-size: 18px; color: #000000;">Thanks for using Compare The Car Part on Alexa. ' + ' You are one step closer to getting the best price for this product.' + ' Please click on the link below to see lowest price part details of your vehicle.</span></p>' + ' </div>' + ' </div>' + ' <div align="center" class="button-container"' + ' style="padding-top:20px;padding-right:10px;padding-bottom:10px;padding-left:10px;">' + ' <a style="-webkit-text-size-adjust: none; text-decoration: none; display: inline-block; color: #ffffff; background-color: #fc7318; border-radius: 15px; -webkit-border-radius: 15px; -moz-border-radius: 15px; width: auto; width: auto; border-top: 1px solid #fc7318; border-right: 1px solid #fc7318; border-bottom: 1px solid #fc7318; border-left: 1px solid #fc7318; padding: 10px; text-align: center; mso-border-alt: none; word-break: keep-all;" href="' + productLink + '" target="_blank">' + ' <span style="font-size: 16px; line-height: 32px;"><strong>VIEW' + ' OFFER</strong></span>' + ' </span></a>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' <div style="background-color:transparent;">' + ' <div class="block-grid"' + ' style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;;">' + ' <div' + ' style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;">' + ' <div class="col num12"' + ' style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top;;">' + ' <div style="width:100% !important;">' + ' <div' + ' style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:20px; padding-bottom:60px; padding-right: 0px; padding-left: 0px;">' + ' <table cellpadding="0" cellspacing="0" class="social_icons"' + ' role="presentation"' + ' style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"' + ' valign="top" width="100%">' + ' <tbody>' + ' <tr style="vertical-align: top;" valign="top">' + ' <td style="word-break: break-word; vertical-align: top; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; border-collapse: collapse;"' + ' valign="top">' + ' <table activate="activate" align="center"' + ' alignment="alignment" cellpadding="0" cellspacing="0"' + ' class="social_table" role="presentation"' + ' style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: undefined; mso-table-tspace: 0; mso-table-rspace: 0; mso-table-bspace: 0; mso-table-lspace: 0;"' + ' to="to" valign="top">' + ' <tbody>' + ' <tr align="center"' + ' style="vertical-align: top; display: inline-block; text-align: center;"' + ' valign="top">' + ' <td style="word-break: break-word; vertical-align: top; padding-bottom: 5px; padding-right: 8px; padding-left: 8px; border-collapse: collapse;"' + ' valign="top"><a' + ' href="https://www.facebook.com/comparethecarpart/"' + ' target="_blank"><img alt="Facebook"' + ' height="32"' + ' src="https://s3.eu-west-2.amazonaws.com/carpart-images-large/facebook%402x.png"' + ' style="outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; clear: both; height: auto; float: none; border: none; display: block;"' + ' title="Facebook" width="32" /></a>' + ' </td>' + ' <td style="word-break: break-word; vertical-align: top; padding-bottom: 5px; padding-right: 8px; padding-left: 8px; border-collapse: collapse;"' + ' valign="top"><a' + ' href="https://twitter.com/comparecarpart"' + ' target="_blank"><img alt="Twitter"' + ' height="32"' + ' src="https://s3.eu-west-2.amazonaws.com/carpart-images-large/twitter%402x.png"' + ' style="outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; clear: both; height: auto; float: none; border: none; display: block;"' + ' title="Twitter" width="32" /></a>' + ' </td>' + ' <td style="word-break: break-word; vertical-align: top; padding-bottom: 5px; padding-right: 8px; padding-left: 8px; border-collapse: collapse;"' + ' valign="top"><a' + ' href="https://www.instagram.com/comparethecarpart/"' + ' target="_blank"><img alt="Instagram"' + ' height="32"' + ' src="https://s3.eu-west-2.amazonaws.com/carpart-images-large/instagram%402x.png"' + ' style="outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; clear: both; height: auto; float: none; border: none; display: block;"' + ' title="Instagram" width="32" /></a>' + ' </td>' + ' </tr>' + ' </tbody>' + ' </table>' + ' </td>' + ' </tr>' + ' </tbody>' + ' </table>' + ' <table border="0" cellpadding="0" cellspacing="0" class="divider"' + ' role="presentation"' + ' style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;"' + ' valign="top" width="100%">' + ' <tbody>' + ' <tr style="vertical-align: top;" valign="top">' + ' <td class="divider_inner"' + ' style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; border-collapse: collapse;"' + ' valign="top">' + ' <table align="center" border="0" cellpadding="0"' + ' cellspacing="0" class="divider_content" height="0"' + ' role="presentation"' + ' style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 60%; border-top: 1px dotted #C4C4C4; height: 0px;"' + ' valign="top" width="60%">' + ' <tbody>' + ' <tr style="vertical-align: top;" valign="top">' + ' <td height="0"' + ' style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; border-collapse: collapse;"' + ' valign="top"><span></span></td>' + ' </tr>' + ' </tbody>' + ' </table>' + ' </td>' + ' </tr>' + ' </tbody>' + ' </table>' + ' <div' + ' style="color:#4F4F4F;font-family:Arial, \'Helvetica Neue\', Helvetica, sans-serif;line-height:120%;padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;">' + ' <div' + ' style="font-size: 12px; line-height: 14px; font-family: Arial, \'Helvetica Neue\', Helvetica, sans-serif; color: #4F4F4F;">' + ' <p' + ' style="font-size: 12px; line-height: 18px; text-align: center; margin: 0;">' + ' <span style="font-size: 15px;"><a' + ' href="https://www.comparethecarpart.com" rel="noopener"' + ' style="text-decoration: underline; color: #2190E3;"' + ' target="_blank">https://www.comparethecarpart.com</a></span>' + ' </p>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </div>' + ' </td>' + ' </tr>' + ' </tbody>' + ' </table>' + '</body>' + '' + '</html>'; var mail = { from: "voice@comparethecarpart.com", to: email, subject: "Compare the car part - " + brand + ' - ' + category, html: emailTemplate } let promise = new Promise((resolve, reject) => { smtpTransport.sendMail(mail, function (error, response) { if (error) { resolve(true); } else { smtpTransport.close(); resolve(true); } }); }); let result = await promise; var welcomeSpeechOutput = 'We send email of lowest price part details to your email address ' + PAUSE + ' Thank you for visiting us' + PAUSE + 'Have a great day'; const speechOutput = welcomeSpeechOutput; return buildResponseWithRepromt(speechOutput, true, "Over 1 million car parts available", 'try again'); } else { const speechOutput = 'You can say ' + PAUSE + ' Registration number is ' + PAUSE + 'l' + PAUSE + 'x' + PAUSE + 'five' + PAUSE + 'two' + PAUSE + 'h' + PAUSE + 'r' + PAUSE + 'm' + PAUSE + ' or ' + PAUSE + 'You can say ' + PAUSE + 'category is air filters' + ' or ' + PAUSE + 'You can say ' + PAUSE + 'Exit'; const reprompt = HELP_REPROMPT var jsonObj = buildResponseWithRepromt(speechOutput, false, "Over 1 million car parts available", reprompt); return jsonObj; } } function buildResponse(speechText, shouldEndSession, cardText) { const speechOutput = "<speak>" + speechText + "</speak>" var jsonObj = { "version": "1.0", "response": { "shouldEndSession": shouldEndSession, "outputSpeech": { "type": "SSML", "ssml": speechOutput } }, "card": { "type": "Simple", "title": SKILL_NAME, "content": cardText, "text": cardText }, } return jsonObj } function buildResponseWithPermission(speechText, shouldEndSession, cardText, reprompt) { const speechOutput = "<speak>" + speechText + "</speak>" var jsonObj = { "version": "1.0", "response": { "shouldEndSession": shouldEndSession, "outputSpeech": { "type": "SSML", "ssml": speechOutput, "text": speechText }, "card": { "type": "AskForPermissionsConsent", "permissions": [ "alexa::profile:name:read", "alexa::profile:email:read" ] }, "reprompt": { "outputSpeech": { "type": "PlainText", "text": reprompt, "ssml": reprompt } } } } return jsonObj } function buildResponseWithRepromt(speechText, shouldEndSession, cardText, reprompt) { const speechOutput = "<speak>" + speechText + "</speak>" var jsonObj = { "version": "1.0", "response": { "shouldEndSession": shouldEndSession, "outputSpeech": { "type": "SSML", "ssml": speechOutput, "text": speechText }, "card": { "type": "Simple", "title": SKILL_NAME, "content": cardText, "text": cardText }, "reprompt": { "outputSpeech": { "type": "PlainText", "text": reprompt, "ssml": reprompt } } } } return jsonObj } app.listen(port); //Mongoose Configurations: mongoose.Promise = global.Promise; mongoose.connection.on('connected', () => { console.log("DATABASE - Connected"); }); mongoose.connection.on('error', (err) => { console.log('DATABASE - Error'); console.log(err); }); mongoose.connection.on('disconnected', () => { console.log('DATABASE - disconnected Retrying....'); }); let connectDb = function () { const dbOptions = { poolSize: 5, reconnectTries: Number.MAX_SAFE_INTEGER, reconnectInterval: 500 }; mongoose.connect(dbURL, dbOptions) .catch(err => { console.log('DATABASE - Error'); console.log(err); }); }; connectDb(); console.log('Alexa list RESTful API server started on: ' + port);
"use strict"; /** * Check if a variable is a plain object * @param o * @returns {boolean} */ const isPlainObject = function (o) { return o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ? false : typeof o == 'object'; }; module.exports = isPlainObject;
$(document).ready(function() { //jquery for toggle sub menus $('.sub-btn').click(function() { $(this).next('.sub-menu').slideToggle(); $(this).find('.dropdown').toggleClass('rotate'); }); //jquery for expand and collapse the sidebar $('.menu-btn').click(function() { $('.side-bar').addClass('active'); $('.menu-btn').css("visibility", "hidden"); }); $('.close-btn').click(function() { $('.side-bar').removeClass('active'); $('.menu-btn').css("visibility", "visible"); }); });
import { Requirement } from "./react-guard/src"; class MyRequirement extends Requirement { constructor(credentials) { super(); this.credentials = credentials; } isSatisfied(credentials) { return this.credentials === credentials; } } const NeedAdmin = new MyRequirement("admin"); const NeedStaff = new MyRequirement("staff"); export { NeedAdmin, NeedStaff };
export const myMissons = { daily : ['pray','meditate', 'exercise','english'] , weekly : ['eyal','running', 'haircut','sunset'] , monthly : ['grendma','party', 'meetup','draw'] , annualy: ['ski','retreat', 'marathon','sea week'], lifetime : ['standup','africa','develop app'] }
fs .factory("Utils", function () { var pageLoading = function (action) { var layer = $("#loading"); var label = layer.find("div"); if (action === "on") { layer.show(); label.css({ "top" : ($(window).height() / 2 - label.outerHeight() / 2) + "px", "left" : ($(window).width() / 2 - label.outerWidth() / 2) + "px" }).show(); } else if (action === "off") { layer.hide(); label.hide(); } }; return { "pageLoading": function (action) { pageLoading(action); }, "error": function (msg) { pageLoading("off"); alert(msg); } }; }) .factory("Rsrc", ["$rootScope", "$resource", function ($rootScope, $resource) { return $resource( $rootScope.api, {}, { "getRoom": { "method": "POST", "params": { "action": "getRoom" } }, "createRoom": { "method": "POST", "params": { "action": "createRoom" } }, "setWords": { "method": "POST", "params": { "action": "setWords" } }, "joinRoom": { "method": "POST", "params": { "action": "joinRoom" } }, "leaveRoom": { "method": "POST", "params": { "action": "leaveRoom" } }, "lockRoom": { "method": "POST", "params": { "action": "lockRoom" } }, "unlockRoom": { "method": "POST", "params": { "action": "unlockRoom" } }, "assignJudge": { "method": "POST", "params": { "action": "assignJudge" } }, "assignSpy": { "method": "POST", "params": { "action": "assignSpy" }, "isArray": true } } ); } ]);
// frz-proto.js // Protocol layout: // UDP: // [MESSAGE_ID /16][SEQ ID /16][FLAGS /16][OPTIONAL /16][PAYLOAD ................] // 0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF-------------------------> // First Message: Sender -> Recv // [MESSAGE ID /16][SEQ ID (0) /16][FIRST FLAG ][TOTAL SEQ ][First payload ] // Last Message: Sender -> Recv // [MESSAGE ID /16][SEQ ID (#) /16][LAST FLAG ][TOTAL SEQ ][First payload ] // Full Message Received: Recv -> Sender // [MESSAGE ID /16][SEQ ID (#) /16][LAST FLAG | ACK ][ null ] // Lost Pack: Recv -> Sender (SEQ ID is last received, but SEQ LOST is the one Recv needs) // [MESSAGE ID /16][SEQ ID (#) /16][LOST FLAG ][SEQ LOST ] // Lost Pack - Resend all from seq num #: Recv -> Sender // [MESSAGE ID /16][SEQ ID (#) /16][LOST | RESEND_ALL][ null ] // Up the protocol stack.. // Events: // [ numbers are bytes ] // // [ HEADER 8 ] [ ------------- PAYLOAD -----------> // Payloads are defined by categories... // [ HEADER 8 ] [ CATG 2 ] // Category: Asynchronous events (pushes from devices) // [ HEADER 8 ] [ 0xF001 ] [ EVENTCODE 2 ] var frz_proto = { CATEGORY : { COMMAND : 0x0001, ASYNC_PUSH : 0xF001 }, // from frzproto.h header // MAX_PACK_SIZE: 120-8, // in bytes FRZ_HEADER_SIZE: 8, FRZ_MAX_TRANSFER_LEN: 120*7, MAX_6LOWPAN_UDP_PAYLOAD: 102, FRZ_IN_TRANSFER: 2, FRZ_WAITING: 0, FRZ_PROCESSING: 4, // offsets are in bytes MESSAGE_ID_OFFSET: 0, SEQ_ID_OFFSET: 2, FRZ_FLAGS_OFFSET : 4, FRZ_OPTIONAL_OFFSET :6, // #define FRZ_FLAG_ACK 0x0001 // #define FRZ_FLAG_FIRST 0x0002 // #define FRZ_FLAG_LAST 0x0004 // #define FRZ_FLAG_LOST 0x1000 // #define FRZ_FLAG_RESET 0x2000 // tells far-end to reset everything they know about previous states // #define FRZ_FLAG_FAIL 0x4000 // tells far-end to reset everything they know about previous states // #define FRZ_ERROR_TOO_BIG 0x0010 FRZ_FLAG_ACK : 0x0001, FRZ_FLAG_FIRST : 0x0002, FRZ_FLAG_LAST : 0x0004, FRZ_FLAG_LOST : 0x1000, FRZ_FLAG_RESET : 0x2000 , // tells far-end to reset everything they know about previous states FRZ_FLAG_FAIL : 0x4000 , // tells far-end to reset everything they know about previous states FRZ_ERROR_TOO_BIG: 0x0010, /* #define SET_FRZ_SEQ_ID( hdr, v ) { *((uint32_t *) hdr) = ((uint32_t) (v) & 0xFF) | (*((uint32_t *) hdr) & 0xFF00); } #define SET_FRZ_MSG_ID( hdr, v ) { *((uint32_t *) hdr) = ((uint32_t) (v) << 16) | (*((uint32_t *) hdr) & 0x00FF); } #define SET_FRZ_FLAGS( hdr, v ) { *((uint32_t *) hdr + 1) = ((uint32_t) (v) & 0xFF) | (*((uint32_t *) hdr) & 0xFF00); } #define SET_FRZ_OPTIONAL( hdr, v ) { *((uint32_t *) hdr + 1) = ((uint32_t) (v) << 16) | (*((uint32_t *) hdr) & 0x00FF); } #define GET_FRZ_SEQ_ID( hdr ) (*((uint32_t *) hdr) & 0xFF) #define GET_FRZ_MSG_ID( hdr ) (*((uint32_t *) hdr) << 16) #define GET_FRZ_FLAGS( hdr ) (*((uint32_t *) hdr + 1) & 0xFF) #define GET_FRZ_OPTIONAL( hdr ) (*((uint32_t *) hdr + 1) << 16) */ // hdr is a nodejs Buffer GET_FRZ_SEQ_ID: function( hdr ) { return hdr.readUInt16LE(this.SEQ_ID_OFFSET); }, GET_FRZ_MSG_ID: function( hdr ) { return hdr.readUInt16LE(this.MESSAGE_ID_OFFSET); }, GET_FRZ_FLAGS: function( hdr ) { return hdr.readUInt16LE(this.FRZ_FLAGS_OFFSET); }, GET_FRZ_OPTIONAL: function( hdr ) { return hdr.readUInt16LE(this.FRZ_OPTIONAL_OFFSET); }, SET_FRZ_SEQ_ID: function( hdr, v ) { return hdr.writeUInt16LE(v,this.SEQ_ID_OFFSET); }, SET_FRZ_MSG_ID: function( hdr, v ) { return hdr.writeUInt16LE(v,this.MESSAGE_ID_OFFSET); }, SET_FRZ_FLAGS: function( hdr, v ) { return hdr.writeUInt16LE(v,this.FRZ_FLAGS_OFFSET); }, SET_FRZ_OPTIONAL: function( hdr, v ) { return hdr.writeUInt16LE(v,this.FRZ_OPTIONAL_OFFSET); } }; frz_proto.MAX_FRZ_PAYLOAD = frz_proto.MAX_6LOWPAN_UDP_PAYLOAD - frz_proto.FRZ_HEADER_SIZE; frz_proto.MIN_AES_PAYLOAD = 16; exports = module.exports = frz_proto;
import styled from "styled-components"; export const Container = styled.div` width: 100%; height: auto; display: flex; justify-content: center; align-items: center; background: rgb(30, 30, 30); flex-direction: column; font-size: 15px; `; export const Fila = styled.div` width: 100%; height: 11.1%; display: flex; justify-content: center; align-items: center; `; export const Num = styled.div` display: flex; justify-content: center; align-items: center; height: 100%; width: 10%; color: #d9d9d9; `; export const Text = styled.div` height: 100%; width: 90%; color: rgb(215, 186, 125); font-weight: bold; label { color: rgb(156, 220, 254); } input { background: transparent; border: none; border-bottom: 1px solid gray; color: rgb(180, 205, 167); font-weight: bold; font-size: 15px; outline: none; width: 40px; &::placeholder { background: transparent; } } `;
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import 'babel-polyfill' import './style/common.scss' import { showLoading, hideLoading } from './component/loading/index.js' Vue.prototype.$showLoading = showLoading; Vue.prototype.$hideLoading = hideLoading; const _vue = new Vue({ el: '#app', router, store, render: h => h(App) }) window.$vue = _vue;
var mongodb = require('./db'); function Comment(comment) { this._id = comment._id; this.pid = comment.pid; this.uid = comment.uid; this.toUid = comment.toUid; this.content = comment.content; this.createTime = comment.createTime; } module.exports = Comment; // 通过特定 query 读取多个评论,其中 query 形如 {pid: 1000000} 的键值类型 // sortRE 为排序参数,形如 {createTime: -1} 逆序 // 返回 Comment 类数组 Comment.getComments = function(query, sortRE, callback) { // 打开数据库 mongodb.open(function(err, db) { if (err) { console.log("打开数据库错误"); return callback(err); // 错误,返回 err 信息 } // 读取 comments 集合 db.collection('comments', function(err, collection) { if (err) { console.log("读取 comments 集合错误"); mongodb.close(); return callback(err); // 错误,返回 err 信息 } // 根据 query 查找 comments 集合 collection.find(query).sort(sortRE).toArray(function(err, docs) { mongodb.close(); if (err) { return callback(err); } var comments = []; docs.forEach(function (doc) { comments.push(new Comment(doc)); }); return callback(null, comments); }); }); }); }; // 添加一条评论,必须有 pid,uid,content 属性 // 前置默认有 以上属性,toUid 可选,无 _id 属性 Comment.addComment = function(newComment, callback) { // 打开数据库 mongodb.open(function(err, db) { if (err) { console.log("打开数据库错误"); return callback(err); // 错误,返回 err 信息 } // 读取 comments 集合 db.collection('comments', function(err, collection) { if (err) { console.log("读取 comments 集合错误"); mongodb.close(); return callback(err); // 错误,返回 err 信息 } var _id = 10000000; collection.find().limit(1).sort({_id: -1}).toArray(function(err, docs) { if (err) { mongodb.close(); return callback(err); } if (docs.length > 0) { _id = docs[0]._id + 1; } collection.ensureIndex({pid: 1}); newComment._id = _id; newComment.createTime = new Date(); collection.insertOne(newComment, function(err, result) { mongodb.close(); if (err) { return callback("添加评论失败!"); } callback(null, result); }); }); }); }); } // 修改评论信息,其中 eComment 必须有 _id 指定要修改的评论 Comment.editComment = function(eComment, callback) { // 打开数据库 mongodb.open(function(err, db) { if (err) { console.log("打开数据库错误"); return callback(err); // 错误,返回 err 信息 } // 读取 comments 集合 db.collection('comments', function(err, collection) { if (err) { console.log("读取 comments 集合错误"); mongodb.close(); return callback(err); // 错误,返回 err 信息 } collection.update({ _id: eComment._id }, { $set: eComment }, function (err) { mongodb.close(); if (err) { return callback(err); } callback(null); }); }); }); }; // 删除评论,根据 query 查询后删除,其中 query 形如 {_id: 10000000} Comment.removeComment = function(query, callback) { // 打开数据库 mongodb.open(function(err, db) { if (err) { console.log("打开数据库错误"); return callback(err); // 错误,返回 err 信息 } // 读取 comments 集合 db.collection('comments', function(err, collection) { if (err) { console.log("读取 comments 集合错误"); mongodb.close(); return callback(err); // 错误,返回 err 信息 } // 根据 query 查询并删除 comments 文档 collection.remove(query, function(err) { mongodb.close(); if (err) { return callback(err); } callback(null); }); }); }); } // For test // Comment.removeComment({_id: 10000001}, function(err) { // if (err) { // console.log("删除操作错误"); // return; // } // console.log("删除操作成功"); // }); // Comment.editComment({ // _id: 10000000, uid: 10000001 // }, function(err) { // if (err) { // console.log("err!"); // return; // } // console.log("succeed!"); // }); // Comment.addComment({ // pid: 10000000, uid: 10000000, toUid: 10000001, content: "你好按时发送" // }, function(err, result) { // if (err) { // console.log(err); // return; // } // console.log("添加成功!"); // }); // Comment.getComments({}, {createTime: -1}, function(err, comments) { // if (err) { // console.log("get err"); // return; // } // console.log(comments); // });
import {StyledInfoSpacer} from "../../../layout/layout"; const InfoSpacer = () => { return <StyledInfoSpacer/> } export default InfoSpacer
if (typeof define !== 'function') { var define = function (f) { module.exports = f (require); } } define(function(require) { 'use strict'; var geom = require('./geom'); var Collision = require('./collision'); function Level (data) { this.solids = data.solids; this.collision = new Collision (this); } Level.prototype.getCurves = function (solidIndex) { var solid = this.solids[solidIndex]; var ret = [[ solid[0] ]]; for (var i = 1; i < solid.length; ) { if (i < solid.length - 2 && solid[i].c && solid[i+1].c) { ret.push ([ solid[i], solid[i+1], solid[i+2] ]); i += 3; } else if (i < solid.length - 1 && solid[i].c) { ret.push ([ solid[i], solid[i+1] ]); i += 2; } else { ret.push ([ solid[i] ]); i++; } } return ret; } return Level; });
const express = require('express'); const cors = require('cors'); const app = express(); const port = 8080; const allowedOrigins = [ 'http://localhost:3000', 'https://localhost:3000', 'https://online-offline.apps.pcfone.io', 'http://online-offline.apps.pcfone.io', 'online-offline.apps.pcfone.io', ]; let value = ""; app.use(express.json()); app.use(cors({ origin: function (origin, callback) { if (!origin) return callback(null, true); if (origin.indexOf("apps.pcfone.io") === -1 && origin.indexOf("localhost:3000")=== -1 ) { const msg = 'The CORS policy for this site does not ' + 'allow access from the specified Origin.'; return callback(new Error(msg), false); } return callback(null, true); } })); app.get('/super-cool-backend', (req, res) => res.send('Hello World!')); app.post("/reverse-me", (req, res) => { console.log("hi ", req.body); value = req.body.text.split("").reverse().join(""); res.send("all good") }); app.get("/reverse-me", (req, res) => { res.send(value) }); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
var utils = require('../../lib/utils'); var assert = require('chai').assert; describe('utils', function () { describe('.mtof(midi)', function () { it('converts midi notes to frequency', function () { var a4 = utils.mtof(69); assert.equal(a4, 440); var c4 = utils.mtof(60); assert.equal(c4.toFixed(1), 261.6); var gb5 = utils.mtof(78); assert.equal(gb5.toFixed(2), 739.99); var c1 = utils.mtof(24); assert.equal(c1.toFixed(2), 32.70); }); }); describe('.ntof(note)', function () { it('converts a note name to a frequency', function () { var a4 = utils.ntof('a4'); assert.equal(a4, 440); var gb7 = utils.ntof('gb5'); assert.equal(gb7.toFixed(2), 739.99); var c1 = utils.ntof('c1'); assert.equal(c1.toFixed(2), 32.70); }); }); describe('.mtop(midi)', function () { it('converts a midi note to a playback rate', function () { var c4 = utils.mtop(60); assert.equal(c4, 1); var c5 = utils.mtop(72); assert.equal(c5, 2); var c3 = utils.mtop(48); assert.equal(c3, 0.5); var a4 = utils.mtop(69); assert.equal(a4.toFixed(2), 1.68); }); }); });
export default { plugins:[ ['umi-plugin-react',{ antd:true, dva:true, locale: { enable: true, } }] ], routes:[{ path:'/', component:'index.js', routes:[ {path:'/',component:'Dashboard/Login'}, {path:'/welcome',component:'Dashboard/Welcome'}, {path:'analysis',component:'Dashboard/Analysis'}, {path:'monitor',component:'Dashboard/Monitor'}, ] }] }
import NavigationService from "../services/nav.service"; export const rootModel = { state: { selectedPage: 1, headerTitle: "Home", isLoading: false, isConnexionSucess: true, }, reducers: { setHeaderTitle(state, payload) { return { ...state, headerTitle: payload }; }, setIsLoading(state, payload) { return { ...state, isLoading: payload }; }, setIsConnexionSucess(state, payload) { return { ...state, isConnexionSucess: payload }; }, goToPage(state, payload) { NavigationService.navigate(payload); return state; }, }, effects: dispatch => ({ goHome() { dispatch.rootModel.goToPage(1); dispatch.rootModel.setHeaderTitle("Home"); }, }), };
import React, { useState } from 'react'; import { Link } from 'react-router-dom' const Header = (props) => { const [inputs, setInputs] = useState({ searchName: "" }); const { searchName } = inputs; const changehandler = (e) => { const { value, name } = e.target; setInputs({ ...inputs, [name]: value }); }; return ( <div className="container flex max-w-full max-h-full justify-between items-center border-b border-gray-400 bg-white px-4 h-14 inset-0"> <div> <span className="mx-4 my-4 font-sans font-bold text-xl"><Link to='/'>Main</Link></span> <span className="mx-4 my-4"> <input className="border-solid border border-blue-600 rounded-l-sm placeholder-gray-400 font-sans font-normal text-sm px-2 py-1 w-64" name="searchName" placeholder="책 이름을 검색하세요. " onChange={changehandler} value={searchName}></input> <Link to={`/bookSearch/${searchName}`}><button className="border-solid border border-blue-600 rounded-r-sm bg-blue-600 font-sans font-normal text-sm text-white px-2 py-1">Search</button></Link> </span> </div> { props.userManagement === 0 ? <div className=""> <span className="mx-4 my-4 font-sans font-light text-xs text-black">{props.userName}님</span> <span className="mx-4 my-4 font-sans font-medium text-base text-gray-400"><Link to='/myInfo'>My Info</Link></span> <span className="mx-4 my-4 font-sans font-medium text-base text-gray-400" onClick={props.logout}><Link to='/'>Logout</Link></span> </div> : props.userManagement === 1 ? <div className=""> <span className="mx-4 my-4 font-sans font-light text-xs text-black">{props.userName} 관리자님</span> <span className="mx-4 my-4 font-sans font-medium text-base text-gray-400"><Link to='/bookRegister'>Book Register</Link></span> <span className="mx-4 my-4 font-sans font-medium text-base text-gray-400" onClick={props.logout}><Link to='/'>Logout</Link></span> </div> : <div className=""> <span className="mx-4 my-4 font-sans font-medium text-base text-gray-400"><Link to='/login'>Login</Link></span> <span className="mx-4 my-4 font-sans font-medium text-base text-gray-400"><Link to='/join'>Join</Link></span> </div> } </div> ); }; export default Header;
module.exports = function(pageName){ return function(data){ var output = '<form method="POST" action="/msgcenter/' + pageName + '/process?_=' + (new Date().getTime()) + '">' +'<table class="report" cellspacing="0" cellpadding="0" style="font-size: 9pt">' + '<tr class="head">' + '<td width="20%">时间</td>' + '<td>内容(提示)</td>' + '<td width="5%">选择</td>' + '</tr>' ; var pager = data.pager, items = data.items; var noItem = (items.length < 1); if(noItem){ output += '<tr><td colspan="3">' + '当前没有项目</td></tr>' + '</table></form>'; } else { for(var i in items){ var item = items[i]; output += '<tr>' + '<td>' + _.format.time2Full( new Date(item.timestamp * 1000) ) + '</td>' ; if('plaintext' == pageName || 'decrypted' == pageName) output += '<td>' + item.data + '<span class="hint">(' + item.comment + ')</span></td>'; else output += '<td class="hint">' + item.comment + '</td>'; output += '<td><input type="checkbox" name="item' + i + '" value="' + item.id + '"/></td></tr>'; }; output += '</table>' + '第' + pager.current + '页/共' + pager.max + '页 ' + pager.navigateBar(function(i, cur){ if(cur) return ('[<font color="#FF0000">' + i + '</font>]'); else return ('[<a href="/msgcenter/' + pageName + '/?page=' + i + '&_=' + process.hrtime()[1] + '">' + i + '</a>]') ; } ) ; if('encrypted' == pageName) output += '' + '<br /><table><tr><td>选中项目:</td>' + '<td><select name="do">' + '<option value="send">选择信道并发送</option>' + '<option value="remove">删除</option>' + '</select></td>' + '<td><button type="submit">操作</button></td>' + '</tr></table>' + '</form>' ; if('plaintext' == pageName) output += '' + '<table><tr><td><a href="/compose/write?_' + process.hrtime()[1] + '">撰写新消息</a>,或对选中项目:</td>' + '<td><select name="do"' + (noItem?' disabled="disabled"':'') + '>' + '<option value="passphrase" selected>加密,使用临时输入的口令</option>' + '<option value="codebook">加密,指定一个或多个收件人,使用密码本</option>' + '<option value="sign">使用公钥签署,但不加密</option>' + '<option value="remove">删除</option>' + '</select></td>' + '<td><button type="submit"' + (noItem?' disabled="disabled"':'') + '>操作</button></td>' + '</tr></table>' + '</form>' ; }; return output; }; };
let uBut = document.getElementById('upper-case'); let lBut = document.getElementById('lower-case'); let pBut = document.getElementById('proper-case'); let sBut = document.getElementById('sentence-case'); let dBut = document.getElementById('save-text-file'); let text = document.getElementById('text'); function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } uBut.addEventListener('click', () => {text.value = text.value.toUpperCase()}); lBut.addEventListener('click', () => {text.value = text.value.toLowerCase()}); pBut.addEventListener('click', () => {text.value = text.value.toLowerCase().split(' ').map((elem)=>elem[0].toUpperCase()+elem.slice(1)).join(' ')}); sBut.addEventListener('click', () => {text.value = text.value.toLowerCase().split('. ').map((elem)=>elem[0].toUpperCase()+elem.slice(1)).join('. ')}); dBut.addEventListener('click', () => {download('text.txt', text.value)});
export const fetchRooms = payload => ({ type: "FETCH_ROOMS", payload }); export const setRoomId = payload => ({ type: "SET_ROOM_ID", payload }); export const fetchMessages = payload => ({ type: "FETCH_MESSAGES", payload });
module.exports = { use: [ [ '@neutrinojs/react', { hot: false, html: { title: 'my app', links: [ { href: 'https://fonts.googleapis.com/css?family=Muli:400,700,800', rel: 'stylesheet', }, ], }, }, ], '@usertech/neutrino-preset-eslint-prettier', (neutrino) => neutrino.config.resolve.modules.add(neutrino.options.source), '@usertech/neutrino-preset-react-storybook', (neutrino) => neutrino.config.output.publicPath('/'), (neutrino) => { neutrino.config.module .rule('graphql') .test(/\.(graphqls?|gql)$/) .include.add(/src/) .end() .use('graphql') .loader('graphql-tag/loader') .end() .end() .end(); }, ], };
import React, {Component} from 'react' import PropTypes from 'prop-types' import {Field} from 'redux-form' import SelectCustom from '../SelectCustom' import DateTimePicker from '../DateTimePicker' import './style.css' const renderInput = ({input, label, type, placeholder, readonly}) => ( <input {...input} placeholder={placeholder} type={type} disabled={readonly} value={input.value}/> ) class Input extends Component { static propTypes = { type: PropTypes.string, label: PropTypes.string, placeholder: PropTypes.string, hint: PropTypes.string, name: PropTypes.string, component: PropTypes.string, options: PropTypes.array, time: PropTypes.number, default: PropTypes.string, onChange: PropTypes.func } static defaultProps = { component: 'input', time: 500 } render() { const { type, name, readonly, label, hint, placeholder, component, ...others } = this.props return ( <label className="input__container"> {label && <div className="input__label">{label}</div>} {hint && <span className="input__hint">{this.props.hint}</span>} {component === 'input' && <Field name={name} onFocus={(e) => e.currentTarget.select()} onChange={this.props.onChange} component={renderInput} type={type} readonly={readonly} placeholder={placeholder} /> } {component === 'select' && <Field name={name} options={this.props.options} component={props => <SelectCustom options={props.options} disabled={props.disabled} clearable={props.clearable} multi={props.multi} searchable={props.searchable} valueKey={props.input.value.value} value={this.getSelectValue(props.input.value, this.props.options)} onChange={this.props.onChange ? this.props.onChange : (e) => { props.input.onChange(e.value) }} /> } /> } {component === 'time' && <DateTimePicker name={name} /> } </label> ) } getSelectValue = (value, options) => { let currentValue = {} options.map((item) => { if (item.value === value && item.title) { currentValue = {label: item.title, value: value} } else if (item.value === value && item.label) { currentValue = {label: item.label, value: value} } }) return currentValue } } export default Input
import { useDispatch } from "react-redux"; function Item({ item }) { const dispatch = useDispatch(); const handleDelete = () => { dispatch({type: 'DELETE_ITEM', payload: item}) } return ( <div> <img src={item.image_url} alt="" /> <p>{item.description}</p> <button onClick={handleDelete}>Delete</button> </div> ); } export default Item;
const stars = document.querySelectorAll(".star"); const output = document.querySelector(".output"); for (x = 0; x < stars.length; x++) { stars[x].starValue=(x+1); ["click","mouseover","mouseout"].forEach(function(e){ stars[x].addEventListener(e,showRating); }) } function showRating(e){ let type = e.type; let starValue = this.starValue; if (type==="click") { if (starValue >=1) { output.innerHTML="You rated this "+starValue+" stars."; } } stars.forEach(function(elem,ind){ if (type==="click") { if (ind < starValue) {elem.classList.add("orange");} else{elem.classList.remove("orange");} } if (type==="mouseover") { if (ind < starValue) { elem.classList.add("yellow"); } else{elem.classList.remove("yellow"); } } if (type==="mouseout") {elem.classList.remove("yellow"); } }) } function nextPage(){ window.location.reload(); }
const alphabet = '23456789ABDEGJKMNPQRVWXYZ'; export function generateId(length = 6) { let id = ''; for (let i = 0; i < length; i++) { id += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); } return id; }
/** * Enomshop IPTV plugin for Showtime * * Copyright (C) 2019 Nphilipe * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ var _PAGE = require('showtime/page'); var _SERVICE = require('showtime/service'); var _SETTINGS = require('showtime/settings'); var _HTTP = require('showtime/http'); var _IO = require('native/io'); var _STRING = require('native/string'); var _HTML = require('showtime/html'); var PLUGIN = JSON.parse(Plugin.manifest); var LOGO = Plugin.path + PLUGIN.icon; function setPageHeader(page, title){ if (page.metadata){ page.metadata.title = title; page.metadata.logo = LOGO; } page.model.contents = 'grid'; page.type = "directory"; page.contents = "items"; } _SERVICE.create(PLUGIN.title, PLUGIN.id + ':start', 'tv', true, LOGO); _SETTINGS.globalSettings(PLUGIN.id, PLUGIN.title, LOGO, PLUGIN.synopsis); new _PAGE.Route(PLUGIN.id + ":start", function(page){ setPageHeader(page, PLUGIN.synopsis); page.loading = true; var _doc = showtime.JSONDecode(showtime.httpReq(PLUGIN.channels).toString()); var _channels = _doc.channels; if (_channels.length == 0){ page.loading = false; return false; } for (v in _channels){ item = _channels[v]; page.appendItem("videoparams:" + showtime.JSONEncode({ title: item.title, sources: item.sources, icon: Plugin.path + "logos/" + item.logo, no_fs_scan: true, no_subtitle_scan: true, }), "video", { title: item.title, icon: (item.logo), description: new showtime.RichText(item.description) }); } page.entries = _channels.length page.loading = false; })
import React from 'react'; const Post = (props) => { let post = props.post; const {snippet} = post; return ( <div className="post w-1/2 sm-w-1/3 md:w-1/4"> <div className="post-thumbnails"> <img src={snippet.thumbnails} alt=''/> </div> <div className="post-title"> {snippet.title} </div> </div> ) } export default Post;
/**Test data to be used for membership values, assume user have been registered earlier * --this will determine how long each user have been a member of the book club */ module.exports = { Users: [{ email: 'tobi_daramola@yahoo.com', createdAt: (new Date()) - (10 * 24 * 60 * 60 * 1000), //resgistered 10days earlier updatedAt: new Date() }, { email: 'hephzaron@gmail.com', createdAt: (new Date()) - (20 * 24 * 60 * 60 * 1000), // registered 20days earlier updatedAt: new Date() }, { email: 'adeyemiadekunle@gmail.com', createdAt: (new Date()) - (30 * 24 * 60 * 60 * 1000), // registered 30days earlier updatedAt: new Date() }], Genres: [{ name: 'Computer science', createdAt: new Date(), updatedAt: new Date() }, { name: 'World Government and Hstory', createdAt: new Date(), updatedAt: new Date() }, { name: 'Data Science', createdAt: new Date(), updatedAt: new Date() }], Books: [{ title: 'Java programming for beginners', genre_id: 1, description: 'Ths introduces readers to the basic of Obejct Oriented Programmng Language', ISBN: '33332-143-2457', quantity: 7, available: 7, createdAt: new Date(), updatedAt: new Date() }, { title: 'Fundamentals of Statistics for Data Scientist', genre_id: 3, description: 'Learn the fundamentals of big data analysis', ISBN: '12-70-894-53', quantity: 3, available: 3, createdAt: new Date(), updatedAt: new Date() }, { title: 'R - the tool for data science', genre_id: 3, description: 'R language is the most widely used language for data analysis..', ISBN: '102-70-8934-5757', quantity: 5, available: 5, createdAt: new Date(), updatedAt: new Date() }, { title: 'Advanced statistics', genre_id: 3, description: 'Learn statistics in a more advanced way', ISBN: '102-70-8934-5757', quantity: 2, available: 2, createdAt: new Date(), updatedAt: new Date() }], /**where returned is specified true, book has been returned otherwise book * is yet to be returned */ Borrowed: [{ userId: 1, bookId: 1, returned: true, createdAt: (new Date()) - (24 * 60 * 60 * 1000), // book borrowed a day earlier updatedAt: new Date() }, { userId: 1, bookId: 2, createdAt: new Date(), updatedAt: new Date() }, { userId: 2, bookId: 2, returned: true, createdAt: (new Date()) - (24 * 60 * 60 * 1000), // book borrowed a day earlier updatedAt: new Date() }, { userId: 2, bookId: 1, createdAt: new Date(), updatedAt: new Date() }, { userId: 2, bookId: 3, createdAt: new Date(), updatedAt: new Date() }, { userId: 3, bookId: 3, returned: true, createdAt: (new Date()) - (24 * 60 * 60 * 1000), // book borrowed a day earlier updatedAt: new Date() }, { userId: 3, bookId: 1, createdAt: new Date(), updatedAt: new Date() }, { userId: 3, bookId: 2, createdAt: new Date(), updatedAt: new Date() }, { userId: 3, bookId: 4, createdAt: new Date(), updatedAt: new Date() }] };
import fs from "fs"; import stringify from "json-stable-stringify"; import jsonminify from "jsonminify"; import path from "path"; function genSelectgroupFileName(id) { return `${encodeURIComponent(id.replaceAll(" ", "_"))}.geojson.json`; } /** * Process selectgroups by: * * - Spliting each selectgroup into its own file * - Minifying the resulting JSON * * Never throws, all errors are caught. * * @param {Object} options * @param {string} options.inputFilePath The input json file that contains all selectgroups * @param {string} options.outputFileBasePath The base path to which processed selectgroups will be * written */ export default async function datagenSelectgroups({ inputFilePath, outputFileBasePath }) { // Read single selectgroups file let selectgroups; try { selectgroups = await fs.promises.readFile(inputFilePath, "utf8"); selectgroups = JSON.parse(selectgroups); } catch (err) { console.error(`Error reading selectgroups: ${inputFilePath}: ${err.message}`); } // Write to separate selectgroup files await Promise.all( selectgroups.features.map(async (f) => { let selectgroup = { type: "FeatureCollection", name: "selectgroups", crs: { type: "name", properties: { name: "urn:ogc:def:crs:OGC:1.3:CRS84" } }, features: [f], }; selectgroup = stringify(selectgroup); selectgroup = jsonminify(selectgroup); const outputPath = path.join(outputFileBasePath, genSelectgroupFileName(f.properties.id)); try { await fs.promises.writeFile(outputPath, selectgroup); } catch (err) { console.error(`Error writing selectgroup ${f.properties.id}: ${err.message}`); } }) ); console.log("Wrote all selectgroups to separate geojson files"); }
({ checkUserRegistration: function (component, event, helper) { let assignmentRecId = component.get("v.recordId"); helper.callServer( component, "c.checkForLearningAssignment", function (isUserRegistered) { if (isUserRegistered === true) { helper.getAssignment(component, event, helper); } else { //Redirect to not registered screen var navEvt = $A.get("e.force:navigateToURL"); navEvt.setParams({ "url": "/not-registered-for-course", "isRedirect": true }); navEvt.fire(); } }, { learningAssignmentId: assignmentRecId }, false ); }, // get course intro getAssignment: function (component, event, helper) { let assignmentRecId = component.get("v.recordId"); helper.callServer( component, "c.getLearningAssignment", function (theAssignment) { //console.log(JSON.stringify(theAssignment)); if (theAssignment) { if (theAssignment.redwing__Training_Plan__c) { component.set("v.courseId", theAssignment.redwing__Training_Plan__c); } if (theAssignment.redwing__Learning__r.Name) { component.set("v.courseName", theAssignment.redwing__Learning__r.Name); //set browser tab name as course name helper.setPageName(component, event, helper); } } }, { learningAssignmentId: assignmentRecId } ); }, setPageName: function (component, event, helper) { let courseName = component.get("v.courseName"); // Set Title with replacing html entity "&amp;" with "&". document.title = courseName.replace(/&amp;/g, "&"); } })