text
stringlengths
7
3.69M
// HTTP status codes const HTTP_SUCCESS_RESPONSE = { OK: 200, CREATED: 201, ACCEPTED: 202, NO_CONTENT: 204, }; const HTTP_ERROR_RESPONSE = { BAD_REQUEST: 400, UN_AUTHORIZED: 401, FORBIDDEN: 403, NOT_FOUND: 404, CONFLICT: 409, INTERNAL_SERVER_ERROR: 500, BAD_GATEWAY: 502, }; // yup validator const STRIP_UNKNOWN = { stripUnknown: true }; // questions const PAGE_LIMIT = 10; module.exports = { HTTP_SUCCESS_RESPONSE, HTTP_ERROR_RESPONSE, STRIP_UNKNOWN, PAGE_LIMIT, };
OC.L10N.register( "settings", { "No user supplied" : "No se especificó un usuario", "Authentication error" : "Error de autenticación", "Wrong admin recovery password. Please check the password and try again." : "Contraseña de recuperación de administrador incorrecta. Por favor compruebe la contraseña e inténtelo de nuevo.", "Unable to change password" : "No se ha podido cambiar la contraseña", "Couldn't send reset email. Please contact your administrator." : "No se pudo enviar correo de restauración de contraseña. Por favor contacta a tu administrador.", "Group already exists." : "Este grupo ya existe.", "Unable to add group." : "No se pudo agregar el grupo.", "Unable to delete group." : "No se pudo eliminar el grupo.", "Saved" : "Guardado", "test email settings" : "probar configuración de correo", "Email sent" : "Correo electrónico enviado", "You need to set your user email before being able to send test emails." : "Necesitas establecer tu correo de usuario antes de poder enviar correos de prueba.", "Invalid mail address" : "Dirección de correo electrónico inválido.", "A user with that name already exists." : "Ya existe un usuario con ese nombre.", "Unable to create user." : "No se pudo crear usuario.", "Unable to delete user." : "No se pudo eliminar usuario.", "Forbidden" : "Prohibido", "Invalid user" : "Usuario inválido", "Unable to change mail address" : "No se pudo cambiar la dirección de correo electrónico", "Your full name has been changed." : "Se ha cambiado su nombre completo.", "Unable to change full name" : "No se puede cambiar el nombre completo", "Create" : "Crear", "Delete" : "Eliminar", "Share" : "Compartir", "Language changed" : "Idioma cambiado", "Invalid request" : "Petición no válida", "Admins can't remove themself from the admin group" : "Los administradores no se pueden eliminar a ellos mismos del grupo de administrador", "Couldn't remove app." : "No se pudo quitar la aplicación.", "Official" : "Oficial", "Approved" : "Aprobados", "All" : "Todos", "Enabled" : "Habilitado", "Not enabled" : "Deshabilitado", "No apps found for your version" : "No se encontraron aplicaciones en su versión.", "The app will be downloaded from the app store" : "La aplicación será descargada de la tienda de aplicaciones", "Official apps are developed by and within the ownCloud community. They offer functionality central to ownCloud and are ready for production use." : "Las aplicaciones oficiales son desarrolladas por y dentro de la comunidad ownCloud. Ofrecen funciones centrales a ownCloud y están listo para uso masivo.", "Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use." : "Las aplicaciones aprobadas son desarrolladas por desarrolladores confiables y han pasado una revisión obligatoria de seguridad. Se les da mantenimiento activamente en un repositorio de código abierto y sus administradores consideran estas aplicaciones como estables para uso casual a normal.", "This app is not checked for security issues and is new or known to be unstable. Install at your own risk." : "Esta aplicación no ha sido revisada en busca de problemas de seguridad y es nueva o se conoce que es inestable. Instálela bajo su propio riesgo.", "Please wait...." : "Espere, por favor....", "Error while disabling app" : "Error mientras se desactivaba la aplicación", "Disable" : "Deshabilitar", "Enable" : "Habilitar", "Error while enabling app" : "Error mientras se activaba la aplicación", "Updating...." : "Actualizando....", "Error while updating app" : "Error mientras se actualizaba la aplicación", "Updated" : "Actualizado", "Uninstalling ...." : "Desinstalando...", "Error while uninstalling app" : "Error al desinstalar aplicación", "Uninstall" : "Desinstalar", "Experimental" : "Experimental", "Migration in progress. Please wait until the migration is finished" : "Migración en proceso. Por favor espere hasta que la migración haya terminado.", "Migration started …" : "Migración iniciada...", "Disconnect" : "Desconectar", "Sending..." : "Enviando...", "Select a profile picture" : "Seleccionar una imagen de perfil", "Groups" : "Grupos", "undo" : "deshacer", "Delete group" : "Eliminar grupo", "never" : "nunca", "add group" : "añadir Grupo", "enabled" : "activado", "disabled" : "desactivado", "Changing the password will result in data loss, because data recovery is not available for this user" : "Cambiar la contraseña resultará en la pérdida de datos, porque la recuperación de datos no está disponible para este usuario", "A valid username must be provided" : "Se debe proporcionar un nombre de usuario válido", "A valid password must be provided" : "Se debe proporcionar una contraseña válida", "Cheers!" : "¡Saludos!", "Language" : "Idioma", "Cron" : "Cron", "Open documentation" : "Abrir documentación", "Execute one task with each page loaded" : "Ejecutar una tarea con cada página cargada", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php se registra en un servicio webcron para llamar a cron.php cada 15 minutos a través de HTTP.", "Server-side encryption" : "Encriptación del lado del servidor", "Be aware that encryption always increases the file size." : "Toma en cuenta que el cifrado siempre aumenta el tamaño de archivo.", "This is the final warning: Do you really want to enable encryption?" : "Ésta es el último aviso: ¿Realmente quieres habilitar el cifrado de archivos?", "Enable encryption" : "Habilitar cifrado", "Sharing" : "Compartiendo", "Allow apps to use the Share API" : "Permitir a las aplicaciones utilizar la API para Compartir", "Allow users to share via link" : "Permitir a los usuarios compatir mediante vínculos", "Allow public uploads" : "Permitir subidas públicas", "Set default expiration date" : "Establecer un periodo de expiración por defecto", "Expire after " : "Expirar después de ", "days" : "días", "Allow users to send mail notification for shared files" : "Permitir a los usuarios mandar notificaciones por correo para archivos compartidos", "Allow users to share file via social media" : "Permitir a los usuarios compartir archivos vía redes sociales", "Allow resharing" : "Permitir a usuarios compartir contenido de otros usuarios", "Allow sharing with groups" : "Permitir compartir con grupos", "Restrict users to only share with users in their groups" : "Restringir a usuarios para que solo puedan compartir con usuarios dentro de sus grupos", "Allow users to send mail notification for shared files to other users" : "Permitir a usuarios mandar notificaciones por correo para archivos compartidos por otros usuarios", "None" : "Ninguno", "Save" : "Guardar", "Everything (fatal issues, errors, warnings, info, debug)" : "Todo (Información, Avisos, Errores, debug y problemas fatales)", "Info, warnings, errors and fatal issues" : "Información, Avisos, Errores y problemas fatales", "Warnings, errors and fatal issues" : "Advertencias, errores y problemas fatales", "Errors and fatal issues" : "Errores y problemas fatales", "Fatal issues only" : "Problemas fatales solamente", "Log" : "Registro", "What to log" : "¿Qué cosas registrar?", "Download logfile (%s)" : "Descargar archivo de registro (%s)", "Login" : "Iniciar sesión", "SSL/TLS" : "SSL/TLS", "STARTTLS" : "STARTTLS", "Email server" : "Servidor de correo electrónico", "Encryption" : "Cifrado", "Authentication method" : "Método de autenticación", "Authentication required" : "Se necesita autenticación", "Server address" : "Dirección del servidor", "Port" : "Puerto", "Credentials" : "Credenciales", "SMTP Username" : "Nombre de usuario SMTP", "SMTP Password" : "Contraseña SMTP", "Store credentials" : "Almacenar credenciales", "Test email settings" : "Probar configuración de correo electrónico", "Send email" : "Enviar correo", "Security & setup warnings" : "Seguridad & alertas de configuración", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "No se ha encontrado el modulo PHP 'fileinfo'. Le recomendamos encarecidamente que habilite este módulo para obtener mejores resultados con la detección de tipos MIME.", "System locale can not be set to a one which supports UTF-8." : "No se puede escoger una configuración regional que soporte UTF-8.", "This means that there might be problems with certain characters in file names." : "Esto significa que puede haber problemas con ciertos caracteres en los nombres de los archivos.", "Get the apps to sync your files" : "Obtener las aplicaciones para sincronizar sus archivos", "Desktop client" : "Cliente de escritorio", "Show First Run Wizard again" : "Mostrar nuevamente el Asistente de ejecución inicial", "Domain" : "Dominio", "Add" : "Agregar", "Profile picture" : "Foto de perfil", "Upload new" : "Subir otra", "Remove image" : "Borrar imagen", "Cancel" : "Cancelar", "Email" : "Correo electrónico", "Your email address" : "Su dirección de correo", "Password" : "Contraseña", "Unable to change your password" : "No se ha podido cambiar su contraseña", "Current password" : "Contraseña actual", "New password" : "Nueva contraseña", "Change password" : "Cambiar contraseña", "Help translate" : "Ayúdanos a traducir", "Sessions" : "Sesiones", "Name" : "Nombre", "Username" : "Nombre de usuario", "Version" : "Versión", "New Password" : "Nueva contraseña", "Confirm Password" : "Confirmar contraseña", "Personal" : "Personal", "Admin" : "Administración", "Settings" : "Configuración", "E-Mail" : "Correo electrónico", "Admin Recovery Password" : "Recuperación de la contraseña de administración", "Enter the recovery password in order to recover the users files during password change" : "Introduzca la contraseña de recuperación a fin de recuperar los archivos de los usuarios durante el cambio de contraseña.", "Group" : "Grupo", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Por favor indique la cúota de almacenamiento (ej: \"512 MB\" o \"12 GB\")", "Unlimited" : "Ilimitado", "Other" : "Otro", "Full Name" : "Nombre completo", "change full name" : "cambiar el nombre completo", "set new password" : "establecer nueva contraseña", "Default" : "Predeterminado" }, "nplurals=2; plural=(n != 1);");
angular.module('weatherApp') .controller('weatherCtrl', function($scope, weatherService){ $scope.getLocation = function(){ weatherService.getLocation() .then(function(data){ $scope.loc = data; $scope.getWeather(data.lat, data.lon); $scope.getForecast(data.city); }); } $scope.getWeather = function(a, b){ weatherService.getWeather(a, b) .then(function(data){ $scope.weather = data; $scope.image = $scope.weather.image; $scope.currentTemp = $scope.weather.currentTemp; $scope.wind = $scope.weather.wind; $scope.humidity = $scope.weather.humid; }); } $scope.getForecast = function(city){ weatherService.getForecast(city) .then(function(data){ $scope.forecast = data; if(data.length == 4){ $scope.forecastLength = 'Four'; } else { $scope.forecastLength = 'Five'; } }); } $scope.getLocation(); });
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Axios from 'axios'; import Saved from './saved.js'; import Search from './search.js'; import Helpers from './utils/helpers.js'; class Main extends Component { constructor(){ super(); this.state = { searchResults: [], savedList: [] } } apiSearch = (subject, startDate, endDate) => { Helpers.queryApi(searchQuery, startDate, endDate) .then((res) =>{ //Get API JSON structure }); } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to the NYT React Search</h2> </div> <p className="App-intro"> </p> </div> ); } } export default Main;
// React Import import React from "react"; // // 1. JSX Imports import { NestedElements, Attribute, Expression, Styling } from './1. JSXelemets' // // 2. Components Imports import { StatelessExample } from './2. Statelesscomponent' import { StatefulExample } from './3. Statefulcomponent' // // 3. State Example import { StateExampleCheck, DerivedClass } from './4. StateExample' // import { Exstate } from './101. PracticeState' // 4.Props import { PropsExample, } from './5. CompenentandProps' import { Propsvalidation } from './6.PropsVadlidation' // 5. ComponentAPIlifecycle import { SetStateComponent } from './ComponentAPI/1.Setstate' import { ForceUpdate } from './ComponentAPI/2. Forceupdate' import { FindDOM } from "./ComponentAPI/3.FindDOM" // import { GenearalStatelifecycleMounting } from './ComponentAPI/5.GenearalStatelifecycleMounting' import { BasicRouting } from './Routing/1.BasicRouting' import { ParamsExample } from './Routing/2.URLparameters' import { NestingExample } from './Routing/3.NestingRoute' import { AuthExample } from './Routing/4.Redirect' import { Mounting } from './ComponentAPIlifecycle/Mounting/1. Mounting' import { Fragment } from './ComponentAPIlifecycle/Mounting/2.Fragments' import { Task } from "./ComponentAPI/6. MountUpdating" // EVent handling import { Toggle, ActionLink } from './Handlingevents/1.Events'; import { Childevent } from "./Handlingevents/2.Childevents"; // Form import { Form } from "./Forms/1.Firstform"; import { Complexform } from './Forms/2.Complexform'; // Refs import { Reference } from "./Forms/References/1.Refs" // import { Greeting } from "./Conditinalrendering/1. Condinatalrendering"; import { LoginControl } from "./Conditionalrendering/2.ElementVaribles"; import { Mailbox } from "./Conditionalrendering/3.Inlineeifhandoperator"; import { Inline, LoginControl2 } from "./Conditionalrendering/4.Inlineifelse"; import { Page } from "./Conditionalrendering/5.Preventcomprendering"; // list and keys import { listItems, element } from "./List And keys/1.Renderingmulcomp"; import { NumberList } from "./List And keys/2.Basiclist" import { listItems2, todoItems } from "./List And keys/3.Keys" import { NumberList3 } from "./List And keys/4.Extractingcompandkeys" import { Blog } from "./List And keys/5.Blogwithkey"; import { Usingstate } from "./List And keys/6.Usingstatespropsandkeys"; // Practice // import {Greeting} from 'C:\Users\Admin\Desktop\React\react_basic\src\Practice\1.Setstate.js' // import { Greeting } from './ComponentAPI/1.Setstate copy'; import { SetSE } from './Practice/1.Setstateobj'; // import { Setarray } from './Practice/2.StateEarray'; import { Setarrayofobjects } from './ComponentAPI/4.Setstatearrayobjects'; // // Material UI Imports // import { makeStyles } from "@material-ui/core/styles"; // import Box from '@material-ui/core/Box'; // import Button from '@material-ui/core/Button'; // // import BottomNavigation from "@material-ui/core/BottomNavigation"; // // import BottomNavigationAction from "@material-ui/core/BottomNavigationAction"; // // import RestoreIcon from "@material-ui/icons/Restore"; // // import FavoriteIcon from "@material-ui/icons/Favorite"; // // import LocationOnIcon from "@material-ui/icons/LocationOn"; // // makeStyles function from Material UI // // const useStyles = makeStyles({ // // root: { // // width: 500 // // }, // // label: { // // color: "red" // // } // // }); export default class App extends React.Component { constructor(props) { super(props); this.state = { header: "Header from state...", content: "Content from state..." } this.messages = ['React', 'Re: React', 'Re:Re: React']; } render() { // const messages = ['React', 'Re: React', 'Re:Re: React']; // // const classes = useStyles(); // // const [value, setValue] = React.useState(0); const numbers = [1, 2, 3, 4, 5]; const posts = [ { id: 1, title: 'Hello World', content: 'Welcome to learning React!' }, { id: 2, title: 'Installation', content: 'You can install React from npm.' } ]; return ( <div> {/* 1. JSX [JavaScript Extended] */} {/* 1.1 Nested Elements */} <NestedElements /> {/* 1.2 Attributes */} <Attribute /> {/* 1.3 Expression */} <Expression /> {/* 1.4 Styling */} <Styling /> {/* 2. Components */} {/* 2 Stateless Component */} <StatelessExample /> {/* 3.StatefulExample */} <StatefulExample /> {/* 3. State Example */} <h1>{this.state.header}</h1> <p>{this.state.content}</p> <StateExampleCheck /> <DerivedClass /> {/* 4. Props Example */} <h1>{this.props.headerProp}</h1> <h2>{this.props.footerProp}</h2> {/* 5. Default Props */} {/* <Exstate /> */} {/* props Example */} <PropsExample /> {/* 6. Propsvalidation */} <Propsvalidation /> {/* 7.ComponentAPIlifecycle */} {/*1. Setstatecomponent */} <SetStateComponent /> {/* Setarrayofobjects */} <Setarrayofobjects /> {/* 2. ForceUpdate */} <ForceUpdate /> <FindDOM /> {/* <Clock /> */} {/* Routing */} <BasicRouting /> <ParamsExample /> <NestingExample /> <AuthExample /> {/* Component APi Lifecycle */} {/* 1.Mounting */} <Mounting /> {/* 2.Fragment */} <Fragment /> {/* Mount Update */} {/* <Task /> */} {/* Handling events */} <Toggle /> <ActionLink /> {/* Forms */} <Form /> <Childevent /> <Complexform /> {/* refs */} <Reference /> {/* Conditonal */} {/* <Greeting isLoggedIn={true} /> */} <LoginControl /> <Mailbox unreadMessages={this.messages} /> <LoginControl2 /> <Page /> {/* list and keys */} <ul> {listItems} {element} </ul> <NumberList numbers={numbers} /> {/* keys */} <ul> {listItems2} {todoItems} </ul> <NumberList3 numbers={numbers} /> <Blog posts2={posts} /> <Usingstate /> {/* Practice */} {/* <Greeting /> */} <SetSE /> {/* <Setarray/> */} </div > ); } } App.defaultProps = { headerProp: "Suhail", footerProp: "Nadeem" }
import connectDb from "../../../utils/connectDb"; import User from "../../../models/User"; const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); connectDb(); const handler = async (req, res) => { switch (req.method) { case "POST": await handlePostRequest(req, res); break; default: res.status(405).send(`Method ${req.method} not allowed`); break; } }; // @route POST api/auth/login // @desc Authenticate account in db (username, email) // @res jwt // @access Public async function handlePostRequest(req, res) { connectDb(); const { email, password } = req.body; try { //check if user exists const user = await User.findOne({ email }).select("+password"); if (!user) { return res.status(401).send("Invalid Credentials"); } //verify credentials const passwordsMatch = await bcrypt.compare(password, user.password); //generate token if (passwordsMatch) { const payload = { user: { id: user.id, role: user.role, }, }; jwt.sign( payload, process.env.JWT_SECRET, { expiresIn: "7d" }, (err, token) => { if (err) throw err; res.status(200).json({ token }); } ); } else { res.status(401).send("Invalid Credentials"); } } catch (err) { console.error(err.message); res.status(500).send("Server Error"); } } export default handler;
import { Comment } from './comment.js'; const comments = []; // add eventListener function listenForClick(){ document.querySelector('#submit-comment').addEventListener('click', readComment); } // method to readComment function readComment() { return document.querySelector('#comment-area').value; } // method to add Comment function addComment(newComment, hikeId) { let brandNewComment = new Comment(newComment, hikeId); comments.push(brandNewComment); } // filterCommentsByHike function filterCommentsByHike(comments, hike) { // hike is a hikeId return comments.filter(comment => { comment.hikeId == hike; }) } // renderCommentList function renderCommentList(filteredComments) { let commentList = document.createElement('ul'); filteredComments.map(comment => { let li = document.createElement('li'); let date = document.createElement('p'); let content = document.createElement('p'); date.textContent = commment.Date; content.textContent = comment.comment; li.appendChild(date); li.appendChild(content); commentList.appendChild(li); }) document.querySelector("#commentsDiv").appendChild(commentList); }
//产品定制左边切换 $(function(){ $(".nodehead span").click(function(){ $(".nodeitem").hide(); $(this).removeClass("nodeshow").addClass("nodehide").parent().siblings().children("span").removeClass("nodehide").addClass("nodeshow"); $(this).parent().next().show(); }); //价格排序 var a=true; var arr1 = []; $(".wrapItem").each(function() { arr1.push($(this)); }); $("#price").click(function(){ for (var i = 0; i < arr1.length-1; i++) { for (var k = 0; k < arr1.length-1- i;k++){ if(parseInt(arr1[k].find(".n_price").text().split('¥')[1])>parseInt(arr1[k+1].find(".n_price").text().split('¥')[1])){ c=arr1[k]; arr1[k]=arr1[k+1]; arr1[k+1]=c; } } } if (a) { a = false; numSort1(arr1); $(this).css("color","red"); }else { a = true; numSort2(arr1); $(this).css("color","blue"); } }); function numSort1($aa) { $(".listWraper").empty(); for (var i = 0; i < $aa.length; i++) { $(".listWraper").append($aa[i]); } } function numSort2($aa) { $(".listWraper").empty(); for (var i = $aa.length; i > 0; i--) { $(".listWraper").append($aa[i]); } } //价格筛选 /*var arr2 = []; $(".interval").find("strong").click(function() { var $small = $(".b").val(); var $big = $(".i").val(); if ($small == "") { $small = 0; } if ($big == "") { $big = 100000; } $(".img1").find("dl").each(function() { if ($(this).find(".n_pri span").text().split('¥')[1] >= $small && $(this).find(".n_pri span").text().split('¥')[1] <= $big) { arr2.push($(this)); } }) $(".img1").empty(); $(".img1").append(arr2); });*/ //点击添加按钮 $(".selectwrap a").click(function(){ var t=$(this).html(); alert(t); var ap=$("<span style='background:red;'><a href='#'>t</a><a href='#'>×</a></span>|"); $("#aa").append(ap); $("#selectedlists").show(); $(this).parent().hide(); }) })
import http from 'axios'; export const getReposForUser=(userName)=>{ return http.get(`https://api.github.com/users/${userName}/repos`) .then((res) => { console.log(`in axios:${res}`); return res.data; }) .catch((err)=>{ console.log(`Returning error: ${err}`) return err; }) };
document.getElementById("button").onclick = function(){ let h = parseFloat(document.getElementById("height").value); let w = parseFloat(document.getElementById("weight").value); let bmi = document.getElementById("bmi"); //toFixed는 소수점 아래 매개변수자리까지만 반환해줌 bmi.innerHTML=(w/h/h).toFixed(1); };
import * as redux from 'redux'; import uuid from 'node-uuid'; import moment from 'moment'; // export var addExercise = name => { // return { // type: 'ADD_EXERCISE', // id: uuid(), // name: name, // sets_reps: [] // }; // }; export function addExercise(name) { const exercises_config = { method: 'PUT', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `bearer ${localStorage.getItem('id_token')}` }, body: `name=${name}` }; const workout_config = { method: 'POST', headers: { 'Authorization': `bearer ${localStorage.getItem('id_token')}` } }; return dispatch => { return fetch('http://localhost:8080/api/workouts', workout_config) .then(response => response.json()) .then(response => { return fetch(`http://localhost:8080/api/workouts/exercises/${response._id}`, exercises_config) .then(response => response.json()) .then(response => { console.log('asslick', response); }) .catch(err => new Error(err)); }) .catch(err => new Error(err)); }; } // export var saveWorkout = (state = [], action) => { // switch (action.type) { // case 'SAVE_WORKOUT': // return update(state, { // $push: [ // { // workoutLabel: action.workoutLabel, // date: action.date, // storedSession: [...state] // } // ] // }); // default: // return state; // } // }; export var createWorkout = name => { return { type: 'SAVE_WORKOUT', name, storedSessoin: [], date: moment().format('MMM Do YYYY') }; }; // export function createWorkout(name) { // const config = { // method: 'POST', // headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // body: `name=${name}` // }; // return dispatch => { // return fetch('http://localhost:8080/api/workouts', config) // .then(response => response.json()) // .then(response => { // if (!response.ok) { // Promise.reject(response); // } else { // Promise.resolve(response); // } // }) // .catch(err => new Error(err)); // }; // } export var addExerciseDetails = (id, weight, reps) => { return { type: 'ADD_EXERCISE_DETAILS', id: id, weight: weight, reps: reps }; }; export var openWorkout = id => { return { type: 'OPEN_WORKOUT', id: id }; }; export var createExercie = props => { return { type: 'CREATE_POST' }; }; // There are three possible states for our login // process and we need actions for each of them export const LOGIN_REQUEST = 'LOGIN_REQUEST'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'LOGIN_FAILURE'; function requestLogin(creds) { return { type: LOGIN_REQUEST, isFetching: true, isAuthenticated: false, creds }; } function receiveLogin(user) { return { type: LOGIN_SUCCESS, isFetching: false, isAuthenticated: true, id_token: user.id_token }; } function loginError(message) { return { type: LOGIN_FAILURE, isFetching: false, isAuthenticated: false, message }; } // Three possible states for our logout process as well. // Since we are using JWTs, we just need to remove the token // from localStorage. These actions are more useful if we // were calling the API to log the user out export const LOGOUT_REQUEST = 'LOGOUT_REQUEST'; export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; export const LOGOUT_FAILURE = 'LOGOUT_FAILURE'; function requestLogout() { return { type: LOGOUT_REQUEST, isFetching: true, isAuthenticated: true }; } function receiveLogout() { return { type: LOGOUT_SUCCESS, isFetching: false, isAuthenticated: false }; } // Calls the API to get a token and // dispatches actions along the way export function loginUser(creds) { const config = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=${creds.username}&password=${creds.password}` }; return dispatch => { // We dispatch requestLogin to kickoff the call to the API dispatch(requestLogin(creds)); return fetch('http://localhost:8080/auth/login', config) .then(response => response.json().then(user => ({ user, response }))) .then(({ user, response }) => { if (!response.ok) { // If there was a problem, we want to // dispatch the error condition dispatch(loginError(user.message)); return Promise.reject(user); } // If login was successful, set the token in local storage localStorage.setItem('id_token', user.token); // Dispatch the success action return dispatch(receiveLogin(user)); }) .catch(err => new Error(err)); }; } // Logs the user out export function logoutUser() { return dispatch => { dispatch(requestLogout()); localStorage.removeItem('id_token'); dispatch(receiveLogout()); }; }
import {fireStore} from '../../config/firebase.config.js'; import {auth} from '../../config/firebase.config.js'; class FirebaseRequests { createUserProfileDocument = async (userAuth, additionalData) => { if (!userAuth) return; const userRef = fireStore.doc(`users/${userAuth.uid}`); const snapShot = await userRef.get(); if (!snapShot.exists) { const { displayName, email } = userAuth; const createdAt = new Date(); try { await userRef.set({ displayName, email, createdAt, ...additionalData }); } catch (error) { throw new Error(error); } } return userRef; } signUp = () => { } signIn = async (email, password) => { try { await auth.signInWithEmailAndPassword(email, password); } catch (error) { throw new Error(error); } } getCurrentUser = () => { return new Promise((res,rej) => { const unsubscribe = auth.onAuthStateChanged( userAuth => { unsubscribe(); res(userAuth); }, rej) }) } } export const addCollectionAndDocuments = async (collectionKey, objectsToAdd) => { try { const collectionRef = fireStore.collection(collectionKey); const batch = fireStore.batch(); objectsToAdd.forEach((obj, index) =>{ const newDocRef = collectionRef.doc() batch.set(newDocRef, obj); }) return await batch.commit(); } catch (error) { console.log(error); } } export const convertCollectionsSnapshotToMap = (collections) => { const transformedCollections = collections.docs.map(doc => { const {title, items} = doc.data(); return { routeName: encodeURI(title), id: doc.id, title, items } }); return transformedCollections.reduce((acc, collection) => { acc[collection.title.toLowerCase()] = collection; return acc },{}) } export default new FirebaseRequests();
$(document).ready(function(){ $('.btn_upload_image').click(function(){ var img_count = $("#show_image_box img").length; if (img_count >=5) { showMsg("Chỉ được tải lên tối đa 5 hình ảnh cho mỗi sản phẩm!"); return false; } $('#hidden_file').click(); }); $('#hidden_file').fileupload({ dataType: 'json', sequentialUploads: true, start: function (e) { $("#modal-progress").modal("show"); }, stop: function (e) { $("#modal-progress").modal("hide"); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); var strProgress = progress + "%"; $(".progress-bar").css({"width": strProgress}); $(".progress-bar").text(strProgress); }, done: function (e, data) { if (data.result.success) { //$('.show_image_box').append(data.result.images); var img_count = $("#show_image_box img").length; //alert(img_count); if (img_count >= 5) { $('#show_image_box').append('<div class="img-hidden-box">'+data.result.images+'</div>'); }else{ $('#show_image_box').append(data.result.images); $('#show_image_box').first().removeClass('img-hidden-box'); $('.layshow-im12').first().removeClass('img-ubox-hidden'); } if (img_count >= 0) { $('.layshow-im12').first().removeClass('img-ubox-mas'); $('.layshow-im12').first().addClass('img-ubox-active'); } }else{ showMsg(data.result.message); } } }); }); $(document).ready(function(){ $('#show_image_box').on('click', '.btn-imgdel', function() { var url = $(this).attr('data-url'); var rfile = $(this).attr('data-id'); $.ajax({ url : url, type : 'POST', dataType :'json', cache : false, data: {'rfile':rfile}, success:function(res){ //alert(res.idImage); $("."+res.idImage).remove(); var img_count = $("#show_image_box img").length; if (img_count > 0) { $('.layshow-im12').first().removeClass('img-ubox-mas'); $('.layshow-im12').first().addClass('img-ubox-active'); if (img_count <= 4) { $('#show_image_box').removeClass('img-hidden-box'); $('.layshow-im12').first().removeClass('img-ubox-hidden'); } } }, error:function(res){ alert(res.rmessage); } }); }); }); $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap_unit"); //Fields wrapper var add_button = $(".add_field_button_unit"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x < max_fields){ //max input box allowed x++; //text box increment $(wrapper).append('<div class="form-group row"><div class="col-sm-12"><input type="text" name="unit[]" class="form-control" style="width: 200px;float:left;"><a href="#" class="remove_field_unit" style="float:left;">Remove</a></div></div>'); //add input box } }); $(wrapper).on("click",".remove_field_unit", function(e){ //user click on remove text e.preventDefault(); $(this).parent('div').remove(); x--; }) });
import React from 'react'; const IngredientSearch = () => { return ( <div> <form className='ingForm' onSubmit={() => {}}> <input type='text' className='inginput' name='ingredient' required /> <button className='ingbutton' type='submit'> Add </button> </form> </div> ); }; export default IngredientSearch;
import axios from "./axios"; const url = "/api/objects"; async function fetch(params) { const {data} = await axios.get(url, {params}); return data; } async function remove(params) { const {data} = await axios.delete(url, {params}); return data; } export default { fetch, remove, };
import "test-case.jsx"; import "js/nodejs.jsx"; class _Test extends TestCase { // NodeJS build-in modules function testProcess() : void { var t0 = process.hrtime(); var cwd = process.cwd(); this.expect(cwd).notToBe(""); this.expect(process.stdin.fd, "stdin.fd").toBeGE(0); this.expect(process.stdout.fd, "stdout.fd").toBeGE(0); this.expect(process.stderr.fd, "stderr.fd").toBeGE(0); var elapsed = process.hrtime(t0); var seconds = elapsed[0] + elapsed[1] / 1e9; //this.note("hrtime: " + seconds as string + " [sec]"); this.expect(seconds).toBeGE(0); } function testBuffer() : void { this.expect(Buffer.byteLength("foo", "ascii"), "Buffer.byteLength").toBe(3); this.expect(Buffer.byteLength("foo", "utf8"), "Buffer.byteLength").toBe(3); this.expect(Buffer.concat([new Buffer("foo", "utf8"), new Buffer("bar", "utf8")]).toString(), "Buffer.concat").toBe("foobar"); this.expect(Buffer.concat([new Buffer("foo", "utf8"), new Buffer("bar", "utf8")], 5).toString(), "Buffer.concat").toBe("fooba"); var b = new Buffer(3); b.write("foo", 0, 3, "ascii"); this.expect(b.length, "length").toBe(3); this.expect(b.toString(), "toString()").toBe("foo"); this.expect(b.toString("utf8"), "toString(encoding)").toBe("foo"); this.expect(b.toString("utf8", 1), "toString(encoding, start)").toBe("oo"); this.expect(b.toString("utf8", 0, 2), "toString(encoding, start, end)").toBe("fo"); this.expect(b.slice(1).toString(), "slice").toBe("oo"); this.expect(b.slice(0, 2).toString(), "slice").toBe("fo"); (new Buffer("bar", "utf8")).copy(b); this.expect(b.toString(), "copy").toBe("bar"); var b2 = new Buffer(1024); b2.writeUInt8(0, 0); this.expect(b2.readUInt8(0), "read/write").toBe(0); b2.writeUInt8(0xff, 1); this.expect(b2.readUInt8(1)).toBe(0xff); b2.writeUInt16LE(0, 2); this.expect(b2.readUInt16LE(2)).toBe(0); b2.writeUInt16LE(0xffff, 4); this.expect(b2.readUInt16LE(4)).toBe(0xffff); b2.writeUInt16BE(0, 6); this.expect(b2.readUInt16BE(6)).toBe(0); b2.writeUInt16BE(0xffff, 8); this.expect(b2.readUInt16BE(8)).toBe(0xffff); b2.writeUInt32LE(0, 10); this.expect(b2.readUInt32LE(10)).toBe(0); b2.writeUInt32LE(0xffffffff, 14); this.expect(b2.readUInt32LE(14)).toBe(0xffffffff); b2.writeUInt32BE(0, 18); this.expect(b2.readUInt32BE(18)).toBe(0); b2.writeUInt32BE(0xffffffff, 22); this.expect(b2.readUInt32BE(22)).toBe(0xffffffff); b2.writeInt8(0, 26); this.expect(b2.readInt8(26)).toBe(0); b2.writeInt8(0x7f, 27); this.expect(b2.readInt8(27)).toBe(0x7f); b2.writeInt8(-0x80, 28); this.expect(b2.readInt8(28)).toBe(-0x80); b2.writeInt16LE(0, 29); this.expect(b2.readInt16LE(29)).toBe(0); b2.writeInt16LE(0x7fff, 31); this.expect(b2.readInt16LE(31)).toBe(0x7fff); b2.writeInt16LE(-0x8000, 33); this.expect(b2.readInt16LE(33)).toBe(-0x8000); b2.writeInt16BE(0, 35); this.expect(b2.readInt16BE(35)).toBe(0); b2.writeInt16BE(0x7fff, 37); this.expect(b2.readInt16BE(37)).toBe(0x7fff); b2.writeInt16BE(-0x8000, 39); this.expect(b2.readInt16BE(39)).toBe(-0x8000); b2.writeInt32LE(0, 41); this.expect(b2.readInt32LE(41)).toBe(0); b2.writeInt32LE(0x7fffffff, 45); this.expect(b2.readInt32LE(45)).toBe(0x7fffffff); b2.writeInt32LE(-0x80000000, 49); this.expect(b2.readInt32LE(49)).toBe(-0x80000000); b2.writeInt32BE(0, 53); this.expect(b2.readInt32BE(53)).toBe(0); b2.writeInt32BE(0x7fffffff, 57); this.expect(b2.readInt32BE(57)).toBe(0x7fffffff); b2.writeInt32BE(-0x80000000, 61); this.expect(b2.readInt32BE(61)).toBe(-0x80000000); b2.writeFloatLE(0.0625, 65); this.expect(b2.readFloatLE(65)).toBe(0.0625); b2.writeFloatBE(0.0625, 69); this.expect(b2.readFloatBE(69)).toBe(0.0625); b2.writeDoubleLE(Math.PI, 73); this.expect(b2.readDoubleLE(73)).toBe(Math.PI); b2.writeDoubleBE(Math.E, 81); this.expect(b2.readDoubleBE(81)).toBe(Math.E); var b3 = new Buffer(5); b3.fill(0x10); this.expect(b3.readUInt8(0), "fill").toBe(0x10); this.expect(b3.readUInt8(4)).toBe(0x10); b3.fill(0x20, 1); this.expect(b3.readUInt8(0)).toBe(0x10); this.expect(b3.readUInt8(1)).toBe(0x20); this.expect(b3.readUInt8(4)).toBe(0x20); b3.fill(0x30, 2, 4); this.expect(b3.readUInt8(0)).toBe(0x10); this.expect(b3.readUInt8(1)).toBe(0x20); this.expect(b3.readUInt8(2)).toBe(0x30); this.expect(b3.readUInt8(3)).toBe(0x30); this.expect(b3.readUInt8(4)).toBe(0x20); } // NodeJS standard modules function testFS() : void { var dir = node.__dirname; var st = node.fs.statSync(dir); this.expect(st.isDirectory()).toBe(true); var tmpFile = dir + '.test.tmp'; node.fs.writeFileSync(tmpFile, 'test1\n'); node.fs.appendFileSync(tmpFile, 'test2\n'); var content = node.fs.readFileSync(tmpFile, 'utf-8'); this.expect(content).toBe('test1\ntest2\n'); node.fs.unlinkSync(tmpFile); var exists = node.fs.existsSync(tmpFile); this.expect(exists).toBe(false); } function testUrl() : void { var url = node.url.parse("http://example.com/foo/bar?k=x&k=y#here"); this.expect(url.protocol).toBe("http:"); this.expect(url.host).toBe("example.com"); this.expect(url.hash).toBe("#here"); this.expect(url.query).toBe("k=x&k=y"); this.expect(url.pathname).toBe("/foo/bar"); this.expect(node.url.resolve("/foo/bar", "baz")).toBe("/foo/baz"); } function testPath() : void { var path = "/foo/bar/baz.txt"; this.expect(node.path.normalize(path)).toBe("/foo/bar/baz.txt"); this.expect(node.path.join('/foo', 'bar', 'baz/asdf', 'auux', '..')).toBe('/foo/bar/baz/asdf'); this.expect(node.path.resolve('/foo/bar', './baz')).toBe('/foo/bar/baz'); this.expect(node.path.resolve('/foo/bar', '/tmp/file/')).toBe('/tmp/file'); this.expect(node.path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')).toBe(process.cwd() + '/wwwroot/static_files/gif/image.gif'); this.expect(node.path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')).toBe('../../impl/bbb'); this.expect(node.path.dirname(path)).toBe("/foo/bar"); this.expect(node.path.basename(path)).toBe("baz.txt"); this.expect(node.path.basename(path, '.txt')).toBe("baz"); this.expect(node.path.extname('index.html')).toBe('.html'); this.expect(node.path.extname('index.')).toBe('.'); this.expect(node.path.extname('index')).toBe(''); this.expect(['/', '\\'].indexOf(node.path.sep) != -1).toBe(true); } function testHttpServer() : void { if (true) return; // SKIP var port = 4321; // TODO: find an empty port correctly this.async((async) -> { process.nextTick(() -> { this.pass("requesting"); node.http.get("http://localhost:"+port.toString()+"/foo/bar", (res) -> { this.expect(res.statusCode, "http request to myself").toBe(200); async.done(); }).on("error", (arg) -> { var error = arg as Error; this.fail("HTTP request error: " + error.toString()); async.done(); });; }); var httpd : HTTPServer = null; httpd = node.http.createServer((req, res) -> { this.expect(req.url, "accept a request").toBe("/foo/bar"); res.writeHead(200, { "content-type" : "text/plain" }); res.write("ok", "utf8"); res.end(); httpd.close(); }); httpd.listen(port); this.pass("listen " + port.toString()); }, 4000); } } // vim: set tabstop=2 shiftwidth=2 expandtab:
import { expect, sinon } from '../../test-helper' import chapterRepository from '../../../src/domain/repositories/chapter-repository' import { Newchapter } from '../../../src/domain/models/index' import chapterOfArticleSaved from '../../fixtures/chapterOfArticleSaved' import chapterOfArticleToSave from '../../fixtures/chapterOfArticleToSave' describe('Unit | Repository | chapter-repository', () => { let chaptersOfArticleToSave let savedChaptersOfArticle let sortedChaptersOfArticle beforeEach(() => { chaptersOfArticleToSave = [chapterOfArticleToSave(), chapterOfArticleToSave()] savedChaptersOfArticle = [chapterOfArticleSaved(99), chapterOfArticleSaved(1)] sortedChaptersOfArticle = [chapterOfArticleSaved(1), chapterOfArticleSaved(99)] }) describe('#createArticleChapters', () => { beforeEach(() => { sinon.stub(Newchapter, 'bulkCreate') }) afterEach(() => { Newchapter.bulkCreate.restore() }) it('should call Sequelize Model#bulkCreate', () => { // given Newchapter.bulkCreate.resolves(savedChaptersOfArticle) // when const promise = chapterRepository.createArticleChapters(chaptersOfArticleToSave) // then return promise.then(res => { expect(Newchapter.bulkCreate).to.have.been.called expect(res).to.deep.equal(savedChaptersOfArticle) }) }) }) describe('#getChaptersOfArticle', () => { const dropboxId = 47 beforeEach(() => { sinon.stub(Newchapter, 'findAll').resolves(savedChaptersOfArticle) }) afterEach(() => { Newchapter.findAll.restore() }) it('should call Sequelize Model#findAll', () => { // when const promise = chapterRepository.getChaptersOfArticle(dropboxId) // then return promise.then(res => { expect(Newchapter.findAll).to.have.been.calledWith({ where: { dropboxId } }) expect(res).to.deep.equal(sortedChaptersOfArticle) }) }) }) describe('#deleteChaptersOfArticle', () => { const dropboxId = 47 beforeEach(() => { sinon.stub(Newchapter, 'destroy').resolves() }) afterEach(() => { Newchapter.destroy.restore() }) it('should call Sequelize Model#destroy', () => { // when const promise = chapterRepository.deleteChaptersOfArticle(dropboxId) // then return promise.then(() => { expect(Newchapter.destroy).to.have.been.calledWith({ where: { dropboxId } }) }) }) }) describe('#deleteChapterOfArticle', () => { const dropboxId = 47 const position = 2 beforeEach(() => { sinon.stub(Newchapter, 'destroy').resolves() }) afterEach(() => { Newchapter.destroy.restore() }) it('should call Sequelize Model#destroy', () => { // when const promise = chapterRepository.deleteChapterOfArticle(dropboxId, position) // then return promise.then(() => { expect(Newchapter.destroy).to.have.been.calledWith({ where: { dropboxId, position } }) }) }) }) })
function getLatestVisitTime(historyResults = []) { const latestVisitSites = historyResults.flat() if (latestVisitSites.length === 0) { return false } const timestamps = latestVisitSites .map(item => item.visitTime) .sort((a, b) => a - b) return timestamps[timestamps.length - 1] } function getLongestStreak(historyResults = []) { const latestVisitSites = historyResults.flat() if (latestVisitSites.length < 2) { return false } const timestamps = latestVisitSites .map(item => item.visitTime) .sort((a, b) => a - b) let streak = { diff: 0, firstTimestamp: 0, secondTimestamp: 0, startOfRecording: timestamps[0], } for (let i = 0; i < timestamps.length; i++) { const currentTimestamp = timestamps[i] const nextTimestamp = timestamps[i + 1] const diff = nextTimestamp - currentTimestamp if (diff > streak.diff) { streak.diff = diff streak.firstTimestamp = currentTimestamp streak.secondTimestamp = nextTimestamp } } return streak } export { getLatestVisitTime, getLongestStreak }
import { useEffect, useState } from "react"; const useLocalStorage = (key, initialState) => { const [values, setValues] = useState( () => JSON.parse(window.localStorage.getItem(key)) || initialState ); useEffect(() => { if (values) { window.localStorage.setItem(key, JSON.stringify(values)); } }, [values, key]); return { values, setValues }; }; export default useLocalStorage;
import Backgrid from 'backgrid'; import 'igui_root/node_modules/backgrid-select-all/backgrid-select-all'; // override code from backgrid-select-all.js // Support for models/rows that are disabled from being 'selectable' export default Backgrid.Extension.SelectAllHeaderCell.extend({ render: function () { this.$el.empty().append('<label class="black-checkbox"><input tabindex="-1" type="checkbox" /><span></span></label>'); this.delegateEvents(); return this; } });
import { WebglBuffer } from "./webgl-buffer.js"; /** * A WebGL implementation of the VertexBuffer. * * @ignore */ class WebglVertexBuffer extends WebglBuffer { // vertex array object vao = null; destroy(device) { super.destroy(device); // clear up bound vertex buffers device.boundVao = null; device.gl.bindVertexArray(null); } loseContext() { super.loseContext(); this.vao = null; } unlock(vertexBuffer) { const device = vertexBuffer.device; super.unlock(device, vertexBuffer.usage, device.gl.ARRAY_BUFFER, vertexBuffer.storage); } } export { WebglVertexBuffer };
// `--init` initialize the project `-i` as shortcut const fs = require('fs') const path = require('path') const { prompt } = require('inquirer'); const json2file = require('./json2file') /* * initialize a new REST API project * <name> for the project name * <description> description of the project * <version> version of the project * <author> the author * <license> the license * <database> the database to use i.e: MongoDB, MySQL, ProsgreSQL etc.. */ const init = () => { // la liste de questions à poser pour initialiser le projet // demander les informations sur le projet const questions = [ { type: 'input', name: 'name', message: 'Enter the project name' }, { type: 'input', name: 'description', message: 'Enter the project description' }, { type: 'input', name: 'author', message: 'Author' }, { type: 'input', name: 'license', message: 'License' }, { type: 'rawlist', name: 'database', message: 'Which database would you like to use?', choices: ['MongoDB', 'MySQL'] } ] prompt(questions).then((answers) => { // create the directory that contains the project // récupérer le chemin du dossier dans lequel on se trouve const rootDirPath = process.cwd() const projectStructure = { "project-name": ["controllers", "helpers", "models", "routes"] } json2file.linearStructure(rootDirPath, projectStructure) // create the `package.json` file fs.writeFileSync('./project-name/package.json', JSON.stringify(answers, null, 2), (err) => { if (err) throw err }) // add it to the project directory console.log(answers) }) } module.exports = init;
define(['myapp/engine', 'myapp/brakes'], function() { return function Car(myapp_Engine, myapp_Brakes) { this.engine = myapp_Engine; this.brakes = myapp_Brakes; this.toString = function() { return 'sportsCar(' + this.engine + ', ' + this.brakes + ')'}; }; });
String.prototype.clr = function (hexColor){ return `<font color='#${hexColor}'>${this}</font>` }; module.exports = function TerableCrafter(mod) { let petInfo = 0n, cycle = false, timeout; mod.command.add(['terac', 'tcraft'], { $none() { if (!petInfo) return; mod.send('C_START_SERVANT_ACTIVE_SKILL', 1, { gameId: petInfo.gameId, id: 5024 }); }, cycle(){ if(petInfo){ cycle = !cycle; mod.command.message(`Cycling TCraft is now ${cycle ? "enabled".clr("00FF00") : "disabled".clr("FF0000")}.`); clearInterval(timeout); if(!cycle) return; mod.send('C_START_SERVANT_ACTIVE_SKILL', 1, { gameId: petInfo.gameId, id: 5024 }); timeout = setInterval(() => { if(petInfo){ mod.send('C_START_SERVANT_ACTIVE_SKILL', 1, { gameId: petInfo.gameId, id: 5024 }); } }, 270000); // reapply every 4.5 mins } else{ cycle = false; mod.command.message(`No servant spawned. Cycling TCraft Disabled`.clr("FF0000")); } } }); mod.hook('S_REQUEST_SPAWN_SERVANT', 1, event => { if (mod.game.me.is(event.ownerId)) { petInfo = event; } }); mod.hook('S_REQUEST_DESPAWN_SERVANT', 1, event => { if (petInfo && petInfo.gameId == event.gameId) { petInfo = null; } }); };
import React, { Component } from 'react'; import { View, Text, TouchableOpacity, TextInput, StyleSheet, Dimensions } from 'react-native'; import axios from 'axios'; import { connect } from 'react-redux'; import { fetchAll } from '../../actions'; const _margin = 30; const _borderRadius = 8; const _width = Dimensions.get('window').width - _margin * 2; const _height = 70; class NewClass extends Component { static navigationOptions = { header: null }; constructor(props) { super(props); this.state = { title: '', desc: '', color: '#E8384F' }; } _createNewClass = async () => { try { const response = await axios.post( 'http://127.0.0.1:8080/fileManage/createCourse', { desc: this.state.title, color: this.state.color, name: this.state.desc } ); await this.props.fetchAll(); await console.log(response.data); await this.props.navigation.goBack(); } catch (error) { console.log(error); } }; render() { return ( <View style={styles.container}> <View style={styles.headerContainer}> <TouchableOpacity style={styles.returnButton} onPress={() => this.props.navigation.goBack()} > <Text style={styles.returnButtonText}>Return</Text> </TouchableOpacity> <Text style={styles.header}>New Class</Text> <TouchableOpacity style={styles.nextButton} onPress={this._createNewClass} > <Text style={styles.nextButtonText}>Create</Text> </TouchableOpacity> </View> <TouchableOpacity style={[ styles.demoContainer, { backgroundColor: this.state.color } ]} > <View> <Text style={styles.demoTitle}> {this.state.desc || 'Course Number'} </Text> <Text style={styles.demoDesc}> {this.state.title || 'Course Description'} </Text> </View> </TouchableOpacity> <TextInput style={styles.titleInput} placeholder="Title" onChangeText={desc => this.setState({ desc })} value={this.state.desc} returnKeyType="next" onSubmitEditing={() => { this.secondTextInput.focus(); }} blurOnSubmit={false} autoFocus={true} /> {/* <Image style={styles.image} source={{ uri: 'https://upload.wikimedia.org/wikipedia/en/3/33/Silicon_valley_title.png' }} /> */} <TextInput ref={input => { this.secondTextInput = input; }} style={styles.descInput} placeholder="Description" onChangeText={title => this.setState({ title })} value={this.state.title} //multiline={true} /> <View style={styles.paletteContainer}> <TouchableOpacity style={[styles.palette, { backgroundColor: '#E8384F' }]} onPress={() => this.setState({ color: '#E8384F' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#EA4E9D' }]} onPress={() => this.setState({ color: '#EA4E9D' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#FD612C' }]} onPress={() => this.setState({ color: '#FD612C' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#FD9A00' }]} onPress={() => this.setState({ color: '#FD9A00' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#EECC16' }]} onPress={() => this.setState({ color: '#EECC16' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#FFDD2B' }]} onPress={() => this.setState({ color: '#FFDD2B' })} /> </View> <View style={styles.paletteContainer}> <TouchableOpacity style={[styles.palette, { backgroundColor: '#62BB35' }]} onPress={() => this.setState({ color: '#62BB35' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#37A862' }]} onPress={() => this.setState({ color: '#37A862' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#20AAEA' }]} onPress={() => this.setState({ color: '#20AAEA' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#4186E0' }]} onPress={() => this.setState({ color: '#4186E0' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#7A6FF0' }]} onPress={() => this.setState({ color: '#7A6FF0' })} /> <TouchableOpacity style={[styles.palette, { backgroundColor: '#AA62E3' }]} onPress={() => this.setState({ color: '#AA62E3' })} /> </View> </View> ); } } export default connect( null, { fetchAll } )(NewClass); const styles = StyleSheet.create({ container: { flex: 1, padding: 30, paddingTop: 45, backgroundColor: '#FFFFFF' }, headerContainer: { flexDirection: 'row', justifyContent: 'center', // horizontal center, marginBottom: 15 }, header: { fontFamily: 'Avenir Next', fontSize: 22, fontWeight: '600' }, nextButton: { backgroundColor: '#EFEFEF', position: 'absolute', padding: 5, paddingLeft: 10, paddingRight: 10, borderRadius: 100, top: 0, right: 0 }, nextButtonText: { fontFamily: 'Avenir Next', fontSize: 16, fontWeight: '600' }, returnButton: { backgroundColor: '#EFEFEF', position: 'absolute', padding: 5, paddingLeft: 10, paddingRight: 10, borderRadius: 100, top: 0, left: 0 }, returnButtonText: { fontFamily: 'Avenir Next', fontSize: 16, fontWeight: '600' }, titleInput: { height: 40, borderWidth: 0, fontFamily: 'Avenir Next', fontWeight: '600', fontSize: 20, marginTop: -2.5 //marginTop: 5, //marginBottom: 2 }, descInput: { borderWidth: 0, fontFamily: 'Avenir Next', fontWeight: '500', fontSize: 18, //marginTop: 2, marginBottom: 12.5 }, image: { height: 200, borderRadius: 10 }, demoContainer: { width: _width, height: _height, borderRadius: _borderRadius, marginTop: 15, marginBottom: 10, shadowOpacity: 0.125, shadowRadius: 5, shadowColor: 'black', shadowOffset: { height: 2, width: 2 } }, demoTitle: { fontSize: 20, fontFamily: 'Avenir Next', color: 'white', fontWeight: '600', margin: 10, marginBottom: 0 }, demoDesc: { fontSize: 14, fontFamily: 'Avenir Next', color: 'white', marginLeft: 10, marginRight: 10, fontWeight: '600' }, paletteContainer: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end', //paddingHorizontal: '6%', paddingTop: '4%' }, palette: { height: 40, width: 40, borderRadius: 20, backgroundColor: 'red' } });
const express = require("express"); const PORT = 5000; const MONGODBURI = "mongodb://localhost:27017/Dashboard"; const connectDB = require("./utils/db"); const session = require("express-session"); const MongoDBStore = require("connect-mongodb-session")(session); const flash = require("connect-flash"); const app = express(); app.set("view engine", "ejs"); app.use(express.json({ extended: false })); app.use(express.urlencoded({ extended: false })); app.use(express.static("public")); const store = new MongoDBStore({ uri: MONGODBURI, collection: "sessions", }); app.use( session({ secret: "this app", resave: false, saveUninitialized: false, store: store, }) ); //for flash msg app.use(flash()); // Defining Routes // routes for auth app.use("/", require("./routes/admin/auth")); // admin product route app.use("/admin/product", require("./routes/admin/products")); // admin employee route app.use("/admin/employee", require("./routes/admin/employee")); // admin device route app.use("/admin/device", require("./routes/admin/device")); app.use("/billing/device-dashboard", require("./routes/billing")); // for screen app.use("/screen", require("./routes/screen")); // for adding a main admin user const addUser = require("./add-main-user"); // connecting DB connectDB(MONGODBURI); const server = app.listen(PORT, () => { console.log(`Server started at http://localhost:${PORT}`); addUser(); }); const io = require("./socket").init(server); io.on("connection", (socket) => { console.log("Socket Connected"); });
// @flow strict import * as React from 'react'; import { graphql, createFragmentContainer } from '@kiwicom/mobile-relay'; import { TextIcon } from '@kiwicom/mobile-shared'; import { Translation } from '@kiwicom/mobile-localization'; import TimelineRow from './TimelineRow'; import type { TimelineTerminal as TimelineTerminalType } from './__generated__/TimelineTerminal.graphql'; type Props = {| +icon: React.Element<typeof TextIcon>, +data: TimelineTerminalType, |}; const TimelineTerminal = ({ data, icon }: Props) => { const terminal = data.terminal; const iata = data.airport?.code ?? ''; const city = data.airport?.city?.name ?? ''; if (terminal == null) { return null; } return ( <TimelineRow icon={icon} value={ <Translation id="mmb.flight_overview.timeline.terminal" values={{ terminal, city, iata, }} /> } /> ); }; export default createFragmentContainer( TimelineTerminal, graphql` fragment TimelineTerminal on RouteStop { terminal airport { code city { name } } } `, );
var express = require('express'), app = express(), port = process.env.PORT || 4114, Question = require('./api/models/question'), Result = require('./api/models/result'), bodyParser = require('body-parser'); app.set('view engine', 'ejs'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var apiRoutes = require('./api/routes'); apiRoutes(app); app.listen(port); console.log('todo list RESTful API server started on: ' + port);
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; var _excluded = ["aria", "bounceEnabled", "children", "classes", "direction", "disabled", "height", "inertiaEnabled", "onBounce", "onEnd", "onPullDown", "onReachBottom", "onScroll", "onStart", "onStop", "onUpdated", "pullDownEnabled", "pulledDownText", "pullingDownText", "reachBottomEnabled", "reachBottomText", "refreshingText", "rtlEnabled", "scrollByContent", "scrollByThumb", "showScrollbar", "updateManually", "useKeyboard", "useNative", "useSimulatedScrollbar", "visible", "width"]; import { createComponentVNode, normalizeProps } from "inferno"; import { InfernoWrapperComponent } from "@devextreme/vdom"; import { current, isMaterial } from "../../../ui/themes"; import { isDefined } from "../../../core/utils/type"; import { Scrollable, defaultOptionRules } from "./scrollable"; import { BaseWidgetProps } from "../common/base_props"; import { ScrollableProps } from "./scrollable_props"; import { WidgetProps } from "../common/widget"; import { ScrollableSimulatedProps } from "./scrollable_simulated_props"; export var viewFunction = viewModel => { var { props: { aria, bounceEnabled, children, direction, disabled, height, inertiaEnabled, onBounce, onEnd, onPullDown, onReachBottom, onScroll, onStart, onStop, onUpdated, pullDownEnabled, reachBottomEnabled, rtlEnabled, scrollByContent, scrollByThumb, showScrollbar, updateManually, useKeyboard, useNative, useSimulatedScrollbar, visible, width }, pulledDownText, pullingDownText, reachBottomText, refreshingText, restAttributes, scrollableRef } = viewModel; return normalizeProps(createComponentVNode(2, Scrollable, _extends({ "useNative": useNative, "classes": "dx-scrollview", "aria": aria, "width": width, "height": height, "disabled": disabled, "visible": visible, "rtlEnabled": rtlEnabled, "direction": direction, "showScrollbar": showScrollbar, "scrollByThumb": scrollByThumb, "updateManually": updateManually, "pullDownEnabled": pullDownEnabled, "reachBottomEnabled": reachBottomEnabled, "onScroll": onScroll, "onUpdated": onUpdated, "onPullDown": onPullDown, "onReachBottom": onReachBottom, "pulledDownText": pulledDownText, "pullingDownText": pullingDownText, "refreshingText": refreshingText, "reachBottomText": reachBottomText, "forceGeneratePockets": true, "needScrollViewContentWrapper": true, "needScrollViewLoadPanel": true, "useSimulatedScrollbar": useSimulatedScrollbar, "inertiaEnabled": inertiaEnabled, "bounceEnabled": bounceEnabled, "scrollByContent": scrollByContent, "useKeyboard": useKeyboard, "onStart": onStart, "onEnd": onEnd, "onBounce": onBounce, "onStop": onStop }, restAttributes, { children: children }), null, scrollableRef)); }; export var ScrollViewProps = _extends({}, ScrollableProps); var ScrollViewPropsType = { useNative: ScrollableProps.useNative, direction: ScrollableProps.direction, showScrollbar: ScrollableProps.showScrollbar, bounceEnabled: ScrollableProps.bounceEnabled, scrollByContent: ScrollableProps.scrollByContent, scrollByThumb: ScrollableProps.scrollByThumb, updateManually: ScrollableProps.updateManually, pullDownEnabled: ScrollableProps.pullDownEnabled, reachBottomEnabled: ScrollableProps.reachBottomEnabled, aria: WidgetProps.aria, disabled: BaseWidgetProps.disabled, visible: BaseWidgetProps.visible, inertiaEnabled: ScrollableSimulatedProps.inertiaEnabled, useKeyboard: ScrollableSimulatedProps.useKeyboard }; import { convertRulesToOptions } from "../../../core/options/utils"; import { createRef as infernoCreateRef } from "inferno"; export class ScrollView extends InfernoWrapperComponent { constructor(props) { super(props); this.state = {}; this.scrollableRef = infernoCreateRef(); this.update = this.update.bind(this); this.release = this.release.bind(this); this.refresh = this.refresh.bind(this); this.content = this.content.bind(this); this.scrollBy = this.scrollBy.bind(this); this.scrollTo = this.scrollTo.bind(this); this.scrollToElement = this.scrollToElement.bind(this); this.scrollHeight = this.scrollHeight.bind(this); this.scrollWidth = this.scrollWidth.bind(this); this.scrollOffset = this.scrollOffset.bind(this); this.scrollTop = this.scrollTop.bind(this); this.scrollLeft = this.scrollLeft.bind(this); this.clientHeight = this.clientHeight.bind(this); this.clientWidth = this.clientWidth.bind(this); } get pullingDownText() { var { pullingDownText } = this.props; if (isDefined(pullingDownText)) { return pullingDownText; } return isMaterial(current()) ? "" : undefined; } get pulledDownText() { var { pulledDownText } = this.props; if (isDefined(pulledDownText)) { return pulledDownText; } return isMaterial(current()) ? "" : undefined; } get refreshingText() { var { refreshingText } = this.props; if (isDefined(refreshingText)) { return refreshingText; } return isMaterial(current()) ? "" : undefined; } get reachBottomText() { var { reachBottomText } = this.props; if (isDefined(reachBottomText)) { return reachBottomText; } return isMaterial(current()) ? "" : undefined; } get scrollable() { return this.scrollableRef.current; } get restAttributes() { var _this$props = this.props, restProps = _objectWithoutPropertiesLoose(_this$props, _excluded); return restProps; } update() { this.scrollable.update(); } release() { this.scrollable.release(); } refresh() { if (this.props.pullDownEnabled) { this.scrollable.refresh(); } } content() { return this.scrollable.content(); } scrollBy(distance) { this.scrollable.scrollBy(distance); } scrollTo(targetLocation) { this.scrollable.scrollTo(targetLocation); } scrollToElement(element) { this.scrollable.scrollToElement(element); } scrollHeight() { return this.scrollable.scrollHeight(); } scrollWidth() { return this.scrollable.scrollWidth(); } scrollOffset() { return this.scrollable.scrollOffset(); } scrollTop() { return this.scrollable.scrollTop(); } scrollLeft() { return this.scrollable.scrollLeft(); } clientHeight() { return this.scrollable.clientHeight(); } clientWidth() { return this.scrollable.clientWidth(); } render() { var props = this.props; return viewFunction({ props: _extends({}, props), scrollableRef: this.scrollableRef, pullingDownText: this.pullingDownText, pulledDownText: this.pulledDownText, refreshingText: this.refreshingText, reachBottomText: this.reachBottomText, scrollable: this.scrollable, restAttributes: this.restAttributes }); } } function __createDefaultProps() { return _extends({}, ScrollViewPropsType, convertRulesToOptions(defaultOptionRules)); } ScrollView.defaultProps = __createDefaultProps(); var __defaultOptionRules = []; export function defaultOptions(rule) { __defaultOptionRules.push(rule); ScrollView.defaultProps = _extends({}, __createDefaultProps(), convertRulesToOptions(__defaultOptionRules)); }
import React from 'react' import { Field, reduxForm } from 'redux-form' import { RenderField } from '../shared' import { alphaNumeric, aol, email, maxLength, minLength, russianPhoneNumberPattern, minValue, number, required, tooYoung } from '../../utils' // eslint-disable-next-line no-template-curly-in-string const maxLength15 = maxLength(15, 'Must be ${max} characters or less, current length is ${length} and the current value is \' ${value}\'') // eslint-disable-next-line no-template-curly-in-string const minLength2 = minLength(2, 'Must be ${min} characters or more, current length is ${length} and the current value is \' ${value}\'') const userNameRequired = required('Username is required') const userNameAlphaNumeric = alphaNumeric('Only alphanumeric characters in username are allowed') const phoneNumberRequired = required('Phone number is required') const userRussianPhoneNumberPattern = russianPhoneNumberPattern() const userEmail = email() const userDeprecetedMail = aol() const userEmailRequired = required('Email is required') const minValue13 = minValue(13) // eslint-disable-next-line no-template-curly-in-string const userTooYoung = tooYoung(16, 'You have met the minimum age requirement! But it\'s better to be ${age}') const userAgeRequired = required('Age is required') const ageNumber = number() const FieldLevelValidation = ({ handleSubmit, pristine, reset, submitting }) => { return ( <form noValidate onSubmit={handleSubmit}> <div className="mt-3"> <Field name="username" type="text" component={RenderField} label="Username" validate={[userNameRequired, maxLength15, minLength2]} warn={userNameAlphaNumeric} /> </div> <div className="mt-3"> <Field name="email" type="email" component={RenderField} label="Email" validate={[userEmailRequired, userEmail]} warn={userDeprecetedMail} /> </div> <div className="mt-3"> <Field name="age" type="text" component={RenderField} label="Age" validate={[userAgeRequired, ageNumber, minValue13]} warn={userTooYoung} /> </div> <div className="mt-3"> <Field name="phone" type="text" component={RenderField} label="Phone number" validate={[phoneNumberRequired, userRussianPhoneNumberPattern]} /> </div> <div> <button type="submit" className="btn btn-secondary" disabled={submitting}> Submit </button> <button type="button" className="btn btn-light ml-3" disabled={pristine || submitting} onClick={reset}> Clear Values </button> </div> </form> ) } export default reduxForm({ form: 'fieldLevelValidation', forceUnregisterOnUnmount: true, destroyOnUnmount: false })(FieldLevelValidation) export const listing = ` import React from 'react' import { Field, reduxForm } from 'redux-form' import { RenderField } from '../shared' import { alphaNumeric, aol, email, maxLength, minLength, russianPhoneNumberPattern, minValue, number, required, tooYoung } from '../../utils' // eslint-disable-next-line no-template-curly-in-string const maxLength15 = maxLength(15, 'Must be \${max} characters or less, current length is \${length} and the current value is \' \${value}\'') // eslint-disable-next-line no-template-curly-in-string const minLength2 = minLength(2, 'Must be \${min} characters or more, current length is \${length} and the current value is \' \${value}\'') const userNameRequired = required('Username is required') const userNameAlphaNumeric = alphaNumeric('Only alphanumeric characters in username are allowed') const phoneNumberRequired = required('Phone number is required') const userRussianPhoneNumberPattern = russianPhoneNumberPattern() const userEmail = email() const userDeprecetedMail = aol() const userEmailRequired = required('Email is required') const minValue13 = minValue(13) // eslint-disable-next-line no-template-curly-in-string const userTooYoung = tooYoung(16, 'You have met the minimum age requirement! But it\'s better to be \${age}') const userAgeRequired = required('Age is required') const ageNumber = number() const FieldLevelValidation = ({ handleSubmit, pristine, reset, submitting }) => { return ( <form noValidate onSubmit={handleSubmit}> <div className="mt-3"> <Field name="username" type="text" component={RenderField} label="Username" validate={[userNameRequired, maxLength15, minLength2]} warn={userNameAlphaNumeric} /> </div> <div className="mt-3"> <Field name="email" type="email" component={RenderField} label="Email" validate={[userEmailRequired, userEmail]} warn={userDeprecetedMail} /> </div> <div className="mt-3"> <Field name="age" type="text" component={RenderField} label="Age" validate={[userAgeRequired, ageNumber, minValue13]} warn={userTooYoung} /> </div> <div className="mt-3"> <Field name="phone" type="text" component={RenderField} label="Phone number" validate={[phoneNumberRequired, userRussianPhoneNumberPattern]} /> </div> <div> <button type="submit" className="btn btn-secondary" disabled={submitting}> Submit </button> <button type="button" className="btn btn-light ml-3" disabled={pristine || submitting} onClick={reset}> Clear Values </button> </div> </form> ) } export default reduxForm({ form: 'fieldLevelValidation', })(FieldLevelValidation) `
import React from 'react'; import AppWrapper from '../containers/AppWrapper'; import PasswordForm from '../containers/password/PasswordForm'; export default function PasswordScreen({navigation}) { return ( <AppWrapper refreshing={false} onRefresh={() => {}} navigation={navigation}> <PasswordForm /> </AppWrapper> ); }
import React from 'react'; import ReactDOM from 'react-dom'; import Bottle from './components/Bottle'; require('../styles/main_styles.sass'); // ReactDOM.render( // <Bottle title="Bottle title via prompts" />, // document.getElementById("app") // ); let HelloMessage = React.createClass({ render: function() { var url = "asdadasasd"; chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) { url = tabs[0].url; console.log(url); }); return <div>Hello {this.props.name} {url}!</div>; } }); console.log(document.getElementById('container')); var btn = document.createElement('BUTTON'); btn.onclick = function() { chrome.storage.local.get(/* String or Array */["tmp_sites_url"], function(items){ var urls = items.tmp_sites_url; chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) { var url = tabs[0].url; chrome.storage.local.set({ "tmp_sites_url": urls + ';' + url }, function(){ // A data saved callback omg so fancy }); }); }); }; document.getElementById('container').appendChild(btn); // ReactDOM.render(<HelloMessage name="Kuba" />, document.getElementById('container'));
"use strict"; require("../models/db"); const assert = require("assert"); const mongoose = require("mongoose"); const Poll = mongoose.model("Poll"); const User = mongoose.model("User"); describe ("Poll", () => { let testPoll; const setupPoll = (poll) => { poll.title = "TestPoll"; poll.entries = []; poll.entries.push({ entryName: "Option1" }); poll.entries.push({ entryName: "Option2" }); } beforeEach((done) => { Poll.find({title: "TestPoll"}).remove((err) => { assert.ifError(err); testPoll = new Poll(); setupPoll(testPoll); testPoll.save((err) => { assert.ifError(err); done(); }); }); }); after((done) => { Poll.find({title: "TestPoll"}).remove((err) => { assert.ifError(err); done(); }); }); it ("Requires a title", (done) => { testPoll.title = ""; testPoll.validate((err) => { assert.ok(err); testPoll.title = "Test title"; testPoll.validate((err) => { assert.equal(err, null); done(); }); }); }); it ("Requires at least two entries", (done) => { testPoll.validate((err) => { assert.ifError(err); testPoll.entries.pop(); testPoll.validate((err) => { assert.ok(err); done(); }); }); }); it ("Can return a list of voters", () => { const voters = testPoll.getVoters(); assert.ok(voters.hasOwnProperty("registered")); assert.ok(voters.hasOwnProperty("anonymous")); assert.ok(Array.isArray(voters.registered)); assert.ok(Array.isArray(voters.anonymous)); }); it ("Adds registered users' votes correctly", (done) => { const user = new User(); testPoll.addVote("Option1", user, (err, vote) => { assert.ifError(err); assert.ok(vote.status); done(); }); }); it ("Adds anonymous users' votes correctly", (done) => { const user = "1111"; testPoll.addVote("Option1", user, (err, vote) => { assert.ifError(err); assert.ok(vote.status); done(); }); }); it ("Rejects anonymous votes when anonymous voting disabled", (done) => { testPoll.allowAnon = false; const user = "1111"; testPoll.addVote("Option1", user, (err, vote) => { assert.ifError(err); assert.equal(vote.status, false); done(); }); }); it ("Rejects duplicate registered voters", (done) => { const user = new User(); testPoll.addVote("Option1", user, (err, vote) => { assert.ifError(err); assert.ok(vote.status); testPoll.addVote("Option2", user, (err, vote) => { assert.ifError(err); assert.equal(vote.status, false); done(); }); }); }); it ("Rejects duplicate anonymous voters", (done) => { const user = "1111"; testPoll.addVote("Option1", user, (err, vote) => { assert.ifError(err); assert.ok(vote.status); testPoll.addVote("Option2", user, (err, vote) => { assert.ifError(err); assert.equal(vote.status, false); done(); }); }); }); it ("Returns an array of poll results", (done) => { const user1 = new User(); const user2 = new User(); testPoll.addVote("Option1", user1, (err, vote) => { assert.ifError(err); testPoll.addVote("Option2", user2, (err, vote) => { assert.ifError(err); testPoll.getResults((err, results) => { assert.ifError(err); const option1 = results[0]; const option2 = results[1]; assert.equal(option1.name, "Option1"); assert.equal(option2.name, "Option2"); assert.equal(option1.percent, 0.5); assert.equal(option2.percent, 0.5); done(); }); }); }); }); it ("Returns null for results if no votes have been cast", (done) => { testPoll.getResults((err, results) => { assert.ifError(err); assert.equal(results, null); done(); }); }); it ("Rejects new entries by default.", (done) => { testPoll.addEntry("Option3", "user", (err, result) => { assert.ifError(err); assert.equal(result.status, false); done(); }); }); it ("Can add new entries when allowed", (done) => { testPoll.allowNewEntries = true; testPoll.addEntry("Option3", "user", (err, result) => { assert.ifError(err); assert.ok(result.status); assert.equal(testPoll.entries[2].entryName, "Option3"); done(); }); }); });
#!/usr/bin/env node /* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /* jshint node: true */ /* jshint strict: global */ /* jshint esversion: 6 */ 'use strict'; var debug = require('debug')('vxs:upgrade:normalizeMetrics'); var Q = require('q'); module.exports = function(settings){ debug('In normalizeMetrics migrator'); const dbHandler = settings._dbHandler; const sql = "insert into metric2 (createdon, type, nameid, value, tenantId)\n " + "select MAX(metric.createdon) as createdon, type, metricname.id as nameid,\n " + "CAST(SUM(CAST(value as int)) as text) as value, tenantId\n " + "from metric, metricname\n " + "where type = 'increment' and metricname.name = metric.name\n " + "group by type, tenantId, metricname.id\n" + "union select MAX(metric.createdon) as createdon, type, metricname.id as nameid,\n " + "CAST(AVG(CAST(value as numeric)) as text) as value, tenantId\n" + "from metric, metricname\n " + "where type = 'gauge' and metricname.name = metric.name\n" + " group by type, tenantId, metricname.id\n " + "union select MAX(metric.createdon) as createdon, type, metricname.id as nameid, value, tenantId\n " + "from metric, metricname\n " + "where type <> 'increment' and type <> 'gauge' and metricname.name = metric.name\n " + "group by value, type, tenantId, metricname.id"; const dropTableSql = "DROP TABLE IF EXISTS metric"; return dbHandler.selectWithParams(["DISTINCT name"], 'metric') .then(names => Q.all(names.map(row => dbHandler.insertWithParams(row, 'metricname', true)))) .then(_ => dbHandler.runSql(sql, [])) .then(_ => dbHandler.runSql(dropTableSql, [])) .catch(err => { if ((err.message.includes('no such table') || err.code === '42P01') && err.message.includes('metric')){ debug("Table 'metric' does not exist. Skipping metric normalization."); return; } return Q.reject(err); }); };
'use strict'; const fs = require('fs'); const events = require('../modular-events/events'); const processFile = require('../modular-events/read-file.js'); describe('validator module performs basic validation of', () => { it('validates if values can be added normally', () => { let tempData; let file = '../test.txt'; fs.readFile(file) .then(data => { tempData = data; console.log(data); }) .catch(error => console.error(error)); // expect(alterFile(file)).toEqual(); }); });
/* Clase 24 - Document Ready */ console.log("1"); (function(){ 'use strict'; // Ejecución en modo estricto document.addEventListener('DOMContentLoaded', function(){ // Se ejecuta hasta que el evento se cargue esto es cuando todo el DOM este listo console.log("2"); }); })(); // Esto se encarga de que nadamas se ejecute el codigo una vez console.log("3");
import React, { useRef, useState} from "react"; import "./styles/addStudent.style.css"; const AddStudent = ({ onChange, onSubmit, onClear, edit }) => { const [editMode] = useState(edit); const firstNameRef = useRef(); const lastNameRef = useRef(); const gradeRef = useRef(); const ageRef = useRef(); const assignToClassRef = useRef(); const onInputChange = (e) => { onChange(e.target.name, e.target.value); }; const onClearClick = () => { firstNameRef.current.value = ""; lastNameRef.current.value = ""; gradeRef.current.value = ""; ageRef.current.value = ""; assignToClassRef.current.value = "-1"; onClear(); }; const onFormSubmit = (e) => { e.preventDefault(); onSubmit(); onClearClick(); onClear(); }; return ( <div className="addStudent"> <form action="" onSubmit={onFormSubmit}> <input type="text" placeholder={"first name"} ref={firstNameRef} name={"firstName"} id={"firstName"} value={edit.student.firstName} onChange={onInputChange} /> <input type="text" placeholder={"last name"} ref={lastNameRef} name={"lastName"} id={"lastName"} value={edit.student.lastName} onChange={onInputChange} /> <input type="text" placeholder={"age"} ref={ageRef} name={"age"} id={"age"} value={edit.student.age} onChange={onInputChange} /> <input type="text" placeholder={"grade"} ref={gradeRef} name={"grade"} id={"grade"} value={edit.student.grade} onChange={onInputChange} /> <select name="assignToClass" ref={assignToClassRef} id="assignToClass" value={edit.student.assignToClass} onChange={onInputChange} > <option value={"-1"} disabled > Chose an option </option> <option value={true}>assign To Class</option> <option value={false}>Not assign To Class</option> </select> {editMode.edit ? ( <> <input value="edit" type={"submit"} /> <input type="button" onClick={editMode.onCancel} value={"Cancel"} /> </> ) : ( <> <input type="submit" value={"Add"} /> <input type="button" value={"Clear"} onClick={onClearClick} /> </> )} </form> </div> ); }; export default AddStudent;
import React from 'react' import { render, cleanup } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import TodoForm from '../../components/TodoForm' describe('TodoForm', () => { let addTodo = null let todoForm = null afterEach(cleanup) beforeEach(() => { addTodo = jest.fn() todoForm = render(<TodoForm addTodo={addTodo} />) }) it('Has a title input', () => { // arrange const { getByTestId } = todoForm // act const titleInput = getByTestId('title') // assert expect(titleInput).not.toBeNull() }) it('Has a description input', () => { // arrange const { getByTestId } = todoForm // act const description = getByTestId('description') // assert expect(description).not.toBeNull() }) describe('Submit button', () => { it('Exists', () => { // arrange const { getByTestId } = todoForm // act const submit = getByTestId('submit-button') // assert expect(submit).not.toBeNull() }) it('Calls addTodo() once when clicked', () => { // arrange const { getByTestId } = todoForm // act getByTestId('title').value = 'foo' getByTestId('description').value = 'bar' getByTestId('submit-button').click() // assert expect(addTodo).toHaveBeenCalledTimes(1) expect(addTodo).toHaveBeenCalledWith({ title: 'foo', description: 'bar' }) }) }) })
import React from 'react'; import { MyStylesheet } from './styles' import DynamicStyles from './dynamicstyles' import { UTCTimeStringfromTime, makeTimeString, validateMonth, validateDate, validateYear, validateMinutes } from './functions'; import CalenderTimeIn from './scheduletimeincalender'; class TimeIn { handleminutes(minutes) { this.setState({ timeinminutes: minutes }) const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { const project = dynamicstyles.getprojectbytitle.call(this, this.props.match.params.projectid) if (project) { const projectid = project.projectid const i = dynamicstyles.getprojectkeybyid.call(this, projectid); if (minutes.length === 2) { if (validateMinutes(minutes)) { if (this.state.active === 'labor') { if (this.state.activelaborid) { const mylabor = dynamicstyles.getschedulelaborbyid.call(this, this.state.activelaborid); if (mylabor) { const j = dynamicstyles.getschedulelaborkeybyid.call(this, this.state.activelaborid) let day = this.state.timeinday; let year = this.state.timeinyear; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.labor[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } else if (this.state.active === 'equipment') { if (this.state.activeequipmentid) { const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, this.state.activeequipmentid) if (myequipment) { if (myequipment) { const j = dynamicstyles.getscheduleequipmentkeybyid.call(this, myequipment.equipmentid) let day = this.state.timeinday; let year = this.state.timeinyear; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.equipment[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } } else { alert(`Invalid minute format ${minutes}`) } } } } } handlehours(hours) { this.setState({ timeinhours: hours }) const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { const project = dynamicstyles.getprojectbytitle.call(this, this.props.match.params.projectid) if (project) { const projectid = project.projectid const i = dynamicstyles.getprojectkeybyid.call(this, projectid); if (hours.length === 2) { if (validateMonth(hours)) { if (this.state.active === 'labor') { if (this.state.activelaborid) { const mylabor = dynamicstyles.getschedulelaborbyid.call(this, this.state.activelaborid); if (mylabor) { const j = dynamicstyles.getschedulelaborkeybyid.call(this, this.state.activelaborid) let day = this.state.timeinday; let year = this.state.timeinyear; let month = this.state.timeinmonth; let minutes = this.state.timeinminutes; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.labor[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } else if (this.state.active === 'equipment') { if (this.state.activeequipmentid) { const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, this.state.activeequipmentid) if (myequipment) { const j = dynamicstyles.getscheduleequipmentkeybyid.call(this, myequipment.equipmentid) let day = this.state.timeinday; let year = this.state.timeinyear; let month = this.state.timeinmonth; let minutes = this.state.timeinminutes; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.equipment[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } else { alert(`Invalid hours ${hours}`) } } } } } handleyear(year) { this.setState({ timeinyear: year }) const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { const project = dynamicstyles.getprojectbytitle.call(this, this.props.match.params.projectid) if (project) { const projectid = project.projectid const i = dynamicstyles.getprojectkeybyid.call(this, projectid); if (year.length === 4) { if (validateYear(year)) { if (this.state.active === 'labor') { if (this.state.activelaborid) { const mylabor = dynamicstyles.getschedulelaborbyid.call(this, this.state.activelaborid); if (mylabor) { const j = dynamicstyles.getschedulelaborkeybyid.call(this, this.state.activelaborid) let day = this.state.timeinday; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let minutes = this.state.timeinminutes; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.labor[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } else if (this.state.active === 'equipment') { if (this.state.activeequipmentid) { const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, this.state.activeequipmentid) if (myequipment) { const j = dynamicstyles.getscheduleequipmentkeybyid.call(this, myequipment.equipmentid) let day = this.state.timeinday; let minutes = this.state.timeinminutes; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.equipment[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } else { alert(`Invalid Year Format ${year}`) } } } } } handleday(day) { day = day.toString(); this.setState({ timeinday: day }) const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { const project = dynamicstyles.getprojectbytitle.call(this, this.props.match.params.projectid) if (project) { const projectid = project.projectid const i = dynamicstyles.getprojectkeybyid.call(this, projectid); if (day.length === 2) { if (validateDate(day)) { if (this.state.active === 'labor') { if (this.state.activelaborid) { const mylabor = dynamicstyles.getschedulelaborbyid.call(this, this.state.activelaborid); if (mylabor) { const j = dynamicstyles.getschedulelaborkeybyid.call(this, this.state.activelaborid) let year = this.state.timeinyear; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let minutes = this.state.timeinminutes; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.labor[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } else if (this.state.active === 'equipment') { if (this.state.activeequipmentid) { const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, this.state.activeequipmentid) if (myequipment) { const j = dynamicstyles.getscheduleequipmentkeybyid.call(this, myequipment.equipmentid) let minutes = this.state.timeinminutes; let year = this.state.timeinyear; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.equipment[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } else { alert(`Invalid Date Format ${day}`) } } } } } handlemonth(month) { this.setState({ timeinmonth: month }) const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { const project = dynamicstyles.getprojectbytitle.call(this, this.props.match.params.projectid) if (project) { const projectid = project.projectid const i = dynamicstyles.getprojectkeybyid.call(this, projectid); if (month.length === 2) { if (validateMonth(month)) { if (this.state.active === 'labor') { if (this.state.activelaborid) { const mylabor = dynamicstyles.getschedulelaborbyid.call(this, this.state.activelaborid); if (mylabor) { const j = dynamicstyles.getschedulelaborkeybyid.call(this, this.state.activelaborid) let day = this.state.timeinday; let year = this.state.timeinyear; let hours = this.state.timeinhours; let minutes = this.state.timeinminutes; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.labor[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } else if (this.state.active === 'equipment') { if (this.state.activeequipmentid) { const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, this.state.activeequipmentid) if (myequipment) { const j = dynamicstyles.getscheduleequipmentkeybyid.call(this, myequipment.equipmentid) let day = this.state.timeinday; let year = this.state.timeinyear; let minutes = this.state.timeinminutes; let hours = this.state.timeinhours; let time = this.state.timeinampm; let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.equipment[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } else { alert(`invalid month format ${month}`) } } } } } toggleampm(ampm) { if (this.state.timeinampm === 'am' && ampm === 'pm') { this.setState({ timeinampm: 'pm' }) } else if (this.state.timeinampm === 'pm' && ampm === 'am') { this.setState({ timeinampm: 'am' }) } const dynamicstyles = new DynamicStyles(); const myuser = dynamicstyles.getuser.call(this) if (myuser) { const project = dynamicstyles.getprojectbytitle.call(this, this.props.match.params.projectid) if (project) { const projectid = project.projectid const i = dynamicstyles.getprojectkeybyid.call(this, projectid); if (this.state.active === 'labor') { if (this.state.activelaborid) { const mylabor = dynamicstyles.getschedulelaborbyid.call(this, this.state.activelaborid); if (mylabor) { const j = dynamicstyles.getschedulelaborkeybyid.call(this, this.state.activelaborid) let day = this.state.timeinday; let year = this.state.timeinyear; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let time = ampm; let minutes = this.state.timeinminutes; let timein = makeTimeString(year, month, day, hours, minutes, time); console.log(timein) timein = UTCTimeStringfromTime(timein); console.log(timein) myuser.company.projects[i].schedule.labor[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } else if (this.state.active === 'equipment') { if (this.state.activeequipmentid) { const myequipment = dynamicstyles.getscheduleequipmentbyid.call(this, this.state.activeequipmentid) if (myequipment) { const j = dynamicstyles.getscheduleequipmentkeybyid.call(this, myequipment.equipmentid) let day = this.state.timeinday; let year = this.state.timeinyear; let month = this.state.timeinmonth; let hours = this.state.timeinhours; let minutes = this.state.timeinminutes; let time = ampm let timein = makeTimeString(year, month, day, hours, minutes, time); timein = UTCTimeStringfromTime(timein); myuser.company.projects[i].schedule.equipment[j].timein = timein; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } } } showampm() { const dynamicstyles = new DynamicStyles(); const styles = MyStylesheet(); const headerFont = dynamicstyles.getHeaderFont.call(this) const timein = new TimeIn(); const showam = () => { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.headerFamily, ...headerFont, ...styles.boldFont, ...styles.alignCenter, ...dynamicstyles.getampmicon.call(this) }} onClick={() => { timein.toggleampm.call(this, 'pm') }}>AM</button> </div>) } const showpm = () => { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.headerFamily, ...headerFont, ...styles.boldFont, ...styles.alignCenter, ...dynamicstyles.getampmicon.call(this) }} onClick={() => { timein.toggleampm.call(this, 'am') }}>PM</button> </div>) } if (this.state.timeinampm === 'am') { return showam() } else if (this.state.timeinampm === 'pm') { return showpm() } } showtimein() { const styles = MyStylesheet(); const dynamicstyles = new DynamicStyles(); const headerFont = dynamicstyles.getHeaderFont.call(this) const regularFont = dynamicstyles.getRegularFont.call(this) const timein = new TimeIn(); const calender = new CalenderTimeIn(); return ( <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex1, ...styles.calenderContainer }}> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> <span style={{ ...styles.generalFont, ...regularFont }}>Time In (MM-DD-YYYY HH mm) </span> </div> </div> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1, ...styles.addMargin }}> <input type="text" style={{ ...styles.generalFont, ...headerFont, ...styles.generalField, ...styles.alignCenter }} value={this.state.timeinmonth} onChange={event => { timein.handlemonth.call(this, event.target.value) }} /> </div> <div style={{ ...styles.flex1, ...styles.addMargin }}> <input type="text" style={{ ...styles.generalFont, ...headerFont, ...styles.generalField, ...styles.alignCenter }} value={this.state.timeinday} onChange={event => { timein.handleday.call(this, event.target.value) }} /> </div> <div style={{ ...styles.flex2, ...styles.addMargin }}> <input type="text" style={{ ...styles.generalFont, ...headerFont, ...styles.generalField, ...styles.alignCenter }} value={this.state.timeinyear} onChange={event => { timein.handleyear.call(this, event.target.value) }} /> </div> <div style={{ ...styles.flex1, ...styles.addMargin }}> <input type="text" style={{ ...styles.generalFont, ...headerFont, ...styles.generalField, ...styles.alignCenter }} value={this.state.timeinhours} onChange={event => { timein.handlehours.call(this, event.target.value) }} /> </div> <div style={{ ...styles.flex1, ...styles.addMargin }}> <input type="text" style={{ ...styles.generalFont, ...headerFont, ...styles.generalField, ...styles.alignCenter }} value={this.state.timeinminutes} onChange={event => { timein.handleminutes.call(this, event.target.value) }} /> </div> <div style={{ ...styles.flex1, ...styles.addMargin }}> {timein.showampm.call(this)} </div> </div> {calender.showCalenderTimeIn.call(this)} </div> </div>) } } export default TimeIn;
// Closures for use in fetchData let employeeData; let renderedData = []; let indexOfModal; // Append Search bar UI to DOM $('.search-container').append(` <form action="#" method="get"> <input type="search" id="search-input" class="search-input" placeholder="Search..."> </form>` ); // Dynamic search function shows and hide matched persons from the fetch below $('#search-input').on('input', () => { let $searchInput = $('#search-input').val(); $searchInput = $searchInput.toLowerCase(); $('.card').each(function(){ if($(this).html().toLowerCase().includes($searchInput)) { $(this).css('display', ''); } else { $(this).css('display', 'none'); } }); }); // Get 12 employees from randomuser.me and handle response const fetchData = fetch('https://randomuser.me/api/?results=12&nat=us') .then(response => response.json()); // Render data cards to DOM fetchData.then(function(data) { employeeData = data.results; renderedData.push(...employeeData); employeeData.forEach(employee => { $('#gallery').append(` <div class="card"> <div class="card-img-container"> <img class="card-img" src="${employee.picture.medium}" alt="profile picture"> </div> <div class="card-info-container"> <h3 class="card-name cap">${employee.name.first} ${employee.name.last}</h3> <p class="card-text">${employee.email}</p> <p class="card-text cap">${employee.location.city}, ${employee.location.state}</p> </div> </div>`); }); }) // Then loop through each employee DOM node and attach event listener that calls generateModalUi() below .then(() => { document.querySelectorAll('.card').forEach((currentCard, i) => { currentCard.addEventListener('click', (e) => { e.preventDefault(); generateModalUi(renderedData, i); }); }); }).catch(() => { console.log('Error fetching API data'); }); // Generate Modal UI and append to end of #gallery div const generateModalUi = (data, i) => { indexOfModal = i; let galleryDiv = document.getElementById('gallery'); console.log(employeeData); galleryDiv.insertAdjacentHTML('beforeend', ` <div class="modal-container"> <div class="modal"> <button onClick="removeModalUi()" type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button> <div class="modal-info-container"> <img class="modal-img" src="${data[i].picture.large}" alt="profile picture"> <h3 id="name" class="modal-name cap">${data[i].name.first} ${data[i].name.last}</h3> <p class="modal-email">${data[i].email}</p> <p class="modal-text cap" id="city">${data[i].location.city}</p> <hr> <p class="modal-text" id="phone">${data[i].phone}</p> <p class="modal-text" id="address">${data[i].location.city}, ${data[i].location.state} ${data[i].location.postcode}</p> <p class="modal-text" id="dob">${data[i].dob.date}</p> </div> </div> <div class="modal-btn-container"> <button type="button" id="modal-prev" class="modal-prev btn">Prev<button> <button type="button" id="modal-next" class="modal-next btn">Next</button> </div> </div> `); if(indexOfModal === 0) { document.querySelector('#modal-prev').disabled = true; } else if(indexOfModal === 11) { document.querySelector('#modal-next').disabled = true; } document.querySelector('#modal-prev').addEventListener('click', () => { cycleModalContent(renderedData, i - 1); }); document.querySelector('#modal-next').addEventListener('click', () => { cycleModalContent(renderedData, i + 1); }); }; // Remove current modal UI from #gallery // NOTE: This function is called from the onClick prop of the modal close button const removeModalUi = () => { document.getElementById('gallery').removeChild(document.querySelector('.modal-container')); }; // Insert modal data at next index respective to the current index being passed at generateModalUi() const cycleModalContent = (data, i) => { indexOfModal = i; document.querySelector('.modal-container').remove(); document.getElementById('gallery').insertAdjacentHTML('beforeend', ` <div class="modal-container"> <div class="modal"> <button onClick="removeModalUi()" type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button> <div class="modal-info-container"> <img class="modal-img" src="${data[i].picture.large}" alt="profile picture"> <h3 id="name" class="modal-name cap">${data[i].name.first} ${data[i].name.last}</h3> <p class="modal-email">${data[i].email}</p> <p class="modal-text cap" id="city">${data[i].location.city}</p> <hr> <p class="modal-text" id="phone">${data[i].phone}</p> <p class="modal-text" id="address">${data[i].location.city}, ${data[i].location.state} ${data[i].location.postcode}</p> <p class="modal-text" id="dob">${data[i].dob.date}</p> </div> </div> <div class="modal-btn-container"> <button type="button" id="modal-prev" class="modal-prev btn">Prev<button> <button type="button" id="modal-next" class="modal-next btn">Next</button> </div> </div> `); if(indexOfModal === 0) { document.querySelector('#modal-prev').disabled = true; } else if(indexOfModal === 11) { document.querySelector('#modal-next').disabled = true; } document.querySelector('#modal-prev').addEventListener('click', () => { cycleModalContent(renderedData, i - 1); }); document.querySelector('#modal-next').addEventListener('click', () => { cycleModalContent(renderedData, i + 1); }); }
angular.module('AdSales').controller('EditSlsSttlmtOpController', function($scope, $routeParams, $location, SlsSttlmtOpResource ) { var self = this; $scope.disabled = false; $scope.$location = $location; $scope.get = function() { var successCallback = function(data){ self.original = data; $scope.slsSttlmtOp = new SlsSttlmtOpResource(self.original); }; var errorCallback = function() { $location.path("/SlsSttlmtOps"); }; SlsSttlmtOpResource.get({SlsSttlmtOpId:$routeParams.SlsSttlmtOpId}, successCallback, errorCallback); }; $scope.isClean = function() { return angular.equals(self.original, $scope.slsSttlmtOp); }; $scope.save = function() { var successCallback = function(){ $scope.get(); $scope.displayError = false; }; var errorCallback = function() { $scope.displayError=true; }; $scope.slsSttlmtOp.$update(successCallback, errorCallback); }; $scope.cancel = function() { $location.path("/SlsSttlmtOps"); }; $scope.remove = function() { var successCallback = function() { $location.path("/SlsSttlmtOps"); $scope.displayError = false; }; var errorCallback = function() { $scope.displayError=true; }; $scope.slsSttlmtOp.$remove(successCallback, errorCallback); }; $scope.get(); });
import React from 'react'; import ReactDOM from 'react-dom'; import App from './Components/App'; import { BrowserRouter as Router } from 'react-router-dom'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import {createStore, applyMiddleware, compose} from 'redux'; import rootReducer from './rootReducer'; import checkAuthrizationToken from './localStorage/tokenCheck' //Redux export const store = createStore ( rootReducer, compose ( //thunk allows us to dispatch a synchronous action //An example of a redux middleware is redux-thunk which allows you // to write action creators that return a function instead of an action. applyMiddleware(thunk), //chrome extension support window.devToolsExtension ? window.devToolsExtension() : f => f ) ); checkAuthrizationToken(); ReactDOM.render( <Provider store={store}> <Router> <App/> </Router> </Provider> , document.getElementById('root')); //registerServiceWorker(); //Steps for integrating Redux: // 1. Wrap the App with Provider which includes the store attribute // 2. Define the store with createStore, it receives reducer and enhancer //[enhancer] (Function): The store enhancer. // You may optionally specify it to enhance the store with third-party // capabilities such as middleware, time travel, persistence, etc. // The only store enhancer that ships with Redux is applyMiddleware(). // 3. Create the actions module and action that will pass to the reducer // 4. In this example the action is invoked in middleware, the reducer gets "mocked" action : (state ={})... // 5. For the top level component which is Signup for now, connect a state and a dispatch function to the props using "connect" method // 5.1 In addition, define propTypes and get the dispatch function from the props in render function ("connect" injects it to the props) // 5.2 If you want to pass it to a child component you have to copy propTypes declaration //Form Creation guidelines: // 1.form state: fields,errors,isLoading // 2.onSubmit,onChange // 3 form validation ( both client and server - reuse code ) // 4.dispatch thunk action // 5.handle response //There are 2 things we need to protect: //1. API endpoints //2. client side routes
import React, { Component } from "react" import "./App.css" import firebase from "firebase" import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth" import { BrowserRouter as Router, Route, Switch} from 'react-router-dom' import SearchImage from './Components/SearchImage' const config = { apiKey: "AIzaSyBbBmSjfFiwSI9MU5-Q5jAFLLXXiVbwziE", authDomain: "app-to-you-image-store.firebaseapp.com" }; firebase.initializeApp(config); export default class App extends Component { state = { isSignedIn: false } state = { images: [] }; uiConfig = { signInFlow: "popup", signInOptions: [ // firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.FacebookAuthProvider.PROVIDER_ID, ], callbacks: { signInSuccess: () => false } } componentDidMount = () => { firebase.auth().onAuthStateChanged(user => { this.setState({ isSignedIn: !!user }) // console.log("user", user) }) } render() { let clickedClass = "clicked"; const body = document.body; const lightTheme = "light"; const darkTheme = "dark"; let theme; if (localStorage) { theme = localStorage.getItem("theme"); } if (theme === lightTheme || theme === darkTheme) { body.classList.add(theme); } else { body.classList.add(lightTheme); } const switchTheme = (e) => { if (theme === darkTheme) { body.classList.replace(darkTheme, lightTheme); e.target.classList.remove(clickedClass); localStorage.setItem("theme", "light"); theme = lightTheme; } else { body.classList.replace(lightTheme, darkTheme); e.target.classList.add(clickedClass); localStorage.setItem("theme", "dark"); theme = darkTheme; } }; return ( <Router> {!this.state.isSignedIn ? ( <Route> <div className="login_page"> <div> <img className="header__icon" src="https://www.apptoyou.it/wp-content/themes/dt-the7-child/frontpage-2020/images/a2y-logo-pos.png" alt="" /> <StyledFirebaseAuth uiConfig={this.uiConfig} firebaseAuth={firebase.auth()} /> </div> </div> </Route> ) : ( <Switch> <Route path='/'> <div> <div className="ui pointing secondary menu"> <a className="active item">Home</a> <div className="right menu"> <div className="dark_bt"> <button className={theme === "dark" ? clickedClass : ""} id="darkMode" onClick={(e) => switchTheme(e)} ></button> </div> <a onClick={() => firebase.auth().signOut()} className="item" >Logout</a> </div> </div> <div className="ui segment"> <img src={firebase.auth().currentUser.photoURL} alt="" /> <h2> Welcome {firebase.auth().currentUser.displayName} </h2> </div> </div> <SearchImage /> <div> </div> </Route> </Switch> )} </Router> ); } }; // import React, { Component } from "react"; // import FacebookLogin from 'react-facebook-login/dist/facebook-login-render-props'; // import './App.css'; // import HomePage from './HomePage'; // className App extends Component { // state = { // isLoggedIn: false, // userID: "", // name: "", // email: "", // picture: "" // }; // componentDidMount() { // const state = sessionStorage.getItem('myRes'); // if (state) { // this.setState(JSON.parse(state)); // } // } // componentDidUpdate() { // const json = JSON.stringify(this.state); // sessionStorage.setItem('myRes', json) // } // onLogout = () => { // window.FB.getLoginStatus(function(response) { // window.FB.logout(function (response) { // // sessionStorage.removeItem('myRes') // sessionStorage.clear() // console.log("Logged Out!"); // window.location = "/"; // }); // }); // // window.FB.logout(() => { // // document.location.reload(); // // sessionStorage.removeItem('myRes', {}) // // }); // // // localStorage.clear(); // } // responseFacebook = response => { // this.setState({ // isLoggedIn: true, // userID: response.userID, // name: response.name, // email: response.email, // picture: response.picture.data.url // }); // }; // render() { // let fbContent; // if (this.state.isLoggedIn) { // fbContent = ( // <div> // <HomePage /> // <div className="user_info"> // <img src={this.state.picture} alt={this.state.name} /> // <h2>Welcome {this.state.name}</h2> // Email: {this.state.email} // <div> // <button onClick={this.onLogout}> // Logout // </button> // </div> // </div> // </div> // ); // } else { // fbContent = ( // <div className="login_page"> // <h1>Welcomwe to App to you Image Stor </h1> // <hr /> // <div> // <FacebookLogin // cookie={true} // appId="291080755709156" // autoLoad={false} // fields="name,email,picture" // callback={this.responseFacebook} // render={renderProps => ( // <button // className="login_button" // onClick={renderProps.onClick}> // Log in with Facebook // </button> // )} // /> // </div> // </div> // ); // } // return ( // <div>{fbContent}</div> // ) // } // } //}
module.exports = { template: require('./App.html'), controller: App }; function App($log, $timeout) { var $ctrl = this; $log.log('iniciando App'); var blankObject = { name: '', location: '', address: '', description: '', projectStyle: '', projectFinishes: '', projectBrand: '', signatureBranding: '', mesurementUnit: '', preCountry: '', preState: '', preCity: '', neighborhood: '', stageOfDevelopment: '', online: '', views: '', totalTowers: '', preBrokerProposed: '', dateStarted: '', expectedDateCompletition: '', completionDelayedWeeks: '', projectPremiums: '' }; var stageOfDevelopmentValues = [ {id: 1, name: 'Proposed'}, {id: 2, name: 'Pre Sales'}, {id: 3, name: 'Ground breaking'}, {id: 4, name: 'Top off'}, {id: 5, name: 'Closing'} ]; var projectPremiumsValues = [ {name: 'waterfront', val: 'waterfront'}, {name: 'beachfront', val: 'beachfront'}, {name: 'retail-anchored', val: 'retail-anchored'}, {name: 'city-views', val: 'city views'}, {name: 'downtown', val: 'downtown'}, {name: 'resorts', val: 'resorts'}, {name: 'mountain', val: 'mountain'}, {name: 'vacational', val: 'vacational'}, {name: 'metropolitan', val: 'metropolitan'}, {name: 'suburban', val: 'suburban'} ]; var projectFinishedValues = [ {name: 'Co decorator ready', val: 'co-decorator-ready'}, {name: 'Finished', val: 'finished'}, {name: 'Finished and furnished', val: 'furnished'} ]; var projectStyles = [{name: 'Modern', val: 'modern'}, {name: 'Signature Design', val: 'signature design'}, {name: 'High Tech', val: 'high tech'}, {name: 'Classic', val: 'classic'}, {name: 'Mediterranean', val: 'mediterranean'}, {name: 'Elegant', val: 'elegant'}]; var objectConfig = { id: {order: 1, type: 'text', header: true}, image: {order: 2, type: 'file', disabled: false, flex: '', header: true, style: 'md-avatar avatar-2x'}, name: {order: 3, type: 'text', header: true, defaultValue: ''}, address: {order: 5, type: 'text', header: true, defaultValue: ''}, address2: {order: 6, type: 'text', defaultValue: ''}, preCountry: {order: 7, type: 'select', defaultValue: '', values: [], model: 'countryCode', show: 'countryName', style: ['black-text'], options: {}}, country: {order: 8, type: 'text', defaultValue: '', header: true, style: ['capitalize']}, preState: {order: 9, type: 'select', values: [], model: 'adminCode1', show: 'adminName1', style: ['black-text'], options: {}}, state: {order: 10, type: 'text', header: true, style: ['capitalize'], defaultValue: ''}, preCity: {order: 11, type: 'select', values: [], model: 'name', show: 'name', style: ['black-text'], options: {}}, city: {order: 12, header: true, type: 'text', style: ['capitalize'], defaultValue: ''}, neighborhood: {order: 14, type: 'text', header: true}, location: {order: 15, type: 'map'}, totalTowers: {order: 16, type: 'number', min: 0, defaultValue: ''}, preBrokerProposed: {order: 17, type: 'select', values: [], model: 'id', show: 'companyName', defaultValue: ''}, stageOfDevelopment: {order: 18, type: 'select', values: stageOfDevelopmentValues, model: 'id', show: 'name', defaultValue: ''}, projectStyle: {order: 19, type: 'select', values: projectStyles, model: 'val', show: 'name', defaultValue: ''}, projectFinishes: {order: 20, type: 'select', values: projectFinishedValues, model: 'val', show: 'name', defaultValue: ''}, projectPremiums: {order: 21, type: 'select-multiple', values: projectPremiumsValues, model: 'val', show: 'name', translate: true, defaultValue: ''}, // views: {order: 22, type: 'select-multiple', values: ProjectView.values, model: 'id', show: 'name', defaultValue: ''}, views: {order: 22, type: 'select-multiple', values: [], model: 'id', show: 'name', defaultValue: ''}, projectBrand: {order: 23, type: 'text', defaultValue: ''}, signatureBranding: {order: 24, type: 'switch', defaultValue: false}, dateStarted: {order: 25, dateOnly: true, defaultValue: new Date()}, expectedDateCompletition: {order: 26, dateOnly: true, defaultValue: new Date()}, completionDelayedWeeks: {order: 27, options: {disabled: 'disabled'}, defaultValue: ''}, mesurementUnit: {order: 28, type: 'radio', model: 'model', show: 'name', values: [{name: 'Imperial', model: true}, {name: 'Metric', model: false}], defaultValue: ''}, description: {order: 29, type: 'text', defaultValue: ''}, online: {order: 30, type: 'checkbox', defaultValue: ''}, pctSold: {order: 31, options: {disabled: 'disabled'}, defaultValue: ''}, totalFloors: {order: 32, options: {disabled: 'disabled'}, defaultValue: ''}, avgPriceSqft: {order: 33, options: {disabled: 'disabled'}, defaultValue: ''}, parkingSpaces: {order: 34, options: {disabled: 'disabled'}, defaultValue: ''}, totalUnits: {order: 35, options: {disabled: 'disabled'}, defaultValue: ''}, projectFail: {order: 36, type: 'switch', defaultValue: ''} }; var formExclude = { developer: true, restangularized: true, reqParams: true, fromServer: true, parentResource: true, restangularCollection: true, singleOne: true, feature: true, route: true, broker: true, investors: true, projectScore: true, currentScore: true, latitude: true, longitude: true, country: true, state: true, city: true, // neighborhood: true, dateCreated: true, image: true, imageFile: true, updatedAt: true, brokerProposed: true, visits: true, developerName: true }; var formInclude = {}; $timeout(function () { $ctrl.formConfig = { columns: 2, object: blankObject, objectConfig: objectConfig, exclude: formExclude, include: formInclude }; }, 3000); $log.log('luego delformconfg'); }
var util = require('util'); var path = require('path'); var events = require('events'); var Factory = require('./factory'); var utils = require('./utils'); var Mixin = utils.Mixin; console.log(Factory) /* * paths and encodeTypes must be an array! @param {Object} paths @param {Object} * encodeTypes @param {Object} callBack @api {Private} */ var ffmpeg2theora = module.exports = function(encodeTypes, callBack) { events.EventEmitter.call(this); var self = this; this.factory = (new Factory()).on('encode', function(result) { self.emit('encode', result); }).on('error', function(error) { self.emit('error', error); }); this.factory.open() } // So will act like an event emitter util.inherits(ffmpeg2theora, events.EventEmitter); ffmpeg2theora.prototype.batch = function(videos, defaults) { defaults = Mixin({ contaners : ['mp4'], quality : { video : 5, audio : 5 }, pingTime : 5000 }, defaults); var quota = []; var factory = this.factory; for(var j = videos.length - 1; j >= 0; j--) { var vid = Mixin(defaults, videos[j]); vid = Mixin(defaults, videos[j]); if(!(vid.source && vid.dest)) { continue; } var contaners = vid.contaners for(var i = contaners.length - 1; i >= 0; i--) { factory.createEncode({ dest : vid.dest + '.' + contaners[i], contaner : contaners[i], quality : vid.quality, source : vid.source, pingTime : vid.pingTime }); } } } ffmpeg2theora.prototype._batch = function(paths, outPutFolder, type, quality, callBack) { var self = this; if(!Array.isArray(paths)) { callBack(false) } var factory = this.factory; var count = paths.length for(var j = paths.length - 1; j >= 0; j--) {(function(p, index) { console.log('index is ' + index) fs.exists(p, function(exists) { if(!exists) { throw ('Path does not exists Path: ' + p) } if(Array.isArray(type)) { for(var i = type.length - 1; i >= 0; i--) { factory.createEncode(p, outPutFolder + '/' + path.basename(p, path.extname(p)) + '.' + type[i], quality); } } else { factory.createEncode(p, outPutFolder + '/' + path.basename(p, path.extname(p)) + '.' + type, quality); } if(--count === 0) { factory.runQuta() } }); })(paths[j], j) } } ffmpeg2theora.prototype.start = function() { this.factory.runQuta() } ffmpeg2theora.prototype.killAll = function() { } ffmpeg2theora.prototype.getActive = function() { return this.factory.activeJobs } ffmpeg2theora.prototype.setThreads = function(c) { return this.factory.setThreads(c) }
import axios from 'axios' import qs from 'qs' import router from '@/router' import { Message, MessageBox } from 'element-ui' // import store from '../store' // import { getToken } from '@/utils/auth' // 创建axios实例 const service = axios.create({ baseURL: '', // api的base_url timeout: 15000 // 请求超时时间 }) // request拦截器 service.interceptors.request.use( config => { var mockUser = window.localStorage.getItem('mockUser');//系统管理员模拟用户 if (mockUser) { if (!config.data) { config.data = {}; } config.data.mock_user = mockUser; } if (config.data) { config.data = qs.stringify(config.data) } return config }, error => { return Promise.reject(error) } ); // respone拦截器 var once = true; service.interceptors.response.use( response => { if (response.data.code == 401 && once) { once = false; MessageBox.alert('请先登录!', '提示', { confirmButtonText: '确定', callback: () => { localStorage.clear(); router.push('/pages/admin/Login') once = true; } }) } else return response; }, error => { Message({ message: '发生了错误', type: 'error', duration: 1 * 1000 }) return Promise.reject(error.response.data) // 返回接口返回的错误信息 }); export default service
import { FETCH_NOTES, FETCH_NOTES_FAILURE, FETCH_NOTES_SUCCESS, SORT_NOTES, SET_ACTIVE_NOTE, DELETE_NOTE, TOGGLE_FAVORITE } from "./actionsTypes"; import { typeSort } from "../../utils"; export const initialStateNotes = { isLoading: false, payload: [], error: null, sortType: typeSort.UPDATED_DESC, activeNote: null }; export const notesReducer = (state = initialStateNotes, action) => { switch (action.type) { case FETCH_NOTES: return { ...state, isLoading: !state.payload.length && true }; case FETCH_NOTES_SUCCESS: return { ...state, isLoading: false, payload: action.payload }; case FETCH_NOTES_FAILURE: return { ...state, isLoading: false, error: action.payload }; case SORT_NOTES: return { ...state, sortType: action.payload }; case SET_ACTIVE_NOTE: return { ...state, activeNote: action.payload }; case DELETE_NOTE: const filtered = state.payload.filter(note => note.id !== action.payload); return { ...state, payload: filtered }; case TOGGLE_FAVORITE: return { ...state, payload: state.payload.map(note => note.id === action.payload.noteId ? { ...note, isFavorite: !note.isFavorite } : note ) }; default: return state; } };
import React from 'react' import './OpenSource.css'; const OpenSource = ({title}) => ( <section className="open-source"> <div className="container"> <div className="row"> <div className="col-12"> <div className="head"> <h5>{title}</h5> <hr/> </div> </div> </div> <div className="row"> <div className="col-md-4 col-xs-12"> <div className="top"> <a href="/" className="header"> laravel-permission </a> </div> <div className="bottom"> <ul className="list-unstyled"> <li>PHP</li> <li>25 548 655 <i className="fa fa-download"></i></li> <li>4548 <i className="fa fa-star"></i></li> </ul> </div> </div> <div className="col-md-6 col-xs-12"> <dv className="top"> <p>Associate users with roles and permissions</p> </dv> <div className="bottom"> <ul className="list-unstyled"> <li>Larvel</li> <li>PHP</li> <li>JS</li> <li>NODE.JS</li> </ul> </div> </div> <div className="col-md-2 col-xs-12"> </div> <div className="line"></div> </div> <div className="row"> <div className="col-md-4 col-xs-12"> <div className="top"> <a href="/" className="header"> laravel-permission </a> </div> <div className="bottom"> <ul className="list-unstyled"> <li>PHP</li> <li>25 548 655 <i className="fa fa-download"></i></li> <li>4548 <i className="fa fa-star"></i></li> </ul> </div> </div> <div className="col-md-6 col-xs-12"> <dv className="top"> <p>Associate users with roles and permissions</p> </dv> <div className="bottom"> <ul className="list-unstyled"> <li>Larvel</li> <li>PHP</li> <li>JS</li> <li>NODE.JS</li> </ul> </div> </div> <div className="col-md-2 col-xs-12"> <div className="top"> <a href="/" className="a"> intoduction </a> </div> <div className="bottom"> <a href="/" className="a"> Documentaion </a> </div> </div> <div className="line"></div> </div> <div className="row"> <div className="col-md-4 col-xs-12"> <div className="top"> <a href="/" className="header"> Javascrpt </a> </div> <div className="bottom"> <ul className="list-unstyled"> <li>VueJS</li> <li>255 5 <i className="fa fa-download"></i></li> <li>665 <i className="fa fa-star"></i></li> <span className="badge badge-primary badge-pill">new</span> </ul> </div> </div> <div className="col-md-6 col-xs-12"> <dv className="top"> <p>Associate users with roles and permissions</p> </dv> <div className="bottom"> <ul className="list-unstyled"> <li>Larvel</li> <li>Anguler</li> <li>JS</li> <li>NODE.JS</li> </ul> </div> </div> <div className="col-md-2 col-xs-12"> <div className="top"> <a href="/" className="a"> intoduction </a> </div> <div className="bottom"> <a href="/" className="a"> Documentaion </a> </div> </div> <div className="line"></div> </div> </div> </section> ) export default OpenSource;
// //oncreated Template.printInvoice.created = function () { this.autorun(function () { this.subscription = Meteor.subscribe('orders'); this.subscription = Meteor.subscribe('customers'); this.subscription = Meteor.subscribe('items'); this.subscription = Meteor.subscribe('orderDetails'); }.bind(this)); }; Template.printInvoice.helpers({ serviceReport(){ if (Session.get('serviceReport')) { return Session.get('serviceReport'); } }, checkPayment(payment){ if (payment == null) { return true } }, company(){ let company = Collection.Company.find(); if (company) { return company; } }, }); Template.printInvoice.events({ 'click .js-back'(){ let params = Router.current().params; let orderId = params.orderId; let order = Collection.Order.findOne(orderId); Router.go(`/itemOrder/orderId/${orderId}?staffId=${order.staffId}&customerId=${order.customerId}`) }, 'click #print'(){ var mode = 'iframe'; // popup var close = mode == "popup"; var options = {mode: mode, popClose: close}; $("div.print").printArea(options); Router.go(`/showOrder`); }, });
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var fs = require('fs'); var http = require('http'); var https = require('https'); var SERVER_ROOT_FOLDER_PATH = '/opt/usr/globalapps/org.tizen.smart-surveillance-camera.dashboard/res/'; var LATEST_FRAME_FILE_PATH = '/opt/usr/home/owner/apps_rw/org.tizen.smart-surveillance-camera/shared/data/latest.jpg' function extractPath(url) { var urlParts = url.split('/'), i = 0, l = urlParts.length, result = []; for (; i < l; ++i) { if (urlParts[i].length > 0) { result.push(urlParts[i]); } } return result; } http.createServer(function(req, res) { req.on('end', function() { var path = extractPath(req.url); console.log(req.url) // var last = path[path.length - 1]; if (path[0] === undefined) { res.writeHead(200); res.end(fs.readFileSync(SERVER_ROOT_FOLDER_PATH + 'public/index.html')); } else if (path[0] == 'test') { res.writeHead(200); res.end(fs.readFileSync(SERVER_ROOT_FOLDER_PATH + 'public/test.html')); } else if (req.url == '/image/image.png') { res.writeHead(200); res.end(fs.readFileSync(SERVER_ROOT_FOLDER_PATH + 'public/image/image.png')); } else if (req.url == '/js/app.js') { res.writeHead(200); res.end(fs.readFileSync(SERVER_ROOT_FOLDER_PATH + 'public/js/app.js')); } else if (req.url == '/css/style.css') { res.writeHead(200); res.end(fs.readFileSync(SERVER_ROOT_FOLDER_PATH + 'public/css/style.css')); } else if (req.url == '/command/on') { res.writeHead(200); res.end(); sendCommand("on"); } else if (req.url == '/command/off') { res.writeHead(200); res.end(); sendCommand("off"); } else if (req.url == '/command/send') { res.writeHead(200); res.end(); sendCommand("send"); } else { res.writeHead(404); res.end(); } }); }).listen(9090); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// var ENABLE_WEBSOCKET = true; if (ENABLE_WEBSOCKET) { var websocket = require('websocket'); var options = { port: 8888 } var server = new websocket.Server(options, Listener); function Listener(ws) { console.log('Client connected: handshake done!'); ws.ack = true; ws.on('message', function (msg) { // console.log('Message received: %s', msg.toString()); // ws.send(msg.toString(), {mask: true, binary: false}); //echo // ws.send('Received: ' + msg.toString()); //echo // server.close(); ws.ack = true; }); ws.on('ping', function (msg) { // console.log('Ping received: %s', msg.toString()); }); ws.on('error', function (msg) { // console.log('Error: %s', msg.toString()); }); // var i = 0; // var prev = 0; var timeout = setInterval(function() { if (!ws.ack) return false; // var now = Date.now(); var data; try { data = fs.readFileSync(LATEST_FRAME_FILE_PATH); } catch (err) { // console.log(err); data = fs.readFileSync(SERVER_ROOT_FOLDER_PATH + 'default.gif'); } ws.send(data, {mask: false, binary: true}); // console.log(`Sending frame(${i++}), interval(${now - prev} ms)`); // server.broadcast(data, {mask: false, binary: true}); // server.broadcast(`HELLO TO ALL FROM IoT.js!!! (${i++}, ${now - prev})`); // prev = now; ws.ack = false; }, 1000 / 15.0); ws.on('close', function (msg) { // console.log('Client close: ' + msg.reason + ' (' + msg.code + ')'); clearInterval(timeout); }); } server.on('error', function (msg) { // console.log('Error: %s', msg.toString()); }); server.on('close', function (msg) { // console.log('Server close: ' + msg.reason + ' (' + msg.code + ')'); }); } var tizen = require('tizen'); var app_id = 'org.tizen.smart-surveillance-camera'; var data = { command: 'command' }; function sendCommand(msg) { data.command = msg; try { var res = tizen.launchAppControl({ app_id: app_id, extra_data: data, }); console.log('Result', res); } catch(e) { console.log(e); } } var lastUpdateId = 0; setTimeout(getUpdates, 1000); function getUpdates(){ https.get({ host: "api.telegram.org", path: "/bot1193973544:AAEAJOr_-i_Yq2mVQnVbs4_OhPLPwFg1sJY/getUpdates?offset=" + (lastUpdateId+1), port: 443, rejectUnauthorized: false }, function(response) { // console.log('Got response'); response.on('data', function(chunk) { // console.log('Chunk: '); var json = JSON.parse(chunk); console.log(json); checkCommand(json); }); setTimeout(getUpdates, 1000); }); } function checkCommand(data) { try { if (!data.ok || !data.result || data.result.length == 0) return; var result = data.result; for (var i = 0; i < result.length; i++) { lastUpdateId = result[i].update_id; excuteCommand(result[i].message.text); } } catch(e) { console.log(e); } } function excuteCommand(command) { try { if (command === '/photo' || command === '/picture') { sendCommand('send'); } else if (command === '/on') { sendCommand('on'); } else if (command === '/off') { sendCommand('off'); } else if (command === '/state') { sendCommand('state'); } } catch(e) { console.log(e); } }
import React, {useState} from 'react'; import './App.css'; import axios from 'axios'; import SearchForm from './components/SearchForm'; import Button from './components/Button'; import Block from './components/Block'; import styled from 'styled-components'; import Error from './components/Error'; import {Link} from 'react-router-dom'; //register on api.edamam.com and get valid recipe API //install and use AXIOS //create get request with AXIOS, use ID and KEY separate //hide ID and Key in .env file //store data in state //create search form and use it as a component //In plans: //Implement semantic UI //Try to use Redux //Use Router to switch between pages const KEY = process.env.REACT_APP_API_KEY; const ID = process.env.REACT_APP_API_ID; const Title = styled.h1` font-size:4em; display: flex; flex-flow:column; align-items:center; justify-content:center; color:rgb(237, 117, 47); text-shadow:6px 6px 3px black; `; const Grid = styled.div` display:grid; grid-template-columns:repeat(5,1fr); grid-template-rows:repeat(3,1fr); grid-gap:1% 1%; justify-content:space-evenly; align-items:flex-start; text-align:center; ` function App() { const[someData,setSomeData] = useState(''); const[mainRecipe,setMainRecipe] = useState([]); const[empty, setEmpty] = useState('') const url = `https://api.edamam.com/search?q=${someData}&app_id=${ID}&app_key=${KEY}`; const onSubmitHandler = async(event) => { if(someData !== '') { event.preventDefault(); const res = await axios.get(url); setMainRecipe(res.data.hits) setSomeData(''); }else{ setEmpty('Search bar is empty'); } } const onChangeHandler = (event) => { setSomeData(event.target.value); } const StyledHeader = styled.div` display: flex; justify-content:space-around; align-items:center; font-size:2rem; text-decoration:none; text-align:center; font-size:1.5em; color:white; text-shadow:2px 2px 1px black; border:4px solid black; background-image:url('https://i.pinimg.com/736x/81/4d/e8/814de875dcd72f4398fb42965fd11a83.jpg'); height:15vh; width:100vw; margin:0; ` const StyledTitle = styled.div` display: flex; justify-content:center; align-items:center; background-color:rgba(0,0,0,0.4); border:2px solid black; margin:40px auto 100px auto; width:40%; height:10vh; box-shadow:10px 10px 2px black; ` const StyledSearch = styled.div` display: flex; flex-flow:column; justify-content:center; align-items:center; background-color:rgba(0,0,0,0.4); border:2px solid black; margin:40px auto 100px auto; width:30%; height:15vh; box-shadow:10px 10px 2px black; padding-top:20px; ` return ( <div className='App'> <StyledHeader> <Link to="/"> Home</Link> <Link to="/top"> Top 5 recipes</Link> <Link to="/motivation"> Why to cook?</Link> </StyledHeader> <div className='App-header'> <StyledTitle><Title>Grandma's Recipe</Title> </StyledTitle> <SearchForm inputChange={onChangeHandler} info={someData}></SearchForm> {empty ? <Error error={empty}/>:null} <Button ClickBtn={onSubmitHandler}></Button> <Grid >{mainRecipe.map((res, index) => <Block key={index} info={res} /> )} </Grid> </div > </div> ); } export default App;
ws = new WebSocket('ws://localhost:8081'); ws.onopen = function () { console.log('connection open'); console.log(arguments); }; ws.onmessage = function (event) { console.log('Message comes \n msg = ', event); $('#output-container').append('<p>' + event.data + '</p>'); }; ws.onclose = function () { console.log('connection close'); console.log(arguments); }; ws.onerror = function () { console.log('error'); }; $('#send-button').click(function(event) { event.preventDefault(); console.log('send msg'); ws.send($('#input-text').val()); $('#input-text').val(''); });
define([ 'jquery', 'siViewerData', 'jquery-ui', 'kendo', 'heatmap', 'highchart-more', 'highstock', 'siViewerNamespace', 'window/charts/com.spacetimeinsight.viewer.window.baseChartWindow', "table-bootstrap", "table-theme", 'table-Grid-API', 'siDropDownList', ], function ($) { $.widget('spacetimeinsight.siViewerXYChart', $.spacetimeinsight.siViewerBaseChartWindow, { options: { id: undefined, showHelpDropdown: true, simpleChartProperties: "", chartSeriesDetails: "", chartProperties: "", chartSelectorFlag: false, }, pluginName: "siViewerXYChart", GENERIC_COMPONENT: kendo.template("<div id ='#= id #' > </div>"), chartTypeDropDownData: [], _create: function () { this._super(); var $this = this; if (this.options.windowConfig) { this.chartTypeDropDownData = this.options.windowConfig.chartTypeDetails; } }, _bindControls: function () { this._super(); // Any Specific drawer function to come here }, _setTimeseriesChartOptions: function () { var $this = this; var timeSeriesDetails = this.options.windowConfig.timeseriesChartDetails; if (timeSeriesDetails) { //in-line time filters if (timeSeriesDetails.inlineTimeFilterProperties) { this.options.chartObj.rangeSelector = timeSeriesDetails.inlineTimeFilterProperties; } //navigator if (timeSeriesDetails.showTimeLineNavigator && timeSeriesDetails.showTimeLineNavigator == true) { if (timeSeriesDetails.timeLineNavigatorProperties) { this.options.chartObj.navigator = timeSeriesDetails.timeLineNavigatorProperties; } } else { this.options.chartObj.navigator = { enabled: false }; } //scrollbar if (timeSeriesDetails.showTimeLineNavigatorScrollbar && timeSeriesDetails.showTimeLineNavigatorScrollbar == true) { if (timeSeriesDetails.timeLineNavigatorScrollbarProperties) { this.options.chartObj.scrollbar = timeSeriesDetails.timeLineNavigatorScrollbarProperties; } } else { this.options.chartObj.scrollbar = { enabled: false }; } } }, //overridden method _onToolBarCreationComplete : function(e,data){ var $this = this; $this._super(); var tool = $this.options.toolBar.find("#chartselectorTool"); if ($this.options.toolBar) { var chartSelectorTool = $this.options.toolBar.find("#chartselectorTool").parent(); var legendTool = $this.element.parent().find("#legendTool"); if(chartSelectorTool){ if ($this.options.simpleChartProperties.chartType == "Heatmap") { $(chartSelectorTool).unbind('click'); } else { $(chartSelectorTool).bind('click'); } } if(legendTool){ if ($this.options.simpleChartProperties.chartType == "Heatmap") { $this.hideLegend(); legendTool.attr("disabled","true"); } } } }, _applyDrawerConfigration: function () { var $this = this; var confData = $this.options.windowConfig; $this.options.drawer[$this.options.drawerWidget]("setHideColumnList", confData); }, _applyDrawerSettings: function (data) { var $this = this; $this.options.drawerFavouriteObj = data; var title = ""; var subTitle = ""; var xyChartObj = JSON.parse(JSON.stringify($this.options.chartObj.yAxis)); if (data.data.plotItems.dataLabel) { this.showHideDataLabels(true); this.showHideDataLabelsTool(true); }else{ this.showHideDataLabels(false); this.showHideDataLabelsTool(false); } if (data.data.plotItems.plotAreaTitle) { $this.showChartTitle(); } else { $this.hideChartTitle(); } if (data.data.plotItems.grid) { if ($this.options.chart) { $this.options.chart.xAxis[0].update({ gridLineWidth: $this.options.chartObj.xAxis.gridLineWidth, minorGridLineWidth: $this.options.chartObj.xAxis.minorGridLineWidth }); if(data.data.yAxisItemsSecondary && data.data.yAxisItemsSecondary.length){ if($this.options.chartObj.yAxis){ $.each($this.options.chartObj.yAxis, function(key,value){ if(value.gridLineWidth){ $this.options.chart.yAxis[key].update({ gridLineWidth: $this.options.chartObj.yAxis[key].gridLineWidth, minorGridLineWidth: $this.options.chartObj.yAxis[key].minorGridLineWidth }); } }); } }else{ $this.options.chart.yAxis[0].update({ gridLineWidth: $this.options.chartObj.yAxis.gridLineWidth }); } $this.options.chartObj.yAxis = xyChartObj; } } else { if ($this.options.chart) { $this.options.chart.xAxis[0].update({ gridLineWidth: 0, minorGridLineWidth: 0 }); if(data.data.yAxisItemsSecondary && data.data.yAxisItemsSecondary.length){ if($this.options.chartObj.yAxis){ $.each($this.options.chartObj.yAxis, function(key,value){ if(value.gridLineWidth){ $this.options.chart.yAxis[key].update({ gridLineWidth: 0, minorGridLineWidth: 0 }); } }); } }else{ $this.options.chart.yAxis[0].update({ gridLineWidth: 0, minorGridLineWidth: 0 }); } $this.options.chartObj.yAxis = xyChartObj; $this.options.chart.reflow(); } } if (data.data.plotItems.guildLines) { $this.options.chart.tooltip.options.crosshairs = [true, true]; } else { $this.options.chart.tooltip.options.crosshairs = [false, false]; } // x-axis drawer changes if (data.data.xAxisItems.xAxisTitle) { $this.options.chart.xAxis[0].setTitle({ text: $this.options.chartObj.xAxis.title.text }); } else { $this.options.chart.xAxis[0].setTitle({ text: "" }); } if (data.data.xAxisItems.xAxisTickMark) { if( $this.options.chartObj.xAxis.tickWidth){ $this.options.chart.xAxis[0].update({ tickWidth: $this.options.chartObj.xAxis.tickWidth, minorTickWidth : $this.options.chartObj.xAxis.minorTickWidth }); } } else { $this.options.chart.xAxis[0].update({ tickWidth: 0, minorTickWidth :0, }); } if (data.data.xAxisItems.xAxisReverseOrder) { $this.options.chart.xAxis[0].update({ reversed: true }); } else { $this.options.chart.xAxis[0].update({ reversed: false }); } // multiple y axis if(data.data.yAxisItemsSecondary && data.data.yAxisItemsSecondary.length){ $.each(data.data.yAxisItemsSecondary, function(key,value){ if (value.yAxisTitle) { $this.options.chart.yAxis[key].setTitle({ text: $this.options.chartObj.yAxis[key].title.text }); } else { $this.options.chart.yAxis[key].setTitle({ text: "" }); } if (value.yAxisTickMark) { if( $this.options.chartObj.yAxis[key].tickWidth){ $this.options.chart.yAxis[key].update({ tickWidth: $this.options.chartObj.yAxis[key].tickWidth, minorTickWidth :$this.options.chartObj.yAxis[key].minorTickWidth }); } } else { $this.options.chart.yAxis[key].update({ tickWidth: 0, minorTickWidth : 0 }); } if (value.yAxisReverseOrder) { $this.options.chart.yAxis[key].update({ reversed: true }); } else { $this.options.chart.yAxis[key].update({ reversed: false }); } $this.options.chartObj.yAxis = xyChartObj; }); }else{ if (data.data.yAxisItemsFirst.yAxisTitle) { $this.options.chart.yAxis[0].setTitle({ text: $this.options.chartObj.yAxis.title.text }); } else { $this.options.chart.yAxis[0].setTitle({ text: "" }); } if (data.data.yAxisItemsFirst.yAxisTickMark) { if($this.options.chartObj.yAxis.tickWidth){ $this.options.chart.yAxis[0].update({ tickWidth: $this.options.chartObj.yAxis.tickWidth, minorTickWidth : $this.options.chartObj.yAxis.minorTickWidth }); } } else { $this.options.chart.yAxis[0].update({ tickWidth: 0, minorTickWidth :0 }); } if (data.data.yAxisItemsFirst.yAxisReverseOrder) { $this.options.chart.yAxis[0].update({ reversed: true }); } else { $this.options.chart.yAxis[0].update({ reversed: false }); } } $this.options.chart.reflow(); }, _setSimpleChartProperties: function () { var $this = this; this.options.simpleChartProperties = this._getWindowConfigurationByProperty("chartDetails"); if (this.options.simpleChartProperties) { this.options.chartObj.chart.type = $this._getChartAndSeriesType($this.options.simpleChartProperties.chartType); } if(this.options.windowConfig.colorAxis) { this.options.chartObj.colorAxis = this.options.windowConfig.colorAxis; } // set axis this.options.chartObj.xAxis = this.options.windowConfig.xaxis; //for tickPositioner setting value if($this.options.windowConfig.xaxis.tickPositioner){ $this.options.windowConfig.xaxis.tickPositioner = $this._setTickPositioner($this.options.windowConfig.xaxis); } try { if (this.options.chartObj.xAxis.events) { $.each(this.options.chartObj.xAxis.events, function (index, jsFunction) { $this.options.chartObj.xAxis.events[index] = window[jsFunction]; }); } } catch (e) { $si.Logger('xyChart').error("Error = [" + e.message + "] occurred while setting events on x-axis"); } if (this.options.windowConfig.yaxisList === undefined) { this.options.chartObj.yAxis = this.options.windowConfig.yaxis; if($this.options.windowConfig.yaxis.tickPositioner){ $this.options.windowConfig.yaxis.tickPositioner = $this._setTickPositioner($this.options.windowConfig.yaxis); } try { if (this.options.chartObj.yAxis && this.options.chartObj.yAxis.events) { $.each(this.options.chartObj.yAxis.events, function (index, jsFunction) { $this.options.chartObj.yAxis.events[index] = window[jsFunction]; }); } } catch (e) { $si.Logger('xyChart').error("Error = [" + e.message + "] occurred while setting events on y-axis"); } } else { this.options.chartObj.yAxis = this.options.windowConfig.yaxisList; if($this.options.chartObj.yAxis){ $.each($this.options.chartObj.yAxis, function(key,value){ if(value.tickPositioner){ $this.options.chartObj.yAxis[key].tickPositioner = $this._setTickPositioner($this.options.chartObj.yAxis[key]); } }); } try { if (this.options.chartObj.yAxis && this.options.chartObj.yAxis.events) { $.each(this.options.chartObj.yAxis.events, function (index, jsFunction) { $this.options.chartObj.yAxis.events[index] = window[jsFunction]; }); } } catch (e) { $si.Logger('xyChart').error("Error = [" + e.message + "] occurred while setting events on multiple y-axis"); } } }, _addChartSeries: function () { var $this = this; var i = 0; $this.options.chartSelectorFlag = true; this.options.chartSeriesDetails = this._getWindowConfigurationByProperty("chartSeries"); if (this.options.chartSeriesDetails.defaultSeriesProperties) { var chartSeries = this.options.chartSeriesDetails.defaultSeriesProperties; try { if (chartSeries.events) { $.each(chartSeries.events, function (index, jsFunction) { chartSeries.events[index] = window[jsFunction]; }); } } catch (e) { $si.Logger('xyChart').error("Error = [" + e.message + "] occurred while setting series events"); } this.options.chartObj.plotOptions.series = chartSeries; } else { this.options.chartObj.plotOptions.series = new Object(); this.options.chartObj.plotOptions.series.dataLabels = new Object(); } var seriesList = $this.options.dataProvider.chartSeriesList; var chartSeriesFields = this.options.chartSeriesDetails["chartSeriesFields"]; // Start - Using in Export to CSV open popup functionality. $si.viewer.xyChartSeriesData = chartSeriesFields; if($this.options.windowConfig.metadata){ $si.viewer.xyChartMetaData = $this.options.windowConfig.metadata; } // End - Using in Export to CSV open popup functionality. var isSeriesInRow = this.options.windowConfig.chartSeries.seriesIn == "Row"; if (seriesList) { $.each(seriesList, function (index, seriesField) { if (seriesField) { chartSeriesField = chartSeriesFields[seriesField.id]; $this.options.chartObj.series[i] = new Object(); $this.options.chartObj.series[i].id = isSeriesInRow ? (seriesField.id + "_" + seriesField.name) : seriesField.id; $this.options.chartObj.series[i].name = seriesField.name; if (seriesField.useRawData === undefined || seriesField.useRawData == false) { $this.options.chartObj.series[i].data = seriesField.data; } else { $this.options.chartObj.series[i].data = seriesField.rawData; } if(chartSeriesField.seriesEnabled){ $this.options.totalSeries++; $this.options.totalDataPoints = $this.options.chartObj.series[i].data.length + $this.options.totalDataPoints; } //to hide/unhide series based on SI Designer properties $this.options.chartObj.series[i].visible = chartSeriesField.seriesEnabled ; if (chartSeriesField && chartSeriesField.seriesProperties) { $.each(chartSeriesField.seriesProperties, function (name, value) { try { if (name == "events") { $.each(value, function (index, jsFunction) { value[index] = window[jsFunction]; }); } } catch (e) { $si.Logger('xyChart').error("Error = [" + e.message + "] occurred while setting series events"); } $this.options.chartObj.series[i][name] = (value == "false") ? false : (value == "true" ? true : value); }); } if (chartSeriesField && $this.options.simpleChartProperties.chartType != "Heatmap") { if (chartSeriesField.seriesColor) { $this.options.chartObj.series[i].color = chartSeriesField.seriesColor; } $this.options.chartObj.series[i].yAxis = chartSeriesField.verticalAxis; if (chartSeriesField.seriesChartType != undefined) { $this.options.chartSelectorFlag = false; $this.options.chartObj.series[i].type = $this._getChartAndSeriesType(chartSeriesField.seriesChartType); } else { $this.options.chartObj.series[i].type = $this._getChartAndSeriesType($this.options.simpleChartProperties.chartType); } } } i = i + 1; }); } else { $this.options.chartObj.series = []; } }, toggleChartTitle: function () { var $this = this; this._super(); }, _enableChartSelectorTool: function () { var $this = this; if ($this.options.toolBar) { var chartSelectorTool = $this.options.toolBar.find("#chartselectorTool").parent(); if ($this.options.chartSelectorFlag == true) { $(chartSelectorTool).bind('click'); } else { $(chartSelectorTool).unbind('click'); } } }, _getChartAndSeriesType: function (type) { switch (type) { case 'AreaChart': return 'area'; case 'AreaRangeChart': return 'arearange'; case 'AreaSplineChart': return 'areaspline'; case 'AreaSplineRangeChart': return 'areasplinerange'; case 'BarChart': return 'bar'; case 'BoxplotChart': return 'boxplot'; case 'BubbleChart': return 'bubble'; case 'ColumnChart': return 'column'; case 'ColumnRangeChart': return 'columnrange'; case 'ErrorbarChart': return 'errorbar'; case 'LineChart': return 'line'; case 'ScatterChart': return 'scatter'; case 'Heatmap': return 'heatmap'; case 'OHLCChart': return 'ohlc'; case 'CandlestickChart': return 'candlestick'; default: return 'line'; } }, _setChartAndSeriesType: function (type) { switch (type) { case 'area': return 'AreaChart'; case 'arearange': return 'AreaRangeChart'; case 'areaspline': return 'AreaSplineChart'; case 'areasplinerange': return 'AreaSplineRangeChart'; case 'bar': return 'BarChart'; case 'boxplot': return 'BoxplotChart'; case 'bubble': return 'BubbleChart'; case 'column': return 'ColumnChart'; case 'columnrange': return 'ColumnRangeChart'; case 'errorbar': return 'ErrorbarChart'; case 'line': return 'LineChart'; case 'scatter': return 'ScatterChart'; case 'heatmap': return 'Heatmap'; default: return 'line'; } }, onChangeDropDown: function (e) { var $this = this; $this.options.chartType = e.sender._selectedValue; var seriesType = $this._getChartAndSeriesType($this.options.chartType); $this.options.chartType = seriesType; $this._changeChartType(); }, // to change series type based on which chart will be changed _changeChartType: function (chartType) { if(chartType === undefined || chartType == "") { chartType = this.options.chartType; } if(chartType === undefined || chartType == "") { return; } var $this = this; var series = $this.options.chart.series; // adding for creating bar chart if ($this.options.chartType == 'bar') { $this.options.chart.inverted = true; $this.options.chart.xAxis[0].update({}, false); $this.options.chart.yAxis[0].update({}, false); } else { $this.options.chart.inverted = false; $this.options.chart.xAxis[0].update({}, false); $this.options.chart.yAxis[0].update({}, false); } for (var i = 0; i < series.length; i++) { $this.options.chart.series[i].update({type:chartType}); } //$this.options.chart.reflow(); }, // To show or hide the series on the chart _hideOrShowSeriesOnChart: function (selectedNode) { var $this = this; var seriesCount = 0; var datapoints = 0; var series = $this.options.chart.series; if (series && series.length > 0 && selectedNode) { for (var i = 0; i < series.length; i++) { if (series[i].name == selectedNode.nodeName) { if ($this.options.chart.series[i].visible) { $this.options.chart.series[i].hide(); datapoints = datapoints + $this.options.chart.series[i].data.length; seriesCount++; } else { $this.options.chart.series[i].show(); seriesCount --; datapoints = datapoints - $this.options.chart.series[i].data.length; } } } $this.options.totalSeries = $this.options.totalSeries - seriesCount; $this.options.totalDataPoints = $this.options.totalDataPoints - datapoints; $($this.options.footer).children().text( $si.i18N.Window.footerLabelSelectedChartSeries + $this.options.totalSeries +" "+$si.i18N.Window.footerLabelChartData + $this.options.totalDataPoints); } }, _getChartLegendsProperties: function () { var $this = this; $this.options.chartLegendFavoriteData = $this.options.chart.series; return $this._super(); }, _applyChartFavorite : function(){ var $this = this; $this._super(); if ($this.options.favouriteObj.chartType && $this.options.favouriteObj.chartType != "") { // var seriesType = $this._getChartAndSeriesType($this.options.favouriteObj.chartType); $this._changeChartType($this.options.favouriteObj.chartType); } }, _applyChartLegendFavorites: function (chartLegendProperties) { var $this = this; var series = $this.options.chart.series; var seriesCount = 0; var datapoints = 0; var j = 0; for (var i = 0; i < series.length; i++) { if (j < chartLegendProperties.length) { if (series[i].name == chartLegendProperties[j].name) { if (!chartLegendProperties[j].visible) { $this.options.chart.series[i].hide(); datapoints = datapoints + $this.options.chart.series[i].data.length; seriesCount++; } else { $this.options.chart.series[i].show(); seriesCount --; datapoints = datapoints - $this.options.chart.series[i].data.length; } j++; } } } $this.options.totalSeries = $this.options.totalSeries - seriesCount; $this.options.totalDataPoints = $this.options.totalDataPoints - datapoints; $($this.options.footer).children().text( $si.i18N.Window.footerLabelSelectedChartSeries + $this.options.totalSeries +" "+$si.i18N.Window.footerLabelChartData + $this.options.totalDataPoints); $this.options.legendContainer.siViewerChartLegend("updateChartLegendState", { series: $this.options.chart.series, }); }, _syncLegendData : function(){ var $this = this; if($this.options.chart.series){ $this._super($this.options.chart.series); } }, updateSeriesDataPointsFooter : function(selectedNode){ var $this = this; var seriesCount = 0; var datapoints = 0; if($this.options.chart){ var series = $this.options.chart.series; if (series && series.length > 0) { for (var i = 0; i < series.length; i++) { if (series[i].name == selectedNode) { if (!$this.options.chart.series[i].visible) { datapoints = datapoints + $this.options.chart.series[i].data.length; seriesCount++; } else { seriesCount --; datapoints = datapoints - $this.options.chart.series[i].data.length; } } } $this.options.totalSeries = $this.options.totalSeries - seriesCount; $this.options.totalDataPoints = $this.options.totalDataPoints - datapoints; $($this.options.footer).children().text( $si.i18N.Window.footerLabelSelectedChartSeries + $this.options.totalSeries +" "+$si.i18N.Window.footerLabelChartData + $this.options.totalDataPoints); } } }, _selectItemInChartTypeDropDown : function(){ var $this = this; var toolbar = $this.options.toolBar; var chartTypeDropdown = toolbar.find("#chartselectorTool"); var dropdownlist = chartTypeDropdown.data("kendoDropDownList"); $this.options.chartType = $this.options.chartObj.chart.type; var setChartType = $this._setChartAndSeriesType($this.options.chartType); if(dropdownlist){ $.each(dropdownlist.dataSource.data(), function(key,value){ if(value.chartType == setChartType){ dropdownlist.select(key); } }); } }, _setDefaultDataLabels: function(){ var $this = this; if ($this.options.chart) { if (this.options.chartSeriesDetails.defaultSeriesProperties.dataLabels) { var dataLabels = this.options.chartSeriesDetails.defaultSeriesProperties.dataLabels; if (dataLabels.enabled) { $this.showHideDataLabels(true); } else { $this.showHideDataLabels(false); } } } var toolbar = $this.options.toolBar; if (toolbar) { var dataLabels = this._getWindowConfigurationByProperty("chartSeries").defaultSeriesProperties.dataLabels; var chartDataLabelTool = $this.element.parent().find("#chartdatalabelTool"); if (dataLabels.enabled) { $this.showHideDataLabelsTool(true); } else { $this.showHideDataLabelsTool(false); } } }, _setTickPositioner : function(data){ var $this = this; if(data.tickPositioner && window[data.tickPositioner]!=undefined){ return window[data.tickPositioner]; } }, onWindowToolControlClick : function(toolId){ var $this = this; if(toolId == "saveasTool"){ $si.viewer.windowParams = windowParams; $this.options.exportToCSVWindow = $si.windowUtil.openExportCSVWindow('xyChart','500','250'); } else { $this._super(toolId); } }, }); });
function solution(w, h) { let min = Math.min(w, h); let max = Math.max(w, h); let gcdVal = gcd(min, max); return (w * h) - (min + max - gcdVal); } function gcd(a, b) { return (a % b === 0) ? b : gcd(b, a % b); }
const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const { comparePasswords } = require('../auth/helpers'); const { Users } = require('../db'); passport.use(new LocalStrategy(async (username, password, done) => { try { const user = await Users.getUserByUsername(username); if (!user) { return done(null, false, { message: "username doesn't exists" }) } const passMatch = await comparePasswords(password, user.password_digest); if (!passMatch) { return done(null, false, { message: "invalid password" }) } delete user.password_digest; done(null, user); } catch (err) { done(err) } })) passport.serializeUser((user, done) => { done(null, user) }) passport.deserializeUser(async (user, done) => { try { let retrievedUser = await Users.getUserById(user.id) delete retrievedUser.password_digest; done(null, retrievedUser) } catch (err) { done(err, false) } }) module.exports = passport;
const insertCategoryButton = document.getElementById("insertCategoryButton"); const insertCategoryArea = document.getElementById("insertCategoryArea"); insertCategoryButton.addEventListener("click", function (e) { e.preventDefault(); insertCategoryArea.innerHTML = "<form action='' class='formInsert' method='post'>" + "<div class='form-group'><label>Nom : <input type='text' class=\"form-control\" name='name_category' placeholder='Kayak' required></label></div>" + "<div class='form-group'><label>Description : <input type='text' class=\"form-control\" name='description_category' placeholder='Un kayak pour faire le mariole' required></label></div>" + "<div class='form-group'><label>Puissance (0 si non motorisé) : <input type='number' class=\"form-control\" name='power' value='0' required></label></div>" + "<div class='form-group'><label>Prix HT (en €) : <input type='number' class=\"form-control\" name='price' placeholder='200' required></label></div>" + "<div class='form-group'><label>Image : <input type='text' class=\"form-control\" name='image' placeholder='Kayak.jpg' required></label></div>" + "<div class='form-group'><label> Quantité </label><input class=\"form-control\" type=\"number\" name=\"amount\" /> "+ " <select class=\"form-control\" name='availability'>" + " <option value=\"1\"> En service </option>" + " <option value=\"2\"> Indisponible </option>" + " <option value=\"3\"> Hors service </option>" + " </select></div>"+ "<button class='btn-success btn' type='submit' name='insert' id='insertEquipment'>Ajouter</button></div>" + "</form>" })
import React from 'react'; import { MyStylesheet } from './styles'; import { registerCompanyIcon, goCheckIcon, goToIcon } from './svg'; import { Link } from 'react-router-dom'; import { RegisterNewCompany } from './actions/api'; import { validateCompanyID } from './functions'; import Construction from './construction'; class Company { validatenewcompany() { let validate = {}; validate.validate = true; validate.message = "" if (!this.state.urlcheck) { validate.validate = false; validate.message += this.state.message; } return validate; } handleurl(url) { this.setState({ url }); let validate = validateCompanyID(url); if (validate) { this.setState({ urlcheck: false, message: validate }) } else { let message = `Your Company Will be Hosted at ${process.env.REACT_APP_CLIENT_API}/company/${url}` this.setState({ urlcheck: true, message }) } } async registernewcompany() { const company = new Company(); const construction = new Construction(); let myuser = construction.getuser.call(this) let validate = company.validatenewcompany.call(this); if (myuser) { if (validate.validate) { if (window.confirm(`Are you sure you want to register Company: ${this.state.url} ?`)) { if (myuser) { let url = this.state.url; let values = {url,providerid:myuser.providerid} try { let response = await RegisterNewCompany(values); console.log(response) if (response.hasOwnProperty("myuser")) { this.props.reduxUser(response.myuser); this.setState({ message: '' }) } } catch (err) { alert(err) } } } } else { this.setState({ message: validate.message }) } } } handleCompany() { const construction = new Construction(); const styles = MyStylesheet() const myuser = construction.getuser.call(this) const headerFont = construction.getHeaderFont.call(this) const regularFont = construction.getRegularFont.call(this) const company = new Company() const goIcon = construction.getgocheckheight.call(this) const registerIcon = construction.getRegisterIcon.call(this); const buttonSize = construction.buttonSize.call(this) const urlicon = (myuser) => { if (this.state.urlcheck && !myuser.hasOwnProperty("company")) { return (<button style={{ ...styles.generalButton, ...goIcon }}>{goCheckIcon()}</button>) } } const registericon = (myuser) => { if (this.state.urlcheck && !myuser.hasOwnProperty("company")) { return (<div style={{ ...styles.generalContainer, ...regularFont, ...styles.generalFont }}> <button style={{ ...styles.generalButton, ...registerIcon }} onClick={() => { company.registernewcompany.call(this) }}> {registerCompanyIcon()} </button> <br /> {this.state.message} </div>) } else { return (<div style={{ ...styles.generalContainer, ...regularFont, ...styles.generalFont }}> {this.state.message} </div>) } } if (myuser) { if (!myuser.hasOwnProperty("company")) { return ( <div style={{ ...styles.generalContainer }}> <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1, ...styles.bottomMargin15 }}> <span style={{ ...styles.generalFont, ...headerFont }}> Create A New Company</span> </div> </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Company URL</span> <br /> <input type="text" value={this.state.url} onChange={event => { company.handleurl.call(this, event.target.value) }} onBlur={event => { construction.validatecompanyid.call(this, event.target.value) }} style={{ ...styles.addLeftMargin, ...regularFont, ...styles.generalFont, ...styles.generalField }} /> {urlicon(myuser)} </div> {registericon(myuser)} </div>) } else { return ( <div style={{ ...styles.generalContainer, ...styles.bottomMargin15 }}> <button style={{...styles.generalButton, ...buttonSize}}>{goToIcon()}</button> <Link to={`/${myuser.profile}/company/${myuser.company.url}`} style={{ ...styles.generalLink, ...styles.generalFont, ...headerFont, ...styles.boldFont }}> {myuser.company.url} </Link> </div>) } } } showCompany() { const construction = new Construction(); const regularFont = construction.getRegularFont.call(this) const styles = MyStylesheet(); const myuser = construction.getuser.call(this) const company = new Company(); if (myuser) { return ( <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> {company.handleCompany.call(this)} </div> </div> ) } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Please Login to View Company </span> </div>) } } } export default Company;
import React, { Component } from 'react'; import logo from './logo.svg'; import {TimelineMax, TweenMax, Elastic} from 'gsap' import './App.css'; // import axios from 'axios'; var tl = new TimelineMax({ repeat:-1 }); let animation = new TimelineMax({ repeat:1, yoyo:true }) class App extends Component { constructor(){ super() this.state = { paused:true, } } componentDidMount() { tl.add( TweenMax.to('.test', 1, {backgroundColor: 'blue'})) tl.add( TweenMax.to('.test', 1, {backgroundColor: 'yellow'})) tl.add( TweenMax.to('.test', 1, {backgroundColor: 'green'})) tl.add( TweenMax.to('.test', 1, {backgroundColor: 'red'})) tl.add( TweenMax.to('.test', 1, {backgroundColor: 'orange'})) tl.pause(); animation.staggerTo('.div', 2, {backgroundColor:'orange', ease:Elastic.easeOut}, .3) .staggerTo('.div', 3, {width:'200px', ease:Elastic.easeOut}, .3) } animate(event) { if (this.state.paused) { tl.resume() this.setState({ paused:false, }) } else { tl.pause() this.setState({ paused:true, }) } } render() { return ( <div className="App"> <div onClick={(e)=>{this.animate(e)}} className='test'>Test div</div> <div className='div'>A</div> <div className='div'>B</div> <div className='div'>C</div> <div className='div'>D</div> <div className='div'>E</div> <div className='div'>F</div> </div> ); } } export default App;
// console.log("Functions in js"); function greet(name, greetText = "Greeetings from Javascript") { let name1 = "Name1"; // console.log(name1); console.log(greetText + " " + name); console.log(name + " is good programmer"); } function sum(a, b, c) { let d = a + b + c; return d; } let name = "Harry"; let name1 = "shubham"; let name2 = "Rohan"; let name3 = "Sagar"; let greetText = "Good Morning"; greet(name, greetText); greet(name1); let returnVal = sum(10, 20, 30); console.log(returnVal); // greet(name2, greetText); // greet(name3, greetText);
window.onload = ()=>{ let cuerpo = document.querySelector('body'); let btnReservar = document.querySelector("button"); btnReservar.addEventListener('click', validar); function validar(){ cuerpo.style.backgroundColor = 'red'; } };
jQuery(document).ready(function($){ var $activeCSSClass = 'active'; $('.ga-tab-link').on('click',function(e){ e.preventDefault(); let $this = $(this), $thisTarget = $this.attr('href'); $('.ga-tab-link').removeClass($activeCSSClass); $('.ga-tab-content').removeClass($activeCSSClass); $this.addClass($activeCSSClass); $($thisTarget).addClass($activeCSSClass); }); $('.backlinker').on('click',function(e){ $('.sub-menu.ga-mobile-menu-sub').removeClass($activeCSSClass); }) $('.menu-item-has-children > a').on('click',function(e){ e.preventDefault(); let $submenu = $(this).siblings( '.sub-menu' ), $allSubmenu = $('.sub-menu.ga-mobile-menu-sub'); $allSubmenu.removeClass( $activeCSSClass ); $submenu.addClass( $activeCSSClass ); }) $('.ga-mobile-menu-toggle').on('click',function( e ){ e.preventDefault(); let $menuToggle = $( this ), $menuContainer = $('#ga-tab-container'); if( $menuToggle.hasClass( $activeCSSClass ) ){ $menuToggle.removeClass( $activeCSSClass ); $menuContainer.removeClass( $activeCSSClass ).slideUp(); }else{ $menuToggle.addClass( $activeCSSClass ); $menuContainer.addClass( $activeCSSClass ).slideDown(); } }); });
const express = require('express'); const Card = require('../models/Card'); const { isLoggedIn } = require('../services/authServices'); const router = express.Router(); // GET view Card screen router.get('/:userName/:cardID', async (req, res) => { // search for card ID, card will contain user ID, return card info console.log(req.params.userName); }); // POST to create a new Card router.post('/add', isLoggedIn, async (req, res) => { // from user screen a new card can be created // purpose - form input, creates a new card that will be stored according to all input data console.log('**************test********', req.user.id); try { let { userName, title, description, skillsRequired, location, endCard, status, } = req.body; let card = new Card(); card.postedBy = req.user.id; // tried req.user, but user name was not being added to card DB. card.title = title; card.description = description; card.skillsRequired = skillsRequired; card.location = location; card.endCard = endCard; card.status = status; await card.save(); res.status(200).json({ data: card }); } catch (err) { console.log(err); res.json({ message: 'An error occured', err }).sendStatus(400); } }); // GET edit Card screen // router.get("/edit/", isLoggedIn, (req, res) => { // // from user screen, select card and make edits, should be able to get req.user - not working at present. // let loggedInName; // console.log(req.user.id, req.params) // User.findOne({_id: req.user.id}, (err, doc) => { // if (err) console.log(err); // loggedInName = doc. // }); // // // need to find card based on URI, // // verify that appropriate user is logged in // if (userName === loggedInName) { //compared to posted by card name // // search for card, verify postedBy matches userName and then provide data // Card.findOne({_id: cardID}, (err, doc) => { // if (err) { // console.log(err); // mongoose.connection.close(); // } else { // if (doc.postedBy === userName) { // console.log("found card", doc) // //provide data ?? // res.status(200).json({data: doc}); // // mongoose.connection.close(); // } else { // console.log("User not authorized to edit card"); // mongoose.connection.close(); // } // } // }); // } // } catch (err) { // console.log(err); // res.json({message: "An error occured", err}).sendStatus(400); // } // // }); // PUT to edit a Card router.put('/update', isLoggedIn, async (req, res) => { console.log(req.user); // data has been updated, saving to card handled Here // verify user is logged in and matches userName, then find card and update values // req.user should return userID }); module.exports = router;
// miniprogram/pages/price/price.js Page({ /** * 页面的初始数据 */ data: { pnum:0, cx:false, jiaru:false, imagelist:[{ "img_url":"https://img11.360buyimg.com/n1/jfs/t3313/167/1704661422/268137/e55d221/583152f9N6660f774.jpg" }, { "img_url":"https://img11.360buyimg.com/n1/jfs/t3778/2/1731259055/268137/e55d221/583152edN9de7ec18.jpg"}] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { const db = wx.cloud.database(); db.collection('details').where({ _id:"W - q6Ftx_Lia3NQnk" }).get({ success: res => { this.setData({ queryResult: res.data }) console.log(this.data.queryResult) }, }) }, jiaru:function(){ var pd = this.data.jiaru if (pd == false) { pd = true } else { pd = false } console.log(pd) this.setData({ jiaru: pd }) }, jia:function(){ var pnum = this.data.pnum pnum++ this.setData({ pnum: pnum }) }, jian: function () { var pnum = this.data.pnum pnum-- if(pnum<=0){ pnum=0 } this.setData({ pnum: pnum }) }, cuxiao:function(){ var pd = this.data.cx if (pd==false){ pd=true }else{ pd = false } console.log(pd) this.setData({ cx:pd }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
import React, { useEffect, useState } from "react"; import { FlatList, Keyboard, Text, TextInput, TouchableOpacity, View, ImageBackground, } from "react-native"; import styles from "./styles"; import { firebase } from "../../firebase/config"; export default function HomeScreen() { return ( <View> <Text>Hello HomeScreen!</Text> </View> ); }
function clearall(){ vectors.removeFeatures(vectors.features); } function clearSelected(){ vectors.removeFeatures(vectors.selectedFeatures); } /*<script type="text/ecmascript">*/ function operation_toggleControl(obj,operation){ //////////////////////pointToggle if (obj==3 && operation=='hide'){ for (var i=0;i<document.getElementsByTagName('circle').length;i++){ document.getElementsByTagName('circle')[i].setAttributeNS(null,"display",'none') } }else if (obj==3 && operation=='show'){ for (var i=0;i<document.getElementsByTagName('circle').length;i++){ document.getElementsByTagName('circle')[i].setAttributeNS(null,"display",'block') } }else if (obj==3 && operation=='delete'){ for (var i=vectors.features.length; i-- > 0;){ if (vectors.features[i].geometry.id.indexOf("OpenLayers.Geometry.Point") !=-1){ vectors.removeFeatures(vectors.features[i]); } } } //////////////lineToggle else if (obj==2 && operation=='hide'){ for (var i=0;i<document.getElementsByTagName('polyline').length;i++){ document.getElementsByTagName('polyline')[i].setAttributeNS(null,"display",'none') } }else if (obj==2 && operation=='show'){ for (var i=0;i<document.getElementsByTagName('polyline').length;i++){ document.getElementsByTagName('polyline')[i].setAttributeNS(null,"display",'block') } }else if (obj==2 && operation=='delete'){ for (var i=vectors.features.length; i-- > 0;){ if (vectors.features[i].geometry.id.indexOf("OpenLayers.Geometry.LineString") !=-1){ vectors.removeFeatures(vectors.features[i]); } } } /////////////////////////polygonToggle else if ((obj==4 || obj==5) && operation=='hide'){ for (var i=0;i<document.getElementsByTagName('path').length;i++){ document.getElementsByTagName('path')[i].setAttributeNS(null,"display",'none') } }else if ((obj==4 || obj==5) && operation=='show'){ for (var i=0;i<document.getElementsByTagName('path').length;i++){ document.getElementsByTagName('path')[i].setAttributeNS(null,"display",'block') } }else if ((obj==4 || obj==5) && operation=='delete'){ for (var i=vectors.features.length; i-- > 0;){ if (vectors.features[i].geometry.id.indexOf("OpenLayers.Geometry.Polygon") !=-1){ vectors.removeFeatures(vectors.features[i]); } } } ////////////////////////markersToggle else if (obj==1 && operation=='hide'){ markersLayer.display(false); } else if (obj==1 && operation=='show'){ markersLayer.display(true); } else if (obj==1 && operation=='delete'){ markersLayer.clearMarkers(); } } function osm_remove_geofence(){ for (var i=document.getElementsByTagName('path').length; i-- > 0;){ document.getElementsByTagName('path')[i].parentNode.removeChild(document.getElementsByTagName('path')[i]); } }
import { Message } from 'element-ui'; import notificationMessages from './messages'; export const createCommaSeparatedList = (array, propertyName) => { return (_.map(array, propertyName)).join(', '); } export const showErrorMessage = (path) => { Message.error(getNotification(path)); }; export const showError = (message) => { Message.error(message); }; export const showSuccessMessage = (path) => { Message.success(getNotification(path)); }; let getNotification = notification => _.get(notificationMessages, notification);
getData(); function getData() { $.get("/ajax/get_host_stats", function(resp) { memory = resp['memory'] cpu_user = resp['cpu_user'] cpu_system = resp['cpu_system'] cpu_guest = resp['cpu_guest'] dates = resp['dates'] iowait = resp['iowait'] max_memory = resp['max_memory'][0] max_memory_arr = resp['max_memory'] console.log(max_memory) d = new Date(); d2 = new Date(); d2.setHours(d.getHours() - 1); makeMemory(); makeCPU(); makeIOwait(); }); }; function makeMemory() { $('#memory').highcharts({ title: { text: "" }, yAxis: { title: { text: 'Memory Used (MB)' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, xAxis: { title: { text: "Minutes Ago" }, categories: [ 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], tickInterval:10 }, tooltip: { valueSuffix: 'MB', shared: 'true' }, legend: { enabled:false }, credits: { enabled:false }, series: [{ name: 'Memory Total (MB)', data: max_memory_arr, type: 'area', color: '#FFA161' }, { name: 'Memory Used (MB)', data: memory, type: 'area', color: '#ff802b' }] }); }; function makeCPU() { $('#cpu').highcharts({ title: { text: "" }, yAxis: { max: 100, title: { text: 'CPU Used (%)' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, xAxis: { title: { text: "Minutes Ago" }, categories: [ 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], tickInterval:10 }, tooltip: { valueSuffix: '%', shared: true }, plotOptions: { area: { stacking: 'normal' } }, legend: { enabled:false }, credits: { enabled:false }, series: [{ name: 'CPU User (%)', data: cpu_user, type: 'area', color: '#FFA161' }, { name: 'CPU Guest (%)', data: cpu_guest, type: 'area', color: '#ff802b' }, { name: 'CPU System (%)', data: cpu_system, type: 'area', color: '#ff6700' }] }); }; function makeIOwait() { $('#iowait').highcharts({ title: { text: "" }, yAxis: { max: 100, title: { text: 'IOWait (%)' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, xAxis: { title: { text: "Minutes Ago" }, categories: [ 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], tickInterval:10 }, tooltip: { valueSuffix: '%' }, legend: { enabled:false }, credits: { enabled:false }, series: [{ name: 'IOWait (%)', data: iowait, type: 'area', color: '#FFA161' }] }); };
// https://www.freecodecamp.org/news/express-explained-with-examples-installation-routing-middleware-and-more/ // https://medium.com/@viral_shah/express-middlewares-demystified-f0c2c37ea6a1 // https://www.sohamkamani.com/blog/2018/05/30/understanding-how-expressjs-works/ var port = 8000; var express = require('express'); var app = express(); var path = require('path'); const { Pool } = require('pg') const pool = new Pool({ user: 'webdbuser', host: 'localhost', database: 'webdb', password: 'password', port: 5432 }); const bodyParser = require('body-parser'); // we used this middleware to parse POST bodies function isObject(o){ return typeof o === 'object' && o !== null; } function isNaturalNumber(value) { return /^\d+$/.test(value); } // app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // app.use(bodyParser.raw()); // support raw bodies // Non authenticated route. Can visit this without credentials app.post('/api/test', function (req, res) { res.status(200); res.json({"message":"got here"}); }); /** * * Retrieve top 10 scores of each level from database * */ app.get('/api/scores', function (req, res) { var easy_scores = {}; var medium_scores = {}; var hard_scores = {}; let sql_easy_scores = "SELECT * FROM ftdstats WHERE level = 'easy' ORDER BY score DESC LIMIT 10;"; let sql_medium_scores = "SELECT * FROM ftdstats WHERE level = 'medium' ORDER BY score DESC LIMIT 10;"; let sql_hard_scores = "SELECT * FROM ftdstats WHERE level = 'hard' ORDER BY score DESC LIMIT 10;"; // the sql callbacks are nested since they are asychronous and the function may return before all scores are retrieved pool.query(sql_easy_scores, [], (err, pgRes) => { if(err){ res.status(404).json({'message': 'Unknown error occured'}); return; } else{ easy_scores = build_scores_json(pgRes); pool.query(sql_medium_scores, [], (err, pgRes) => { if(err){ res.status(404).json({'message': 'Unknown error occured'}); return; } else{ medium_scores = build_scores_json(pgRes); pool.query(sql_hard_scores, [], (err, pgRes) => { if(err){ res.status(404).json({'message': 'Unknown error occured'}); return; } else{ hard_scores = build_scores_json(pgRes); // All scores are retrieved now so return to the users res.status(200); res.json({"message":"scores retrieved", "easy_scores":easy_scores, "medium_scores":medium_scores, "hard_scores":hard_scores}); } }); } }); } }); }); /** * * Retrieve top 10 number of enemies of each level from database * */ app.get('/api/enemies', function (req, res) { var easy_numbers_of_enemies = {}; var medium_numbers_of_enemies = {}; var hard_numbers_of_enemies = {}; let sql_easy_numbers_of_enemies = "SELECT * FROM ftdstats WHERE level = 'easy' ORDER BY enemies DESC LIMIT 10;"; let sql_medium_numbers_of_enemies = "SELECT * FROM ftdstats WHERE level = 'medium' ORDER BY enemies DESC LIMIT 10;"; let sql_hard_numbers_of_enemies = "SELECT * FROM ftdstats WHERE level = 'hard' ORDER BY enemies DESC LIMIT 10;"; // the sql callbacks are nested since they are asychronous and the function may return before all numbers of enemies are retrieved pool.query(sql_easy_numbers_of_enemies, [], (err, pgRes) => { if(err){ res.status(404).json({'message': 'Unknown error occured'}); return; } else{ easy_numbers_of_enemies = build_numbers_of_enemies_json(pgRes); pool.query(sql_medium_numbers_of_enemies, [], (err, pgRes) => { if(err){ res.status(404).json({'message': 'Unknown error occured'}); return; } else{ medium_numbers_of_enemies = build_numbers_of_enemies_json(pgRes); pool.query(sql_hard_numbers_of_enemies, [], (err, pgRes) => { if(err){ res.status(404).json({'message': 'Unknown error occured'}); return; } else{ hard_numbers_of_enemies = build_numbers_of_enemies_json(pgRes); // All numbers of enemies are retrieved now so return to the users res.status(200); res.json({"message":"enemies retrieved", "easy_numbers_of_enemies":easy_numbers_of_enemies, "medium_numbers_of_enemies":medium_numbers_of_enemies, "hard_numbers_of_enemies":hard_numbers_of_enemies}); } }); } }); } }); }); /** * * Handle registration requests from users * */ app.post('/api/register', function (req, res) { // check if the information provided by the user contains any error (backend validation) var input_error = register_validate(req); if (JSON.stringify(input_error) != '{}'){ return res.status(404).json(input_error); } var username = req.body['reg_username']; // get the username that the user requests // check if the username already exists in the db let sql_username = 'SELECT * FROM ftduser WHERE username=$1'; pool.query(sql_username, [username], (err, pgRes) => { if (err){ res.status(404).json({'message': 'Unknown error occured'}); } else if(pgRes.rowCount != 0){ // username already exists return res.status(409).json({"message":"Username exists"}); } else{ // username doesn't exist in db, so insert the user into db let sql_register = "INSERT INTO ftduser VALUES($1, sha512($2), $3, $4, $5, $6, true)"; pool.query(sql_register, [req.body['reg_username'], req.body['reg_password'], req.body['reg_email'], req.body['reg_phone'], req.body['reg_birthday'], req.body['reg_level']], (err, pgRes) => { if (err){ res.status(404).json({'message': 'Unknown error occured'}); } else { res.status(201).json({'message': 'Registration succeeded'}); } }); } }); }); /** * This is middleware to restrict access to subroutes of /api/auth/ * To get past this middleware, all requests should be sent with appropriate * credentials. Now this is not secure, but this is a first step. * * Authorization: Basic YXJub2xkOnNwaWRlcm1hbg== * Authorization: Basic " + btoa("arnold:spiderman"); in javascript **/ app.use('/api/auth', function (req, res,next) { if (!req.headers.authorization) { return res.status(401).json({ error: 'No credentials sent!' }); } try { // var credentialsString = Buffer.from(req.headers.authorization.split(" ")[1], 'base64').toString(); var m = /^Basic\s+(.*)$/.exec(req.headers.authorization); var user_pass = Buffer.from(m[1], 'base64').toString() m = /^(.*):(.*)$/.exec(user_pass); // probably should do better than this var username = m[1]; var password = m[2]; // check if the username matches the password in db let sql_login = 'SELECT * FROM ftduser WHERE username=$1 and password=sha512($2)'; pool.query(sql_login, [username, password], (err, pgRes) => { if (err){ res.status(401).json({ error: 'Not authorized'}); } else if(pgRes.rowCount == 1){ next(); } else { res.status(401).json({ error: 'Not authorized'}); } }); } catch(err) { res.status(401).json({ error: 'Not authorized'}); } }); // All routes below /api/auth require credentials /** * * Handle login requests from uesrs * */ app.post('/api/auth/login', function (req, res) { // retrieve the username from the authorization header var m = /^Basic\s+(.*)$/.exec(req.headers.authorization); var user_pass = Buffer.from(m[1], 'base64').toString() m = /^(.*):(.*)$/.exec(user_pass); // probably should do better than this var username = m[1]; // search the user in db and return all the information of the user except password let sql_login = 'SELECT username, email, phone, birthday, level FROM ftduser WHERE username=$1'; pool.query(sql_login, [username], (err, pgRes) => { if (err){ res.status(403).json({ error: 'Unknown error'}); } else if(pgRes.rowCount == 1){ // find the user // return all the information of the user var info = {}; info["username"] = pgRes["rows"][0]["username"]; info["email"] = pgRes["rows"][0]["email"]; info["phone"] = pgRes["rows"][0]["phone"]; info["birthday"] = pgRes["rows"][0]["birthday"]; info["level"] = pgRes["rows"][0]["level"]; info["message"] = "authentication success"; res.status(200); res.json(info); } else { res.status(404).json({ error: 'Unknown error'}); } }); }); /** * * Handle profile modification requests from users * */ app.put('/api/auth/modify', function (req, res) { // check if the information provided by the user contains any error (backend validation) var input_error = save_validate(req); if (JSON.stringify(input_error) != '{}'){ return res.status(404).json(input_error); } // Check if password needs to be updated if (req.body['profile_password'] != ""){ // need to update password let sql_update = "UPDATE ftduser SET password = sha512($1), email = $2, phone = $3, birthday = $4, level = $5 WHERE username = $6;"; pool.query(sql_update, [req.body['profile_password'], req.body['profile_email'], req.body['profile_phone'], req.body['profile_birthday'], req.body['profile_level'], req.body['profile_username']], (err, pgRes) => { if (err){ res.status(403).json({'message': 'Unknown error occured'}); } else { res.status(200).json({'message': 'Save succeeded'}); } }); } else{ // don't need to update password let sql_update = "UPDATE ftduser SET email = $1, phone = $2, birthday = $3, level = $4 WHERE username = $5;"; pool.query(sql_update, [req.body['profile_email'], req.body['profile_phone'], req.body['profile_birthday'], req.body['profile_level'], req.body['profile_username']], (err, pgRes) => { if (err){ res.status(403).json({'message': 'Unknown error occured'}); } else { res.status(200).json({'message': 'Save succeeded'}); } }); } }); /** * * Handle profile deletion requests from users * */ app.delete('/api/auth/delete', function (req, res) { // retrieve the username from the authorization header var m = /^Basic\s+(.*)$/.exec(req.headers.authorization); var user_pass = Buffer.from(m[1], 'base64').toString() m = /^(.*):(.*)$/.exec(user_pass); // probably should do better than this var username = m[1]; // delete the user in db and return let sql_update = "DELETE FROM ftduser WHERE username = $1;"; pool.query(sql_update, [username], (err, pgRes) => { if (err){ res.status(403).json({'message': 'Fail to delete profile'}); } else { res.status(200).json({'message': 'Profile deleted'}); } }); }); /** * * Handle recording stats requests from users * */ app.post('/api/auth/record', function (req, res) { // check if the information provided by the user contains any error (backend validation) if (!("score" in req.body) || !isNaturalNumber(req.body["score"]) || req.body["score"] < 0 || req.body["score"] > 2147483647){ return res.status(404).json({'message': 'Invalid score'}); } if (!("enemies" in req.body) || !isNaturalNumber(req.body["enemies"]) || req.body["enemies"] < 0 || req.body["enemies"] > 2147483647){ return res.status(404).json({'message': 'Invalid enemies'}); } if (!('level' in req.body) || (req.body['level'] != 'easy' && req.body['level'] != 'medium' && req.body['level'] != 'hard')){ return res.status(404).json({'message': 'Invalid level'}); } // retrieve the username from the authorization header var m = /^Basic\s+(.*)$/.exec(req.headers.authorization); var user_pass = Buffer.from(m[1], 'base64').toString() m = /^(.*):(.*)$/.exec(user_pass); // probably should do better than this var username = m[1]; // insert the username, stats and level of difficulty to db let sql_record = "INSERT INTO ftdstats VALUES(CURRENT_TIMESTAMP, $1, $2, $3, $4)"; pool.query(sql_record, [username, req.body['level'], req.body['score'], req.body['enemies']], (err, pgRes) => { if (err){ res.status(404).json({'message': 'Unknown error occured'}); } else { res.status(201).json({'message': 'Score and enemies recorded'}); } }); }); app.post('/api/auth/test', function (req, res) { res.status(200); res.json({"message":"got to /api/auth/test"}); }); // serve all static files app.use('/',express.static(path.join(__dirname + '/static_content/'))); app.listen(port, function () { console.log('Example app listening on port '+port); }); // ------------------------------------------------------------Helper Function--------------------------------------------- /** * * Retrieve the usernamse and the scores from pgRes and package them into json * */ function build_scores_json(pgRes){ var scores = {}; for (var i=0;i<pgRes.rowCount;i++){ var score_user = pgRes["rows"][i]["username"]; var score_num = pgRes["rows"][i]["score"]; var score = {score_user, score_num}; scores[i+1] = score; } return scores; } /** * * Retrieve the usernamse and the numbers of enemies from pgRes and package them into json * */ function build_numbers_of_enemies_json(pgRes){ var numbers_of_enemies = {}; for (var i=0;i<pgRes.rowCount;i++){ var number_of_enemies_user = pgRes["rows"][i]["username"]; var number_of_enemies_num = pgRes["rows"][i]["enemies"]; var number_of_enemies = {number_of_enemies_user, number_of_enemies_num}; numbers_of_enemies[i+1] = number_of_enemies; } return numbers_of_enemies; } /** * * Check all the information in users' registration requests to see if there is any error * */ function register_validate(req){ var input_error = {}; // validate all inputs // username must not include colon if (!('reg_username' in req.body) || req.body['reg_username'] == '' || req.body['reg_username'].includes(':') || req.body['reg_username'].length > 20){ input_error["reg_username"] = "is invalid" } // password must have length >= 3 if (!('reg_password' in req.body) || req.body['reg_password'].length < 3){ input_error["reg_password"] = "is invalid" } // password must match if (!('reg_password_again' in req.body) || req.body['reg_password'] != req.body['reg_password_again']){ input_error["reg_password"] = "is invalid" } // email must contain @ and have length >=3 if (!('reg_email' in req.body) || req.body['reg_email'].length < 3 || !req.body['reg_email'].includes('@') || req.body['reg_email'].length > 256){ input_error["reg_email"] = "is invalid" } // phone must match the regex var regex_phone = new RegExp("[0-9]{3}-[0-9]{3}-[0-9]{4}"); if (!('reg_phone' in req.body) || req.body['reg_phone'].length != 12 || !regex_phone.test(req.body['reg_phone'])){ input_error["reg_phone"] = "is invalid" } // birthday must match the regex var regex_date = new RegExp("[0-9]{4}-[0-9]{2}-[0-9]{2}"); if (!('reg_birthday' in req.body) || req.body['reg_birthday'].length != 10 || !regex_date.test(req.body['reg_birthday'])){ input_error["reg_birthday"] = "is invalid" } else{ var date_check = new Date(req.body['reg_birthday']); if (isNaN(date_check.getTime())){ input_error["reg_birthday"] = "is invalid" } } // level must be one of easy, medium, hard if (!('reg_level' in req.body) || (req.body['reg_level'] != 'easy' && req.body['reg_level'] != 'medium' && req.body['reg_level'] != 'hard')){ input_error["reg_level"] = "is invalid" } // privacy must be checked if (!('reg_privacy' in req.body) || req.body['reg_privacy'] != 'true'){ input_error["reg_privacy"] = "is invalid" } return input_error; } /** * * Check all the information in users' profile modificatioin requests to see if there is any error * */ function save_validate(req){ var input_error = {}; // retrieve the username var m = /^Basic\s+(.*)$/.exec(req.headers.authorization); var user_pass = Buffer.from(m[1], 'base64').toString() m = /^(.*):(.*)$/.exec(user_pass); // probably should do better than this var username = m[1]; // validate all inputs // username must not include colon if (!('profile_username' in req.body) || req.body['profile_username'] != username || req.body['profile_username'].length > 20){ input_error["profile_username"] = "is invalid" } if ('profile_password' in req.body && 'profile_password_again' in req.body){ // password must have length >= 3 if (req.body['profile_password'] == "" && req.body['profile_password_again'] == ""){ } else{ // password must match if (req.body['profile_password'].length < 3 || req.body['profile_password'] != req.body['profile_password_again']){ input_error["profile_password"] = "is invalid" } } } else{ input_error["profile_password"] = "is invalid" } // email must contain @ and have length >=3 if (!('profile_email' in req.body) || req.body['profile_email'].length < 3 || !req.body['profile_email'].includes('@') || req.body['profile_email'].length > 256){ input_error["profile_email"] = "is invalid" } // phone must match the regex var regex_phone = new RegExp("[0-9]{3}-[0-9]{3}-[0-9]{4}"); if (!('profile_phone' in req.body) || req.body['profile_phone'].length != 12 || !regex_phone.test(req.body['profile_phone'])){ input_error["profile_phone"] = "is invalid" } // birthday must match the regex var regex_date = new RegExp("[0-9]{4}-[0-9]{2}-[0-9]{2}"); if (!('profile_birthday' in req.body) || req.body['profile_birthday'].length != 10 || !regex_date.test(req.body['profile_birthday'])){ input_error["profile_birthday"] = "is invalid" } else{ var date_check = new Date(req.body['profile_birthday']); if (isNaN(date_check.getTime())){ input_error["profile_birthday"] = "is invalid" } } // level must be one of easy, medium, hard if (!('profile_level' in req.body) || (req.body['profile_level'] != 'easy' && req.body['profile_level'] != 'medium' && req.body['profile_level'] != 'hard')){ input_error["profile_level"] = "is invalid" } // privacy must be checked if (!('profile_privacy' in req.body) || req.body['profile_privacy'] != 'true'){ input_error["profile_privacy"] = "is invalid" } return input_error; }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var axios = _interopDefault(require('axios')); var lodash = require('lodash'); var inflection = require('inflection'); // default http client let client; // supported content type const CONTENT_TYPE = 'application/json'; // default http headers const HEADERS = { Accept: CONTENT_TYPE, 'Content-Type': CONTENT_TYPE, }; /** * @function createHttpClient * @name createHttpClient * @description create an http client if not exists * @param {String} API_URL base url to use to api calls * @return {Axios} A new instance of Axios * @since 0.1.0 * @version 0.1.0 * @static * @public * @example * import { createHttpClient } from 'emis-api-client'; * const httpClient = createHttpClient(); */ const createHttpClient = API_BASE_URL => { if (!client) { // Dont destructure: Fix:ReferenceError: process is not defined in react const env = process.env; // eslint-disable-line const { EMIS_API_URL, REACT_APP_EMIS_API_URL } = env; const BASE_URL = API_BASE_URL || EMIS_API_URL || REACT_APP_EMIS_API_URL; const options = { baseURL: BASE_URL, headers: HEADERS }; client = axios.create(options); client.id = Date.now(); } return client; }; /** * @function disposeHttpClient * @name disposeHttpClient * @description reset current http client in use. * @since 0.1.0 * @version 0.1.0 * @example * import { disposeHttpClient } from 'emis-api-client'; * disposeHttpClient(); */ const disposeHttpClient = () => { client = null; return client; }; /** * @function get * @name get * @description issue http get request to specified url. * @param {String} url valid http path. * @param {Object} [params] params that will be encoded into url query params. * @return {Promise} promise resolve with data on success or error on failure. * @since 0.1.0 * @version 0.1.0 * @example * import { get } from 'emis-api-client'; * * // list * const getUsers = get('/users', { age: { $in: [1, 2] } }); * getUsers.then(users => { ... }).catch(error => { ... }); * * // single * const getUser = get('/users/12'); * getUser.then(user => { ... }).catch(error => { ... }); */ const get = (url, params) => { const httpClient = createHttpClient(); return httpClient.get(url, { params }); }; /** * @function post * @name post * @description issue http post request to specified url. * @param {String} url valid http path. * @param {Object} data request payload to be encoded on http request body * @return {Promise} promise resolve with data on success or error on failure. * @since 0.1.0 * @version 0.1.0 * @example * import { post } from 'emis-api-client'; * * const postUser = post('/users', { age: 14 }); * postUser.then(user => { ... }).catch(error => { ... }); */ const post = (url, data) => { if (lodash.isEmpty(data)) { return Promise.reject(new Error('Missing Payload')); } const httpClient = createHttpClient(); return httpClient.post(url, data); }; /** * @function put * @name put * @description issue http put request to specified url. * @param {String} url valid http path. * @param {Object} data request payload to be encoded on http request body * @return {Promise} promise resolve with data on success or error on failure. * @since 0.1.0 * @version 0.1.0 * @example * import { put } from 'emis-api-client'; * * const putUser = put('/users/5c1766243c9d520004e2b542', { age: 11 }); * putUser.then(user => { ... }).catch(error => { ... }); */ const put = (url, data) => { if (lodash.isEmpty(data)) { return Promise.reject(new Error('Missing Payload')); } const httpClient = createHttpClient(); return httpClient.put(url, data); }; /** * @function patch * @name patch * @description issue http patch request to specified url. * @param {String} url valid http path. * @param {Object} data request payload to be encoded on http request body * @return {Promise} promise resolve with data on success or error on failure. * @since 0.1.0 * @version 0.1.0 * @example * import { patch } from 'emis-api-client'; * * const patchUser = patch('/users/5c1766243c9d520004e2b542', { age: 10 }); * patchUser.then(user => { ... }).catch(error => { ... }); */ const patch = (url, data) => { if (lodash.isEmpty(data)) { return Promise.reject(new Error('Missing Payload')); } const httpClient = createHttpClient(); return httpClient.patch(url, data); }; /** * @function del * @name del * @description issue http delete request to specified url. * @param {String} url valid http path. * @return {Promise} promise resolve with data on success or error on failure. * @since 0.1.0 * @version 0.1.0 * @example * import { del } from 'emis-api-client'; * * const deleteUser = del('/users/5c1766243c9d520004e2b542'); * deleteUser.then(user => { ... }).catch(error => { ... }); */ const del = url => { const httpClient = createHttpClient(); return httpClient.delete(url); }; // create dynamic camelized function name const fn = (...name) => lodash.camelCase([...name].join(' ')); // get resource id from payload const idOf = data => lodash.get(data, '_id') || lodash.get(data, 'id'); /** * @function createHttpActionsFor * @name createHttpActionsFor * @description generate name http action shortcut to interact with resource * @param {String} resource valid http resource. * @return {Object} http actions to interact with a resource * @since 0.1.0 * @version 0.1.0 * @example * import { createHttpActionsFor } from 'emis-api-client'; * * const { deleteUser } = createHttpActionsFor('user'); * const deleteUser = del('/users/5c1766243c9d520004e2b542'); * deleteUser.then(user => { ... }).catch(error => { ... }); */ const createHttpActionsFor = resource => { const singular = inflection.singularize(resource); const plural = inflection.pluralize(resource); const httpActions = { [fn('get', singular, 'Schema')]: () => get(`/${lodash.toLower(plural)}/schema`).then(response => response.data), [fn('get', plural)]: params => get(`/${lodash.toLower(plural)}`, params).then(response => response.data), [fn('get', singular)]: id => get(`/${lodash.toLower(plural)}/${id}`).then(response => response.data), [fn('post', singular)]: data => post(`/${lodash.toLower(plural)}`, data).then(response => response.data), [fn('put', singular)]: data => put(`/${lodash.toLower(plural)}/${idOf(data)}`, data).then( response => response.data ), [fn('patch', singular)]: data => patch(`/${lodash.toLower(plural)}/${idOf(data)}`, data).then( response => response.data ), [fn('delete', singular)]: id => del(`/${lodash.toLower(plural)}/${id}`).then(response => response.data), }; return httpActions; }; const { getActivitySchema, getActivities, getActivity, postActivity, putActivity, patchActivity, deleteActivity, } = createHttpActionsFor('activity'); const { getAdjustmentSchema, getAdjustments, getAdjustment, postAdjustment, putAdjustment, patchAdjustment, deleteAdjustment, } = createHttpActionsFor('adjustment'); const { getAlertSchema, getAlerts, getAlert, postAlert, putAlert, patchAlert, deleteAlert, } = createHttpActionsFor('alert'); const { getAssessmentSchema, getAssessments, getAssessment, postAssessment, putAssessment, patchAssessment, deleteAssessment, } = createHttpActionsFor('assessment'); const { getFeatureSchema, getFeatures, getFeature, postFeature, putFeature, patchFeature, deleteFeature, } = createHttpActionsFor('feature'); const { getIncidentTypeSchema, getIncidentTypes, getIncidentType, postIncidentType, putIncidentType, patchIncidentType, deleteIncidentType, } = createHttpActionsFor('incidentType'); const { getIndicatorSchema, getIndicators, getIndicator, postIndicator, putIndicator, patchIndicator, deleteIndicator, } = createHttpActionsFor('indicator'); const { getItemSchema, getItems, getItem, postItem, putItem, patchItem, deleteItem, } = createHttpActionsFor('item'); const { getPartySchema, getParties, getParty, postParty, putParty, patchParty, deleteParty, } = createHttpActionsFor('party'); const { getPermissionSchema, getPermissions, getPermission, postPermission, putPermission, patchPermission, deletePermission, } = createHttpActionsFor('permission'); const { getPlanSchema, getPlans, getPlan, postPlan, putPlan, patchPlan, deletePlan, } = createHttpActionsFor('plan'); const { getProcedureSchema, getProcedures, getProcedure, postProcedure, putProcedure, patchProcedure, deleteProcedure, } = createHttpActionsFor('procedure'); const { getQuestionSchema, getQuestions, getQuestion, postQuestion, putQuestion, patchQuestion, deleteQuestion, } = createHttpActionsFor('question'); const { getQuestionnaireSchema, getQuestionnaires, getQuestionnaire, postQuestionnaire, putQuestionnaire, patchQuestionnaire, deleteQuestionnaire, } = createHttpActionsFor('questionnaire'); const { getRoleSchema, getRoles, getRole, postRole, putRole, patchRole, deleteRole, } = createHttpActionsFor('role'); const { getStockSchema, getStocks, getStock, postStock, putStock, patchStock, deleteStock, } = createHttpActionsFor('stock'); const { getWarehouseSchema, getWarehouses, getWarehouse, postWarehouse, putWarehouse, patchWarehouse, deleteWarehouse, } = createHttpActionsFor('warehouse'); exports.getActivitySchema = getActivitySchema; exports.getActivities = getActivities; exports.getActivity = getActivity; exports.postActivity = postActivity; exports.putActivity = putActivity; exports.patchActivity = patchActivity; exports.deleteActivity = deleteActivity; exports.getAdjustmentSchema = getAdjustmentSchema; exports.getAdjustments = getAdjustments; exports.getAdjustment = getAdjustment; exports.postAdjustment = postAdjustment; exports.putAdjustment = putAdjustment; exports.patchAdjustment = patchAdjustment; exports.deleteAdjustment = deleteAdjustment; exports.getAlertSchema = getAlertSchema; exports.getAlerts = getAlerts; exports.getAlert = getAlert; exports.postAlert = postAlert; exports.putAlert = putAlert; exports.patchAlert = patchAlert; exports.deleteAlert = deleteAlert; exports.getAssessmentSchema = getAssessmentSchema; exports.getAssessments = getAssessments; exports.getAssessment = getAssessment; exports.postAssessment = postAssessment; exports.putAssessment = putAssessment; exports.patchAssessment = patchAssessment; exports.deleteAssessment = deleteAssessment; exports.getFeatureSchema = getFeatureSchema; exports.getFeatures = getFeatures; exports.getFeature = getFeature; exports.postFeature = postFeature; exports.putFeature = putFeature; exports.patchFeature = patchFeature; exports.deleteFeature = deleteFeature; exports.getIncidentTypeSchema = getIncidentTypeSchema; exports.getIncidentTypes = getIncidentTypes; exports.getIncidentType = getIncidentType; exports.postIncidentType = postIncidentType; exports.putIncidentType = putIncidentType; exports.patchIncidentType = patchIncidentType; exports.deleteIncidentType = deleteIncidentType; exports.getIndicatorSchema = getIndicatorSchema; exports.getIndicators = getIndicators; exports.getIndicator = getIndicator; exports.postIndicator = postIndicator; exports.putIndicator = putIndicator; exports.patchIndicator = patchIndicator; exports.deleteIndicator = deleteIndicator; exports.getItemSchema = getItemSchema; exports.getItems = getItems; exports.getItem = getItem; exports.postItem = postItem; exports.putItem = putItem; exports.patchItem = patchItem; exports.deleteItem = deleteItem; exports.getPartySchema = getPartySchema; exports.getParties = getParties; exports.getParty = getParty; exports.postParty = postParty; exports.putParty = putParty; exports.patchParty = patchParty; exports.deleteParty = deleteParty; exports.getPermissionSchema = getPermissionSchema; exports.getPermissions = getPermissions; exports.getPermission = getPermission; exports.postPermission = postPermission; exports.putPermission = putPermission; exports.patchPermission = patchPermission; exports.deletePermission = deletePermission; exports.getPlanSchema = getPlanSchema; exports.getPlans = getPlans; exports.getPlan = getPlan; exports.postPlan = postPlan; exports.putPlan = putPlan; exports.patchPlan = patchPlan; exports.deletePlan = deletePlan; exports.getProcedureSchema = getProcedureSchema; exports.getProcedures = getProcedures; exports.getProcedure = getProcedure; exports.postProcedure = postProcedure; exports.putProcedure = putProcedure; exports.patchProcedure = patchProcedure; exports.deleteProcedure = deleteProcedure; exports.getQuestionSchema = getQuestionSchema; exports.getQuestions = getQuestions; exports.getQuestion = getQuestion; exports.postQuestion = postQuestion; exports.putQuestion = putQuestion; exports.patchQuestion = patchQuestion; exports.deleteQuestion = deleteQuestion; exports.getQuestionnaireSchema = getQuestionnaireSchema; exports.getQuestionnaires = getQuestionnaires; exports.getQuestionnaire = getQuestionnaire; exports.postQuestionnaire = postQuestionnaire; exports.putQuestionnaire = putQuestionnaire; exports.patchQuestionnaire = patchQuestionnaire; exports.deleteQuestionnaire = deleteQuestionnaire; exports.getRoleSchema = getRoleSchema; exports.getRoles = getRoles; exports.getRole = getRole; exports.postRole = postRole; exports.putRole = putRole; exports.patchRole = patchRole; exports.deleteRole = deleteRole; exports.getStockSchema = getStockSchema; exports.getStocks = getStocks; exports.getStock = getStock; exports.postStock = postStock; exports.putStock = putStock; exports.patchStock = patchStock; exports.deleteStock = deleteStock; exports.getWarehouseSchema = getWarehouseSchema; exports.getWarehouses = getWarehouses; exports.getWarehouse = getWarehouse; exports.postWarehouse = postWarehouse; exports.putWarehouse = putWarehouse; exports.patchWarehouse = patchWarehouse; exports.deleteWarehouse = deleteWarehouse; exports.CONTENT_TYPE = CONTENT_TYPE; exports.HEADERS = HEADERS; exports.createHttpClient = createHttpClient; exports.disposeHttpClient = disposeHttpClient; exports.get = get; exports.post = post; exports.put = put; exports.patch = patch; exports.del = del; exports.createHttpActionsFor = createHttpActionsFor;
function provjera(string) { if(string.name == "name") { if(string.value =="" || !provjeriIme(string.value)) { string.style.backgroundColor = "red"; document.getElementById("imeError").innerHTML = "Ime je obavezno polje - 3 ili vise slova"; return false; } else { string.style.backgroundColor = "white"; document.getElementById("imeError").innerHTML = ""; document.getElementById("dugmeError").innerHTML = ""; return true; } } else if(string.name == "email") { if(!provjeriEmail(string.value)) { string.style.backgroundColor = "red"; document.getElementById("mailError").innerHTML = "Unesite ispravan email: primjer@primjer.com"; return false; } else { string.style.backgroundColor = "white"; document.getElementById("mailError").innerHTML = ""; document.getElementById("dugmeError").innerHTML = ""; return true; } } else if(string.name == "poruka") { if(string.value =="") { string.style.backgroundColor = "red"; document.getElementById("porukaError").innerHTML = "Molimo Vas unesite poruku"; return false; } else { string.style.backgroundColor = "white"; document.getElementById("porukaError").innerHTML = ""; document.getElementById("dugmeError").innerHTML = ""; return true; } } } function provjeriEmail(mail) { var regex = /^[^\s@]+\@[^\s@]+\.[^\s@]+$/g; return regex.test(mail); } function provjeriIme(ime) { var regex = /^[a-zA-Z ]{3,30}$/; return regex.test(ime); } function provjeriPoruku(poruka) { if(poruka =="") { document.getElementById("porukaError").innerHTML = "Molimo Vas unesite poruku"; return false; } return true; } function provjeriFormu() //posalji { var ime = document.getElementById("name"); var mail = document.getElementById("email"); var poruka= document.getElementById("poruka"); if(!provjeriIme(ime.value)) { document.getElementById("dugmeError").innerHTML = "Molimo Vas unesite sva polja ispravno!"; return false; } else if(!provjeriEmail(mail.value)) { document.getElementById("dugmeError").innerHTML = "Molimo Vas unesite sva polja ispravno!"; return false; } else if(!provjeriPoruku(poruka.value)) { document.getElementById("dugmeError").innerHTML = "Molimo Vas unesite sva polja ispravno!"; return false; } else { document.getElementById("dugmeError").innerHTML = ""; return true; } }
//////////////////////////////////////////////////////////////////////////////// // Component: PostContent.js // Description: content area of a blog post // Author: Andrew McNaught // Date Created: 20/10/2016 // Date Modified: 20/10/2016 //////////////////////////////////////////////////////////////////////////////// import React from "react"; export default class PostContent extends React.Component { constructor() { super(); this.state = { }; } render() { //console.log("rendering post content"); return ( <div className="post-content" > <div className="post-content-inner" > {this.props.content} </div> </div> ); } }
/*** Date picker ***/ $(function() { jQuery( "#date_of_birth" ).datepicker({ changeMonth: true, changeYear: true, yearRange: '1950:' + new Date().getFullYear(), dateFormat: 'dd-mm-yy', maxDate: "+0D" }); }); /** DatetimePicker with start and end date **/ <!-- Jquery Time Date Picker insert css and js --> <style type="text/css"> .ui-timepicker-div .ui-widget-header { margin-bottom: 8px; } .ui-timepicker-div dl { text-align: left; } .ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; } .ui-timepicker-div dl dd { margin: 10px 10px 10px 65px; } .ui-timepicker-div td { font-size: 90%; } .ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; } </style> <script type="text/javascript" src="js/jquery-ui-1.10.3.custom.min.js"></script> <script type="text/javascript" src="js/jquery-ui-timepicker-addon.js"></script> <script type="text/javascript" src="js/jquery-ui-sliderAccess.js"></script> $(function() { /*** For date and time picker ***/ var startDateTextBox = $('#event_start_date'); var endDateTextBox = $('#event_end_date'); startDateTextBox.datetimepicker({ ampm: true, changeMonth: true, changeYear: true, yearRange: "-10:+10", dateFormat: 'dd-mm-yy', minDateTime: 0, onSelect: function (selectedDateTime){ var time = new Date($(this).datetimepicker('getDate').getTime()); endDateTextBox.datetimepicker('option', 'minDateTime',time); // endDateTextBox.datetimepicker('option', 'minDateTime', startDateTextBox.datetimepicker('getDate') ); }, beforeShow: function(){ startDateTextBox.datetimepicker("option", { maxDate: endDateTextBox.datetimepicker('getDate') }); } }); endDateTextBox.datetimepicker({ ampm: true, changeMonth: true, changeYear: true, yearRange: "-10:+10", dateFormat: 'dd-mm-yy', minDateTime: 0, onClose: function(dateText, inst) { if (startDateTextBox.val() != '') { var testStartDate = startDateTextBox.datetimepicker('getDate'); var testEndDate = endDateTextBox.datetimepicker('getDate'); if (testStartDate > testEndDate) startDateTextBox.datetimepicker('setDate', testEndDate); }else { startDateTextBox.val(dateText); } }, onSelect: function (selectedDateTime){ var time = new Date($(this).datetimepicker('getDate').getTime()); startDateTextBox.datetimepicker('option', 'maxDateTime',time); //startDateTextBox.datetimepicker('option', 'maxTimeDate', endDateTextBox.datetimepicker('getDate') ); }, beforeShow: function(){ if (startDateTextBox.val() != '') { endDateTextBox.datetimepicker("option", { minDate: startDateTextBox.datetimepicker('getDate') }); } } }); /** For timepicker only **/ var time = new Date(); $('#from').timepicker({ ampm: true, hourMin: 9, hourMax: 19, timeFormat: 'hh:mm TT', onClose: function(dateText, inst) { var startDateTextBox = $('#to'); if (startDateTextBox.val() != '') { var testStartDate = new Date(startDateTextBox.val()); var testEndDate = new Date(dateText); if (testStartDate > testEndDate) startDateTextBox.val(dateText); } else { startDateTextBox.val(dateText); } }, onSelect: function(dateText){ var time = new Date($(this).datetimepicker('getDate').getTime()); $('#to').timepicker('option', 'minDateTime',time); } }); $('#to').timepicker({ ampm: true, hourMin: 10, hourMax: 21, timeFormat: 'hh:mm TT', onClose: function(dateText, inst) { var startDateTextBox = $('#from'); if (startDateTextBox.val() != '') { var testStartDate = new Date(startDateTextBox.val()); var testEndDate = new Date(dateText); if (testStartDate > testEndDate) startDateTextBox.val(dateText); } else { startDateTextBox.val(dateText); } }, onSelect: function(dateText){ var time = new Date($(this).datetimepicker('getDate').getTime()); $('#from').timepicker('option', 'maxDateTime',time); } }); /** Date time picker with one date **/ <script> $(function() { $('#deal_end_date').datetimepicker({ changeMonth: true, changeYear: true, yearRange: "-10:+10", dateFormat: 'dd-mm-yy', timeFormat: "hh:mm tt", minDateTime: 0,// minDate: "+0D", ampm: true, }); $("#from_date").datepicker({ dateFormat: 'dd-mm-yy', changeMonth: true, changeYear: true, maxDate: new Date(), onSelect: function(selected) { var date = $(this).datepicker('getDate'); if(date != null){ date.setDate(date.getDate() + 1); $('#to_date').datepicker('option', 'minDate', date); } }, beforeShow: function(){ var date = $(this).datepicker('getDate'); if(date != null){ date.setDate(date.getDate() + 1); $('#to_date').datepicker('option', 'minDate', date); } } }); $("#to_date").datepicker({ dateFormat: 'dd-mm-yy', changeMonth: true, changeYear: true, maxDate: new Date(), onSelect: function(selected) { var date = $(this).datepicker('getDate'); if(date != null){ date.setDate(date.getDate() - 1); $("#from_date").datepicker("option","maxDate", date) } }, beforeShow: function(){ var date = $(this).datepicker('getDate'); if(date != null){ date.setDate(date.getDate() - 1); $("#from_date").datepicker("option","maxDate", date) } } }); }); </script> $('#task_start_time').timepicker({ ampm: true, timeFormat: 'hh:mm TT', }); $('#task_end_time').timepicker({ ampm: true, timeFormat: 'hh:mm TT', beforeShow: function(){ task_start_date = $("#task_start_date").val() task_end_date = $("#task_end_date").val() if(task_start_date.valueOf() == task_end_date.valueOf()){ task_start_time = $("#task_start_time").val() if(task_start_time == ""){ var time = new Date(); $('#task_end_time').timepicker('option', 'minDateTime',time); }else{ var time = new Date($('#task_start_time').datetimepicker('getDate').getTime()); $('#task_end_time').timepicker('option', 'minDateTime',time); } }else{ var time = new Date($('#task_start_time').datetimepicker("getDate")); $('#task_end_time').timepicker('option', 'minDateTime',null); } } }); Validation var today = new Date(); function parseDMY(value) { var date = value.split("/"); var d = parseInt(date[0], 10), m = parseInt(date[1], 10), y = parseInt(date[2], 10); return new Date(y, m - 1, d); } var authorValidator = $("#itemAuthorForm").validate({ rules: { dateOfBirth: { required: false, dateITA: true, dateLessThan: '#expiredDate' }, expiredDate: { required: false, dateITA: true, dateGreaterThan: "#dateOfBirth" } }, onfocusout: function (element) { if ($(element).val()) { $(element).valid(); } } }); var dateOptionsDOE = { maxDate: today, dateFormat: "dd/mm/yy", changeMonth: true, changeYear: true, onClose: function (selectedDate) { $("#dateOfBirth").datepicker("option", "maxDate", selectedDate); } }; var dateOptionsDOB = { maxDate: today, dateFormat: "dd/mm/yy", changeMonth: true, changeYear: true, onClose: function (selectedDate) { $("#expiredDate").datepicker("option", "minDate", selectedDate); } }; jQuery.validator.addMethod("dateGreaterThan", function (value, element, params) { var theDate = parseDMY(value); var paramDate = parseDMY($(params).val()); if ($(params).val() === "") return true; if (!/Invalid|NaN/.test(theDate)) { return theDate > paramDate; } return isNaN(value) && isNaN($(params).val()) || (Number(value) > Number($(params).val())); }, 'Must be greater than {0}.'); jQuery.validator.addMethod("dateLessThan", function (value, element, params) { var theDate = parseDMY(value); var paramDate = parseDMY($(params).val()); if ($(params).val() === "") return true; if (!/Invalid|NaN/.test(theDate)) { return theDate < paramDate; } return isNaN(value) && isNaN($(params).val()) || (Number(value) < Number($(params).val())); }, 'Must be less than {0}.'); $("#expiredDate").datepicker($.extend({}, $.datepicker.regional['en-GB'], dateOptionsDOE)); $("#dateOfBirth").datepicker($.extend({}, $.datepicker.regional['en-GB'], dateOptionsDOB)); function( value, element ) { return this.optional(element) || /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(value); } //dd-mm-yy $.validator.addMethod("dateValid", function(value, element) { return this.optional(element) || /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(value); }); my_date_format('2015-07-11') var my_date_format = function(input){ //console.log(input) var d = new Date(Date.parse(input.replace(/-/g, "/"))); //console.log(d) var month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; //var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; //var date = d.getDate() + "-" + month[d.getMonth()] + "-" + d.getFullYear(); var date = ("0" + d.getDate()).slice(-2) + "-" + month[d.getMonth()] + "-" + d.getFullYear(); var time = d.toLocaleTimeString().toLowerCase().replace(/([\d]+:[\d]+):[\d]+(\s\w+)/g, "$1$2"); //console.log(date) return (date); }; Greater than current date and time dateHigherThanToday: true $.validator.addMethod("dateLessThanToday", function(value, element) { var date= value; var myDate=new Date(date.split("-").reverse().join("-")); return myDate < new Date(); }); $.validator.addMethod("dateHigherThanToday", function(value, element) { var date= value; var myDate=new Date(date.split("-").reverse().join("-")); return myDate >= new Date(); }); Greater than current date function leadingZero(value){ if(value < 10){ return "0" + value.toString(); } return value.toString(); } $.validator.addMethod("dateHigherThanToday", function(value, element) { var date = value; var myDate = new Date(date.split("-").reverse().join("-")); console.log(myDate) //convert month to 2 digits<p> var targetDate = new Date(); targetDate.setDate(targetDate.getDate() ); var dd = targetDate.getDate(); var mm = targetDate.getMonth() + 1; var yyyy = targetDate.getFullYear(); var dateCurrent = leadingZero(dd) + "-" + leadingZero(mm) + "-" + yyyy; dateCurrent = new Date(dateCurrent.split("-").reverse().join("-")); console.log(dateCurrent); return myDate >= dateCurrent; }); /** +18 validation **/ $.validator.addMethod("check_date_of_birth", function(value, element) { var day = $("#dob_day").val(); var month = $("#dob_month").val(); var year = $("#dob_year").val(); var age = 18; var mydate = new Date(); mydate.setFullYear(year, month-1, day); var currdate = new Date(); currdate.setFullYear(currdate.getFullYear() - age); return currdate > mydate; }, "You must be at least 18 years of age."); PYDOB: { required: true, date: true, check_date_of_birth:true }, $.validator.addMethod("check_date_of_birth", function(value, element) { var dobDate = $("#PYDOB").val(); var age = 18; var mydate = new Date(dobDate); var currdate = new Date(); currdate.setFullYear(currdate.getFullYear() - age); return currdate > mydate; }, "You must be at least 18 years of age."); $('#PYDOB').datepicker({ changeMonth: true, changeYear: true, //yearRange: '1950:' + new Date().getFullYear(), dateFormat: 'mm/dd/yy', //maxDate: "+0D", yearRange: "-115:-18", //18 years or older up until 115yo (oldest person ever, can be sensibly set to something much smaller in most cases) maxDate: "-18Y", //Will only allow the selection of dates more than 18 years ago, useful if you need to restrict this minDate: "-115Y" }); var day = $("#dobDay").val(); var month = $("#dobMonth").val(); var year = $("#dobYear").val(); var age = 18; var mydate = new Date(); mydate.setFullYear(year, month-1, day); var currdate = new Date(); currdate.setFullYear(currdate.getFullYear() - age); var output = currdate - mydate if ((currdate - mydate) > 0){ // you are not 18 } /** boostrap */ var from = $('.from').datepicker({ autoclose: true }).on('changeDate', function(e){ $('.to').datepicker({ autoclose: true }).datepicker('setStartDate', e.date).focus(); }); //var _startDate = new Date(2012,1,20); //var _endDate = new Date(2012,1,25); var _startDate = new Date(); //alert(_startDate); var _endDate = new Date(_startDate.getTime() + (24 * 60 * 60 * 1000)); //plus 1 day $('#from').datepicker({ format: 'mm/dd/yyyy', autoclose: true, startDate: _startDate, todayHighlight: true }).on('changeDate', function(e){ _endDate = new Date(e.date.getTime() + (24 * 60 * 60 * 1000)); //set new end date $('#to').datepicker('setStartDate', _endDate); //dynamically set new start date for #to }); $('#to').datepicker({ format: 'mm/dd/yyyy', autoclose: true, startDate: _endDate, todayHighlight: false }).on('changeDate', function(e){ //if current date is bigger than start date if (e.date.valueOf() < _startDate.valueOf()){ alert(e.date.toString()); //called when date is changed } }); $('#txtDateTo').datepicker({ autoclose: true, endDate: "today", format: 'dd-M-yyyy', clearBtn: true }).on('changeDate', function (ev) { endDate = new Date(ev.date.getTime() + (24 * 60 * 60 * 1000)); $('#txtDateFrom').data('datepicker').setStartDate(endDate); }) $('#txtDateFrom').datepicker({ autoclose: true, endDate: "today", format: 'dd-M-yyyy', clearBtn: true }).on('changeDate', function (ev) { startDate = new Date(ev.date.getTime() - (24 * 60 * 60 * 1000)); $('#txtDateTo').data('datepicker').setEndDate(startDate); }) /** datetime difference */ var fromdate = "2016-05-21 16:07:53"; var todate = "2016-05-21 13:07:53"; fromdate = new Date(Date.parse(fromdate.replace(/-/g, "/"))); todate = new Date(Date.parse(todate.replace(/-/g, "/"))); var min = ( fromdate - todate ) / 1000 / 60; //var sec = ( fromdate - todate ) / 1000 / 60 / 60; //var hour = ( fromdate - todate ) / 1000; /** Converting a datetime string to timestamp in Javascript **/ var dateString = '17-09-2013 10:08', dateTimeParts = dateString.split(' '), timeParts = dateTimeParts[1].split(':'), dateParts = dateTimeParts[0].split('-'), date; date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]); console.log(date.getTime()); //1379426880000 console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400 $('#ftd-Form input[name="selFDD"]:radio').click(function() { //radio button click radio_val = $(this).val(); // to get radio button value if(radio_val == 'Today'){ var dt = new Date(); var dt2 = new Date() date2 = dt2.getDate(); month2 = dt2.getMonth(); year2 = dt2.getFullYear(); var breakfast = "09:00:00"; breakfastSplit = breakfast.split(':') var lunch = "12:00:00"; lunchSplit = lunch.split(':') var dinner = "19:00:00"; dinnerSplit = dinner.split(':') bfDate = new Date(year2, month2, date2, breakfastSplit[0], breakfastSplit[1], breakfastSplit[2]); lDate = new Date(year2, month2, date2, lunchSplit[0], lunchSplit[1], lunchSplit[2]); DDate = new Date(year2, month2, date2, dinnerSplit[0], dinnerSplit[1], dinnerSplit[2]); /** console.log(dt.getTime()); console.log(bfDate.getTime()); console.log(lDate.getTime()); console.log(DDate.getTime()); */ if(dt.getTime() > bfDate.getTime()){ $("#FTDS-selDT option[value='Break Fast']").attr('disabled','disabled'); } if(dt.getTime() > lDate.getTime()){ $("#FTDS-selDT option[value='Lunch']").attr('disabled','disabled'); } if(dt.getTime() > DDate.getTime()){ $("#FTDS-selDT option[value='Dinner']").attr('disabled','disabled'); } }else{ $('#FTDS-selDT').find("option").removeAttr("disabled"); } $('#FTDS-selDT').removeAttr("disabled"); }); /** current date conversion **/ $.fn.getFormattedDate = function(date) { var year = date.getFullYear(); var month = (1 + date.getMonth()).toString(); month = month.length > 1 ? month : '0' + month; var day = date.getDate().toString(); day = day.length > 1 ? day : '0' + day; return year + '-' + month + '-' + day; }//yyy-mm-dd var date = new Date(); var getdate = $.fn.getFormattedDate(date); getdate = $.fn.my_date_format_dd_M_yyyy(getdate); $('#txtRWHDate').val( getdate ); //** Bootstrap datepicker **/ $('#txtWWHDate').datepicker({ autoclose: true, endDate: "today", format: 'dd-M-yyyy' }).on('show', function(e){ if($('#txtWWHDate').val()){ var attval = $.fn.my_date_format_yyyymmdd($('#txtWWHDate').val()); var setDate = new Date(attval); //console.log(setDate) $('#txtWWHDate').datepicker('setDate', setDate); } }).on('hide', function(e){ if($('#txtWWHDate').val()){ }else{ var date = new Date(); var getdate = $.fn.getFormattedDate(date); getdate = $.fn.my_date_format_dd_M_yyyy(getdate); $('#txtWWHDate').val( getdate ) } }); /*** Time Convertion **/ function tConvert (time) { // Check correct time format and split into components time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time]; if (time.length > 1) { // If time format correct time = time.slice (1); // Remove full string match value time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM time[0] = +time[0] % 12 || 12; // Adjust hours } return time.join (''); // return adjusted time or original string } tConvert ('18:00:00'); var timeString = "18:00:00"; var H = +timeString.substr(0, 2); var h = (H % 12) || 12; var ampm = H < 12 ? "AM" : "PM"; timeString = h + timeString.substr(2, 3) + ampm; document.write(timeString); /** Bootstrap **/ $.fn.my_date_format_yyyymmdd = function(input){ //console.log(input) var d = new Date(Date.parse(input.replace(/-/g, "/"))); //console.log(d) var month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; var date = d.getFullYear() + "-" + month[d.getMonth()] + "-" + ("0" + d.getDate()).slice(-2); return (date); }; $('#txtDate').datepicker({ autoclose: true, endDate: "today", format: 'dd-M-yyyy' }).on('show', function(e){ var offset = $('#txtDate').offset(); $('.datepicker').css({top: offset.top +"px"}) if($('#txtDate').val()){ var attval = $.fn.my_date_format_yyyymmdd($('#txtDate').val()); var setDate = new Date(attval); //console.log(setDate) $('#txtDate').datepicker('setDate', setDate); } }).on('hide', function(e){ //$('#txtA5').focus(); }); /** bootstrap timepicker **/ $('#dtpSTime').datetimepicker({ format: 'LT', stepping: 15, }).on("dp.show", function (e) { if ($("#dpEdate").val() != '') { var dpEdate = $("#dpEdate").val(); dpEdate = $.fn.date_yyyymmdd(dpEdate); dsplit = new Array(); dsplit = dpEdate.split("-"); y = dsplit[2]; m = dsplit[1]; d = dsplit[0]; if (Date.parse(new Date()) > Date.parse( new Date(y,m,d) )) { var dt = new Date(); var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); $('#dtpSTime').data("DateTimePicker").minDate(moment({hour: dt.getHours(), minute: dt.getMinutes()})); }else{ $('#dtpSTime').data("DateTimePicker").minDate(moment({hour: 00, minute: 00})); } } }).on("dp.change", function (e) { if ($("#dpEdate").val() != '') { var dpEdate = $("#dpEdate").val(); dpEdate = $.fn.date_yyyymmdd(dpEdate); dsplit = new Array(); dsplit = dpEdate.split("-"); y = dsplit[2]; m = dsplit[1]; d = dsplit[0]; if (Date.parse(new Date()) > Date.parse( new Date(y,m,d) )) { var dt = new Date(); var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); $('#dtpSTime').data("DateTimePicker").minDate(moment({hour: dt.getHours(), minute: dt.getMinutes()})); }else{ $('#dtpSTime').data("DateTimePicker").minDate(moment({hour: 00, minute: 00})); } } }); $('#dtpETime').datetimepicker({ format: 'LT', stepping: 15, }).on("dp.show", function (e) { if ($("#dtpSTime").val() != '') { var dtpSTime = $("#dtpSTime").val(); dtpSTime = $.fn.convertTime12to24(dtpSTime) dsplit = new Array(); dsplit = dtpSTime.split(":"); h = dsplit[0]; m = dsplit[1]; $('#dtpETime').data("DateTimePicker").minDate(moment({hour: h, minute: m})); } }); /** Current time **/ var dt = new Date(); var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); /** date compare current date **/ date = $("#datepicker").val(); dsplit = new Array(); dsplit = dpEdate.split("-"); y = dsplit[2]; m = dsplit[1]; d = dsplit[0]; if (Date.parse(new Date()) > Date.parse( new Date(y,m,d) )) { console.log('in') }else{ console.log('out') } //$("#dtpSTime").mask("Hh:Mm Pp"); //$("#dtpETime").mask("Hh:Mm Pp"); //$("#dtpSTime").mask("Hh:Mm"); //$("#dtpETime").mask("Hh:Mm"); $.fn.fomartTimeShow = function(time) { // Check correct time format and split into components time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time]; if (time.length > 1) { // If time format correct time = time.slice (1); // Remove full string match value time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM time[0] = +time[0] % 12 || 12; // Adjust hours } return time.join (''); // return adjusted time or original string } $.fn.fomartTimeShow2 = function(timeString) { var hourEnd = timeString.indexOf(":"); var H = +timeString.substr(0, hourEnd); var h = H % 12 || 12; var ampm = H < 12 ? " AM" : " PM"; timeString = h + timeString.substr(hourEnd, 3) + ampm; return timeString; } //$("#dtpSTime").mask("Hh:Mm Pp"); //$("#dtpETime").mask("Hh:Mm Pp"); $.mask.definitions['H'] = "[0-1]"; $.mask.definitions['h'] = "[0-9]"; $.mask.definitions['M'] = "[0-5]"; $.mask.definitions['m'] = "[0-9]"; $.mask.definitions['P'] = "[AaPp]"; $.mask.definitions['p'] = "[Mm]";
import React from "react"; import { Spring } from "react-spring/renderprops"; export default function Component1() { return ( <Spring from={{ opacity: 0, marginTop: -500 }} to={{ opacity: 1, marginTop: 0 }} > {props => ( <div style={props}> <div style={c1style}> <h1>Component 1</h1> <p> Incididunt et qui occaecat tempor duis ut et elit reprehenderit nostrud. Officia adipisicing veniam quis fugiat. Tempor nostrud eu enim tempor ut veniam veniam. Velit commodo reprehenderit dolor irure mollit veniam magna. Laboris excepteur ipsum anim Lorem tempor sit ut occaecat. </p> <Spring from={{ number: 0 }} to={{ number: 10 }} //it will take 10 secs to animate, toFixed() gets rid of decimals config={{ duration: 10000 }} > {props => ( <div style={props}> <h1 style={counter}>{props.number.toFixed()}</h1> </div> )} </Spring> </div> </div> )} </Spring> ); } const c1style = { background: "steelblue", color: "white", padding: "1.5rem" }; const counter = { background: "#333", textAlign: "center", width: "100px", borderRadius: "50%", margin: "1rem auto" };
import {useReducer} from "react" export const sortOptions = { ASC_TITLE: "asc_title", DSC_TITLE: "dsc_title", ASC_YEAR: "asc_year", DSC_YEAR: "dsc_year" } const initialState = { input: "", sortOption: sortOptions.ASC_TITLE } const actions = { CHANGE_INPUT: "change_input", SET_SORT: "set_sort" } function reducer(state, action){ switch(action.type){ case actions.CHANGE_INPUT: return { ...state, input: action.payload } case actions.SET_SORT: return { ...state, sortOption: action.payload } } } export function useContentState(){ const [state, dispatch] = useReducer(reducer, initialState) return [state, dispatch, actions, sortOptions] }
export const defaultDirection = "new-app"; export const CLI_MESSAGES = { PRJOECT_NAME_QUESTION: "Enter Your Project Name or Default 'new-app' ", SELECT_OPTION_QUESTION: "Select boilerplate to install", SUCCESS_MESSAGE: "Your boilerplate is Successfully created! it's time to hack! (ノ◕ヮ◕)ノ*:・゚✧", FAILURE_MESSAGE: "We can't create bolierplate now. Please try again\n", QUIT_MESSAGE: "Bye!(・∀・)ノ", EXISTED_DEST_ERROR: "Your selected Directory is already existed. Please select other directory\n", EXISTED_TARGET_ERROR: "Your selected Directory is already taken. Please select other directory or empty space\n", INVALID_DIR_NAME_ERROR: "Invalid Directory name\n", }; export const TYPES = { CREATE: "CREATE", QUIT: "QUIT", EXIST_DEST: "EXIST_DEST", EXIST_TARGET: "EXIST_TARGET", };
import { MEDIUM_COVERAGE, SUPER_SALE } from '../../product/constants'; import CarInsuranceModule from '../index'; import ProductModule from '../../product'; let TestCarInsurance = null; const productsList = [ new ProductModule(MEDIUM_COVERAGE, 10, 20), new ProductModule(SUPER_SALE, 3, 6), ]; describe('Module CarInsurance', () => { beforeEach(() => { TestCarInsurance = new CarInsuranceModule(productsList); }); it('should return initial values of products', () => { const { products } = TestCarInsurance; expect(products).toContain(productsList[0]); }); it('should return default values of products', () => { const EmptyCarInsurance = new CarInsuranceModule(); const { products } = EmptyCarInsurance; expect(products).toMatchObject([]); }); it('should return products in string format by day', () => { const string = TestCarInsurance.stringByDay(1); expect(string).toMatch(/-------- day 1 --------/); expect(string).toMatch(/name, sellIn, price/); expect(string).toMatch(/Medium Coverage, 10, 20/); }); it('should return products in string format fort all days', () => { const string = TestCarInsurance.stringAll(5); expect(string).toMatch(/-------- day 0 --------/); expect(string).toMatch(/-------- day 1 --------/); expect(string).toMatch(/-------- day 3 --------/); expect(string).toMatch(/-------- day 5 --------/); expect(string).toMatch(/name, sellIn, price/); expect(string).toMatch(/Medium Coverage, 10, 20/); expect(string).toMatch(/Medium Coverage, 9, 19/); expect(string).toMatch(/Medium Coverage, 7, 17/); expect(string).toMatch(/Medium Coverage, 5, 15/); }); });
var {get} = require("./index"); module.exports = { get: function(req, res, next) { req.params.resource = "football_" + req.params.resource; return get(req, res, next); } };
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const metadataSchema = require('../../../../antares_core/models/metadata-part.model'); const titleSchema = require('../../../../antares_core/models/title-part.model'); const bodySchema = require('../../../../antares_core/models/body-part.model'); const coordinatesSchema = require('../../../../antares_core/models/coordinates-part.model'); let pageSchema = new Schema({ //metadata: [metadataSchema], titleSchema, bodySchema, coordinatesSchema }); // compile schema to bson, telling mongo to use 'pages' collection mongoose.model('Page', pageSchema, 'pages');
import classes from './Contacts.module.css' function Contacts() { return ( <div className={classes.Contacts}> Contacts <h1>Контакты</h1> <div className={classes.iconPhoneBlock}> <i className={classes.icon_phone}></i> <p className={classes.phone}><b> +7-(999)-435-74-36</b></p> </div> <p>Адрес:</p> <p>Старый Бондарь</p> <p>Ростовская область</p> <p>г. Ростов-на-Дону, ул. Берегова 5, въезд со двора.</p> <div className={classes.icons}> <a href="https://instagram.com/nazim_nazimovich_?igshid=1tj08ijhov5vx"> <i className={classes.instogram}></i> </a> <a href="https://l.instagram.com/?u=https%3A%2F%2Fwa.me%2Fc%2F79994357436&e=ATP94kP_1O82lWo8s_3qioGcrn9fr2pLtJCASNUpqSGpXJydGKiES7Hux-qYEupaSI3ZMUux9CwCsz3t&s=1"> <i className={classes.whatsapp}></i> </a> <a href=""> <i className={classes.telegram}></i> </a> </div> </div > ) } export default Contacts;
import fetch from 'unfetch' const getStats = () => { const query = ` query Stats { commits tweets places steps sleep songs album { name artist } books { name author } } ` return fetch('https://stats.lowmess.com/graphql', { method: 'POST', body: JSON.stringify({ query }), headers: { 'Content-Type': 'application/json', }, }) .then(response => { if (!response.ok) { throw new Error(`${response.status}: ${response.statusText}`) } return response.json() }) .then(json => json.data) .catch(error => { console.error(error) }) } export default getStats
import axios from 'axios'; import jwt_decode from 'jwt-decode'; const setAuthToken = (token) => { if (token) { const decoded_token = jwt_decode(token); const tenant = decoded_token.organization; if (typeof tenant === 'undefined') { // remove stored tokens to enable user to re-login localStorage.removeItem('jwtToken'); localStorage.removeItem('currentUser'); throw new Error( "This user's organization could not be determined, Please refresh to login again" ); } // Apply authorization token to every request if logged in axios.defaults.headers.common['Authorization'] = token; axios.interceptors.request.use((config) => { const params = config.params || {}; return { ...config, params: { tenant, ...params } }; }); } else { // Update auth header token to support data access for non-auth users axios.defaults.headers.common[ 'Authorization' ] = `JWT ${process.env.REACT_APP_AUTHORIZATION_TOKEN}`; } }; export default setAuthToken;
var express = require('express'); var router = express.Router(); var TaskCtrl = require("./../app/controller/task"); var path = require('path'); var fs = require('fs'); var multer = require('multer') var passport = require('passport'); var Strategy = require('passport-http-bearer').Strategy; var jsonwebtoken = require('jsonwebtoken'); passport.use(new Strategy( function(token, callback) { jsonwebtoken.verify(token, 'shhhhh', function(err, decoded) { if(err){ console.log(err); callback('Invalid token'); }else{ console.log(decoded) callback(false,decoded); } }); })); var storage = multer.diskStorage({ filename: function (req, file, cb) { console.log(file) cb(null, file.originalname) } }) var upload = multer({ storage: storage }) router.post('/uploadImage',passport.authenticate('bearer', { session: false }),upload.single('file'),TaskCtrl.uploadImage); router.get('/auth', passport.authenticate('bearer', { session: false }),TaskCtrl.auth); router.get('/authr', passport.authenticate('bearer', { session: false }),TaskCtrl.authr); router.get('/myaccount', passport.authenticate('bearer', { session: false }), TaskCtrl.getAtask) router.get('/ques/:id',TaskCtrl.getAques); router.get('/', TaskCtrl.getAlltask); router.get('/contact', TaskCtrl.getAllcontact); router.get('/:id',TaskCtrl.updatetask) router.post('/addtask',TaskCtrl.addtask); router.post('/addcontact',TaskCtrl.addcontact); router.post('/editUser',passport.authenticate('bearer', { session: false }),TaskCtrl.edittask) router.delete('/:id',TaskCtrl.deletetask); router.delete('/contact/:id',TaskCtrl.deletecontact); router.post('/login',TaskCtrl.login); router.get('/gt/',TaskCtrl.greater); router.get('/lt/',TaskCtrl.getMin); router.get('/max/',TaskCtrl.getMax); router.get('/avg/',TaskCtrl.getAvg); router.get('/push/',TaskCtrl.getPushData); router.get('/sum/',TaskCtrl.getSum); module.exports = router;
import React from 'react' import { StyleSheet } from 'quantum' import { ArrowIcon } from 'bypass/ui/icons' const styles = StyleSheet.create({ self: { transition: 'all 0.3s', borderTop: '1px solid #ffffff', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'flex-start', cursor: 'pointer', border: '1px solid #f5f5f5', borderLeft: 0, background: '#e7ecf0', }, viewed: { background: '#ffffff', }, }) const detail = { width: '18px', dataKey: 'detail', flexShrink: 0, cellRenderer: (cellData, dataKey, rowData) => ( <div className={styles({ viewed: rowData.get('cust_id') })}> <ArrowIcon right width={11} /> </div> ), } export default detail
function get10(){ return new Promise((resolve, reject) => { setTimeout(() => resolve(10), 1000) }) } get10().then(() => 20).then(val => console.log(val)). //20 then(50).then(val => console.log(val)). // undefined then(() => get10()).then(val => console.log(val)). // 10 then(get10).then(val => console.log(val)). // 10 then(get10()).then(val => console.log(val)) // undefined
import React,{Component} from 'react' import {connect} from 'react-redux' import {postVote,deletePostAPI} from '../utils/APIcalls' import { votePost,deletePost } from '../actions' import HomeIcon from 'react-icons/lib/md/home' import {Link} from 'react-router-dom' import DetailedPostInfo from './DetailedPostInfo' import CommentGrid from './CommentGrid' import PropTypes from 'prop-types' const homeLink = <Link className="btn btn-link" to="/"><HomeIcon size={30}/></Link> const noPostRender = <div className="container"><br/><br/><br/><h3 className="text-center">No post with that ID and category found, Click {homeLink} for HomePage</h3></div> const PostDeleted = <div className="container"><br/><br/><br/><h3 className="text-center">This post has been deleted, Click {homeLink} for HomePage</h3></div> class DetailedPostPage extends Component { doVote = (id,centiment) => { this.props.votePost(id,centiment) postVote(id,centiment) } postDelete = (id) => { this.props.deletePostById(id) deletePostAPI(id) } render(){ const {post,match} = this.props return <div>{post===undefined || post.category !== match.params.category ? noPostRender : (post.deleted === true ? PostDeleted : <div> <DetailedPostInfo post={post} doVote={this.doVote} deletePostById={this.postDelete}/> <CommentGrid id={post.id}/> </div>)} </div> } } const mapStateToProps = (state,{match}) =>({ post:state[match.params.id] }) const mapDispatchToProps = { votePost, deletePostById:deletePost } DetailedPostPage.propTypes = { votePost:PropTypes.func, deletePostById:PropTypes.func, post:PropTypes.object } export default connect(mapStateToProps,mapDispatchToProps)(DetailedPostPage)
const router = require('express').Router(); const models = require('../models'); const Order = models.Order; router.get("/", (req, res) => { Order.findAll() .then(users => { const userList = users.map(user => Order.dataValues) res.send(userList) }); }); router.get("/:id", (req, resp) => { Order.findOne({where: {id:req.params.id}}) Order.findByPk(req.params.id) .then( user => { resp.send(user) }) }); router.post("/", (req, res) => { Order.create(req.body) .then(user => { res.status(201).send(user) }); }); router.put("/:id", (req, res) => { Order.update({... req.params.body}, {where: {id: req.params.id}}) .then(() => { Order .findByPk(req.params.id) .then(user => res.send(user.dataValues)) }); }); router.delete("/:id", (req, res) => { Order.destroy({where: {id: req.params.id}}) .then(() => res.sendStatus(200)); }); module.exports = router;
import React, { Component } from 'react'; import axios from 'axios'; import Error from '../Error'; import UserDetails from '../UserDetails'; class User extends Component { constructor(props) { super(props); this.state = { response: 0 } this.fetchUser = this.fetchUser.bind(this); this.renderError = this.renderError.bind(this); } componentWillMount() { this.fetchUser(this.props); } componentWillReceiveProps(nextProps) { this.fetchUser(nextProps); } renderPage() { if (this.state.response === 200) { return this.renderUser(); } if (this.state.response === 404) { return this.renderError(); } return ( <div>Loading...</div> ); } renderError() { return ( <Error /> ); } renderUser() { return ( <UserDetails user={this.state.user} friends={this.state.friends} /> ); } async fetchUser(props) { try { const userId = props.match.params.id; const user = await axios.get(`http://localhost:5000/ssn-api/users/${userId}`); const friends = await axios.get(`http://localhost:5000/ssn-api/users/${userId}/friends`); this.setState({ response: 200, user: user.data.user, friends: friends.data.allFriends }); } catch(err) { if (err.response.status === 404) { this.setState({ response: 404 }); } } } render() { return ( <div> {this.renderPage()} </div> ); } } export default User;
(function() { 'use strict'; angular.module('app.controllers') .controller('NoteCtrl', function($scope, session, $stateParams, SessionNotesFactory, $rootScope, $state, note, pictures, videos, audios, DialogFactory) { $scope.init = function() { $rootScope.$emit('inChildState'); // indicate to the nav ctrl that we are in child state to display back button $scope.sessionId = $stateParams.sessionId; $scope.session = session; $scope.noteId = $stateParams.noteId; $scope.note = note; $scope.mode = $stateParams.mode;; $scope.pictures = pictures; $scope.newPictures = []; $scope.audios = audios; $scope.newAudios = []; $scope.videos = videos; $scope.newVideos = []; makeNoteCopy(); // create a copy of the note to know if any note's attribute changed }; $scope.updateNote = function() { if ($scope.noteChanged()) { var queryFn; var message; if ($scope.mode === 'create') { queryFn = SessionNotesFactory.addNote; message = 'créée'; } else { queryFn = SessionNotesFactory.updateNote; message = 'mise à jour'; } queryFn($scope.note, $scope.newPictures, $scope.newVideos, $scope.newAudios).then(function(res) { updateMediasIds(res[1], res[2], res[3]); $scope.mode = 'edit'; // ensure we pass in edit mode if we were in create mode makeNoteCopy(); // actualize savedNote resetMedia(); DialogFactory.showSuccessDialog('La note a bien été ' + message); }, function(err) { DialogFactory.showErrorDialog('Erreur, la note n\'a pas pu être ' + message); }); } }; function updateMediasIds(updatedPictures, updatedVideos, updatedAudios) { for (var i in $scope.newPictures) { $scope.pictures[$scope.pictures.indexOf($scope.newPictures[i])].id = updatedPictures[i].insertId; } for (var i in $scope.newVideos) { $scope.videos[$scope.videos.indexOf($scope.newVideos[i])].id = updatedVideos[i].insertId; } for (var i in $scope.newAudios) { $scope.audios.indexOf($scope.newAudios[i]); $scope.audios[$scope.audios.indexOf($scope.newAudios[i])].id = updatedAudios[i].insertId; } }; function makeNoteCopy() { $scope.savedNote = angular.copy($scope.note); }; function resetMedia() { $scope.newPictures = []; $scope.newVideos = []; $scope.newAudios = []; }; $scope.deleteNote = function() { SessionNotesFactory.deleteNote($scope.noteId).then(function(res) { DialogFactory.showSuccessDialog('La note a bien été supprimée'); $state.go("sessions-detail-notes", { 'sessionId': $scope.sessionId }, { location: "replace", reload: true }); }, function(err) { DialogFactory.showErrorDialog('Erreur, la note n\'a pas été supprimée'); }); }; // to check if the title or comment of the note changed $scope.noteChanged = function() { return $scope.note.title !== $scope.savedNote.title || $scope.note.comment !== $scope.savedNote.comment || $scope.newPictures.length > 0 || $scope.newVideos.length > 0 || $scope.newAudios.length > 0; }; $scope.init(); }); })();
// @flow import { createConnection, type Config } from './Connection'; import type { SocketResponse, SocketAction } from '../types'; type ExtendedConfig = {| dispatch(SocketAction): void, socketUrl: string, |}; export class ConnectionManager { config: ExtendedConfig; connection: $Call<typeof createConnection, Config>; constructor(config: ExtendedConfig) { this.config = config; this.connection = createConnection({ onMessage: this.onMessage, socketUrl: config.socketUrl, reconnect: config.reconnect, onSocketClose: config.onSocketClose, onSocketError: config.onSocketError, onSocketOpen: config.onSocketOpen, }); } send(...args: Array<Object>) { this.connection.send(...args); } close = () => { this.connection.close(); }; onMessage = (message: SocketResponse) => { const action = getAction(message); if (action) { this.config.dispatch(action); } }; } function getAction(obj: SocketResponse): null | SocketAction { if (obj.type) { // $FlowExpectedError return obj; } if (obj.message && obj.message.type) { return obj.message; } return null; }
id: { static: { id: "signUp" }, kreoView: { id: "kreoView" }, kreoPlan: { id: "kreoPlan" } }
/** * Created by jlin on 2016/8/10. */ const React = require('react'); import {connect} from "react-redux"; import {mapStateToProps} from "./ConnectUtil"; const Welcome = React.createClass({ render() { console.log(this.props); return ( <div>Greetings {this.props.userData.name}! </div> ) } }); module.exports = connect(mapStateToProps)(Welcome);
/** * Created by Administrator on 2016/5/20. */ var $root=getRootPath(); function getRootPath(){ //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath=window.document.location.href; //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //获取主机地址,如: http://localhost:8083 var localhostPaht=curWwwPath.substring(0,pos); //获取带"/"的项目名,如:/uimcardprj var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); return(localhostPaht+projectName+"/"); } function getCode() { var couponCode=$("#couponCode").val(); if(""==couponCode||null==couponCode){ Dialog.show("兑换码不能为空", 2, 1000); return ; } Dialog.show("正在处理请求", 3, -1); var url=$root+"/vc/tuihuan.html"; $.ajax({ type:"post", url: url, data:{"couponCode":couponCode}, async : false, success:function(data){ if(data.success=='-1'){ Dialog.show("兑换码不正确", 2, 2000); }else if(data.success=='1'){ Dialog.show("兑换码已经被使用", 2, 2000); }else if(data.success=='2'){ Dialog.show("兑换码已经失效", 2, 2000); }else if(data.success="0"){ Dialog.show("兑换成功", 1, 2000); location.reload(); }else{ Dialog.show("服务器出问题了", 2, 2000); } },error:function(data){ alert("服务器duang了,你可以休息片刻再回来收藏"); } }); // e.stopPropagation(); } //使用优惠券 function useCoupon(money,name,vipCouponId){ /* $("#coupon_price",window.parent.document).html(money); $("#vipCouponName",window.parent.document).html(name); $("#vipCouponId",window.parent.document).val(vipCouponId); //隐藏此iframe $("#vipCouponIframe",window.parent.document).hide(); $("#myform",window.parent.document).show(); //显示主页 window.parent.getTotalPrice();*/ // }
/* * The reducer takes care of state changes in our app through actions */ import {FETCH_ALL_SCHEDULE_TYPES, FETCH_SCHEDULE_TYPES_FULFILLED, SCHEDULE_TYPE_OPERATION_REJECTED,} from '../Actions/ActionTypes' // The initial scheduled state let initialState = { fetchedScheduleTypes: [], ownerType: null, scanType: null, fetching: false, fetched: false, error: null } // Takes care of changing the scheduled state function reducer(state = initialState, action) { switch (action.type) { case FETCH_ALL_SCHEDULE_TYPES: return { ...state, deleteResponse: null, updateResponse: null, createResponse: null, fetching: true, } case FETCH_SCHEDULE_TYPES_FULFILLED: return { ...state, fetched: true, fetchedScheduleTypes: action.payload.items, ownerType: action.payload.ownerType, scanType: action.payload.scanType } case SCHEDULE_TYPE_OPERATION_REJECTED: return { ...state, fetched: false, error: action.payload, } default: return state } } export default reducer
import React from "react"; //Need form elements for: School name, location, degree, start date, end date, description of achievements function EducationForm(props) { const { educationArr, handleEducation, handleNewEducation } = props; const educationList = educationArr.map((school, index) => { return ( <div key={school.id}> <div id="sectionTitle"> <h3>Education {index + 1}</h3> <button className="delSkill" id={school.id} onClick={handleEducation}>X</button> </div> <form> <label htmlFor="schoolName">School Name</label> <input type="text" className={school.id} id="schoolName" name="schoolName" placeholder="School Name" onChange={handleEducation}></input> <label htmlFor="schoolLocation">School Location</label> <input type="text" className={school.id} id="schoolLocation" name="schoolLocation" placeholder="School Location" onChange={handleEducation}></input> <label htmlFor="degree">Degree</label> <input type="text" className={school.id} id="degree" name="degree" placeholder="Degree" onChange={handleEducation}></input> <label htmlFor="schoolDates">Dates Attended - Example: May 2018-Present</label> <input type="text" className={school.id} id="schoolDates" name="schoolDates" placeholder="Dates Attended - Example: May 2018-Present" onChange={handleEducation}></input> <label htmlFor="schoolEnd">End Date</label> <input type="text" className={school.id} id="schoolEnd" name="schoolEnd" placeholder="End Date: Any Format" onChange={handleEducation}></input> <label htmlFor="schoolAchievements">Description of Achievements</label> <textarea className={school.id} id="schoolAchievements" name="schoolAchievements" placeholder="Description of Achievements" onChange={handleEducation}></textarea> </form> </div> ) }); return ( <div> {educationList} <button className="newEducationButton" onClick={handleNewEducation}>+ Add</button> </div> ) } export default EducationForm;
var refreshInterval = 1000; var processIteration = 0; var firstShift = true; var overviewChartMargin = 30; // pulled from lineChart overview margin function d(s){console.debug(s)} window.refresher = null; function toggleData() { // Pause button is displayed on page load when streaming. // Play button is shown when streaming is paused. if (window.refresher) { // streaming => pause clearInterval(window.refresher); window.refresher = null; $("#toggle #play").show()//addClass("disabled"); $("#toggle #pause").hide()//removeClass("disabled"); } else { // pause => streaming window.refresher = setInterval(refresh, refreshInterval); $("#toggle #play").hide()//;removeClass("disabled"); $("#toggle #pause").show()//;addClass("disabled"); } } var graphs = {}; var Processes={ index:{}, // processName: {count:chart, cpu:chart, memory:chart, row:jQueryObject} element:null, // passed on init tableBody:null, // jQuery object, saved here for fast access tableRowTemplate:null, // a handlebars template - is compiled on init sortBy:"memory", init:function(opts){ Processes.options = $.merge({},opts) Processes.element=opts.element Processes.tableBody=$(Processes.element).find("tbody"); Processes.tableRowTemplate = Handlebars.compile($("#process-template").html()); // process sorting $('#processes th[data-sort-by="memory"] .sort-down').show(); $(Processes.element).find("th").hover().click(function(e){ $this=$(this); $(Processes.element).find('.sort-down, .sort-up').hide(); $this.find('.sort-down').show(); Processes.setSort($this.data('sort-by')); e.stopPropagation(); }) }, update:function(raw_processes){ var values = Object.keys(raw_processes).map(function (key) { return raw_processes[key]; }); values.sort(function(a, b) { return b[Processes.sortBy] - a[Processes.sortBy] }); values = values.slice(0, 10); var processes = {} $.each(values, function(index, value) { processes[value.cmd] = value; }); if(processIteration % 10 == 0) { // 1. create any elements that are missing for(cmd in processes) { if(!Processes.index[cmd]) { Processes.add(processes[cmd]); } } // 2. delete any elements that are redundant for(cmd in Processes.index) { if(!processes[cmd]) { Processes.remove(cmd); } } } // 3. add data and update charts for(cmd in Processes.index) { data = metrics['processes'][cmd]; row = Processes.index[cmd].row; $.each(['count', 'cpu', 'memory'], function(index, metric) { var graph = Processes.index[cmd][metric]; if(graph && data) { graph.data.push({time: new Date().getTime(), value: [data[metric]]}); graph.data.shift(); } }); if(data) { Processes.index[cmd]['row'].data({'memory':data['memory'],'cpu':data['cpu'],'count':data['count']}); // raw numbers for sorting } } if(processIteration % 10 == 0) { // 4. reorder table rows as needed rows = Processes.tableBody.children('tr').get(); rows.sort(function(a, b) { var compA = $(a).data(Processes.sortBy); var compB = $(b).data(Processes.sortBy); return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; }) $.each(rows, function(idx, itm) { Processes.tableBody.prepend(itm); }); } processIteration++; }, add:function(process){ Processes.index[cmd]={}; html=Processes.tableRowTemplate(process); $row = $(html).appendTo(Processes.tableBody); var chart; $row.find(".chart").each(function(i){ var $chart=$(this); $chart.width($chart.parent().width()); // set the width - necessary for firefox var metric = $chart.data("type"); if(historical_metrics.processes[cmd]) { var bufferedData = historical_metrics.processes[cmd][metric]; } else { var bufferedData = []; for (var i = 0; i < 61; i++) { bufferedData[i] = 0; } } // explicit times aren't passed, but these are required for the d3 x time scale. startTime = new Date()-(bufferedData.length*1000); // get the data into a proper format - [{time: ms since EPOCH, value: [array of values]}] data = []; $.each(bufferedData, function(data_index, value) { data.push({time: startTime + data_index * 1000, value: [value]}) }); chart = new lineChart({ element: $(this).get(0), data: data, metadata: meta.processes[metric], type: 'process' }); chart.draw(); Processes.index[cmd][metric] = chart; }); Processes.index[cmd]['row'] = $row; }, remove:function(cmd){ Processes.index[cmd]['row'].remove(); delete Processes.index[cmd]; }, setSort:function(sortBy){ if (sortBy != Processes.sortBy) { Processes.sortBy = sortBy; processIteration = 0; Processes.update(metrics['processes']); } } } /* --------------------------------------- */ $(document).ready(init); function init() { Processes.init({element:document.getElementById('processes')}); setOverviewChartWidths(); $(window).on("debouncedresize", function( event ) { setOverviewChartWidths(); }); $(".overview_chart").each(function (i) { var $chart = $(this); var collector = $chart.data("collector"); var chartMetrics = $chart.data("metrics"); var chartInstanceName = $chart.data("instance-name"); var yScaleMax = $chart.data('y_scale_max'); var id = collector + chartInstanceName; var dataSource; if (chartInstanceName != '') { dataSource = historical_metrics[collector][chartInstanceName]; } else { dataSource = historical_metrics[collector]; } if(Object.keys(dataSource).length > 0) { var bufferedData = dataSource[chartMetrics[0]]; // explicit times aren't passed, but these are required for the d3 x time scale. startTime = new Date()-(bufferedData.length*1000); // get the data into a proper format - [{time: ms since EPOCH, value: [array of values]}] data = []; $.each(bufferedData, function(data_index, value) { var valueBreakdown = {}; var valueSum = 0; $.each(chartMetrics, function(metric_index, metric) { var metricValue = dataSource[metric][data_index] || 0; valueBreakdown[metric] = metricValue; valueSum += metricValue; }); data.push({time: startTime + data_index * 1000, value: [valueSum], valueBreakdown: valueBreakdown}) }); chart = new lineChart({ element: $chart.get(0), data: data, yScaleMax: yScaleMax, metadata: (chartMetrics.length > 1 ? meta[collector] : meta[collector][chartMetrics[0]]), type: 'overview' }); chart.draw(); graphs[id] = chart; } else { console.log('No data reported for ' + collector); } }); $('#toggle .button').on('click', function() { toggleData(); }); updateGraphData(); // uncomment to get an initial render toggleData(); // uncomment to get continuous data // setTimeout(updateGraphData, 1000) // uncomment to get ONE update in a second (for development) // normally, lines 1 and 2 above will be uncommented // in chrome, the initial chart size is larger than what the parent container is. calling it here resets things. // still need to call it before drawing charts as FF won't draw it full width. setOverviewChartWidths() } function updateGraphData() { Processes.update(metrics['processes']); $(".overview_chart").each(function (i) { var $chart = $(this); var collector = $chart.data("collector"); var chartMetrics = $chart.data("metrics"); var chartInstanceName = $chart.data("instance-name"); var id = collector + chartInstanceName; var graph = graphs[id]; if(graph) { // if this metric did not initially report, it cannot be updated if (chartInstanceName != '') { dataSource = metrics[collector][chartInstanceName]; } else { dataSource = metrics[collector] } var valueBreakdown = {}; var valueSum = 0; $.each(chartMetrics, function(metric_index, metric) { value = dataSource[metric] || 0; valueBreakdown[metric] = value; valueSum += value; }); graph.data.push({time: new Date().getTime(), value: [valueSum], valueBreakdown: valueBreakdown}); if(firstShift) { // only don't shift off the data on the first iteration. leave it a tail so the graph does not clip along choppily firstShift = false; } else { graph.data.shift(); } } }); $('#report-time').html(formatTime(new Date)); $('#memory-used').html(parseInt(metrics.memory.used)); $('#memory-size').html(parseInt(metrics.memory.size)); $('#disk-used').html(parseInt(metrics.disk[Object.keys(metrics.disk)[0]].used)); $('#disk-size').html(parseInt(metrics.disk[Object.keys(metrics.disk)[0]].size)); } function formatTime(timestamp) { var date = new Date(timestamp); var hour = date.getHours(); var ampm; if(hour > 12) { hour = hour - 12; ampm = 'pm'; } else { ampm = 'am'; } dateString = '' return dateString + hour + ':' + (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() + ':' + (date.getSeconds() < 10 ? '0' : '') + date.getSeconds() + ' ' + ampm; } function refresh() { $.getJSON("stats.json", function (d) { metrics = d; updateGraphData(); }).fail(function() { toggleData(); $('#fail_message').show(); }); } /* Called on initial load. Just sets the svg element to the size of its parent. This is needed on firefox. Why don't we just use % widths for containers? The chart SVGs have a 30px left margin to handle the y-axis. We need to shift the charts over 30px to the left to handle this. We also need to add 30px to the width of the chart so it ends up using the entire container width after the 30px left shift. */ function setOverviewChartWidths(){ $overview_charts_td = $('#overview_charts'); totalWidth = $overview_charts_td.width(); // width of the td container for the 4 overview charts padding = parseInt($overview_charts_td.css('padding-left')); containerWidth = (totalWidth-2*padding-5)/2; // why -5? chrome overlaps at -4, ff at -5. don't know why. $('.overview_chart_container').each(function(i,e) { $(e).width(containerWidth).css('margin-right',padding) }); $('.overview_chart').each(function(i,e){ $svg=$(e); $svg.width(containerWidth+overviewChartMargin); }); }
import React, { Component } from 'react'; import styles from './Features.module.css'; import Feature from './Feature/Feature'; import icon from './feature.svg'; import Container from '../../Container/Container'; class Features extends Component { render() { return ( <div className={styles.featuresWrapper}> <Container> <div className={styles.features}> <div className={styles.featureWrapper}> <Feature icon={icon} title="Start your marketing" subtitle="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam." /> </div> <div className={styles.featureWrapper}> <Feature icon={icon} title="Find your favourite niche" subtitle="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam." /> </div> <div className={styles.featureWrapper}> <Feature icon={icon} title="Optimize your article" subtitle="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam." /> </div> </div> </Container> </div> ); } } export default Features;
import TSP from './TSP/TSP'; import Canvas from './Canvas/Canvas'; import UI from './UI/UI'; import Tour from './Tour/Tour' import Listeners from './Listeners/Listeners'; window.addEventListener('load', function () { const tour = new Tour(); const tempTour = new Tour(); const canvas = new Canvas(window.document); const ui = new UI(window.document); const tsp = new TSP(tour, tempTour, ui, canvas); Listeners.initializeFirstTour(tsp); Listeners.startStopSimulationListener(tsp); Listeners.generateNewProblemListener(tsp); Listeners.fileUploadSubmitListener(tsp); Listeners.setDelayListener(canvas); });
var shaders = require('./shaders') var { drawModel, makeModel} = require('./models') var m = require('./matrix') var vec = require('./vector') window.playFlag = 1; window.grayScale = 0; window.nightVision = 0; window.gFlag = 1; window.nFlag = 1; // window.gravity = 0.001; window.velocity = 1; window.level = 1; window.score = 0; window.prevScore = -10; var numObstacles = 7; var numObstacles2 = 5; var then = 0; var scalex = 1; var scaley = 1; var scalez = 1; var up = [0, 1, 0]; var outerRadius = 50.0 * scalex; var revolveRadius = outerRadius; window.revolveAngle = 0; window.revolveSpeed = 18; window.octRadius = 5 * scalex;//0.25 window.octAngle = 270; window.octSpeed = 200; window.octStepsA = 0; window.octStepsD = 0; var Camera = { x: revolveRadius, y: 0, z: 0, lookx: 0, looky: 0, lookz: 0, tempx: 0, tempz: 0, } function toRadians (angle) { return angle * (Math.PI / 180); } window.Matrices = {} window.models = {} window.addEventListener('keydown', keyChecker) window.addEventListener('keyup', keyChecker) window.keyMap = {} function keyChecker (key) { window.keyMap[key.keyCode] = (key.type == "keydown") } function keyImplementation () { if (window.keyMap[65]) { window.octStepsA -= 1; } if (window.keyMap[68]) { window.octStepsD -= 1; } if (window.keyMap[87]) { window.revolveAngle -= 0.7; } if (window.keyMap[83]) { window.revolveAngle += 0.7; } if (window.keyMap[71] && window.gFlag) { window.grayScale = !window.grayScale; window.gFlag = 0; gl.uniform1i(gl.getUniformLocation(program, 'grayScale'), window.grayScale); } if (!window.keyMap[71]) { window.gFlag = 1; } if (window.keyMap[78] && window.nFlag) { window.nightVision = !window.nightVision; window.nFlag = 0; gl.uniform1i(gl.getUniformLocation(program, 'nightVision'), window.nightVision); console.log('n'); // console.log(window.nightVision); } if (!window.keyMap[78]) { window.nFlag = 1; } } function autoMovement() { Camera.x = revolveRadius * Math.cos(toRadians(window.revolveAngle)); Camera.z = revolveRadius * Math.sin(toRadians(window.revolveAngle)); window.octAngle += Math.round(window.octStepsA - window.octStepsD) * window.deltaTime * window.octSpeed; var tempx = window.octRadius * Math.cos(toRadians(window.octAngle)) * Math.cos(toRadians(window.revolveAngle)); Camera.y = window.octRadius * Math.sin(toRadians(window.octAngle)); var tempz = window.octRadius * Math.cos(toRadians(window.octAngle)) * Math.sin(toRadians(window.revolveAngle)); Camera.x += tempx; Camera.z += tempz; window.octStepsA = 0; window.octStepsD = 0; var look = vec.normalize(vec.cross(vec.normalize([Camera.x, Camera.y, Camera.z]), [0, 1, 0])); Camera.lookx = -look[0]; Camera.looky = -look[1]; Camera.lookz = -look[2]; if(window.playFlag == 1) { window.revolveAngle -= window.revolveSpeed * window.deltaTime; } Camera.tempx = tempx; Camera.tempz = tempz; up[0] = Math.round(-tempx); up[1] = Math.round(-Camera.y); up[2] = Math.round(-tempz); if (window.jumpFlag == 0) { var cos = vec.dot(vec.normalize(up), vec.normalize([Camera.x, Camera.y, Camera.z])) var jump_angle = Math.round(Math.acos(cos) * (180 / Math.PI)); if((window.octAngle % 360) <= 180 && window.octAngle >= 0) { jump_angle = 180 + 180 - jump_angle; } else if (window.octAngle < 0 && (window.octAngle % 360) <= -180) { jump_angle = 180 + 180 - jump_angle; } if (window.velocity > 4) { window.velocity = 4; window.gravity = -window.gravity; } else if (window.velocity < 0) { window.velocity = 0; window.gravity = 0; } window.velocity += window.gravity; } } function resizeCanvas() { window.canvas.height = window.innerHeight; window.canvas.width = window.innerWidth; } function Initialize() { document.getElementById('backaudio').play(); window.canvas = document.getElementById("canvas"); resizeCanvas(); window.addEventListener('resize', resizeCanvas); window.gl = canvas.getContext("experimental-webgl"); gl.clearColor(0.0, 0.0, 0.0, 1.0); // setup a GLSL program shaders.createShader('material') // pipe model makeModel('pipe', 'assets/pipe',[0, 0, 0],[scalex, scaley, scalez], [0, 0, 0])//rotate dummy value = [0, 0, 0] //obstacles model for(var i = 0; i < numObstacles; i++) { var temp = (Math.random() * 1000 % 360) - 360; makeModel('obstacle' + i, 'assets/cubetex', [revolveRadius * Math.cos(toRadians(temp)), 0, revolveRadius * Math.sin(toRadians(temp))], [8, 1, 1], //scale temp, //rotateAngle1 Math.random() * 1000 % 360, //rotateAngle2 0) } //start the animation requestAnimationFrame(tick); } window.Initialize = Initialize window.Camera = Camera function animate(now) { if(window.playFlag) { window.score += 1; } if(window.score == 300) { window.prevScore = window.score; window.level++; window.revolveSpeed *= 1.5; for(var i = 0; i < numObstacles; i++) { var rotationSpeed = Math.random() * (1.5 - 0.5 + 1) + 0.5; models["obstacle" + i].rotationSpeed = rotationSpeed; } for(i = 0; i < numObstacles2; i++) { var temp = (Math.random() * 1000 % 360) - 360; rotationSpeed = Math.random() * (2.5 - 0.5 + 1) + 0.5; makeModel('obstacleBig' + i, 'assets/cubetex', [revolveRadius * Math.cos(toRadians(temp)), 0, revolveRadius * Math.sin(toRadians(temp))], [8, 2, 1], //scale temp, //rotateAngle1 Math.random() * 1000 % 360, //rotateAngle2 rotationSpeed) } } if (window.score == 2 * window.prevScore && window.score > 150) { window.prevScore = window.score; window.level++; window.revolveSpeed *= 1.5; for (i = 0; i < numObstacles; i++) { models["obstacle" + i].rotationSpeed *= 1.25; } for (i = 0; i < numObstacles2; i++) { models["obstacleBig" + i].rotationSpeed *= 1.25; } } if(window.revolveSpeed > 50) window.revolveSpeed = 50; var score = document.getElementById('score') score.innerText = 'SCORE: ' + window.score + '\n\n' + 'LEVEL: ' + window.level; now *= 0.001 // var timeNow = new Date().getTime(); // if (lastTime == 0) { lastTime = timeNow; return; } window.deltaTime = now - then; updateCamera(); then = now; } function drawScene() { gl.viewport(0, 0, canvas.width, canvas.height); gl.clearColor(0.1, 0.1, 0.1, 1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); shaders.useShader('material') gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); for(var i = 0; i < numObstacles; i++) { Matrices.model = m.multiply(m.translate(models["obstacle" + i].center), m.multiply(m.rotateY(toRadians(-models["obstacle" + i].rotateAngle1)), m.multiply(m.rotateZ(toRadians(models["obstacle" + i].rotateAngle2 += models["obstacle" + i].rotationSpeed)), m.scale(models["obstacle" + i].scale)))); drawModel(models["obstacle" + i]); } if(window.level >= 2) { for(i = 0; i < numObstacles2; i++) { Matrices.model = m.multiply(m.translate(models["obstacleBig" + i].center), m.multiply(m.rotateY(toRadians(-models["obstacleBig" + i].rotateAngle1)), m.multiply(m.rotateZ(toRadians(models["obstacleBig" + i].rotateAngle2 += models["obstacleBig" + i].rotationSpeed)), // m.multiply(m.translate([0, 4, 0]),m.scale(models["obstacleBig" + i].scale))))); m.scale(models["obstacleBig" + i].scale)))); drawModel(models["obstacleBig" + i]); } } Matrices.model = m.multiply(m.translate(models.pipe.center), m.scale(models.pipe.scale)) drawModel(models.pipe) gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); } function updateCamera() { var eye = [Camera.x, Camera.y, Camera.z] var target = [Camera.x + Camera.lookx, Camera.y + Camera.looky, Camera.z + Camera.lookz] Matrices.view = m.lookAt(eye, target, up); Matrices.projection = m.perspective(Math.PI/2, canvas.width / canvas.height, 0.1, 500); gl.uniformMatrix4fv(gl.getUniformLocation(program, "view"), false, Matrices.view); gl.uniformMatrix4fv(gl.getUniformLocation(program, "projection"), false, Matrices.projection); var lightPos = [ revolveRadius * Math.cos(toRadians(window.revolveAngle - 25)), 0, revolveRadius * Math.sin(toRadians(window.revolveAngle - 25)) ] // var lightPos = target var lightPosLoc = gl.getUniformLocation(program, "light.position"); var viewPosLoc = gl.getUniformLocation(program, "viewPos"); gl.uniform3f(lightPosLoc, lightPos[0], lightPos[1], lightPos[2]); gl.uniform3f(viewPosLoc, target[0], target[1], target[2]); var lightColor = []; lightColor[0] = 1; lightColor[1] = 1; lightColor[2] = 1; var diffuseColor = vec.multiplyScalar(lightColor, 1); // Decrease the influence var ambientColor = vec.multiplyScalar(diffuseColor, 1); // Low influence gl.uniform3f(gl.getUniformLocation(program, "light.ambient"), ambientColor[0], ambientColor[1], ambientColor[2]); gl.uniform3f(gl.getUniformLocation(program, "light.diffuse"), diffuseColor[0], diffuseColor[1], diffuseColor[2]); gl.uniform3f(gl.getUniformLocation(program, "light.specular"), 1.0, 1.0, 1.0); } function tick(now) { requestAnimationFrame(tick); if (!window.program) return; animate(now); keyImplementation(); autoMovement(); drawScene(); detectCollisions(); } function detectCollisions () { var angle = 0; var i = 0; for(i = 0; i < numObstacles; i++) { // console.log(i); angle = Math.atan(models["obstacle" + i].scale[1] / models["obstacle" + i].scale[0]) * 180 / Math.PI; if((window.octAngle % 180 >= (models["obstacle" + i].rotateAngle2 % 180 - angle) && window.octAngle % 180 <= (models["obstacle" + i].rotateAngle2 % 180 + angle)) && ((window.revolveAngle % 360 <= models["obstacle" + i].rotateAngle1 + 4) && window.revolveAngle % 360 >= models["obstacle" + i].rotateAngle1 - 4) ) { window.playFlag = 0; document.getElementById('gameOverContainer').style.visibility = "visible"; document.getElementById('scoreContainer').style.visibility = "hidden"; document.getElementById('gameOver').innerText = "GAME OVER \n\n SCORE: " + window.score + "\n\n" + "LEVEL: " + window.level; console.log("yes" + i); } } if(window.level >= 2) { for(i = 0; i < numObstacles2; i++) { // console.log("obstacle.y" + i, models["obstacleBig" + i].center[1] - 4); // console.log("dist", Math.abs(models["obstacleBig" + i].center[1] - Camera.y)); angle = Math.atan(models["obstacleBig" + i].scale[1] / models["obstacleBig" + i].scale[0]) * 180 / Math.PI; if((window.octAngle % 180 >= (models["obstacleBig" + i].rotateAngle2 % 180 - angle) && window.octAngle % 180 <= (models["obstacleBig" + i].rotateAngle2 % 180 + angle)) && ((window.revolveAngle % 360 <= models["obstacleBig" + i].rotateAngle1 + 4) && window.revolveAngle % 360 >= models["obstacleBig" + i].rotateAngle1 - 4) // (Math.abs(models["obstacleBig" + i].center[1] - 4 - Camera.y) <= 5) ) { window.playFlag = 0; document.getElementById('gameOverContainer').style.visibility = "visible"; document.getElementById('scoreContainer').style.visibility = "hidden"; document.getElementById('gameOver').innerText = "GAME OVER \n\n SCORE: " + window.score + "\n\n" + "LEVEL: " + window.level; } } } }
const initState = { items: [], cartPrice: 0, itemsNumber: 0, }; export const cartReducer = (state = initState, action) => { switch (action.type) { case "ADD_TO_CART": { const newItem = { model: action.dreamcatcher.model, amount: parseInt(action.amount), price: action.dreamcatcher.price, img: action.dreamcatcher.img, }; const itemIndex = state.items.findIndex( (item) => item.model === newItem.model ); const price = parseInt(newItem.price.slice(0, 3)); //Updating the amount field if the model is already in the array. if (itemIndex >= 0) { if (newItem.amount < action.dreamcatcher.amount) //exceeding max inventory. return state; let newArray = [...state.items]; newArray[itemIndex] = { ...newArray[itemIndex], amount: newArray[itemIndex].amount + newItem.amount, }; return { ...state, items: [...newArray], cartPrice: state.cartPrice + price * newItem.amount, itemsNumber: state.itemsNumber + newItem.amount, }; } return { ...state, items: [...state.items, newItem], cartPrice: state.cartPrice + price * newItem.amount, itemsNumber: state.itemsNumber + newItem.amount, }; } case "REMOVE_FROM_CART": { const newArray = state.items.filter( (item) => item.model !== action.item.model ); const price = parseInt(action.item.price.slice(0, 3)); const amount = action.item.amount; return { ...state, items: [...newArray], cartPrice: state.cartPrice - price * amount, itemsNumber: state.itemsNumber - amount, }; } default: return state; } };
.pragma library var CanMove = true; var matrix= new Array(); var block_11 = [ [0,11,11,0], [0,11,11,0], ] var block_12 = [ [0,12,0,0], [0,12,0,0], [0,12,12,0], ] var block_13 = [ [0,13,0,0], [13,13,13,0], ] var block_14 = [ [0,13,0,0], [0,13,13,0], [0,13,0,0], ] var newBlock; function initMatrix(){ var row = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for(var i=0; i<24; i++) { matrix[i] = new Array(); for(var j=0; j< 19; j++){ matrix[i][j] = 0; } } } function func() { } function nextBlock(){ } function createBlock(blockIndex){ newBlock = block_13; switch(blockIndex) { case 0: newBlock = block_11;break; case 1:newBlock = block_12; break; case 2:newBlock = block_13;break; case 3:newBlock = block_14;break; default: break; } for(var i=0; i< newBlock.length; i++) { for(var j=0; j< newBlock[i].length; j++) matrix[i][j+7] = newBlock[i][j] } } function moveDown(){ for(var i=matrix.length-1; i>=0; i--) { for(var j=0; j< matrix[i].length; j++) { if(matrix[i][j] !== 0 && matrix[i][j] !== 1){ if (i == matrix.length-1) { matrix[i][j] =1 ; } else { // Cell touch Cell if (matrix[i + 1][j] === 1) { matrix[i][j] = 1; fixAllCell(); break; } else if(j != matrix[i].length-1 && (matrix[i][j + 1] > 1 && matrix[i + 1][j + 1] === 1) ){ matrix[i][j] = 1; fixAllCell(); break; }else if (matrix[i + 1][j] === 0){ matrix[i + 1][j] = matrix[i][j]; matrix[i][j] = 0; } } } } } } function fixAllCell(){ for(var i=0; i< matrix.length; i++) { for(var j=0; j< matrix[i].length; j++) { if(matrix[i][j] !== 0 && matrix[i][j] !== 1){ matrix[i][j] = 1 ; } } } createBlock(Math.floor(Math.random()*4)); } function changeShape(){ console.log("u"); for(var i=0; i< matrix.length; i++) { for(var j=0; j< matrix[i].length; j++) { if(matrix[i][j] !== 0 && matrix[i][j] !== 1 && i !== j){ // var tmp = i - j; // matrix[j + 5][i - 5] = matrix[i][j]; // matrix[i][j] = 99; } } } } function moveLeft(){ for(var j=0; j< matrix[0].length; j++) { for(var i=matrix.length-1; i>=0; i--) { if (0 == j && matrix[i][j] > 1) { CanMove = false; } if(matrix[i][j] !== 0 && matrix[i][j] !== 1 && true == CanMove){ if (matrix[i][j - 1] === 0){ matrix[i][j - 1] = matrix[i][j]; matrix[i][j] = 0; } } } } CanMove = true; } function moveRight(){ for(var j=matrix[0].length -1 ; j>=0 ; j--) { for(var i=matrix.length-1; i>=0; i--) { if (matrix[0].length -1 == j && matrix[i][j] > 1) { CanMove = false; } if(matrix[i][j] !== 0 && matrix[i][j] !== 1 && true === CanMove){ if (matrix[i][j + 1] === 0){ matrix[i][j + 1] = matrix[i][j]; matrix[i][j] = 0; } } } } CanMove = true; }